repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
mottosso/be
be/lib.py
slice
def slice(index, template): """Slice a template based on it's positional argument Arguments: index (int): Position at which to slice template (str): Template to slice Example: >>> slice(0, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}' >>> slice(1, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}/assets/{1}' """ try: return re.match("^.*{[%i]}" % index, template).group() except AttributeError: raise ValueError("Index %i not found in template: %s" % (index, template))
python
def slice(index, template): """Slice a template based on it's positional argument Arguments: index (int): Position at which to slice template (str): Template to slice Example: >>> slice(0, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}' >>> slice(1, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}/assets/{1}' """ try: return re.match("^.*{[%i]}" % index, template).group() except AttributeError: raise ValueError("Index %i not found in template: %s" % (index, template))
[ "def", "slice", "(", "index", ",", "template", ")", ":", "try", ":", "return", "re", ".", "match", "(", "\"^.*{[%i]}\"", "%", "index", ",", "template", ")", ".", "group", "(", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"Index %i ...
Slice a template based on it's positional argument Arguments: index (int): Position at which to slice template (str): Template to slice Example: >>> slice(0, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}' >>> slice(1, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}/assets/{1}'
[ "Slice", "a", "template", "based", "on", "it", "s", "positional", "argument" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/lib.py#L656-L675
train
mottosso/be
be/vendor/requests/adapters.py
HTTPAdapter.proxy_manager_for
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 """ if not proxy in self.proxy_manager: proxy_headers = self.proxy_headers(proxy) 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 self.proxy_manager[proxy]
python
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 """ if not proxy in self.proxy_manager: proxy_headers = self.proxy_headers(proxy) 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 self.proxy_manager[proxy]
[ "def", "proxy_manager_for", "(", "self", ",", "proxy", ",", "*", "*", "proxy_kwargs", ")", ":", "if", "not", "proxy", "in", "self", ".", "proxy_manager", ":", "proxy_headers", "=", "self", ".", "proxy_headers", "(", "proxy", ")", "self", ".", "proxy_manage...
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
[ "Return", "urllib3", "ProxyManager", "for", "the", "given", "proxy", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/adapters.py#L136-L157
train
mottosso/be
be/vendor/requests/adapters.py
HTTPAdapter.cert_verify
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: Whether we should actually verify the certificate. :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 = DEFAULT_CA_BUNDLE_PATH if not cert_loc: raise Exception("Could not find a suitable SSL CA certificate bundle.") conn.cert_reqs = 'CERT_REQUIRED' conn.ca_certs = cert_loc else: conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert
python
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: Whether we should actually verify the certificate. :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 = DEFAULT_CA_BUNDLE_PATH if not cert_loc: raise Exception("Could not find a suitable SSL CA certificate bundle.") conn.cert_reqs = 'CERT_REQUIRED' conn.ca_certs = cert_loc else: conn.cert_reqs = 'CERT_NONE' conn.ca_certs = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert
[ "def", "cert_verify", "(", "self", ",", "conn", ",", "url", ",", "verify", ",", "cert", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "'https'", ")", "and", "verify", ":", "cert_loc", "=", "None", "# Allow self-specified cert loc...
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: Whether we should actually verify the certificate. :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", ...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/adapters.py#L159-L194
train
mottosso/be
be/vendor/requests/adapters.py
HTTPAdapter.get_connection
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. """ proxies = proxies or {} proxy = proxies.get(urlparse(url.lower()).scheme) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') 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
python
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. """ proxies = proxies or {} proxy = proxies.get(urlparse(url.lower()).scheme) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') 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
[ "def", "get_connection", "(", "self", ",", "url", ",", "proxies", "=", "None", ")", ":", "proxies", "=", "proxies", "or", "{", "}", "proxy", "=", "proxies", ".", "get", "(", "urlparse", "(", "url", ".", "lower", "(", ")", ")", ".", "scheme", ")", ...
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.
[ "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", "<req...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/adapters.py#L232-L253
train
mottosso/be
be/vendor/requests/adapters.py
HTTPAdapter.request_url
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 to proxy URLs. """ proxies = proxies or {} scheme = urlparse(request.url).scheme proxy = proxies.get(scheme) if proxy and scheme != 'https': url = urldefragauth(request.url) else: url = request.path_url return url
python
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 to proxy URLs. """ proxies = proxies or {} scheme = urlparse(request.url).scheme proxy = proxies.get(scheme) if proxy and scheme != 'https': url = urldefragauth(request.url) else: url = request.path_url return url
[ "def", "request_url", "(", "self", ",", "request", ",", "proxies", ")", ":", "proxies", "=", "proxies", "or", "{", "}", "scheme", "=", "urlparse", "(", "request", ".", "url", ")", ".", "scheme", "proxy", "=", "proxies", ".", "get", "(", "scheme", ")"...
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 to proxy URLs.
[ "Obtain", "the", "url", "to", "use", "when", "making", "the", "final", "request", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/adapters.py#L263-L285
train
mottosso/be
be/vendor/requests/adapters.py
HTTPAdapter.proxy_headers
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 proxies: The url of the proxy being used for this request. :param kwargs: Optional additional keyword arguments. """ headers = {} username, password = get_auth_from_url(proxy) if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers
python
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 proxies: The url of the proxy being used for this request. :param kwargs: Optional additional keyword arguments. """ headers = {} username, password = get_auth_from_url(proxy) if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers
[ "def", "proxy_headers", "(", "self", ",", "proxy", ")", ":", "headers", "=", "{", "}", "username", ",", "password", "=", "get_auth_from_url", "(", "proxy", ")", "if", "username", "and", "password", ":", "headers", "[", "'Proxy-Authorization'", "]", "=", "_...
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 proxies: The url of the proxy being used for this request. :param kwargs: Optional additional keyword arguments.
[ "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", ...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/adapters.py#L301-L321
train
mottosso/be
be/vendor/requests/api.py
request
def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]> """ session = sessions.Session() response = session.request(method=method, url=url, **kwargs) # By explicitly closing the session, we avoid leaving sockets open which # can trigger a ResourceWarning in some cases, and look like a memory leak # in others. session.close() return response
python
def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]> """ session = sessions.Session() response = session.request(method=method, url=url, **kwargs) # By explicitly closing the session, we avoid leaving sockets open which # can trigger a ResourceWarning in some cases, and look like a memory leak # in others. session.close() return response
[ "def", "request", "(", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "session", "=", "sessions", ".", "Session", "(", ")", "response", "=", "session", ".", "request", "(", "method", "=", "method", ",", "url", "=", "url", ",", "*", "*", ...
Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]>
[ "Constructs", "and", "sends", "a", ":", "class", ":", "Request", "<Request", ">", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/api.py#L17-L55
train
mottosso/be
be/vendor/requests/packages/urllib3/util/connection.py
is_connection_dropped
def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, 'sock', False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True if not poll: if not select: # Platform-specific: AppEngine return False try: return select([sock], [], [], 0.0)[0] except socket.error: return True # This version is better on platforms that support it. p = poll() p.register(sock, POLLIN) for (fno, ev) in p.poll(0.0): if fno == sock.fileno(): # Either data is buffered (bad), or the connection is dropped. return True
python
def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, 'sock', False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True if not poll: if not select: # Platform-specific: AppEngine return False try: return select([sock], [], [], 0.0)[0] except socket.error: return True # This version is better on platforms that support it. p = poll() p.register(sock, POLLIN) for (fno, ev) in p.poll(0.0): if fno == sock.fileno(): # Either data is buffered (bad), or the connection is dropped. return True
[ "def", "is_connection_dropped", "(", "conn", ")", ":", "# Platform-specific", "sock", "=", "getattr", "(", "conn", ",", "'sock'", ",", "False", ")", "if", "sock", "is", "False", ":", "# Platform-specific: AppEngine", "return", "False", "if", "sock", "is", "Non...
Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us.
[ "Returns", "True", "if", "the", "connection", "is", "dropped", "and", "should", "be", "closed", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/connection.py#L12-L43
train
mottosso/be
be/vendor/requests/cookies.py
morsel_to_cookie
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: expires = time.time() + morsel['max-age'] elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = time.mktime( time.strptime(morsel['expires'], time_template)) - time.timezone return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
python
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: expires = time.time() + morsel['max-age'] elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = time.mktime( time.strptime(morsel['expires'], time_template)) - time.timezone return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
[ "def", "morsel_to_cookie", "(", "morsel", ")", ":", "expires", "=", "None", "if", "morsel", "[", "'max-age'", "]", ":", "expires", "=", "time", ".", "time", "(", ")", "+", "morsel", "[", "'max-age'", "]", "elif", "morsel", "[", "'expires'", "]", ":", ...
Convert a Morsel object into a Cookie containing the one k/v pair.
[ "Convert", "a", "Morsel", "object", "into", "a", "Cookie", "containing", "the", "one", "k", "/", "v", "pair", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/cookies.py#L397-L421
train
mottosso/be
be/vendor/requests/cookies.py
RequestsCookieJar.get_dict
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.""" 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
python
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.""" 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
[ "def", "get_dict", "(", "self", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "dictionary", "=", "{", "}", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "(", "domain", "is", "None", "or", "cookie", ".", "domain", "...
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.
[ "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", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/cookies.py#L264-L273
train
mottosso/be
be/vendor/requests/packages/chardet/chardistribution.py
CharDistributionAnalysis.feed
def feed(self, aBuf, aCharLen): """feed a character with known length""" if aCharLen == 2: # we only care about 2-bytes character in our distribution analysis order = self.get_order(aBuf) else: order = -1 if order >= 0: self._mTotalChars += 1 # order is valid if order < self._mTableSize: if 512 > self._mCharToFreqOrder[order]: self._mFreqChars += 1
python
def feed(self, aBuf, aCharLen): """feed a character with known length""" if aCharLen == 2: # we only care about 2-bytes character in our distribution analysis order = self.get_order(aBuf) else: order = -1 if order >= 0: self._mTotalChars += 1 # order is valid if order < self._mTableSize: if 512 > self._mCharToFreqOrder[order]: self._mFreqChars += 1
[ "def", "feed", "(", "self", ",", "aBuf", ",", "aCharLen", ")", ":", "if", "aCharLen", "==", "2", ":", "# we only care about 2-bytes character in our distribution analysis", "order", "=", "self", ".", "get_order", "(", "aBuf", ")", "else", ":", "order", "=", "-...
feed a character with known length
[ "feed", "a", "character", "with", "known", "length" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/chardet/chardistribution.py#L68-L80
train
mottosso/be
be/vendor/requests/packages/chardet/chardistribution.py
CharDistributionAnalysis.get_confidence
def get_confidence(self): """return confidence based on existing data""" # if we didn't receive any character in our consideration range, # return negative answer if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD: return SURE_NO if self._mTotalChars != self._mFreqChars: r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars) * self._mTypicalDistributionRatio)) if r < SURE_YES: return r # normalize confidence (we don't want to be 100% sure) return SURE_YES
python
def get_confidence(self): """return confidence based on existing data""" # if we didn't receive any character in our consideration range, # return negative answer if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD: return SURE_NO if self._mTotalChars != self._mFreqChars: r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars) * self._mTypicalDistributionRatio)) if r < SURE_YES: return r # normalize confidence (we don't want to be 100% sure) return SURE_YES
[ "def", "get_confidence", "(", "self", ")", ":", "# if we didn't receive any character in our consideration range,", "# return negative answer", "if", "self", ".", "_mTotalChars", "<=", "0", "or", "self", ".", "_mFreqChars", "<=", "MINIMUM_DATA_THRESHOLD", ":", "return", "...
return confidence based on existing data
[ "return", "confidence", "based", "on", "existing", "data" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/chardet/chardistribution.py#L82-L96
train
mottosso/be
be/vendor/requests/packages/urllib3/__init__.py
add_stderr_logger
def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another package. logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger.addHandler(handler) logger.setLevel(level) logger.debug('Added a stderr logging handler to logger: %s' % __name__) return handler
python
def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another package. logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger.addHandler(handler) logger.setLevel(level) logger.debug('Added a stderr logging handler to logger: %s' % __name__) return handler
[ "def", "add_stderr_logger", "(", "level", "=", "logging", ".", "DEBUG", ")", ":", "# This method needs to be in this __init__.py to get the __name__ correct", "# even if urllib3 is vendored within another package.", "logger", "=", "logging", ".", "getLogger", "(", "__name__", "...
Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it.
[ "Helper", "for", "quickly", "adding", "a", "StreamHandler", "to", "the", "logger", ".", "Useful", "for", "debugging", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/__init__.py#L37-L52
train
mottosso/be
be/vendor/requests/packages/urllib3/util/ssl_.py
assert_fingerprint
def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ # Maps the length of a digest to a possible hash function producing # this digest. hashfunc_map = { 16: md5, 20: sha1, 32: sha256, } fingerprint = fingerprint.replace(':', '').lower() digest_length, odd = divmod(len(fingerprint), 2) if odd or digest_length not in hashfunc_map: raise SSLError('Fingerprint is of invalid length.') # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) hashfunc = hashfunc_map[digest_length] cert_digest = hashfunc(cert).digest() if not cert_digest == fingerprint_bytes: raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(hexlify(fingerprint_bytes), hexlify(cert_digest)))
python
def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ # Maps the length of a digest to a possible hash function producing # this digest. hashfunc_map = { 16: md5, 20: sha1, 32: sha256, } fingerprint = fingerprint.replace(':', '').lower() digest_length, odd = divmod(len(fingerprint), 2) if odd or digest_length not in hashfunc_map: raise SSLError('Fingerprint is of invalid length.') # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) hashfunc = hashfunc_map[digest_length] cert_digest = hashfunc(cert).digest() if not cert_digest == fingerprint_bytes: raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(hexlify(fingerprint_bytes), hexlify(cert_digest)))
[ "def", "assert_fingerprint", "(", "cert", ",", "fingerprint", ")", ":", "# Maps the length of a digest to a possible hash function producing", "# this digest.", "hashfunc_map", "=", "{", "16", ":", "md5", ",", "20", ":", "sha1", ",", "32", ":", "sha256", ",", "}", ...
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons.
[ "Checks", "if", "given", "fingerprint", "matches", "the", "supplied", "certificate", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/ssl_.py#L94-L128
train
mottosso/be
be/vendor/requests/packages/urllib3/util/ssl_.py
create_urllib3_context
def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6 context.set_ciphers(ciphers or _DEFAULT_CIPHERS) context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context
python
def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6 context.set_ciphers(ciphers or _DEFAULT_CIPHERS) context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context
[ "def", "create_urllib3_context", "(", "ssl_version", "=", "None", ",", "cert_reqs", "=", "ssl", ".", "CERT_REQUIRED", ",", "options", "=", "None", ",", "ciphers", "=", "None", ")", ":", "context", "=", "SSLContext", "(", "ssl_version", "or", "ssl", ".", "P...
All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext
[ "All", "arguments", "have", "the", "same", "meaning", "as", "ssl_wrap_socket", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/ssl_.py#L170-L227
train
mottosso/be
be/vendor/requests/packages/urllib3/util/ssl_.py
ssl_wrap_socket
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None): """ All arguments except for server_hostname and ssl_context have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. This is not supported on Python 2.6 as the ssl module does not support it. """ context = ssl_context if context is None: context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs: try: context.load_verify_locations(ca_certs) except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
python
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None): """ All arguments except for server_hostname and ssl_context have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. This is not supported on Python 2.6 as the ssl module does not support it. """ context = ssl_context if context is None: context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs: try: context.load_verify_locations(ca_certs) except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
[ "def", "ssl_wrap_socket", "(", "sock", ",", "keyfile", "=", "None", ",", "certfile", "=", "None", ",", "cert_reqs", "=", "None", ",", "ca_certs", "=", "None", ",", "server_hostname", "=", "None", ",", "ssl_version", "=", "None", ",", "ciphers", "=", "Non...
All arguments except for server_hostname and ssl_context have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. This is not supported on Python 2.6 as the ssl module does not support it.
[ "All", "arguments", "except", "for", "server_hostname", "and", "ssl_context", "have", "the", "same", "meaning", "as", "they", "do", "when", "using", ":", "func", ":", "ssl", ".", "wrap_socket", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/util/ssl_.py#L230-L266
train
mottosso/be
be/vendor/requests/packages/urllib3/connectionpool.py
connection_from_url
def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example:: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') """ scheme, host, port = get_host(url) if scheme == 'https': return HTTPSConnectionPool(host, port=port, **kw) else: return HTTPConnectionPool(host, port=port, **kw)
python
def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example:: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') """ scheme, host, port = get_host(url) if scheme == 'https': return HTTPSConnectionPool(host, port=port, **kw) else: return HTTPConnectionPool(host, port=port, **kw)
[ "def", "connection_from_url", "(", "url", ",", "*", "*", "kw", ")", ":", "scheme", ",", "host", ",", "port", "=", "get_host", "(", "url", ")", "if", "scheme", "==", "'https'", ":", "return", "HTTPSConnectionPool", "(", "host", ",", "port", "=", "port",...
Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example:: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/')
[ "Given", "a", "url", "return", "an", ":", "class", ":", ".", "ConnectionPool", "instance", "of", "its", "host", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/connectionpool.py#L772-L796
train
mottosso/be
be/vendor/requests/packages/urllib3/connectionpool.py
HTTPConnectionPool._put_conn
def _put_conn(self, conn): """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded. """ try: self.pool.put(conn, block=False) return # Everything is dandy, done. except AttributeError: # self.pool is None. pass except Full: # This should never happen if self.block == True log.warning( "Connection pool is full, discarding connection: %s" % self.host) # Connection never got put back into the pool, close it. if conn: conn.close()
python
def _put_conn(self, conn): """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded. """ try: self.pool.put(conn, block=False) return # Everything is dandy, done. except AttributeError: # self.pool is None. pass except Full: # This should never happen if self.block == True log.warning( "Connection pool is full, discarding connection: %s" % self.host) # Connection never got put back into the pool, close it. if conn: conn.close()
[ "def", "_put_conn", "(", "self", ",", "conn", ")", ":", "try", ":", "self", ".", "pool", ".", "put", "(", "conn", ",", "block", "=", "False", ")", "return", "# Everything is dandy, done.", "except", "AttributeError", ":", "# self.pool is None.", "pass", "exc...
Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded.
[ "Put", "a", "connection", "back", "into", "the", "pool", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/connectionpool.py#L248-L276
train
mottosso/be
be/vendor/requests/packages/urllib3/connectionpool.py
HTTPConnectionPool._make_request
def _make_request(self, conn, method, url, timeout=_Default, **httplib_request_kw): """ Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts. """ self.num_requests += 1 timeout_obj = self._get_timeout(timeout) timeout_obj.start_connect() conn.timeout = timeout_obj.connect_timeout # Trigger any extra validation we need to do. try: self._validate_conn(conn) except (SocketTimeout, BaseSSLError) as e: # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) raise # conn.request() calls httplib.*.request, not the method in # urllib3.request. It also calls makefile (recv) on the socket. conn.request(method, url, **httplib_request_kw) # Reset the timeout for the recv() on the socket read_timeout = timeout_obj.read_timeout # App Engine doesn't have a sock attr if getattr(conn, 'sock', None): # In Python 3 socket.py will catch EAGAIN and return None when you # try and read into the file pointer created by http.client, which # instead raises a BadStatusLine exception. Instead of catching # the exception and assuming all BadStatusLine exceptions are read # timeouts, check for a zero timeout before making the request. if read_timeout == 0: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % read_timeout) if read_timeout is Timeout.DEFAULT_TIMEOUT: conn.sock.settimeout(socket.getdefaulttimeout()) else: # None or a value conn.sock.settimeout(read_timeout) # Receive the response from the server try: try: # Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) except TypeError: # Python 2.6 and older httplib_response = conn.getresponse() except (SocketTimeout, BaseSSLError, SocketError) as e: self._raise_timeout(err=e, url=url, timeout_value=read_timeout) raise # AppEngine doesn't have a version attr. http_version = getattr(conn, '_http_vsn_str', 'HTTP/?') log.debug("\"%s %s %s\" %s %s" % (method, url, http_version, httplib_response.status, httplib_response.length)) return httplib_response
python
def _make_request(self, conn, method, url, timeout=_Default, **httplib_request_kw): """ Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts. """ self.num_requests += 1 timeout_obj = self._get_timeout(timeout) timeout_obj.start_connect() conn.timeout = timeout_obj.connect_timeout # Trigger any extra validation we need to do. try: self._validate_conn(conn) except (SocketTimeout, BaseSSLError) as e: # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) raise # conn.request() calls httplib.*.request, not the method in # urllib3.request. It also calls makefile (recv) on the socket. conn.request(method, url, **httplib_request_kw) # Reset the timeout for the recv() on the socket read_timeout = timeout_obj.read_timeout # App Engine doesn't have a sock attr if getattr(conn, 'sock', None): # In Python 3 socket.py will catch EAGAIN and return None when you # try and read into the file pointer created by http.client, which # instead raises a BadStatusLine exception. Instead of catching # the exception and assuming all BadStatusLine exceptions are read # timeouts, check for a zero timeout before making the request. if read_timeout == 0: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % read_timeout) if read_timeout is Timeout.DEFAULT_TIMEOUT: conn.sock.settimeout(socket.getdefaulttimeout()) else: # None or a value conn.sock.settimeout(read_timeout) # Receive the response from the server try: try: # Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) except TypeError: # Python 2.6 and older httplib_response = conn.getresponse() except (SocketTimeout, BaseSSLError, SocketError) as e: self._raise_timeout(err=e, url=url, timeout_value=read_timeout) raise # AppEngine doesn't have a version attr. http_version = getattr(conn, '_http_vsn_str', 'HTTP/?') log.debug("\"%s %s %s\" %s %s" % (method, url, http_version, httplib_response.status, httplib_response.length)) return httplib_response
[ "def", "_make_request", "(", "self", ",", "conn", ",", "method", ",", "url", ",", "timeout", "=", "_Default", ",", "*", "*", "httplib_request_kw", ")", ":", "self", ".", "num_requests", "+=", "1", "timeout_obj", "=", "self", ".", "_get_timeout", "(", "ti...
Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts.
[ "Perform", "a", "request", "on", "a", "given", "urllib", "connection", "object", "taken", "from", "our", "pool", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/connectionpool.py#L317-L384
train
mottosso/be
be/vendor/requests/packages/urllib3/connectionpool.py
HTTPConnectionPool.urlopen
def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw): """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` """ if headers is None: headers = self.headers if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if release_conn is None: release_conn = response_kw.get('preload_content', True) # Check host if assert_same_host and not self.is_same_host(url): raise HostChangedError(self, url, retries) conn = None # Merge the proxy headers. Only do this in HTTP. We have to copy the # headers dict so we can safely change it without those changes being # reflected in anyone else's copy. if self.scheme == 'http': headers = headers.copy() headers.update(self.proxy_headers) # Must keep the exception bound to a separate variable or else Python 3 # complains about UnboundLocalError. err = None try: # Request a connection from the queue. timeout_obj = self._get_timeout(timeout) conn = self._get_conn(timeout=pool_timeout) conn.timeout = timeout_obj.connect_timeout is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None) if is_new_proxy_conn: self._prepare_proxy(conn) # Make the request on the httplib connection object. httplib_response = self._make_request(conn, method, url, timeout=timeout_obj, body=body, headers=headers) # If we're going to release the connection in ``finally:``, then # the request doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = not release_conn and conn # Import httplib's response into our own wrapper object response = HTTPResponse.from_httplib(httplib_response, pool=self, connection=response_conn, **response_kw) # else: # The connection will be put back into the pool when # ``response.release_conn()`` is called (implicitly by # ``response.read()``) except Empty: # Timed out by queue. raise EmptyPoolError(self, "No pool connections are available.") except (BaseSSLError, CertificateError) as e: # Close the connection. If a connection is reused on which there # was a Certificate error, the next request will certainly raise # another Certificate error. if conn: conn.close() conn = None raise SSLError(e) except SSLError: # Treat SSLError separately from BaseSSLError to preserve # traceback. if conn: conn.close() conn = None raise except (TimeoutError, HTTPException, SocketError, ConnectionError) as e: if conn: # Discard the connection for these exceptions. It will be # be replaced during the next _get_conn() call. conn.close() conn = None if isinstance(e, SocketError) and self.proxy: e = ProxyError('Cannot connect to proxy.', e) elif isinstance(e, (SocketError, HTTPException)): e = ProtocolError('Connection aborted.', e) retries = retries.increment(method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]) retries.sleep() # Keep track of the error for the retry warning. err = e finally: if release_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. self._put_conn(conn) if not conn: # Try again log.warning("Retrying (%r) after connection " "broken by '%r': %s" % (retries, err, url)) return self.urlopen(method, url, body, headers, retries, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: if response.status == 303: method = 'GET' try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_redirect: raise return response log.info("Redirecting %s -> %s" % (url, redirect_location)) return self.urlopen(method, redirect_location, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) # Check if we should retry the HTTP response. if retries.is_forced_retry(method, status_code=response.status): retries = retries.increment(method, url, response=response, _pool=self) retries.sleep() log.info("Forced retry: %s" % url) return self.urlopen(method, url, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) return response
python
def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw): """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` """ if headers is None: headers = self.headers if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if release_conn is None: release_conn = response_kw.get('preload_content', True) # Check host if assert_same_host and not self.is_same_host(url): raise HostChangedError(self, url, retries) conn = None # Merge the proxy headers. Only do this in HTTP. We have to copy the # headers dict so we can safely change it without those changes being # reflected in anyone else's copy. if self.scheme == 'http': headers = headers.copy() headers.update(self.proxy_headers) # Must keep the exception bound to a separate variable or else Python 3 # complains about UnboundLocalError. err = None try: # Request a connection from the queue. timeout_obj = self._get_timeout(timeout) conn = self._get_conn(timeout=pool_timeout) conn.timeout = timeout_obj.connect_timeout is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None) if is_new_proxy_conn: self._prepare_proxy(conn) # Make the request on the httplib connection object. httplib_response = self._make_request(conn, method, url, timeout=timeout_obj, body=body, headers=headers) # If we're going to release the connection in ``finally:``, then # the request doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = not release_conn and conn # Import httplib's response into our own wrapper object response = HTTPResponse.from_httplib(httplib_response, pool=self, connection=response_conn, **response_kw) # else: # The connection will be put back into the pool when # ``response.release_conn()`` is called (implicitly by # ``response.read()``) except Empty: # Timed out by queue. raise EmptyPoolError(self, "No pool connections are available.") except (BaseSSLError, CertificateError) as e: # Close the connection. If a connection is reused on which there # was a Certificate error, the next request will certainly raise # another Certificate error. if conn: conn.close() conn = None raise SSLError(e) except SSLError: # Treat SSLError separately from BaseSSLError to preserve # traceback. if conn: conn.close() conn = None raise except (TimeoutError, HTTPException, SocketError, ConnectionError) as e: if conn: # Discard the connection for these exceptions. It will be # be replaced during the next _get_conn() call. conn.close() conn = None if isinstance(e, SocketError) and self.proxy: e = ProxyError('Cannot connect to proxy.', e) elif isinstance(e, (SocketError, HTTPException)): e = ProtocolError('Connection aborted.', e) retries = retries.increment(method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]) retries.sleep() # Keep track of the error for the retry warning. err = e finally: if release_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. self._put_conn(conn) if not conn: # Try again log.warning("Retrying (%r) after connection " "broken by '%r': %s" % (retries, err, url)) return self.urlopen(method, url, body, headers, retries, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: if response.status == 303: method = 'GET' try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_redirect: raise return response log.info("Redirecting %s -> %s" % (url, redirect_location)) return self.urlopen(method, redirect_location, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) # Check if we should retry the HTTP response. if retries.is_forced_retry(method, status_code=response.status): retries = retries.increment(method, url, response=response, _pool=self) retries.sleep() log.info("Forced retry: %s" % url) return self.urlopen(method, url, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) return response
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "retries", "=", "None", ",", "redirect", "=", "True", ",", "assert_same_host", "=", "True", ",", "timeout", "=", "_Default", ",", "p...
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib`
[ "Get", "a", "connection", "from", "the", "pool", "and", "perform", "an", "HTTP", "request", ".", "This", "is", "the", "lowest", "level", "call", "for", "making", "a", "request", "so", "you", "ll", "need", "to", "specify", "all", "the", "raw", "details", ...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/connectionpool.py#L421-L650
train
mottosso/be
be/vendor/requests/packages/urllib3/connectionpool.py
HTTPSConnectionPool._new_conn
def _new_conn(self): """ Return a fresh :class:`httplib.HTTPSConnection`. """ self.num_connections += 1 log.info("Starting new HTTPS connection (%d): %s" % (self.num_connections, self.host)) if not self.ConnectionCls or self.ConnectionCls is DummyConnection: # Platform-specific: Python without ssl raise SSLError("Can't connect to HTTPS URL because the SSL " "module is not available.") actual_host = self.host actual_port = self.port if self.proxy is not None: actual_host = self.proxy.host actual_port = self.proxy.port conn = self.ConnectionCls(host=actual_host, port=actual_port, timeout=self.timeout.connect_timeout, strict=self.strict, **self.conn_kw) return self._prepare_conn(conn)
python
def _new_conn(self): """ Return a fresh :class:`httplib.HTTPSConnection`. """ self.num_connections += 1 log.info("Starting new HTTPS connection (%d): %s" % (self.num_connections, self.host)) if not self.ConnectionCls or self.ConnectionCls is DummyConnection: # Platform-specific: Python without ssl raise SSLError("Can't connect to HTTPS URL because the SSL " "module is not available.") actual_host = self.host actual_port = self.port if self.proxy is not None: actual_host = self.proxy.host actual_port = self.proxy.port conn = self.ConnectionCls(host=actual_host, port=actual_port, timeout=self.timeout.connect_timeout, strict=self.strict, **self.conn_kw) return self._prepare_conn(conn)
[ "def", "_new_conn", "(", "self", ")", ":", "self", ".", "num_connections", "+=", "1", "log", ".", "info", "(", "\"Starting new HTTPS connection (%d): %s\"", "%", "(", "self", ".", "num_connections", ",", "self", ".", "host", ")", ")", "if", "not", "self", ...
Return a fresh :class:`httplib.HTTPSConnection`.
[ "Return", "a", "fresh", ":", "class", ":", "httplib", ".", "HTTPSConnection", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/connectionpool.py#L729-L752
train
mottosso/be
be/vendor/requests/packages/urllib3/connectionpool.py
HTTPSConnectionPool._validate_conn
def _validate_conn(self, conn): """ Called right before a request is made, after the socket is created. """ super(HTTPSConnectionPool, self)._validate_conn(conn) # Force connect early to allow us to validate the connection. if not getattr(conn, 'sock', None): # AppEngine might not have `.sock` conn.connect() if not conn.is_verified: warnings.warn(( 'Unverified HTTPS request is being made. ' 'Adding certificate verification is strongly advised. See: ' 'https://urllib3.readthedocs.org/en/latest/security.html'), InsecureRequestWarning)
python
def _validate_conn(self, conn): """ Called right before a request is made, after the socket is created. """ super(HTTPSConnectionPool, self)._validate_conn(conn) # Force connect early to allow us to validate the connection. if not getattr(conn, 'sock', None): # AppEngine might not have `.sock` conn.connect() if not conn.is_verified: warnings.warn(( 'Unverified HTTPS request is being made. ' 'Adding certificate verification is strongly advised. See: ' 'https://urllib3.readthedocs.org/en/latest/security.html'), InsecureRequestWarning)
[ "def", "_validate_conn", "(", "self", ",", "conn", ")", ":", "super", "(", "HTTPSConnectionPool", ",", "self", ")", ".", "_validate_conn", "(", "conn", ")", "# Force connect early to allow us to validate the connection.", "if", "not", "getattr", "(", "conn", ",", ...
Called right before a request is made, after the socket is created.
[ "Called", "right", "before", "a", "request", "is", "made", "after", "the", "socket", "is", "created", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/connectionpool.py#L754-L769
train
mottosso/be
be/vendor/requests/packages/chardet/chardetect.py
description_of
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = UniversalDetector() for line in lines: u.feed(line) u.close() result = u.result if result['encoding']: return '{0}: {1} with confidence {2}'.format(name, result['encoding'], result['confidence']) else: return '{0}: no result'.format(name)
python
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = UniversalDetector() for line in lines: u.feed(line) u.close() result = u.result if result['encoding']: return '{0}: {1} with confidence {2}'.format(name, result['encoding'], result['confidence']) else: return '{0}: no result'.format(name)
[ "def", "description_of", "(", "lines", ",", "name", "=", "'stdin'", ")", ":", "u", "=", "UniversalDetector", "(", ")", "for", "line", "in", "lines", ":", "u", ".", "feed", "(", "line", ")", "u", ".", "close", "(", ")", "result", "=", "u", ".", "r...
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
[ "Return", "a", "string", "describing", "the", "probable", "encoding", "of", "a", "file", "or", "list", "of", "strings", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/chardet/chardetect.py#L26-L45
train
mottosso/be
be/vendor/requests/packages/chardet/chardetect.py
main
def main(argv=None): ''' Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str ''' # Get command line arguments parser = argparse.ArgumentParser( description="Takes one or more file paths and reports their detected \ encodings", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler='resolve') parser.add_argument('input', help='File whose encoding we would like to determine.', type=argparse.FileType('rb'), nargs='*', default=[sys.stdin]) parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__)) args = parser.parse_args(argv) for f in args.input: if f.isatty(): print("You are running chardetect interactively. Press " + "CTRL-D twice at the start of a blank line to signal the " + "end of your input. If you want help, run chardetect " + "--help\n", file=sys.stderr) print(description_of(f, f.name))
python
def main(argv=None): ''' Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str ''' # Get command line arguments parser = argparse.ArgumentParser( description="Takes one or more file paths and reports their detected \ encodings", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler='resolve') parser.add_argument('input', help='File whose encoding we would like to determine.', type=argparse.FileType('rb'), nargs='*', default=[sys.stdin]) parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__)) args = parser.parse_args(argv) for f in args.input: if f.isatty(): print("You are running chardetect interactively. Press " + "CTRL-D twice at the start of a blank line to signal the " + "end of your input. If you want help, run chardetect " + "--help\n", file=sys.stderr) print(description_of(f, f.name))
[ "def", "main", "(", "argv", "=", "None", ")", ":", "# Get command line arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Takes one or more file paths and reports their detected \\\n encodings\"", ",", "formatter_class"...
Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str
[ "Handles", "command", "line", "arguments", "and", "gets", "things", "started", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/chardet/chardetect.py#L48-L76
train
mottosso/be
be/vendor/click/termui.py
get_terminal_size
def get_terminal_size(): """Returns the current size of the terminal as tuple in the form ``(width, height)`` in columns and rows. """ # If shutil has get_terminal_size() (Python 3.3 and later) use that if sys.version_info >= (3, 3): import shutil shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None) if shutil_get_terminal_size: sz = shutil_get_terminal_size() return sz.columns, sz.lines if get_winterm_size is not None: return get_winterm_size() def ioctl_gwinsz(fd): try: import fcntl import termios cr = struct.unpack( 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except Exception: return return cr cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) try: cr = ioctl_gwinsz(fd) finally: os.close(fd) except Exception: pass if not cr or not cr[0] or not cr[1]: cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', DEFAULT_COLUMNS)) return int(cr[1]), int(cr[0])
python
def get_terminal_size(): """Returns the current size of the terminal as tuple in the form ``(width, height)`` in columns and rows. """ # If shutil has get_terminal_size() (Python 3.3 and later) use that if sys.version_info >= (3, 3): import shutil shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None) if shutil_get_terminal_size: sz = shutil_get_terminal_size() return sz.columns, sz.lines if get_winterm_size is not None: return get_winterm_size() def ioctl_gwinsz(fd): try: import fcntl import termios cr = struct.unpack( 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except Exception: return return cr cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2) if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) try: cr = ioctl_gwinsz(fd) finally: os.close(fd) except Exception: pass if not cr or not cr[0] or not cr[1]: cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', DEFAULT_COLUMNS)) return int(cr[1]), int(cr[0])
[ "def", "get_terminal_size", "(", ")", ":", "# If shutil has get_terminal_size() (Python 3.3 and later) use that", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "3", ")", ":", "import", "shutil", "shutil_get_terminal_size", "=", "getattr", "(", "shutil", ",", ...
Returns the current size of the terminal as tuple in the form ``(width, height)`` in columns and rows.
[ "Returns", "the", "current", "size", "of", "the", "terminal", "as", "tuple", "in", "the", "form", "(", "width", "height", ")", "in", "columns", "and", "rows", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/termui.py#L148-L186
train
mottosso/be
be/vendor/click/termui.py
style
def style(text, fg=None, bg=None, bold=None, dim=None, underline=None, blink=None, reverse=None, reset=True): """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``reset`` (reset the color code only) .. versionadded:: 2.0 :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles. """ bits = [] if fg: try: bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30)) except ValueError: raise TypeError('Unknown color %r' % fg) if bg: try: bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40)) except ValueError: raise TypeError('Unknown color %r' % bg) if bold is not None: bits.append('\033[%dm' % (1 if bold else 22)) if dim is not None: bits.append('\033[%dm' % (2 if dim else 22)) if underline is not None: bits.append('\033[%dm' % (4 if underline else 24)) if blink is not None: bits.append('\033[%dm' % (5 if blink else 25)) if reverse is not None: bits.append('\033[%dm' % (7 if reverse else 27)) bits.append(text) if reset: bits.append(_ansi_reset_all) return ''.join(bits)
python
def style(text, fg=None, bg=None, bold=None, dim=None, underline=None, blink=None, reverse=None, reset=True): """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``reset`` (reset the color code only) .. versionadded:: 2.0 :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles. """ bits = [] if fg: try: bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30)) except ValueError: raise TypeError('Unknown color %r' % fg) if bg: try: bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40)) except ValueError: raise TypeError('Unknown color %r' % bg) if bold is not None: bits.append('\033[%dm' % (1 if bold else 22)) if dim is not None: bits.append('\033[%dm' % (2 if dim else 22)) if underline is not None: bits.append('\033[%dm' % (4 if underline else 24)) if blink is not None: bits.append('\033[%dm' % (5 if blink else 25)) if reverse is not None: bits.append('\033[%dm' % (7 if reverse else 27)) bits.append(text) if reset: bits.append(_ansi_reset_all) return ''.join(bits)
[ "def", "style", "(", "text", ",", "fg", "=", "None", ",", "bg", "=", "None", ",", "bold", "=", "None", ",", "dim", "=", "None", ",", "underline", "=", "None", ",", "blink", "=", "None", ",", "reverse", "=", "None", ",", "reset", "=", "True", ")...
Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) Supported color names: * ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``reset`` (reset the color code only) .. versionadded:: 2.0 :param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.
[ "Styles", "a", "text", "with", "ANSI", "styles", "and", "returns", "the", "new", "string", ".", "By", "default", "the", "styling", "is", "self", "contained", "which", "means", "that", "at", "the", "end", "of", "the", "string", "a", "reset", "code", "is",...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/termui.py#L316-L382
train
mottosso/be
be/vendor/click/termui.py
secho
def secho(text, file=None, nl=True, err=False, color=None, **styles): """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. .. versionadded:: 2.0 """ return echo(style(text, **styles), file=file, nl=nl, err=err, color=color)
python
def secho(text, file=None, nl=True, err=False, color=None, **styles): """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. .. versionadded:: 2.0 """ return echo(style(text, **styles), file=file, nl=nl, err=err, color=color)
[ "def", "secho", "(", "text", ",", "file", "=", "None", ",", "nl", "=", "True", ",", "err", "=", "False", ",", "color", "=", "None", ",", "*", "*", "styles", ")", ":", "return", "echo", "(", "style", "(", "text", ",", "*", "*", "styles", ")", ...
This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on which one they go with. .. versionadded:: 2.0
[ "This", "function", "combines", ":", "func", ":", "echo", "and", ":", "func", ":", "style", "into", "one", "call", ".", "As", "such", "the", "following", "two", "calls", "are", "the", "same", "::" ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/termui.py#L397-L409
train
mottosso/be
be/vendor/requests/sessions.py
merge_setting
def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """ Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. for (k, v) in request_setting.items(): if v is None: del merged_setting[k] merged_setting = dict((k, v) for (k, v) in merged_setting.items() if v is not None) return merged_setting
python
def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """ Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. for (k, v) in request_setting.items(): if v is None: del merged_setting[k] merged_setting = dict((k, v) for (k, v) in merged_setting.items() if v is not None) return merged_setting
[ "def", "merge_setting", "(", "request_setting", ",", "session_setting", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_setting", "is", "None", ":", "return", "request_setting", "if", "request_setting", "is", "None", ":", "return", "session_setting",...
Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class`
[ "Determines", "appropriate", "setting", "for", "a", "given", "request", "taking", "into", "account", "the", "explicit", "setting", "on", "that", "request", "and", "the", "setting", "in", "the", "session", ".", "If", "a", "setting", "is", "a", "dictionary", "...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/sessions.py#L42-L72
train
mottosso/be
be/vendor/requests/sessions.py
SessionRedirectMixin.resolve_redirects
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Receives a Response. Returns a generator of Responses.""" i = 0 hist = [] # keep track of history while resp.is_redirect: prepared_request = req.copy() if i > 0: # Update history and keep track of redirects. hist.append(resp) new_hist = list(hist) resp.history = new_hist try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if i >= self.max_redirects: raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects) # Release the connection back into the pool. resp.close() url = resp.headers['location'] method = req.method # Handle redirection without scheme (see: RFC 1808 Section 4) if url.startswith('//'): parsed_rurl = urlparse(resp.url) url = '%s:%s' % (parsed_rurl.scheme, url) # The scheme should be lower case... parsed = urlparse(url) url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) # Cache the url, unless it redirects to itself. if resp.is_permanent_redirect and req.url != prepared_request.url: self.redirect_cache[req.url] = prepared_request.url # http://tools.ietf.org/html/rfc7231#section-6.4.4 if (resp.status_code == codes.see_other and method != 'HEAD'): method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if resp.status_code == codes.found and method != 'HEAD': method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if resp.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method # https://github.com/kennethreitz/requests/issues/1084 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): if 'Content-Length' in prepared_request.headers: del prepared_request.headers['Content-Length'] prepared_request.body = None headers = prepared_request.headers try: del headers['Cookie'] except KeyError: pass # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # Override the original request. req = prepared_request resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) i += 1 yield resp
python
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Receives a Response. Returns a generator of Responses.""" i = 0 hist = [] # keep track of history while resp.is_redirect: prepared_request = req.copy() if i > 0: # Update history and keep track of redirects. hist.append(resp) new_hist = list(hist) resp.history = new_hist try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if i >= self.max_redirects: raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects) # Release the connection back into the pool. resp.close() url = resp.headers['location'] method = req.method # Handle redirection without scheme (see: RFC 1808 Section 4) if url.startswith('//'): parsed_rurl = urlparse(resp.url) url = '%s:%s' % (parsed_rurl.scheme, url) # The scheme should be lower case... parsed = urlparse(url) url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) # Cache the url, unless it redirects to itself. if resp.is_permanent_redirect and req.url != prepared_request.url: self.redirect_cache[req.url] = prepared_request.url # http://tools.ietf.org/html/rfc7231#section-6.4.4 if (resp.status_code == codes.see_other and method != 'HEAD'): method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if resp.status_code == codes.found and method != 'HEAD': method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if resp.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method # https://github.com/kennethreitz/requests/issues/1084 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): if 'Content-Length' in prepared_request.headers: del prepared_request.headers['Content-Length'] prepared_request.body = None headers = prepared_request.headers try: del headers['Cookie'] except KeyError: pass # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) prepared_request._cookies.update(self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # Override the original request. req = prepared_request resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) i += 1 yield resp
[ "def", "resolve_redirects", "(", "self", ",", "resp", ",", "req", ",", "stream", "=", "False", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ",", "proxies", "=", "None", ")", ":", "i", "=", "0", "hist", "=", "...
Receives a Response. Returns a generator of Responses.
[ "Receives", "a", "Response", ".", "Returns", "a", "generator", "of", "Responses", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/sessions.py#L92-L201
train
mottosso/be
be/vendor/requests/sessions.py
Session.send
def send(self, request, **kwargs): """Send a given PreparedRequest.""" # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if not isinstance(request, PreparedRequest): raise ValueError('You can only send PreparedRequests.') checked_urls = set() while request.url in self.redirect_cache: checked_urls.add(request.url) new_url = self.redirect_cache.get(request.url) if new_url in checked_urls: break request.url = new_url # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') timeout = kwargs.get('timeout') verify = kwargs.get('verify') cert = kwargs.get('cert') proxies = kwargs.get('proxies') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = datetime.utcnow() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) r.elapsed = datetime.utcnow() - start # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Redirect resolving generator. gen = self.resolve_redirects(r, request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies) # Resolve redirects if allowed. history = [resp for resp in gen] if allow_redirects else [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history if not stream: r.content return r
python
def send(self, request, **kwargs): """Send a given PreparedRequest.""" # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if not isinstance(request, PreparedRequest): raise ValueError('You can only send PreparedRequests.') checked_urls = set() while request.url in self.redirect_cache: checked_urls.add(request.url) new_url = self.redirect_cache.get(request.url) if new_url in checked_urls: break request.url = new_url # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') timeout = kwargs.get('timeout') verify = kwargs.get('verify') cert = kwargs.get('cert') proxies = kwargs.get('proxies') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = datetime.utcnow() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) r.elapsed = datetime.utcnow() - start # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Redirect resolving generator. gen = self.resolve_redirects(r, request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies) # Resolve redirects if allowed. history = [resp for resp in gen] if allow_redirects else [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history if not stream: r.content return r
[ "def", "send", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "# Set defaults that the hooks can utilize to ensure they always have", "# the correct parameters to reproduce the previous request.", "kwargs", ".", "setdefault", "(", "'stream'", ",", "self", "...
Send a given PreparedRequest.
[ "Send", "a", "given", "PreparedRequest", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/sessions.py#L538-L615
train
mottosso/be
be/vendor/requests/packages/urllib3/response.py
HTTPResponse.stream
def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data
python
def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data
[ "def", "stream", "(", "self", ",", "amt", "=", "2", "**", "16", ",", "decode_content", "=", "None", ")", ":", "while", "not", "is_fp_closed", "(", "self", ".", "_fp", ")", ":", "data", "=", "self", ".", "read", "(", "amt", "=", "amt", ",", "decod...
A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header.
[ "A", "generator", "wrapper", "for", "the", "read", "()", "method", ".", "A", "call", "will", "block", "until", "amt", "bytes", "have", "been", "read", "from", "the", "connection", "or", "until", "the", "connection", "is", "closed", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/response.py#L256-L276
train
mottosso/be
be/vendor/requests/models.py
PreparedRequest.prepare_method
def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = self.method.upper()
python
def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = self.method.upper()
[ "def", "prepare_method", "(", "self", ",", "method", ")", ":", "self", ".", "method", "=", "method", "if", "self", ".", "method", "is", "not", "None", ":", "self", ".", "method", "=", "self", ".", "method", ".", "upper", "(", ")" ]
Prepares the given HTTP method.
[ "Prepares", "the", "given", "HTTP", "method", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/models.py#L328-L332
train
mottosso/be
be/vendor/requests/models.py
PreparedRequest.prepare_headers
def prepare_headers(self, headers): """Prepares the given HTTP headers.""" if headers: self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) else: self.headers = CaseInsensitiveDict()
python
def prepare_headers(self, headers): """Prepares the given HTTP headers.""" if headers: self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) else: self.headers = CaseInsensitiveDict()
[ "def", "prepare_headers", "(", "self", ",", "headers", ")", ":", "if", "headers", ":", "self", ".", "headers", "=", "CaseInsensitiveDict", "(", "(", "to_native_string", "(", "name", ")", ",", "value", ")", "for", "name", ",", "value", "in", "headers", "....
Prepares the given HTTP headers.
[ "Prepares", "the", "given", "HTTP", "headers", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/models.py#L406-L412
train
mottosso/be
be/vendor/requests/models.py
Response.iter_content
def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): try: # Special case for urllib3. try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) except AttributeError: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks
python
def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): try: # Special case for urllib3. try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) except AttributeError: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks
[ "def", "iter_content", "(", "self", ",", "chunk_size", "=", "1", ",", "decode_unicode", "=", "False", ")", ":", "def", "generate", "(", ")", ":", "try", ":", "# Special case for urllib3.", "try", ":", "for", "chunk", "in", "self", ".", "raw", ".", "strea...
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. If decode_unicode is True, content will be decoded using the best available encoding based on the response.
[ "Iterates", "over", "the", "response", "data", ".", "When", "stream", "=", "True", "is", "set", "on", "the", "request", "this", "avoids", "reading", "the", "content", "at", "once", "into", "memory", "for", "large", "responses", ".", "The", "chunk", "size",...
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/models.py#L642-L686
train
mottosso/be
be/vendor/requests/models.py
Response.json
def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return json.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return json.loads(self.text, **kwargs)
python
def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return json.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return json.loads(self.text, **kwargs)
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should expect", "# UTF-8, -16 or -32. Detect w...
Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
[ "Returns", "the", "json", "-", "encoded", "content", "of", "a", "response", "if", "any", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/models.py#L781-L802
train
mottosso/be
be/vendor/requests/models.py
Response.raise_for_status
def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason) elif 500 <= self.status_code < 600: http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason) if http_error_msg: raise HTTPError(http_error_msg, response=self)
python
def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason) elif 500 <= self.status_code < 600: http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason) if http_error_msg: raise HTTPError(http_error_msg, response=self)
[ "def", "raise_for_status", "(", "self", ")", ":", "http_error_msg", "=", "''", "if", "400", "<=", "self", ".", "status_code", "<", "500", ":", "http_error_msg", "=", "'%s Client Error: %s'", "%", "(", "self", ".", "status_code", ",", "self", ".", "reason", ...
Raises stored :class:`HTTPError`, if one occurred.
[ "Raises", "stored", ":", "class", ":", "HTTPError", "if", "one", "occurred", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/models.py#L822-L834
train
mottosso/be
be/vendor/requests/packages/urllib3/poolmanager.py
PoolManager._new_pool
def _new_pool(self, scheme, host, port): """ Create a new :class:`ConnectionPool` based on host, port and scheme. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = pool_classes_by_scheme[scheme] kwargs = self.connection_pool_kw if scheme == 'http': kwargs = self.connection_pool_kw.copy() for kw in SSL_KEYWORDS: kwargs.pop(kw, None) return pool_cls(host, port, **kwargs)
python
def _new_pool(self, scheme, host, port): """ Create a new :class:`ConnectionPool` based on host, port and scheme. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = pool_classes_by_scheme[scheme] kwargs = self.connection_pool_kw if scheme == 'http': kwargs = self.connection_pool_kw.copy() for kw in SSL_KEYWORDS: kwargs.pop(kw, None) return pool_cls(host, port, **kwargs)
[ "def", "_new_pool", "(", "self", ",", "scheme", ",", "host", ",", "port", ")", ":", "pool_cls", "=", "pool_classes_by_scheme", "[", "scheme", "]", "kwargs", "=", "self", ".", "connection_pool_kw", "if", "scheme", "==", "'http'", ":", "kwargs", "=", "self",...
Create a new :class:`ConnectionPool` based on host, port and scheme. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization.
[ "Create", "a", "new", ":", "class", ":", "ConnectionPool", "based", "on", "host", "port", "and", "scheme", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/poolmanager.py#L75-L90
train
mottosso/be
be/vendor/requests/packages/urllib3/poolmanager.py
PoolManager.connection_from_host
def connection_from_host(self, host, port=None, scheme='http'): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. """ if not host: raise LocationValueError("No host specified.") scheme = scheme or 'http' port = port or port_by_scheme.get(scheme, 80) pool_key = (scheme, host, port) with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type pool = self._new_pool(scheme, host, port) self.pools[pool_key] = pool return pool
python
def connection_from_host(self, host, port=None, scheme='http'): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. """ if not host: raise LocationValueError("No host specified.") scheme = scheme or 'http' port = port or port_by_scheme.get(scheme, 80) pool_key = (scheme, host, port) with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type pool = self._new_pool(scheme, host, port) self.pools[pool_key] = pool return pool
[ "def", "connection_from_host", "(", "self", ",", "host", ",", "port", "=", "None", ",", "scheme", "=", "'http'", ")", ":", "if", "not", "host", ":", "raise", "LocationValueError", "(", "\"No host specified.\"", ")", "scheme", "=", "scheme", "or", "'http'", ...
Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``.
[ "Get", "a", ":", "class", ":", "ConnectionPool", "based", "on", "the", "host", "port", "and", "scheme", "." ]
0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/packages/urllib3/poolmanager.py#L101-L127
train
box/genty
genty/genty_repeat.py
genty_repeat
def genty_repeat(count): """ To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @genty_dataset(True, False) def test_some__other_function(self, bool_value): ... This will run 6 tests in total, 3 each of the True and False cases. :param count: The number of times to run the test. :type count: `int` """ if count < 0: raise ValueError( "Really? Can't have {0} iterations. Please pick a value >= 0." .format(count) ) def wrap(test_method): test_method.genty_repeat_count = count return test_method return wrap
python
def genty_repeat(count): """ To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @genty_dataset(True, False) def test_some__other_function(self, bool_value): ... This will run 6 tests in total, 3 each of the True and False cases. :param count: The number of times to run the test. :type count: `int` """ if count < 0: raise ValueError( "Really? Can't have {0} iterations. Please pick a value >= 0." .format(count) ) def wrap(test_method): test_method.genty_repeat_count = count return test_method return wrap
[ "def", "genty_repeat", "(", "count", ")", ":", "if", "count", "<", "0", ":", "raise", "ValueError", "(", "\"Really? Can't have {0} iterations. Please pick a value >= 0.\"", ".", "format", "(", "count", ")", ")", "def", "wrap", "(", "test_method", ")", ":", "test...
To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @genty_dataset(True, False) def test_some__other_function(self, bool_value): ... This will run 6 tests in total, 3 each of the True and False cases. :param count: The number of times to run the test. :type count: `int`
[ "To", "use", "in", "conjunction", "with", "a", "TestClass", "wrapped", "with", "@genty", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_repeat.py#L6-L36
train
abingham/docopt-subcommands
docopt_subcommands/__init__.py
command
def command(name=None): """A decorator to register a subcommand with the global `Subcommands` instance. """ def decorator(f): _commands.append((name, f)) return f return decorator
python
def command(name=None): """A decorator to register a subcommand with the global `Subcommands` instance. """ def decorator(f): _commands.append((name, f)) return f return decorator
[ "def", "command", "(", "name", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "_commands", ".", "append", "(", "(", "name", ",", "f", ")", ")", "return", "f", "return", "decorator" ]
A decorator to register a subcommand with the global `Subcommands` instance.
[ "A", "decorator", "to", "register", "a", "subcommand", "with", "the", "global", "Subcommands", "instance", "." ]
4b5cd75bb8eed01f9405345446ca58e9a29d67ad
https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/__init__.py#L8-L14
train
abingham/docopt-subcommands
docopt_subcommands/__init__.py
main
def main(program=None, version=None, doc_template=None, commands=None, argv=None, exit_at_end=True): """Top-level driver for creating subcommand-based programs. Args: program: The name of your program. version: The version string for your program. doc_template: The top-level docstring template for your program. If `None`, a standard default version is applied. commands: A `Subcommands` instance. argv: The command-line arguments to parse. If `None`, this defaults to `sys.argv[1:]` exit_at_end: Whether to call `sys.exit()` at the end of the function. There are two ways to use this function. First, you can pass `program`, `version`, and `doc_template`, in which case `docopt_subcommands` will use these arguments along with the subcommands registered with `command()` to define you program. The second way to use this function is to pass in a `Subcommands` objects via the `commands` argument. In this case the `program`, `version`, and `doc_template` arguments are ignored, and the `Subcommands` instance takes precedence. In both cases the `argv` argument can be used to specify the arguments to be parsed. """ if commands is None: if program is None: raise ValueError( '`program` required if subcommand object not provided') if version is None: raise ValueError( '`version` required if subcommand object not provided') commands = Subcommands(program, version, doc_template=doc_template) for name, handler in _commands: commands.add_command(handler, name) if argv is None: argv = sys.argv[1:] result = commands(argv) if exit_at_end: sys.exit(result) else: return result
python
def main(program=None, version=None, doc_template=None, commands=None, argv=None, exit_at_end=True): """Top-level driver for creating subcommand-based programs. Args: program: The name of your program. version: The version string for your program. doc_template: The top-level docstring template for your program. If `None`, a standard default version is applied. commands: A `Subcommands` instance. argv: The command-line arguments to parse. If `None`, this defaults to `sys.argv[1:]` exit_at_end: Whether to call `sys.exit()` at the end of the function. There are two ways to use this function. First, you can pass `program`, `version`, and `doc_template`, in which case `docopt_subcommands` will use these arguments along with the subcommands registered with `command()` to define you program. The second way to use this function is to pass in a `Subcommands` objects via the `commands` argument. In this case the `program`, `version`, and `doc_template` arguments are ignored, and the `Subcommands` instance takes precedence. In both cases the `argv` argument can be used to specify the arguments to be parsed. """ if commands is None: if program is None: raise ValueError( '`program` required if subcommand object not provided') if version is None: raise ValueError( '`version` required if subcommand object not provided') commands = Subcommands(program, version, doc_template=doc_template) for name, handler in _commands: commands.add_command(handler, name) if argv is None: argv = sys.argv[1:] result = commands(argv) if exit_at_end: sys.exit(result) else: return result
[ "def", "main", "(", "program", "=", "None", ",", "version", "=", "None", ",", "doc_template", "=", "None", ",", "commands", "=", "None", ",", "argv", "=", "None", ",", "exit_at_end", "=", "True", ")", ":", "if", "commands", "is", "None", ":", "if", ...
Top-level driver for creating subcommand-based programs. Args: program: The name of your program. version: The version string for your program. doc_template: The top-level docstring template for your program. If `None`, a standard default version is applied. commands: A `Subcommands` instance. argv: The command-line arguments to parse. If `None`, this defaults to `sys.argv[1:]` exit_at_end: Whether to call `sys.exit()` at the end of the function. There are two ways to use this function. First, you can pass `program`, `version`, and `doc_template`, in which case `docopt_subcommands` will use these arguments along with the subcommands registered with `command()` to define you program. The second way to use this function is to pass in a `Subcommands` objects via the `commands` argument. In this case the `program`, `version`, and `doc_template` arguments are ignored, and the `Subcommands` instance takes precedence. In both cases the `argv` argument can be used to specify the arguments to be parsed.
[ "Top", "-", "level", "driver", "for", "creating", "subcommand", "-", "based", "programs", "." ]
4b5cd75bb8eed01f9405345446ca58e9a29d67ad
https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/__init__.py#L17-L69
train
alecxe/scrapy-beautifulsoup
scrapy_beautifulsoup/middleware.py
BeautifulSoupMiddleware.process_response
def process_response(self, request, response, spider): """Overridden process_response would "pipe" response.body through BeautifulSoup.""" return response.replace(body=str(BeautifulSoup(response.body, self.parser)))
python
def process_response(self, request, response, spider): """Overridden process_response would "pipe" response.body through BeautifulSoup.""" return response.replace(body=str(BeautifulSoup(response.body, self.parser)))
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ",", "spider", ")", ":", "return", "response", ".", "replace", "(", "body", "=", "str", "(", "BeautifulSoup", "(", "response", ".", "body", ",", "self", ".", "parser", ")", ")", "...
Overridden process_response would "pipe" response.body through BeautifulSoup.
[ "Overridden", "process_response", "would", "pipe", "response", ".", "body", "through", "BeautifulSoup", "." ]
733f50e83a5b60edc9325e4f14cd4ab2b3914555
https://github.com/alecxe/scrapy-beautifulsoup/blob/733f50e83a5b60edc9325e4f14cd4ab2b3914555/scrapy_beautifulsoup/middleware.py#L14-L16
train
box/genty
genty/genty.py
genty
def genty(target_cls): """ This decorator takes the information provided by @genty_dataset, @genty_dataprovider, and @genty_repeat and generates the corresponding test methods. :param target_cls: Test class whose test methods have been decorated. :type target_cls: `class` """ tests = _expand_tests(target_cls) tests_with_datasets = _expand_datasets(tests) tests_with_datasets_and_repeats = _expand_repeats(tests_with_datasets) _add_new_test_methods(target_cls, tests_with_datasets_and_repeats) return target_cls
python
def genty(target_cls): """ This decorator takes the information provided by @genty_dataset, @genty_dataprovider, and @genty_repeat and generates the corresponding test methods. :param target_cls: Test class whose test methods have been decorated. :type target_cls: `class` """ tests = _expand_tests(target_cls) tests_with_datasets = _expand_datasets(tests) tests_with_datasets_and_repeats = _expand_repeats(tests_with_datasets) _add_new_test_methods(target_cls, tests_with_datasets_and_repeats) return target_cls
[ "def", "genty", "(", "target_cls", ")", ":", "tests", "=", "_expand_tests", "(", "target_cls", ")", "tests_with_datasets", "=", "_expand_datasets", "(", "tests", ")", "tests_with_datasets_and_repeats", "=", "_expand_repeats", "(", "tests_with_datasets", ")", "_add_new...
This decorator takes the information provided by @genty_dataset, @genty_dataprovider, and @genty_repeat and generates the corresponding test methods. :param target_cls: Test class whose test methods have been decorated. :type target_cls: `class`
[ "This", "decorator", "takes", "the", "information", "provided", "by", "@genty_dataset", "@genty_dataprovider", "and", "@genty_repeat", "and", "generates", "the", "corresponding", "test", "methods", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L21-L38
train
box/genty
genty/genty.py
_expand_datasets
def _expand_datasets(test_functions): """ Generator producing test_methods, with an optional dataset. :param test_functions: Iterator over tuples of test name and test unbound function. :type test_functions: `iterator` of `tuple` of (`unicode`, `function`) :return: Generator yielding a tuple of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dataset - dataset : Tuple representing the args for a test - param factory : Function that returns params for the test method :rtype: `generator` of `tuple` of ( `unicode`, `function`, `unicode` or None, `tuple` or None, `function` or None, ) """ for name, func in test_functions: dataset_tuples = chain( [(None, getattr(func, 'genty_datasets', {}))], getattr(func, 'genty_dataproviders', []), ) no_datasets = True for dataprovider, datasets in dataset_tuples: for dataset_name, dataset in six.iteritems(datasets): no_datasets = False yield name, func, dataset_name, dataset, dataprovider if no_datasets: # yield the original test method, unaltered yield name, func, None, None, None
python
def _expand_datasets(test_functions): """ Generator producing test_methods, with an optional dataset. :param test_functions: Iterator over tuples of test name and test unbound function. :type test_functions: `iterator` of `tuple` of (`unicode`, `function`) :return: Generator yielding a tuple of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dataset - dataset : Tuple representing the args for a test - param factory : Function that returns params for the test method :rtype: `generator` of `tuple` of ( `unicode`, `function`, `unicode` or None, `tuple` or None, `function` or None, ) """ for name, func in test_functions: dataset_tuples = chain( [(None, getattr(func, 'genty_datasets', {}))], getattr(func, 'genty_dataproviders', []), ) no_datasets = True for dataprovider, datasets in dataset_tuples: for dataset_name, dataset in six.iteritems(datasets): no_datasets = False yield name, func, dataset_name, dataset, dataprovider if no_datasets: # yield the original test method, unaltered yield name, func, None, None, None
[ "def", "_expand_datasets", "(", "test_functions", ")", ":", "for", "name", ",", "func", "in", "test_functions", ":", "dataset_tuples", "=", "chain", "(", "[", "(", "None", ",", "getattr", "(", "func", ",", "'genty_datasets'", ",", "{", "}", ")", ")", "]"...
Generator producing test_methods, with an optional dataset. :param test_functions: Iterator over tuples of test name and test unbound function. :type test_functions: `iterator` of `tuple` of (`unicode`, `function`) :return: Generator yielding a tuple of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dataset - dataset : Tuple representing the args for a test - param factory : Function that returns params for the test method :rtype: `generator` of `tuple` of ( `unicode`, `function`, `unicode` or None, `tuple` or None, `function` or None, )
[ "Generator", "producing", "test_methods", "with", "an", "optional", "dataset", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L62-L101
train
box/genty
genty/genty.py
_expand_repeats
def _expand_repeats(test_functions): """ Generator producing test_methods, with any repeat count unrolled. :param test_functions: Sequence of tuples of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dataset - dataset : Tuple representing the args for a test - param factory : Function that returns params for the test method :type test_functions: `iterator` of `tuple` of (`unicode`, `function`, `unicode` or None, `tuple` or None, `function`) :return: Generator yielding a tuple of (method_name, unbound function, dataset, name dataset, repeat_suffix) :rtype: `generator` of `tuple` of (`unicode`, `function`, `unicode` or None, `tuple` or None, `function`, `unicode`) """ for name, func, dataset_name, dataset, dataprovider in test_functions: repeat_count = getattr(func, 'genty_repeat_count', 0) if repeat_count: for i in range(1, repeat_count + 1): repeat_suffix = _build_repeat_suffix(i, repeat_count) yield ( name, func, dataset_name, dataset, dataprovider, repeat_suffix, ) else: yield name, func, dataset_name, dataset, dataprovider, None
python
def _expand_repeats(test_functions): """ Generator producing test_methods, with any repeat count unrolled. :param test_functions: Sequence of tuples of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dataset - dataset : Tuple representing the args for a test - param factory : Function that returns params for the test method :type test_functions: `iterator` of `tuple` of (`unicode`, `function`, `unicode` or None, `tuple` or None, `function`) :return: Generator yielding a tuple of (method_name, unbound function, dataset, name dataset, repeat_suffix) :rtype: `generator` of `tuple` of (`unicode`, `function`, `unicode` or None, `tuple` or None, `function`, `unicode`) """ for name, func, dataset_name, dataset, dataprovider in test_functions: repeat_count = getattr(func, 'genty_repeat_count', 0) if repeat_count: for i in range(1, repeat_count + 1): repeat_suffix = _build_repeat_suffix(i, repeat_count) yield ( name, func, dataset_name, dataset, dataprovider, repeat_suffix, ) else: yield name, func, dataset_name, dataset, dataprovider, None
[ "def", "_expand_repeats", "(", "test_functions", ")", ":", "for", "name", ",", "func", ",", "dataset_name", ",", "dataset", ",", "dataprovider", "in", "test_functions", ":", "repeat_count", "=", "getattr", "(", "func", ",", "'genty_repeat_count'", ",", "0", ")...
Generator producing test_methods, with any repeat count unrolled. :param test_functions: Sequence of tuples of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dataset - dataset : Tuple representing the args for a test - param factory : Function that returns params for the test method :type test_functions: `iterator` of `tuple` of (`unicode`, `function`, `unicode` or None, `tuple` or None, `function`) :return: Generator yielding a tuple of (method_name, unbound function, dataset, name dataset, repeat_suffix) :rtype: `generator` of `tuple` of (`unicode`, `function`, `unicode` or None, `tuple` or None, `function`, `unicode`)
[ "Generator", "producing", "test_methods", "with", "any", "repeat", "count", "unrolled", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L104-L139
train
box/genty
genty/genty.py
_is_referenced_in_argv
def _is_referenced_in_argv(method_name): """ Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. :type method_name: `unicode` :return: Is the given method referenced by the command line. :rtype: `bool` """ expr = '.*[:.]{0}$'.format(method_name) regex = re.compile(expr) return any(regex.match(arg) for arg in sys.argv)
python
def _is_referenced_in_argv(method_name): """ Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. :type method_name: `unicode` :return: Is the given method referenced by the command line. :rtype: `bool` """ expr = '.*[:.]{0}$'.format(method_name) regex = re.compile(expr) return any(regex.match(arg) for arg in sys.argv)
[ "def", "_is_referenced_in_argv", "(", "method_name", ")", ":", "expr", "=", "'.*[:.]{0}$'", ".", "format", "(", "method_name", ")", "regex", "=", "re", ".", "compile", "(", "expr", ")", "return", "any", "(", "regex", ".", "match", "(", "arg", ")", "for",...
Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. :type method_name: `unicode` :return: Is the given method referenced by the command line. :rtype: `bool`
[ "Various", "test", "runners", "allow", "one", "to", "run", "a", "specific", "test", "like", "so", ":", "python", "-", "m", "unittest", "-", "v", "<test_module", ">", ".", "<test_name", ">" ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L193-L211
train
box/genty
genty/genty.py
_build_repeat_suffix
def _build_repeat_suffix(iteration, count): """ Return the suffix string to identify iteration X out of Y. For example, with a count of 100, this will build strings like "iteration_053" or "iteration_008". :param iteration: Current iteration. :type iteration: `int` :param count: Total number of iterations. :type count: `int` :return: Repeat suffix. :rtype: `unicode` """ format_width = int(math.ceil(math.log(count + 1, 10))) new_suffix = 'iteration_{0:0{width}d}'.format( iteration, width=format_width ) return new_suffix
python
def _build_repeat_suffix(iteration, count): """ Return the suffix string to identify iteration X out of Y. For example, with a count of 100, this will build strings like "iteration_053" or "iteration_008". :param iteration: Current iteration. :type iteration: `int` :param count: Total number of iterations. :type count: `int` :return: Repeat suffix. :rtype: `unicode` """ format_width = int(math.ceil(math.log(count + 1, 10))) new_suffix = 'iteration_{0:0{width}d}'.format( iteration, width=format_width ) return new_suffix
[ "def", "_build_repeat_suffix", "(", "iteration", ",", "count", ")", ":", "format_width", "=", "int", "(", "math", ".", "ceil", "(", "math", ".", "log", "(", "count", "+", "1", ",", "10", ")", ")", ")", "new_suffix", "=", "'iteration_{0:0{width}d}'", ".",...
Return the suffix string to identify iteration X out of Y. For example, with a count of 100, this will build strings like "iteration_053" or "iteration_008". :param iteration: Current iteration. :type iteration: `int` :param count: Total number of iterations. :type count: `int` :return: Repeat suffix. :rtype: `unicode`
[ "Return", "the", "suffix", "string", "to", "identify", "iteration", "X", "out", "of", "Y", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L214-L239
train
box/genty
genty/genty.py
_build_final_method_name
def _build_final_method_name( method_name, dataset_name, dataprovider_name, repeat_suffix, ): """ Return a nice human friendly name, that almost looks like code. Example: a test called 'test_something' with a dataset of (5, 'hello') Return: "test_something(5, 'hello')" Example: a test called 'test_other_stuff' with dataset of (9) and repeats Return: "test_other_stuff(9) iteration_<X>" :param method_name: Base name of the method to add. :type method_name: `unicode` :param dataset_name: Base name of the data set. :type dataset_name: `unicode` or None :param dataprovider_name: If there's a dataprovider involved, then this is its name. :type dataprovider_name: `unicode` or None :param repeat_suffix: Suffix to append to the name of the generated method. :type repeat_suffix: `unicode` or None :return: The fully composed name of the generated test method. :rtype: `unicode` """ # For tests using a dataprovider, append "_<dataprovider_name>" to # the test method name suffix = '' if dataprovider_name: suffix = '_{0}'.format(dataprovider_name) if not dataset_name and not repeat_suffix: return '{0}{1}'.format(method_name, suffix) if dataset_name: # Nosetest multi-processing code parses the full test name # to discern package/module names. Thus any periods in the test-name # causes that code to fail. So replace any periods with the unicode # middle-dot character. Yes, this change is applied independent # of the test runner being used... and that's fine since there is # no real contract as to how the fabricated tests are named. dataset_name = dataset_name.replace('.', REPLACE_FOR_PERIOD_CHAR) # Place data_set info inside parens, as if it were a function call suffix = '{0}({1})'.format(suffix, dataset_name or "") if repeat_suffix: suffix = '{0} {1}'.format(suffix, repeat_suffix) test_method_name_for_dataset = "{0}{1}".format( method_name, suffix, ) return test_method_name_for_dataset
python
def _build_final_method_name( method_name, dataset_name, dataprovider_name, repeat_suffix, ): """ Return a nice human friendly name, that almost looks like code. Example: a test called 'test_something' with a dataset of (5, 'hello') Return: "test_something(5, 'hello')" Example: a test called 'test_other_stuff' with dataset of (9) and repeats Return: "test_other_stuff(9) iteration_<X>" :param method_name: Base name of the method to add. :type method_name: `unicode` :param dataset_name: Base name of the data set. :type dataset_name: `unicode` or None :param dataprovider_name: If there's a dataprovider involved, then this is its name. :type dataprovider_name: `unicode` or None :param repeat_suffix: Suffix to append to the name of the generated method. :type repeat_suffix: `unicode` or None :return: The fully composed name of the generated test method. :rtype: `unicode` """ # For tests using a dataprovider, append "_<dataprovider_name>" to # the test method name suffix = '' if dataprovider_name: suffix = '_{0}'.format(dataprovider_name) if not dataset_name and not repeat_suffix: return '{0}{1}'.format(method_name, suffix) if dataset_name: # Nosetest multi-processing code parses the full test name # to discern package/module names. Thus any periods in the test-name # causes that code to fail. So replace any periods with the unicode # middle-dot character. Yes, this change is applied independent # of the test runner being used... and that's fine since there is # no real contract as to how the fabricated tests are named. dataset_name = dataset_name.replace('.', REPLACE_FOR_PERIOD_CHAR) # Place data_set info inside parens, as if it were a function call suffix = '{0}({1})'.format(suffix, dataset_name or "") if repeat_suffix: suffix = '{0} {1}'.format(suffix, repeat_suffix) test_method_name_for_dataset = "{0}{1}".format( method_name, suffix, ) return test_method_name_for_dataset
[ "def", "_build_final_method_name", "(", "method_name", ",", "dataset_name", ",", "dataprovider_name", ",", "repeat_suffix", ",", ")", ":", "# For tests using a dataprovider, append \"_<dataprovider_name>\" to", "# the test method name", "suffix", "=", "''", "if", "dataprovider...
Return a nice human friendly name, that almost looks like code. Example: a test called 'test_something' with a dataset of (5, 'hello') Return: "test_something(5, 'hello')" Example: a test called 'test_other_stuff' with dataset of (9) and repeats Return: "test_other_stuff(9) iteration_<X>" :param method_name: Base name of the method to add. :type method_name: `unicode` :param dataset_name: Base name of the data set. :type dataset_name: `unicode` or None :param dataprovider_name: If there's a dataprovider involved, then this is its name. :type dataprovider_name: `unicode` or None :param repeat_suffix: Suffix to append to the name of the generated method. :type repeat_suffix: `unicode` or None :return: The fully composed name of the generated test method. :rtype: `unicode`
[ "Return", "a", "nice", "human", "friendly", "name", "that", "almost", "looks", "like", "code", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L270-L335
train
box/genty
genty/genty.py
_build_dataset_method
def _build_dataset_method(method, dataset): """ Return a fabricated method that marshals the dataset into parameters for given 'method' :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of the dataset. :type dataset: `tuple` or :class:`GentyArgs` :return: Return an unbound function that will become a test method :rtype: `function` """ if isinstance(dataset, GentyArgs): test_method = lambda my_self: method( my_self, *dataset.args, **dataset.kwargs ) else: test_method = lambda my_self: method( my_self, *dataset ) return test_method
python
def _build_dataset_method(method, dataset): """ Return a fabricated method that marshals the dataset into parameters for given 'method' :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of the dataset. :type dataset: `tuple` or :class:`GentyArgs` :return: Return an unbound function that will become a test method :rtype: `function` """ if isinstance(dataset, GentyArgs): test_method = lambda my_self: method( my_self, *dataset.args, **dataset.kwargs ) else: test_method = lambda my_self: method( my_self, *dataset ) return test_method
[ "def", "_build_dataset_method", "(", "method", ",", "dataset", ")", ":", "if", "isinstance", "(", "dataset", ",", "GentyArgs", ")", ":", "test_method", "=", "lambda", "my_self", ":", "method", "(", "my_self", ",", "*", "dataset", ".", "args", ",", "*", "...
Return a fabricated method that marshals the dataset into parameters for given 'method' :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of the dataset. :type dataset: `tuple` or :class:`GentyArgs` :return: Return an unbound function that will become a test method :rtype: `function`
[ "Return", "a", "fabricated", "method", "that", "marshals", "the", "dataset", "into", "parameters", "for", "given", "method", ":", "param", "method", ":", "The", "underlying", "test", "method", ".", ":", "type", "method", ":", "callable", ":", "param", "datas...
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L338-L366
train
box/genty
genty/genty.py
_build_dataprovider_method
def _build_dataprovider_method(method, dataset, dataprovider): """ Return a fabricated method that calls the dataprovider with the given dataset, and marshals the return value from that into params to the underlying test 'method'. :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of the dataset. :type dataset: `tuple` or :class:`GentyArgs` :param dataprovider: The unbound function that's responsible for generating the actual params that will be passed to the test function. :type dataprovider: `callable` :return: Return an unbound function that will become a test method :rtype: `function` """ if isinstance(dataset, GentyArgs): final_args = dataset.args final_kwargs = dataset.kwargs else: final_args = dataset final_kwargs = {} def test_method_wrapper(my_self): args = dataprovider( my_self, *final_args, **final_kwargs ) kwargs = {} if isinstance(args, GentyArgs): kwargs = args.kwargs args = args.args elif not isinstance(args, (tuple, list)): args = (args, ) return method(my_self, *args, **kwargs) return test_method_wrapper
python
def _build_dataprovider_method(method, dataset, dataprovider): """ Return a fabricated method that calls the dataprovider with the given dataset, and marshals the return value from that into params to the underlying test 'method'. :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of the dataset. :type dataset: `tuple` or :class:`GentyArgs` :param dataprovider: The unbound function that's responsible for generating the actual params that will be passed to the test function. :type dataprovider: `callable` :return: Return an unbound function that will become a test method :rtype: `function` """ if isinstance(dataset, GentyArgs): final_args = dataset.args final_kwargs = dataset.kwargs else: final_args = dataset final_kwargs = {} def test_method_wrapper(my_self): args = dataprovider( my_self, *final_args, **final_kwargs ) kwargs = {} if isinstance(args, GentyArgs): kwargs = args.kwargs args = args.args elif not isinstance(args, (tuple, list)): args = (args, ) return method(my_self, *args, **kwargs) return test_method_wrapper
[ "def", "_build_dataprovider_method", "(", "method", ",", "dataset", ",", "dataprovider", ")", ":", "if", "isinstance", "(", "dataset", ",", "GentyArgs", ")", ":", "final_args", "=", "dataset", ".", "args", "final_kwargs", "=", "dataset", ".", "kwargs", "else",...
Return a fabricated method that calls the dataprovider with the given dataset, and marshals the return value from that into params to the underlying test 'method'. :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of the dataset. :type dataset: `tuple` or :class:`GentyArgs` :param dataprovider: The unbound function that's responsible for generating the actual params that will be passed to the test function. :type dataprovider: `callable` :return: Return an unbound function that will become a test method :rtype: `function`
[ "Return", "a", "fabricated", "method", "that", "calls", "the", "dataprovider", "with", "the", "given", "dataset", "and", "marshals", "the", "return", "value", "from", "that", "into", "params", "to", "the", "underlying", "test", "method", ".", ":", "param", "...
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L369-L416
train
box/genty
genty/genty.py
_add_method_to_class
def _add_method_to_class( target_cls, method_name, func, dataset_name, dataset, dataprovider, repeat_suffix, ): """ Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: `class` :param method_name: Base name of the method to add. :type method_name: `unicode` :param func: The underlying test function to call. :type func: `callable` :param dataset_name: Base name of the data set. :type dataset_name: `unicode` or None :param dataset: Tuple containing the args of the dataset. :type dataset: `tuple` or None :param repeat_suffix: Suffix to append to the name of the generated method. :type repeat_suffix: `unicode` or None :param dataprovider: The unbound function that's responsible for generating the actual params that will be passed to the test function. Can be None. :type dataprovider: `callable` """ # pylint: disable=too-many-arguments test_method_name_for_dataset = _build_final_method_name( method_name, dataset_name, dataprovider.__name__ if dataprovider else None, repeat_suffix, ) test_method_for_dataset = _build_test_method(func, dataset, dataprovider) test_method_for_dataset = functools.update_wrapper( test_method_for_dataset, func, ) test_method_name_for_dataset = encode_non_ascii_string( test_method_name_for_dataset, ) test_method_for_dataset.__name__ = test_method_name_for_dataset test_method_for_dataset.genty_generated_test = True # Add the method to the class under the proper name setattr(target_cls, test_method_name_for_dataset, test_method_for_dataset)
python
def _add_method_to_class( target_cls, method_name, func, dataset_name, dataset, dataprovider, repeat_suffix, ): """ Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: `class` :param method_name: Base name of the method to add. :type method_name: `unicode` :param func: The underlying test function to call. :type func: `callable` :param dataset_name: Base name of the data set. :type dataset_name: `unicode` or None :param dataset: Tuple containing the args of the dataset. :type dataset: `tuple` or None :param repeat_suffix: Suffix to append to the name of the generated method. :type repeat_suffix: `unicode` or None :param dataprovider: The unbound function that's responsible for generating the actual params that will be passed to the test function. Can be None. :type dataprovider: `callable` """ # pylint: disable=too-many-arguments test_method_name_for_dataset = _build_final_method_name( method_name, dataset_name, dataprovider.__name__ if dataprovider else None, repeat_suffix, ) test_method_for_dataset = _build_test_method(func, dataset, dataprovider) test_method_for_dataset = functools.update_wrapper( test_method_for_dataset, func, ) test_method_name_for_dataset = encode_non_ascii_string( test_method_name_for_dataset, ) test_method_for_dataset.__name__ = test_method_name_for_dataset test_method_for_dataset.genty_generated_test = True # Add the method to the class under the proper name setattr(target_cls, test_method_name_for_dataset, test_method_for_dataset)
[ "def", "_add_method_to_class", "(", "target_cls", ",", "method_name", ",", "func", ",", "dataset_name", ",", "dataset", ",", "dataprovider", ",", "repeat_suffix", ",", ")", ":", "# pylint: disable=too-many-arguments", "test_method_name_for_dataset", "=", "_build_final_met...
Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: `class` :param method_name: Base name of the method to add. :type method_name: `unicode` :param func: The underlying test function to call. :type func: `callable` :param dataset_name: Base name of the data set. :type dataset_name: `unicode` or None :param dataset: Tuple containing the args of the dataset. :type dataset: `tuple` or None :param repeat_suffix: Suffix to append to the name of the generated method. :type repeat_suffix: `unicode` or None :param dataprovider: The unbound function that's responsible for generating the actual params that will be passed to the test function. Can be None. :type dataprovider: `callable`
[ "Add", "the", "described", "method", "to", "the", "given", "class", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L450-L514
train
bcbnz/python-rofi
rofi.py
Rofi.close
def close(self): """Close any open window. Note that this only works with non-blocking methods. """ if self._process: # Be nice first. self._process.send_signal(signal.SIGINT) # If it doesn't close itself promptly, be brutal. # Python 3.2+ added the timeout option to wait() and the # corresponding TimeoutExpired exception. If they exist, use them. if hasattr(subprocess, 'TimeoutExpired'): try: self._process.wait(timeout=1) except subprocess.TimeoutExpired: self._process.send_signal(signal.SIGKILL) # Otherwise, roll our own polling loop. else: # Give it 1s, checking every 10ms. count = 0 while count < 100: if self._process.poll() is not None: break time.sleep(0.01) # Still hasn't quit. if self._process.poll() is None: self._process.send_signal(signal.SIGKILL) # Clean up. self._process = None
python
def close(self): """Close any open window. Note that this only works with non-blocking methods. """ if self._process: # Be nice first. self._process.send_signal(signal.SIGINT) # If it doesn't close itself promptly, be brutal. # Python 3.2+ added the timeout option to wait() and the # corresponding TimeoutExpired exception. If they exist, use them. if hasattr(subprocess, 'TimeoutExpired'): try: self._process.wait(timeout=1) except subprocess.TimeoutExpired: self._process.send_signal(signal.SIGKILL) # Otherwise, roll our own polling loop. else: # Give it 1s, checking every 10ms. count = 0 while count < 100: if self._process.poll() is not None: break time.sleep(0.01) # Still hasn't quit. if self._process.poll() is None: self._process.send_signal(signal.SIGKILL) # Clean up. self._process = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_process", ":", "# Be nice first.", "self", ".", "_process", ".", "send_signal", "(", "signal", ".", "SIGINT", ")", "# If it doesn't close itself promptly, be brutal.", "# Python 3.2+ added the timeout option to...
Close any open window. Note that this only works with non-blocking methods.
[ "Close", "any", "open", "window", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L157-L190
train
bcbnz/python-rofi
rofi.py
Rofi._run_blocking
def _run_blocking(self, args, input=None): """Internal API: run a blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process. Returns ------- (returncode, stdout) The exit code (integer) and stdout value (string) from the process. """ # Close any existing dialog. if self._process: self.close() # Make sure we grab stdout as text (not bytes). kwargs = {} kwargs['stdout'] = subprocess.PIPE kwargs['universal_newlines'] = True # Use the run() method if available (Python 3.5+). if hasattr(subprocess, 'run'): result = subprocess.run(args, input=input, **kwargs) return result.returncode, result.stdout # Have to do our own. If we need to feed stdin, we must open a pipe. if input is not None: kwargs['stdin'] = subprocess.PIPE # Start the process. with Popen(args, **kwargs) as proc: # Talk to it (no timeout). This will wait until termination. stdout, stderr = proc.communicate(input) # Find out the return code. returncode = proc.poll() # Done. return returncode, stdout
python
def _run_blocking(self, args, input=None): """Internal API: run a blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process. Returns ------- (returncode, stdout) The exit code (integer) and stdout value (string) from the process. """ # Close any existing dialog. if self._process: self.close() # Make sure we grab stdout as text (not bytes). kwargs = {} kwargs['stdout'] = subprocess.PIPE kwargs['universal_newlines'] = True # Use the run() method if available (Python 3.5+). if hasattr(subprocess, 'run'): result = subprocess.run(args, input=input, **kwargs) return result.returncode, result.stdout # Have to do our own. If we need to feed stdin, we must open a pipe. if input is not None: kwargs['stdin'] = subprocess.PIPE # Start the process. with Popen(args, **kwargs) as proc: # Talk to it (no timeout). This will wait until termination. stdout, stderr = proc.communicate(input) # Find out the return code. returncode = proc.poll() # Done. return returncode, stdout
[ "def", "_run_blocking", "(", "self", ",", "args", ",", "input", "=", "None", ")", ":", "# Close any existing dialog.", "if", "self", ".", "_process", ":", "self", ".", "close", "(", ")", "# Make sure we grab stdout as text (not bytes).", "kwargs", "=", "{", "}",...
Internal API: run a blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process. Returns ------- (returncode, stdout) The exit code (integer) and stdout value (string) from the process.
[ "Internal", "API", ":", "run", "a", "blocking", "command", "with", "subprocess", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L193-L238
train
bcbnz/python-rofi
rofi.py
Rofi._run_nonblocking
def _run_nonblocking(self, args, input=None): """Internal API: run a non-blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process. """ # Close any existing dialog. if self._process: self.close() # Start the new one. self._process = subprocess.Popen(args, stdout=subprocess.PIPE)
python
def _run_nonblocking(self, args, input=None): """Internal API: run a non-blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process. """ # Close any existing dialog. if self._process: self.close() # Start the new one. self._process = subprocess.Popen(args, stdout=subprocess.PIPE)
[ "def", "_run_nonblocking", "(", "self", ",", "args", ",", "input", "=", "None", ")", ":", "# Close any existing dialog.", "if", "self", ".", "_process", ":", "self", ".", "close", "(", ")", "# Start the new one.", "self", ".", "_process", "=", "subprocess", ...
Internal API: run a non-blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process.
[ "Internal", "API", ":", "run", "a", "non", "-", "blocking", "command", "with", "subprocess", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L241-L259
train
bcbnz/python-rofi
rofi.py
Rofi.error
def error(self, message, rofi_args=None, **kwargs): """Show an error window. This method blocks until the user presses a key. Fullscreen mode is not supported for error windows, and if specified will be ignored. Parameters ---------- message: string Error message to show. """ rofi_args = rofi_args or [] # Generate arguments list. args = ['rofi', '-e', message] args.extend(self._common_args(allow_fullscreen=False, **kwargs)) args.extend(rofi_args) # Close any existing window and show the error. self._run_blocking(args)
python
def error(self, message, rofi_args=None, **kwargs): """Show an error window. This method blocks until the user presses a key. Fullscreen mode is not supported for error windows, and if specified will be ignored. Parameters ---------- message: string Error message to show. """ rofi_args = rofi_args or [] # Generate arguments list. args = ['rofi', '-e', message] args.extend(self._common_args(allow_fullscreen=False, **kwargs)) args.extend(rofi_args) # Close any existing window and show the error. self._run_blocking(args)
[ "def", "error", "(", "self", ",", "message", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "rofi_args", "=", "rofi_args", "or", "[", "]", "# Generate arguments list.", "args", "=", "[", "'rofi'", ",", "'-e'", ",", "message", "]", "a...
Show an error window. This method blocks until the user presses a key. Fullscreen mode is not supported for error windows, and if specified will be ignored. Parameters ---------- message: string Error message to show.
[ "Show", "an", "error", "window", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L295-L316
train
bcbnz/python-rofi
rofi.py
Rofi.status
def status(self, message, rofi_args=None, **kwargs): """Show a status message. This method is non-blocking, and intended to give a status update to the user while something is happening in the background. To close the window, either call the close() method or use any of the display methods to replace it with a different window. Fullscreen mode is not supported for status messages and if specified will be ignored. Parameters ---------- message: string Progress message to show. """ rofi_args = rofi_args or [] # Generate arguments list. args = ['rofi', '-e', message] args.extend(self._common_args(allow_fullscreen=False, **kwargs)) args.extend(rofi_args) # Update the status. self._run_nonblocking(args)
python
def status(self, message, rofi_args=None, **kwargs): """Show a status message. This method is non-blocking, and intended to give a status update to the user while something is happening in the background. To close the window, either call the close() method or use any of the display methods to replace it with a different window. Fullscreen mode is not supported for status messages and if specified will be ignored. Parameters ---------- message: string Progress message to show. """ rofi_args = rofi_args or [] # Generate arguments list. args = ['rofi', '-e', message] args.extend(self._common_args(allow_fullscreen=False, **kwargs)) args.extend(rofi_args) # Update the status. self._run_nonblocking(args)
[ "def", "status", "(", "self", ",", "message", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "rofi_args", "=", "rofi_args", "or", "[", "]", "# Generate arguments list.", "args", "=", "[", "'rofi'", ",", "'-e'", ",", "message", "]", "...
Show a status message. This method is non-blocking, and intended to give a status update to the user while something is happening in the background. To close the window, either call the close() method or use any of the display methods to replace it with a different window. Fullscreen mode is not supported for status messages and if specified will be ignored. Parameters ---------- message: string Progress message to show.
[ "Show", "a", "status", "message", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L319-L344
train
bcbnz/python-rofi
rofi.py
Rofi.select
def select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs): """Show a list of options and return user selection. This method blocks until the user makes their choice. Parameters ---------- prompt: string The prompt telling the user what they are selecting. options: list of strings The options they can choose from. Any newline characters are replaced with spaces. message: string, optional Message to show between the prompt and the options. This can contain Pango markup, and any text content should be escaped. select: integer, optional Set which option is initially selected. keyN: tuple (string, string); optional Custom key bindings where N is one or greater. The first entry in the tuple should be a string defining the key, e.g., "Alt+x" or "Delete". Note that letter keys should be lowercase ie.e., Alt+a not Alt+A. The second entry should be a short string stating the action the key will take. This is displayed to the user at the top of the dialog. If None or an empty string, it is not displayed (but the binding is still set). By default, key1 through key9 are set to ("Alt+1", None) through ("Alt+9", None) respectively. Returns ------- tuple (index, key) The index of the option the user selected, or -1 if they cancelled the dialog. Key indicates which key was pressed, with 0 being 'OK' (generally Enter), -1 being 'Cancel' (generally escape), and N being custom key N. """ rofi_args = rofi_args or [] # Replace newlines and turn the options into a single string. optionstr = '\n'.join(option.replace('\n', ' ') for option in options) # Set up arguments. args = ['rofi', '-dmenu', '-p', prompt, '-format', 'i'] if select is not None: args.extend(['-selected-row', str(select)]) # Key bindings to display. display_bindings = [] # Configure the key bindings. user_keys = set() for k, v in kwargs.items(): # See if the keyword name matches the needed format. if not k.startswith('key'): continue try: keynum = int(k[3:]) except ValueError: continue # Add it to the set. key, action = v user_keys.add(keynum) args.extend(['-kb-custom-{0:s}'.format(k[3:]), key]) if action: display_bindings.append("<b>{0:s}</b>: {1:s}".format(key, action)) # And the global exit bindings. exit_keys = set() next_key = 10 for key in self.exit_hotkeys: while next_key in user_keys: next_key += 1 exit_keys.add(next_key) args.extend(['-kb-custom-{0:d}'.format(next_key), key]) next_key += 1 # Add any displayed key bindings to the message. message = message or "" if display_bindings: message += "\n" + " ".join(display_bindings) message = message.strip() # If we have a message, add it to the arguments. if message: args.extend(['-mesg', message]) # Add in common arguments. args.extend(self._common_args(**kwargs)) args.extend(rofi_args) # Run the dialog. returncode, stdout = self._run_blocking(args, input=optionstr) # Figure out which option was selected. stdout = stdout.strip() index = int(stdout) if stdout else -1 # And map the return code to a key. if returncode == 0: key = 0 elif returncode == 1: key = -1 elif returncode > 9: key = returncode - 9 if key in exit_keys: raise SystemExit() else: self.exit_with_error("Unexpected rofi returncode {0:d}.".format(results.returncode)) # And return. return index, key
python
def select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs): """Show a list of options and return user selection. This method blocks until the user makes their choice. Parameters ---------- prompt: string The prompt telling the user what they are selecting. options: list of strings The options they can choose from. Any newline characters are replaced with spaces. message: string, optional Message to show between the prompt and the options. This can contain Pango markup, and any text content should be escaped. select: integer, optional Set which option is initially selected. keyN: tuple (string, string); optional Custom key bindings where N is one or greater. The first entry in the tuple should be a string defining the key, e.g., "Alt+x" or "Delete". Note that letter keys should be lowercase ie.e., Alt+a not Alt+A. The second entry should be a short string stating the action the key will take. This is displayed to the user at the top of the dialog. If None or an empty string, it is not displayed (but the binding is still set). By default, key1 through key9 are set to ("Alt+1", None) through ("Alt+9", None) respectively. Returns ------- tuple (index, key) The index of the option the user selected, or -1 if they cancelled the dialog. Key indicates which key was pressed, with 0 being 'OK' (generally Enter), -1 being 'Cancel' (generally escape), and N being custom key N. """ rofi_args = rofi_args or [] # Replace newlines and turn the options into a single string. optionstr = '\n'.join(option.replace('\n', ' ') for option in options) # Set up arguments. args = ['rofi', '-dmenu', '-p', prompt, '-format', 'i'] if select is not None: args.extend(['-selected-row', str(select)]) # Key bindings to display. display_bindings = [] # Configure the key bindings. user_keys = set() for k, v in kwargs.items(): # See if the keyword name matches the needed format. if not k.startswith('key'): continue try: keynum = int(k[3:]) except ValueError: continue # Add it to the set. key, action = v user_keys.add(keynum) args.extend(['-kb-custom-{0:s}'.format(k[3:]), key]) if action: display_bindings.append("<b>{0:s}</b>: {1:s}".format(key, action)) # And the global exit bindings. exit_keys = set() next_key = 10 for key in self.exit_hotkeys: while next_key in user_keys: next_key += 1 exit_keys.add(next_key) args.extend(['-kb-custom-{0:d}'.format(next_key), key]) next_key += 1 # Add any displayed key bindings to the message. message = message or "" if display_bindings: message += "\n" + " ".join(display_bindings) message = message.strip() # If we have a message, add it to the arguments. if message: args.extend(['-mesg', message]) # Add in common arguments. args.extend(self._common_args(**kwargs)) args.extend(rofi_args) # Run the dialog. returncode, stdout = self._run_blocking(args, input=optionstr) # Figure out which option was selected. stdout = stdout.strip() index = int(stdout) if stdout else -1 # And map the return code to a key. if returncode == 0: key = 0 elif returncode == 1: key = -1 elif returncode > 9: key = returncode - 9 if key in exit_keys: raise SystemExit() else: self.exit_with_error("Unexpected rofi returncode {0:d}.".format(results.returncode)) # And return. return index, key
[ "def", "select", "(", "self", ",", "prompt", ",", "options", ",", "rofi_args", "=", "None", ",", "message", "=", "\"\"", ",", "select", "=", "None", ",", "*", "*", "kwargs", ")", ":", "rofi_args", "=", "rofi_args", "or", "[", "]", "# Replace newlines a...
Show a list of options and return user selection. This method blocks until the user makes their choice. Parameters ---------- prompt: string The prompt telling the user what they are selecting. options: list of strings The options they can choose from. Any newline characters are replaced with spaces. message: string, optional Message to show between the prompt and the options. This can contain Pango markup, and any text content should be escaped. select: integer, optional Set which option is initially selected. keyN: tuple (string, string); optional Custom key bindings where N is one or greater. The first entry in the tuple should be a string defining the key, e.g., "Alt+x" or "Delete". Note that letter keys should be lowercase ie.e., Alt+a not Alt+A. The second entry should be a short string stating the action the key will take. This is displayed to the user at the top of the dialog. If None or an empty string, it is not displayed (but the binding is still set). By default, key1 through key9 are set to ("Alt+1", None) through ("Alt+9", None) respectively. Returns ------- tuple (index, key) The index of the option the user selected, or -1 if they cancelled the dialog. Key indicates which key was pressed, with 0 being 'OK' (generally Enter), -1 being 'Cancel' (generally escape), and N being custom key N.
[ "Show", "a", "list", "of", "options", "and", "return", "user", "selection", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L347-L462
train
bcbnz/python-rofi
rofi.py
Rofi.generic_entry
def generic_entry(self, prompt, validator=None, message=None, rofi_args=None, **kwargs): """A generic entry box. Parameters ---------- prompt: string Text prompt for the entry. validator: function, optional A function to validate and convert the value entered by the user. It should take one parameter, the string that the user entered, and return a tuple (value, error). The value should be the users entry converted to the appropriate Python type, or None if the entry was invalid. The error message should be a string telling the user what was wrong, or None if the entry was valid. The prompt will be re-displayed to the user (along with the error message) until they enter a valid value. If no validator is given, the text that the user entered is returned as-is. message: string Optional message to display under the entry. Returns ------- The value returned by the validator, or None if the dialog was cancelled. Examples -------- Enforce a minimum entry length: >>> r = Rofi() >>> validator = lambda s: (s, None) if len(s) > 6 else (None, "Too short") >>> r.generic_entry('Enter a 7-character or longer string: ', validator) """ error = "" rofi_args = rofi_args or [] # Keep going until we get something valid. while True: args = ['rofi', '-dmenu', '-p', prompt, '-format', 's'] # Add any error to the given message. msg = message or "" if error: msg = '<span color="#FF0000" font_weight="bold">{0:s}</span>\n{1:s}'.format(error, msg) msg = msg.rstrip('\n') # If there is actually a message to show. if msg: args.extend(['-mesg', msg]) # Add in common arguments. args.extend(self._common_args(**kwargs)) args.extend(rofi_args) # Run it. returncode, stdout = self._run_blocking(args, input="") # Was the dialog cancelled? if returncode == 1: return None # Get rid of the trailing newline and check its validity. text = stdout.rstrip('\n') if validator: value, error = validator(text) if not error: return value else: return text
python
def generic_entry(self, prompt, validator=None, message=None, rofi_args=None, **kwargs): """A generic entry box. Parameters ---------- prompt: string Text prompt for the entry. validator: function, optional A function to validate and convert the value entered by the user. It should take one parameter, the string that the user entered, and return a tuple (value, error). The value should be the users entry converted to the appropriate Python type, or None if the entry was invalid. The error message should be a string telling the user what was wrong, or None if the entry was valid. The prompt will be re-displayed to the user (along with the error message) until they enter a valid value. If no validator is given, the text that the user entered is returned as-is. message: string Optional message to display under the entry. Returns ------- The value returned by the validator, or None if the dialog was cancelled. Examples -------- Enforce a minimum entry length: >>> r = Rofi() >>> validator = lambda s: (s, None) if len(s) > 6 else (None, "Too short") >>> r.generic_entry('Enter a 7-character or longer string: ', validator) """ error = "" rofi_args = rofi_args or [] # Keep going until we get something valid. while True: args = ['rofi', '-dmenu', '-p', prompt, '-format', 's'] # Add any error to the given message. msg = message or "" if error: msg = '<span color="#FF0000" font_weight="bold">{0:s}</span>\n{1:s}'.format(error, msg) msg = msg.rstrip('\n') # If there is actually a message to show. if msg: args.extend(['-mesg', msg]) # Add in common arguments. args.extend(self._common_args(**kwargs)) args.extend(rofi_args) # Run it. returncode, stdout = self._run_blocking(args, input="") # Was the dialog cancelled? if returncode == 1: return None # Get rid of the trailing newline and check its validity. text = stdout.rstrip('\n') if validator: value, error = validator(text) if not error: return value else: return text
[ "def", "generic_entry", "(", "self", ",", "prompt", ",", "validator", "=", "None", ",", "message", "=", "None", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "error", "=", "\"\"", "rofi_args", "=", "rofi_args", "or", "[", "]", "# ...
A generic entry box. Parameters ---------- prompt: string Text prompt for the entry. validator: function, optional A function to validate and convert the value entered by the user. It should take one parameter, the string that the user entered, and return a tuple (value, error). The value should be the users entry converted to the appropriate Python type, or None if the entry was invalid. The error message should be a string telling the user what was wrong, or None if the entry was valid. The prompt will be re-displayed to the user (along with the error message) until they enter a valid value. If no validator is given, the text that the user entered is returned as-is. message: string Optional message to display under the entry. Returns ------- The value returned by the validator, or None if the dialog was cancelled. Examples -------- Enforce a minimum entry length: >>> r = Rofi() >>> validator = lambda s: (s, None) if len(s) > 6 else (None, "Too short") >>> r.generic_entry('Enter a 7-character or longer string: ', validator)
[ "A", "generic", "entry", "box", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L465-L533
train
bcbnz/python-rofi
rofi.py
Rofi.text_entry
def text_entry(self, prompt, message=None, allow_blank=False, strip=True, rofi_args=None, **kwargs): """Prompt the user to enter a piece of text. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. allow_blank: Boolean Whether to allow blank entries. strip: Boolean Whether to strip leading and trailing whitespace from the entered value. Returns ------- string, or None if the dialog was cancelled. """ def text_validator(text): if strip: text = text.strip() if not allow_blank: if not text: return None, "A value is required." return text, None return self.generic_entry(prompt, text_validator, message, rofi_args, **kwargs)
python
def text_entry(self, prompt, message=None, allow_blank=False, strip=True, rofi_args=None, **kwargs): """Prompt the user to enter a piece of text. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. allow_blank: Boolean Whether to allow blank entries. strip: Boolean Whether to strip leading and trailing whitespace from the entered value. Returns ------- string, or None if the dialog was cancelled. """ def text_validator(text): if strip: text = text.strip() if not allow_blank: if not text: return None, "A value is required." return text, None return self.generic_entry(prompt, text_validator, message, rofi_args, **kwargs)
[ "def", "text_entry", "(", "self", ",", "prompt", ",", "message", "=", "None", ",", "allow_blank", "=", "False", ",", "strip", "=", "True", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "text_validator", "(", "text", ")", ":...
Prompt the user to enter a piece of text. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. allow_blank: Boolean Whether to allow blank entries. strip: Boolean Whether to strip leading and trailing whitespace from the entered value. Returns ------- string, or None if the dialog was cancelled.
[ "Prompt", "the", "user", "to", "enter", "a", "piece", "of", "text", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L536-L566
train
bcbnz/python-rofi
rofi.py
Rofi.integer_entry
def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter an integer. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: integer, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- integer, or None if the dialog is cancelled. """ # Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def integer_validator(text): error = None # Attempt to convert to integer. try: value = int(text) except ValueError: return None, "Please enter an integer value." # Check its within limits. if (min is not None) and (value < min): return None, "The minimum allowable value is {0:d}.".format(min) if (max is not None) and (value > max): return None, "The maximum allowable value is {0:d}.".format(max) return value, None return self.generic_entry(prompt, integer_validator, message, rofi_args, **kwargs)
python
def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter an integer. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: integer, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- integer, or None if the dialog is cancelled. """ # Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def integer_validator(text): error = None # Attempt to convert to integer. try: value = int(text) except ValueError: return None, "Please enter an integer value." # Check its within limits. if (min is not None) and (value < min): return None, "The minimum allowable value is {0:d}.".format(min) if (max is not None) and (value > max): return None, "The maximum allowable value is {0:d}.".format(max) return value, None return self.generic_entry(prompt, integer_validator, message, rofi_args, **kwargs)
[ "def", "integer_entry", "(", "self", ",", "prompt", ",", "message", "=", "None", ",", "min", "=", "None", ",", "max", "=", "None", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Sanity check.", "if", "(", "min", "is", "not", "...
Prompt the user to enter an integer. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: integer, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- integer, or None if the dialog is cancelled.
[ "Prompt", "the", "user", "to", "enter", "an", "integer", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L569-L607
train
bcbnz/python-rofi
rofi.py
Rofi.float_entry
def float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a floating point number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: float, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- float, or None if the dialog is cancelled. """ # Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def float_validator(text): error = None # Attempt to convert to float. try: value = float(text) except ValueError: return None, "Please enter a floating point value." # Check its within limits. if (min is not None) and (value < min): return None, "The minimum allowable value is {0}.".format(min) if (max is not None) and (value > max): return None, "The maximum allowable value is {0}.".format(max) return value, None return self.generic_entry(prompt, float_validator, message, rofi_args, **kwargs)
python
def float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a floating point number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: float, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- float, or None if the dialog is cancelled. """ # Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def float_validator(text): error = None # Attempt to convert to float. try: value = float(text) except ValueError: return None, "Please enter a floating point value." # Check its within limits. if (min is not None) and (value < min): return None, "The minimum allowable value is {0}.".format(min) if (max is not None) and (value > max): return None, "The maximum allowable value is {0}.".format(max) return value, None return self.generic_entry(prompt, float_validator, message, rofi_args, **kwargs)
[ "def", "float_entry", "(", "self", ",", "prompt", ",", "message", "=", "None", ",", "min", "=", "None", ",", "max", "=", "None", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Sanity check.", "if", "(", "min", "is", "not", "No...
Prompt the user to enter a floating point number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: float, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- float, or None if the dialog is cancelled.
[ "Prompt", "the", "user", "to", "enter", "a", "floating", "point", "number", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L610-L648
train
bcbnz/python-rofi
rofi.py
Rofi.decimal_entry
def decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a decimal number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: Decimal, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- Decimal, or None if the dialog is cancelled. """ # Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def decimal_validator(text): error = None # Attempt to convert to decimal. try: value = Decimal(text) except InvalidOperation: return None, "Please enter a decimal value." # Check its within limits. if (min is not None) and (value < min): return None, "The minimum allowable value is {0}.".format(min) if (max is not None) and (value > max): return None, "The maximum allowable value is {0}.".format(max) return value, None return self.generic_entry(prompt, decimal_validator, message, rofi_args, **kwargs)
python
def decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a decimal number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: Decimal, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- Decimal, or None if the dialog is cancelled. """ # Sanity check. if (min is not None) and (max is not None) and not (max > min): raise ValueError("Maximum limit has to be more than the minimum limit.") def decimal_validator(text): error = None # Attempt to convert to decimal. try: value = Decimal(text) except InvalidOperation: return None, "Please enter a decimal value." # Check its within limits. if (min is not None) and (value < min): return None, "The minimum allowable value is {0}.".format(min) if (max is not None) and (value > max): return None, "The maximum allowable value is {0}.".format(max) return value, None return self.generic_entry(prompt, decimal_validator, message, rofi_args, **kwargs)
[ "def", "decimal_entry", "(", "self", ",", "prompt", ",", "message", "=", "None", ",", "min", "=", "None", ",", "max", "=", "None", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Sanity check.", "if", "(", "min", "is", "not", "...
Prompt the user to enter a decimal number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: Decimal, optional Minimum and maximum values to allow. If None, no limit is imposed. Returns ------- Decimal, or None if the dialog is cancelled.
[ "Prompt", "the", "user", "to", "enter", "a", "decimal", "number", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L651-L689
train
bcbnz/python-rofi
rofi.py
Rofi.date_entry
def date_entry(self, prompt, message=None, formats=['%x', '%d/%m/%Y'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter dates in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a date object without error is selected. Note that the '%x' in the default list is the current locale's date representation. show_example: Boolean If True, today's date in the first format given is appended to the message. Returns ------- datetime.date, or None if the dialog is cancelled. """ def date_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough for us. return (dt.date(), None) # None of the formats worked. return (None, 'Please enter a valid date.') # Add an example to the message? if show_example: message = message or "" message += "Today's date in the correct format: " + datetime.now().strftime(formats[0]) return self.generic_entry(prompt, date_validator, message, rofi_args, **kwargs)
python
def date_entry(self, prompt, message=None, formats=['%x', '%d/%m/%Y'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter dates in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a date object without error is selected. Note that the '%x' in the default list is the current locale's date representation. show_example: Boolean If True, today's date in the first format given is appended to the message. Returns ------- datetime.date, or None if the dialog is cancelled. """ def date_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough for us. return (dt.date(), None) # None of the formats worked. return (None, 'Please enter a valid date.') # Add an example to the message? if show_example: message = message or "" message += "Today's date in the correct format: " + datetime.now().strftime(formats[0]) return self.generic_entry(prompt, date_validator, message, rofi_args, **kwargs)
[ "def", "date_entry", "(", "self", ",", "prompt", ",", "message", "=", "None", ",", "formats", "=", "[", "'%x'", ",", "'%d/%m/%Y'", "]", ",", "show_example", "=", "False", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "date_...
Prompt the user to enter a date. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter dates in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a date object without error is selected. Note that the '%x' in the default list is the current locale's date representation. show_example: Boolean If True, today's date in the first format given is appended to the message. Returns ------- datetime.date, or None if the dialog is cancelled.
[ "Prompt", "the", "user", "to", "enter", "a", "date", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L692-L737
train
bcbnz/python-rofi
rofi.py
Rofi.time_entry
def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M', '%I.%M'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter times in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a time object without error is selected. Note that the '%X' in the default list is the current locale's time representation. show_example: Boolean If True, the current time in the first format given is appended to the message. Returns ------- datetime.time, or None if the dialog is cancelled. """ def time_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough for us. return (dt.time(), None) # None of the formats worked. return (None, 'Please enter a valid time.') # Add an example to the message? if show_example: message = message or "" message += "Current time in the correct format: " + datetime.now().strftime(formats[0]) return self.generic_entry(prompt, time_validator, message, rofi_args=None, **kwargs)
python
def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M', '%I.%M'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter times in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a time object without error is selected. Note that the '%X' in the default list is the current locale's time representation. show_example: Boolean If True, the current time in the first format given is appended to the message. Returns ------- datetime.time, or None if the dialog is cancelled. """ def time_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough for us. return (dt.time(), None) # None of the formats worked. return (None, 'Please enter a valid time.') # Add an example to the message? if show_example: message = message or "" message += "Current time in the correct format: " + datetime.now().strftime(formats[0]) return self.generic_entry(prompt, time_validator, message, rofi_args=None, **kwargs)
[ "def", "time_entry", "(", "self", ",", "prompt", ",", "message", "=", "None", ",", "formats", "=", "[", "'%X'", ",", "'%H:%M'", ",", "'%I:%M'", ",", "'%H.%M'", ",", "'%I.%M'", "]", ",", "show_example", "=", "False", ",", "rofi_args", "=", "None", ",", ...
Prompt the user to enter a time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter times in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a time object without error is selected. Note that the '%X' in the default list is the current locale's time representation. show_example: Boolean If True, the current time in the first format given is appended to the message. Returns ------- datetime.time, or None if the dialog is cancelled.
[ "Prompt", "the", "user", "to", "enter", "a", "time", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L740-L785
train
bcbnz/python-rofi
rofi.py
Rofi.datetime_entry
def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date and time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter the date and time in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a datetime object without error is selected. Note that the '%x %X' in the default list is the current locale's date and time representation. show_example: Boolean If True, the current date and time in the first format given is appended to the message. Returns ------- datetime.datetime, or None if the dialog is cancelled. """ def datetime_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough for us. return (dt, None) # None of the formats worked. return (None, 'Please enter a valid date and time.') # Add an example to the message? if show_example: message = message or "" message += "Current date and time in the correct format: " + datetime.now().strftime(formats[0]) return self.generic_entry(prompt, datetime_validator, message, rofi_args, **kwargs)
python
def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date and time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter the date and time in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a datetime object without error is selected. Note that the '%x %X' in the default list is the current locale's date and time representation. show_example: Boolean If True, the current date and time in the first format given is appended to the message. Returns ------- datetime.datetime, or None if the dialog is cancelled. """ def datetime_validator(text): # Try them in order. for format in formats: try: dt = datetime.strptime(text, format) except ValueError: continue else: # This one worked; good enough for us. return (dt, None) # None of the formats worked. return (None, 'Please enter a valid date and time.') # Add an example to the message? if show_example: message = message or "" message += "Current date and time in the correct format: " + datetime.now().strftime(formats[0]) return self.generic_entry(prompt, datetime_validator, message, rofi_args, **kwargs)
[ "def", "datetime_entry", "(", "self", ",", "prompt", ",", "message", "=", "None", ",", "formats", "=", "[", "'%x %X'", "]", ",", "show_example", "=", "False", ",", "rofi_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "datetime_validator", ...
Prompt the user to enter a date and time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter the date and time in. These should be format strings as accepted by the datetime.datetime.strptime() function from the standard library. They are tried in order, and the first that returns a datetime object without error is selected. Note that the '%x %X' in the default list is the current locale's date and time representation. show_example: Boolean If True, the current date and time in the first format given is appended to the message. Returns ------- datetime.datetime, or None if the dialog is cancelled.
[ "Prompt", "the", "user", "to", "enter", "a", "date", "and", "time", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L788-L833
train
bcbnz/python-rofi
rofi.py
Rofi.exit_with_error
def exit_with_error(self, error, **kwargs): """Report an error and exit. This raises a SystemExit exception to ask the interpreter to quit. Parameters ---------- error: string The error to report before quitting. """ self.error(error, **kwargs) raise SystemExit(error)
python
def exit_with_error(self, error, **kwargs): """Report an error and exit. This raises a SystemExit exception to ask the interpreter to quit. Parameters ---------- error: string The error to report before quitting. """ self.error(error, **kwargs) raise SystemExit(error)
[ "def", "exit_with_error", "(", "self", ",", "error", ",", "*", "*", "kwargs", ")", ":", "self", ".", "error", "(", "error", ",", "*", "*", "kwargs", ")", "raise", "SystemExit", "(", "error", ")" ]
Report an error and exit. This raises a SystemExit exception to ask the interpreter to quit. Parameters ---------- error: string The error to report before quitting.
[ "Report", "an", "error", "and", "exit", "." ]
d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4
https://github.com/bcbnz/python-rofi/blob/d20b3a2ba4ba1b294b002f25a8fb526c5115d0d4/rofi.py#L836-L848
train
box/genty
genty/private/__init__.py
format_kwarg
def format_kwarg(key, value): """ Return a string of form: "key=<value>" If 'value' is a string, we want it quoted. The goal is to make the string a named parameter in a method call. """ translator = repr if isinstance(value, six.string_types) else six.text_type arg_value = translator(value) return '{0}={1}'.format(key, arg_value)
python
def format_kwarg(key, value): """ Return a string of form: "key=<value>" If 'value' is a string, we want it quoted. The goal is to make the string a named parameter in a method call. """ translator = repr if isinstance(value, six.string_types) else six.text_type arg_value = translator(value) return '{0}={1}'.format(key, arg_value)
[ "def", "format_kwarg", "(", "key", ",", "value", ")", ":", "translator", "=", "repr", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "else", "six", ".", "text_type", "arg_value", "=", "translator", "(", "value", ")", "return", "'...
Return a string of form: "key=<value>" If 'value' is a string, we want it quoted. The goal is to make the string a named parameter in a method call.
[ "Return", "a", "string", "of", "form", ":", "key", "=", "<value", ">" ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/private/__init__.py#L7-L17
train
box/genty
genty/private/__init__.py
format_arg
def format_arg(value): """ :param value: Some value in a dataset. :type value: varies :return: unicode representation of that value :rtype: `unicode` """ translator = repr if isinstance(value, six.string_types) else six.text_type return translator(value)
python
def format_arg(value): """ :param value: Some value in a dataset. :type value: varies :return: unicode representation of that value :rtype: `unicode` """ translator = repr if isinstance(value, six.string_types) else six.text_type return translator(value)
[ "def", "format_arg", "(", "value", ")", ":", "translator", "=", "repr", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", "else", "six", ".", "text_type", "return", "translator", "(", "value", ")" ]
:param value: Some value in a dataset. :type value: varies :return: unicode representation of that value :rtype: `unicode`
[ ":", "param", "value", ":", "Some", "value", "in", "a", "dataset", ".", ":", "type", "value", ":", "varies", ":", "return", ":", "unicode", "representation", "of", "that", "value", ":", "rtype", ":", "unicode" ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/private/__init__.py#L20-L32
train
box/genty
genty/private/__init__.py
encode_non_ascii_string
def encode_non_ascii_string(string): """ :param string: The string to be encoded :type string: unicode or str :return: The encoded string :rtype: str """ encoded_string = string.encode('utf-8', 'replace') if six.PY3: encoded_string = encoded_string.decode() return encoded_string
python
def encode_non_ascii_string(string): """ :param string: The string to be encoded :type string: unicode or str :return: The encoded string :rtype: str """ encoded_string = string.encode('utf-8', 'replace') if six.PY3: encoded_string = encoded_string.decode() return encoded_string
[ "def", "encode_non_ascii_string", "(", "string", ")", ":", "encoded_string", "=", "string", ".", "encode", "(", "'utf-8'", ",", "'replace'", ")", "if", "six", ".", "PY3", ":", "encoded_string", "=", "encoded_string", ".", "decode", "(", ")", "return", "encod...
:param string: The string to be encoded :type string: unicode or str :return: The encoded string :rtype: str
[ ":", "param", "string", ":", "The", "string", "to", "be", "encoded", ":", "type", "string", ":", "unicode", "or", "str", ":", "return", ":", "The", "encoded", "string", ":", "rtype", ":", "str" ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/private/__init__.py#L35-L50
train
box/genty
genty/genty_dataset.py
genty_dataprovider
def genty_dataprovider(builder_function): """Decorator defining that this test gets parameters from the given build_function. :param builder_function: A callable that returns parameters that will be passed to the method decorated by this decorator. If the builder_function returns a tuple or list, then that will be passed as *args to the decorated method. If the builder_function returns a :class:`GentyArgs`, then that will be used to pass *args and **kwargs to the decorated method. Any other return value will be treated as a single parameter, and passed as such to the decorated method. :type builder_function: `callable` """ datasets = getattr(builder_function, 'genty_datasets', {None: ()}) def wrap(test_method): # Save the data providers in the test method. This data will be # consumed by the @genty decorator. if not hasattr(test_method, 'genty_dataproviders'): test_method.genty_dataproviders = [] test_method.genty_dataproviders.append( (builder_function, datasets), ) return test_method return wrap
python
def genty_dataprovider(builder_function): """Decorator defining that this test gets parameters from the given build_function. :param builder_function: A callable that returns parameters that will be passed to the method decorated by this decorator. If the builder_function returns a tuple or list, then that will be passed as *args to the decorated method. If the builder_function returns a :class:`GentyArgs`, then that will be used to pass *args and **kwargs to the decorated method. Any other return value will be treated as a single parameter, and passed as such to the decorated method. :type builder_function: `callable` """ datasets = getattr(builder_function, 'genty_datasets', {None: ()}) def wrap(test_method): # Save the data providers in the test method. This data will be # consumed by the @genty decorator. if not hasattr(test_method, 'genty_dataproviders'): test_method.genty_dataproviders = [] test_method.genty_dataproviders.append( (builder_function, datasets), ) return test_method return wrap
[ "def", "genty_dataprovider", "(", "builder_function", ")", ":", "datasets", "=", "getattr", "(", "builder_function", ",", "'genty_datasets'", ",", "{", "None", ":", "(", ")", "}", ")", "def", "wrap", "(", "test_method", ")", ":", "# Save the data providers in th...
Decorator defining that this test gets parameters from the given build_function. :param builder_function: A callable that returns parameters that will be passed to the method decorated by this decorator. If the builder_function returns a tuple or list, then that will be passed as *args to the decorated method. If the builder_function returns a :class:`GentyArgs`, then that will be used to pass *args and **kwargs to the decorated method. Any other return value will be treated as a single parameter, and passed as such to the decorated method. :type builder_function: `callable`
[ "Decorator", "defining", "that", "this", "test", "gets", "parameters", "from", "the", "given", "build_function", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L15-L47
train
box/genty
genty/genty_dataset.py
genty_dataset
def genty_dataset(*args, **kwargs): """Decorator defining data sets to provide to a test. Inspired by http://sebastian-bergmann.de/archives/ 702-Data-Providers-in-PHPUnit-3.2.html The canonical way to call @genty_dataset, with each argument each representing a data set to be injected in the test method call: @genty_dataset( ('a1', 'b1'), ('a2', 'b2'), ) def test_some_function(a, b) ... If the test function takes only one parameter, you can replace the tuples by a single value. So instead of the more verbose: @genty_dataset( ('c1',), ('c2',), ) def test_some_other_function(c) ... One can write: @genty_dataset('c1', 'c2') def test_some_other_function(c) ... For each set of arguments, a suffix identifying that argument set is built by concatenating the string representation of the arguments together. You can control the test names for each data set by passing the data sets as keyword args, where the keyword is the desired suffix. For example: @genty_dataset( ('a1', 'b1), ) def test_function(a, b) ... produces a test named 'test_function_for_a1_and_b1', while @genty_dataset( happy_path=('a1', 'b1'), ) def test_function(a, b) ... produces a test named test_function_for_happy_path. These are just parameters to a method call, so one can have unnamed args first followed by keyword args @genty_dataset( ('x', 'y'), ('p', 'q'), Monday=('a1', 'b1'), Tuesday=('t1', 't2'), ) def test_function(a, b) ... Finally, datasets can be chained. Useful for example if there are distinct sets of params that make sense (cleaner, more readable, or semantically nicer) if kept separate. A fabricated example: @genty_dataset( *([i for i in range(10)] + [(i, i) for i in range(10)]) ) def test_some_other_function(param1, param2=None) ... -- vs -- @genty_dataset(*[i for i in range(10)]) @genty_dataset(*[(i, i) for i in range(10)]) def test_some_other_function(param1, param2=None) ... If the names of datasets conflict across chained genty_datasets, the key&value pair from the outer (first) decorator will override the data from the inner. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies """ datasets = _build_datasets(*args, **kwargs) def wrap(test_method): # Save the datasets in the test method. This data will be consumed # by the @genty decorator. if not hasattr(test_method, 'genty_datasets'): test_method.genty_datasets = OrderedDict() test_method.genty_datasets.update(datasets) return test_method return wrap
python
def genty_dataset(*args, **kwargs): """Decorator defining data sets to provide to a test. Inspired by http://sebastian-bergmann.de/archives/ 702-Data-Providers-in-PHPUnit-3.2.html The canonical way to call @genty_dataset, with each argument each representing a data set to be injected in the test method call: @genty_dataset( ('a1', 'b1'), ('a2', 'b2'), ) def test_some_function(a, b) ... If the test function takes only one parameter, you can replace the tuples by a single value. So instead of the more verbose: @genty_dataset( ('c1',), ('c2',), ) def test_some_other_function(c) ... One can write: @genty_dataset('c1', 'c2') def test_some_other_function(c) ... For each set of arguments, a suffix identifying that argument set is built by concatenating the string representation of the arguments together. You can control the test names for each data set by passing the data sets as keyword args, where the keyword is the desired suffix. For example: @genty_dataset( ('a1', 'b1), ) def test_function(a, b) ... produces a test named 'test_function_for_a1_and_b1', while @genty_dataset( happy_path=('a1', 'b1'), ) def test_function(a, b) ... produces a test named test_function_for_happy_path. These are just parameters to a method call, so one can have unnamed args first followed by keyword args @genty_dataset( ('x', 'y'), ('p', 'q'), Monday=('a1', 'b1'), Tuesday=('t1', 't2'), ) def test_function(a, b) ... Finally, datasets can be chained. Useful for example if there are distinct sets of params that make sense (cleaner, more readable, or semantically nicer) if kept separate. A fabricated example: @genty_dataset( *([i for i in range(10)] + [(i, i) for i in range(10)]) ) def test_some_other_function(param1, param2=None) ... -- vs -- @genty_dataset(*[i for i in range(10)]) @genty_dataset(*[(i, i) for i in range(10)]) def test_some_other_function(param1, param2=None) ... If the names of datasets conflict across chained genty_datasets, the key&value pair from the outer (first) decorator will override the data from the inner. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies """ datasets = _build_datasets(*args, **kwargs) def wrap(test_method): # Save the datasets in the test method. This data will be consumed # by the @genty decorator. if not hasattr(test_method, 'genty_datasets'): test_method.genty_datasets = OrderedDict() test_method.genty_datasets.update(datasets) return test_method return wrap
[ "def", "genty_dataset", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "datasets", "=", "_build_datasets", "(", "*", "args", ",", "*", "*", "kwargs", ")", "def", "wrap", "(", "test_method", ")", ":", "# Save the datasets in the test method. This data wil...
Decorator defining data sets to provide to a test. Inspired by http://sebastian-bergmann.de/archives/ 702-Data-Providers-in-PHPUnit-3.2.html The canonical way to call @genty_dataset, with each argument each representing a data set to be injected in the test method call: @genty_dataset( ('a1', 'b1'), ('a2', 'b2'), ) def test_some_function(a, b) ... If the test function takes only one parameter, you can replace the tuples by a single value. So instead of the more verbose: @genty_dataset( ('c1',), ('c2',), ) def test_some_other_function(c) ... One can write: @genty_dataset('c1', 'c2') def test_some_other_function(c) ... For each set of arguments, a suffix identifying that argument set is built by concatenating the string representation of the arguments together. You can control the test names for each data set by passing the data sets as keyword args, where the keyword is the desired suffix. For example: @genty_dataset( ('a1', 'b1), ) def test_function(a, b) ... produces a test named 'test_function_for_a1_and_b1', while @genty_dataset( happy_path=('a1', 'b1'), ) def test_function(a, b) ... produces a test named test_function_for_happy_path. These are just parameters to a method call, so one can have unnamed args first followed by keyword args @genty_dataset( ('x', 'y'), ('p', 'q'), Monday=('a1', 'b1'), Tuesday=('t1', 't2'), ) def test_function(a, b) ... Finally, datasets can be chained. Useful for example if there are distinct sets of params that make sense (cleaner, more readable, or semantically nicer) if kept separate. A fabricated example: @genty_dataset( *([i for i in range(10)] + [(i, i) for i in range(10)]) ) def test_some_other_function(param1, param2=None) ... -- vs -- @genty_dataset(*[i for i in range(10)]) @genty_dataset(*[(i, i) for i in range(10)]) def test_some_other_function(param1, param2=None) ... If the names of datasets conflict across chained genty_datasets, the key&value pair from the outer (first) decorator will override the data from the inner. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies
[ "Decorator", "defining", "data", "sets", "to", "provide", "to", "a", "test", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L50-L148
train
box/genty
genty/genty_dataset.py
_build_datasets
def _build_datasets(*args, **kwargs): """Build the datasets into a dict, where the keys are the name of the data set and the values are the data sets themselves. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies :return: The dataset dict. :rtype: `dict` """ datasets = OrderedDict() _add_arg_datasets(datasets, args) _add_kwarg_datasets(datasets, kwargs) return datasets
python
def _build_datasets(*args, **kwargs): """Build the datasets into a dict, where the keys are the name of the data set and the values are the data sets themselves. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies :return: The dataset dict. :rtype: `dict` """ datasets = OrderedDict() _add_arg_datasets(datasets, args) _add_kwarg_datasets(datasets, kwargs) return datasets
[ "def", "_build_datasets", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "datasets", "=", "OrderedDict", "(", ")", "_add_arg_datasets", "(", "datasets", ",", "args", ")", "_add_kwarg_datasets", "(", "datasets", ",", "kwargs", ")", "return", "datasets" ...
Build the datasets into a dict, where the keys are the name of the data set and the values are the data sets themselves. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies :return: The dataset dict. :rtype: `dict`
[ "Build", "the", "datasets", "into", "a", "dict", "where", "the", "keys", "are", "the", "name", "of", "the", "data", "set", "and", "the", "values", "are", "the", "data", "sets", "themselves", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L151-L171
train
box/genty
genty/genty_dataset.py
_add_arg_datasets
def _add_arg_datasets(datasets, args): """Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param args: Tuple of unnamed data sets. :type args: `tuple` of varies """ for dataset in args: # turn a value into a 1-tuple. if not isinstance(dataset, (tuple, GentyArgs)): dataset = (dataset,) # Create a test_name_suffix - basically the parameter list if isinstance(dataset, GentyArgs): dataset_strings = dataset # GentyArgs supports iteration else: dataset_strings = [format_arg(data) for data in dataset] test_method_suffix = ", ".join(dataset_strings) datasets[test_method_suffix] = dataset
python
def _add_arg_datasets(datasets, args): """Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param args: Tuple of unnamed data sets. :type args: `tuple` of varies """ for dataset in args: # turn a value into a 1-tuple. if not isinstance(dataset, (tuple, GentyArgs)): dataset = (dataset,) # Create a test_name_suffix - basically the parameter list if isinstance(dataset, GentyArgs): dataset_strings = dataset # GentyArgs supports iteration else: dataset_strings = [format_arg(data) for data in dataset] test_method_suffix = ", ".join(dataset_strings) datasets[test_method_suffix] = dataset
[ "def", "_add_arg_datasets", "(", "datasets", ",", "args", ")", ":", "for", "dataset", "in", "args", ":", "# turn a value into a 1-tuple.", "if", "not", "isinstance", "(", "dataset", ",", "(", "tuple", ",", "GentyArgs", ")", ")", ":", "dataset", "=", "(", "...
Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param args: Tuple of unnamed data sets. :type args: `tuple` of varies
[ "Add", "data", "sets", "of", "the", "given", "args", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L174-L198
train
box/genty
genty/genty_dataset.py
_add_kwarg_datasets
def _add_kwarg_datasets(datasets, kwargs): """Add data sets of the given kwargs. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies """ for test_method_suffix, dataset in six.iteritems(kwargs): datasets[test_method_suffix] = dataset
python
def _add_kwarg_datasets(datasets, kwargs): """Add data sets of the given kwargs. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies """ for test_method_suffix, dataset in six.iteritems(kwargs): datasets[test_method_suffix] = dataset
[ "def", "_add_kwarg_datasets", "(", "datasets", ",", "kwargs", ")", ":", "for", "test_method_suffix", ",", "dataset", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "datasets", "[", "test_method_suffix", "]", "=", "dataset" ]
Add data sets of the given kwargs. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies
[ "Add", "data", "sets", "of", "the", "given", "kwargs", "." ]
85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_dataset.py#L201-L214
train
abingham/docopt-subcommands
docopt_subcommands/subcommands.py
dedent
def dedent(s): """Removes the hanging dedent from all the first line of a string.""" head, _, tail = s.partition('\n') dedented_tail = textwrap.dedent(tail) result = "{head}\n{tail}".format( head=head, tail=dedented_tail) return result
python
def dedent(s): """Removes the hanging dedent from all the first line of a string.""" head, _, tail = s.partition('\n') dedented_tail = textwrap.dedent(tail) result = "{head}\n{tail}".format( head=head, tail=dedented_tail) return result
[ "def", "dedent", "(", "s", ")", ":", "head", ",", "_", ",", "tail", "=", "s", ".", "partition", "(", "'\\n'", ")", "dedented_tail", "=", "textwrap", ".", "dedent", "(", "tail", ")", "result", "=", "\"{head}\\n{tail}\"", ".", "format", "(", "head", "=...
Removes the hanging dedent from all the first line of a string.
[ "Removes", "the", "hanging", "dedent", "from", "all", "the", "first", "line", "of", "a", "string", "." ]
4b5cd75bb8eed01f9405345446ca58e9a29d67ad
https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/subcommands.py#L20-L27
train
abingham/docopt-subcommands
docopt_subcommands/subcommands.py
Subcommands.top_level_doc
def top_level_doc(self): """The top-level documentation string for the program. """ return self._doc_template.format( available_commands='\n '.join(sorted(self._commands)), program=self.program)
python
def top_level_doc(self): """The top-level documentation string for the program. """ return self._doc_template.format( available_commands='\n '.join(sorted(self._commands)), program=self.program)
[ "def", "top_level_doc", "(", "self", ")", ":", "return", "self", ".", "_doc_template", ".", "format", "(", "available_commands", "=", "'\\n '", ".", "join", "(", "sorted", "(", "self", ".", "_commands", ")", ")", ",", "program", "=", "self", ".", "progr...
The top-level documentation string for the program.
[ "The", "top", "-", "level", "documentation", "string", "for", "the", "program", "." ]
4b5cd75bb8eed01f9405345446ca58e9a29d67ad
https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/subcommands.py#L83-L88
train
abingham/docopt-subcommands
docopt_subcommands/subcommands.py
Subcommands.command
def command(self, name=None): """A decorator to add subcommands. """ def decorator(f): self.add_command(f, name) return f return decorator
python
def command(self, name=None): """A decorator to add subcommands. """ def decorator(f): self.add_command(f, name) return f return decorator
[ "def", "command", "(", "self", ",", "name", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "add_command", "(", "f", ",", "name", ")", "return", "f", "return", "decorator" ]
A decorator to add subcommands.
[ "A", "decorator", "to", "add", "subcommands", "." ]
4b5cd75bb8eed01f9405345446ca58e9a29d67ad
https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/subcommands.py#L90-L96
train
abingham/docopt-subcommands
docopt_subcommands/subcommands.py
Subcommands.add_command
def add_command(self, handler, name=None): """Add a subcommand `name` which invokes `handler`. """ if name is None: name = docstring_to_subcommand(handler.__doc__) # TODO: Prevent overwriting 'help'? self._commands[name] = handler
python
def add_command(self, handler, name=None): """Add a subcommand `name` which invokes `handler`. """ if name is None: name = docstring_to_subcommand(handler.__doc__) # TODO: Prevent overwriting 'help'? self._commands[name] = handler
[ "def", "add_command", "(", "self", ",", "handler", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "docstring_to_subcommand", "(", "handler", ".", "__doc__", ")", "# TODO: Prevent overwriting 'help'?", "self", ".", "_commands"...
Add a subcommand `name` which invokes `handler`.
[ "Add", "a", "subcommand", "name", "which", "invokes", "handler", "." ]
4b5cd75bb8eed01f9405345446ca58e9a29d67ad
https://github.com/abingham/docopt-subcommands/blob/4b5cd75bb8eed01f9405345446ca58e9a29d67ad/docopt_subcommands/subcommands.py#L98-L105
train
elektito/finglish
finglish/f2p.py
variations
def variations(word): """Create variations of the word based on letter combinations like oo, sh, etc.""" if len(word) == 1: return [[word[0]]] elif word == 'aa': return [['A']] elif word == 'ee': return [['i']] elif word == 'ei': return [['ei']] elif word in ['oo', 'ou']: return [['u']] elif word == 'kha': return [['kha'], ['kh', 'a']] elif word in ['kh', 'gh', 'ch', 'sh', 'zh', 'ck']: return [[word]] elif word in ["'ee", "'ei"]: return [["'i"]] elif word in ["'oo", "'ou"]: return [["'u"]] elif word in ["a'", "e'", "o'", "i'", "u'", "A'"]: return [[word[0] + "'"]] elif word in ["'a", "'e", "'o", "'i", "'u", "'A"]: return [["'" + word[1]]] elif len(word) == 2 and word[0] == word[1]: return [[word[0]]] if word[:2] == 'aa': return [['A'] + i for i in variations(word[2:])] elif word[:2] == 'ee': return [['i'] + i for i in variations(word[2:])] elif word[:2] in ['oo', 'ou']: return [['u'] + i for i in variations(word[2:])] elif word[:3] == 'kha': return \ [['kha'] + i for i in variations(word[3:])] + \ [['kh', 'a'] + i for i in variations(word[3:])] + \ [['k', 'h', 'a'] + i for i in variations(word[3:])] elif word[:2] in ['kh', 'gh', 'ch', 'sh', 'zh', 'ck']: return \ [[word[:2]] + i for i in variations(word[2:])] + \ [[word[0]] + i for i in variations(word[1:])] elif word[:2] in ["a'", "e'", "o'", "i'", "u'", "A'"]: return [[word[:2]] + i for i in variations(word[2:])] elif word[:3] in ["'ee", "'ei"]: return [["'i"] + i for i in variations(word[3:])] elif word[:3] in ["'oo", "'ou"]: return [["'u"] + i for i in variations(word[3:])] elif word[:2] in ["'a", "'e", "'o", "'i", "'u", "'A"]: return [[word[:2]] + i for i in variations(word[2:])] elif len(word) >= 2 and word[0] == word[1]: return [[word[0]] + i for i in variations(word[2:])] else: return [[word[0]] + i for i in variations(word[1:])]
python
def variations(word): """Create variations of the word based on letter combinations like oo, sh, etc.""" if len(word) == 1: return [[word[0]]] elif word == 'aa': return [['A']] elif word == 'ee': return [['i']] elif word == 'ei': return [['ei']] elif word in ['oo', 'ou']: return [['u']] elif word == 'kha': return [['kha'], ['kh', 'a']] elif word in ['kh', 'gh', 'ch', 'sh', 'zh', 'ck']: return [[word]] elif word in ["'ee", "'ei"]: return [["'i"]] elif word in ["'oo", "'ou"]: return [["'u"]] elif word in ["a'", "e'", "o'", "i'", "u'", "A'"]: return [[word[0] + "'"]] elif word in ["'a", "'e", "'o", "'i", "'u", "'A"]: return [["'" + word[1]]] elif len(word) == 2 and word[0] == word[1]: return [[word[0]]] if word[:2] == 'aa': return [['A'] + i for i in variations(word[2:])] elif word[:2] == 'ee': return [['i'] + i for i in variations(word[2:])] elif word[:2] in ['oo', 'ou']: return [['u'] + i for i in variations(word[2:])] elif word[:3] == 'kha': return \ [['kha'] + i for i in variations(word[3:])] + \ [['kh', 'a'] + i for i in variations(word[3:])] + \ [['k', 'h', 'a'] + i for i in variations(word[3:])] elif word[:2] in ['kh', 'gh', 'ch', 'sh', 'zh', 'ck']: return \ [[word[:2]] + i for i in variations(word[2:])] + \ [[word[0]] + i for i in variations(word[1:])] elif word[:2] in ["a'", "e'", "o'", "i'", "u'", "A'"]: return [[word[:2]] + i for i in variations(word[2:])] elif word[:3] in ["'ee", "'ei"]: return [["'i"] + i for i in variations(word[3:])] elif word[:3] in ["'oo", "'ou"]: return [["'u"] + i for i in variations(word[3:])] elif word[:2] in ["'a", "'e", "'o", "'i", "'u", "'A"]: return [[word[:2]] + i for i in variations(word[2:])] elif len(word) >= 2 and word[0] == word[1]: return [[word[0]] + i for i in variations(word[2:])] else: return [[word[0]] + i for i in variations(word[1:])]
[ "def", "variations", "(", "word", ")", ":", "if", "len", "(", "word", ")", "==", "1", ":", "return", "[", "[", "word", "[", "0", "]", "]", "]", "elif", "word", "==", "'aa'", ":", "return", "[", "[", "'A'", "]", "]", "elif", "word", "==", "'ee...
Create variations of the word based on letter combinations like oo, sh, etc.
[ "Create", "variations", "of", "the", "word", "based", "on", "letter", "combinations", "like", "oo", "sh", "etc", "." ]
3d6953d7ad385f860fac4b9110da4205326e4de5
https://github.com/elektito/finglish/blob/3d6953d7ad385f860fac4b9110da4205326e4de5/finglish/f2p.py#L74-L129
train
elektito/finglish
finglish/f2p.py
f2p_word
def f2p_word(word, max_word_size=15, cutoff=3): """Convert a single word from Finglish to Persian. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By default 3 of these possibilities are considered for each word. This number can be changed by this argument. """ original_word = word word = word.lower() c = dictionary.get(word) if c: return [(c, 1.0)] if word == '': return [] elif len(word) > max_word_size: return [(original_word, 1.0)] results = [] for w in variations(word): results.extend(f2p_word_internal(w, original_word)) # sort results based on the confidence value results.sort(key=lambda r: r[1], reverse=True) # return the top three results in order to cut down on the number # of possibilities. return results[:cutoff]
python
def f2p_word(word, max_word_size=15, cutoff=3): """Convert a single word from Finglish to Persian. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By default 3 of these possibilities are considered for each word. This number can be changed by this argument. """ original_word = word word = word.lower() c = dictionary.get(word) if c: return [(c, 1.0)] if word == '': return [] elif len(word) > max_word_size: return [(original_word, 1.0)] results = [] for w in variations(word): results.extend(f2p_word_internal(w, original_word)) # sort results based on the confidence value results.sort(key=lambda r: r[1], reverse=True) # return the top three results in order to cut down on the number # of possibilities. return results[:cutoff]
[ "def", "f2p_word", "(", "word", ",", "max_word_size", "=", "15", ",", "cutoff", "=", "3", ")", ":", "original_word", "=", "word", "word", "=", "word", ".", "lower", "(", ")", "c", "=", "dictionary", ".", "get", "(", "word", ")", "if", "c", ":", "...
Convert a single word from Finglish to Persian. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By default 3 of these possibilities are considered for each word. This number can be changed by this argument.
[ "Convert", "a", "single", "word", "from", "Finglish", "to", "Persian", "." ]
3d6953d7ad385f860fac4b9110da4205326e4de5
https://github.com/elektito/finglish/blob/3d6953d7ad385f860fac4b9110da4205326e4de5/finglish/f2p.py#L131-L164
train
elektito/finglish
finglish/f2p.py
f2p_list
def f2p_list(phrase, max_word_size=15, cutoff=3): """Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By default 3 of these possibilities are considered for each word. This number can be changed by this argument. Returns a list of lists, each sub-list contains a number of possibilities for each word as a pair of (word, confidence) values. """ # split the phrase into words results = [w for w in sep_regex.split(phrase) if w] # return an empty list if no words if results == []: return [] # convert each word separately results = [f2p_word(w, max_word_size, cutoff) for w in results] return results
python
def f2p_list(phrase, max_word_size=15, cutoff=3): """Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By default 3 of these possibilities are considered for each word. This number can be changed by this argument. Returns a list of lists, each sub-list contains a number of possibilities for each word as a pair of (word, confidence) values. """ # split the phrase into words results = [w for w in sep_regex.split(phrase) if w] # return an empty list if no words if results == []: return [] # convert each word separately results = [f2p_word(w, max_word_size, cutoff) for w in results] return results
[ "def", "f2p_list", "(", "phrase", ",", "max_word_size", "=", "15", ",", "cutoff", "=", "3", ")", ":", "# split the phrase into words", "results", "=", "[", "w", "for", "w", "in", "sep_regex", ".", "split", "(", "phrase", ")", "if", "w", "]", "# return an...
Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By default 3 of these possibilities are considered for each word. This number can be changed by this argument. Returns a list of lists, each sub-list contains a number of possibilities for each word as a pair of (word, confidence) values.
[ "Convert", "a", "phrase", "from", "Finglish", "to", "Persian", "." ]
3d6953d7ad385f860fac4b9110da4205326e4de5
https://github.com/elektito/finglish/blob/3d6953d7ad385f860fac4b9110da4205326e4de5/finglish/f2p.py#L166-L194
train
elektito/finglish
finglish/f2p.py
f2p
def f2p(phrase, max_word_size=15, cutoff=3): """Convert a Finglish phrase to the most probable Persian phrase. """ results = f2p_list(phrase, max_word_size, cutoff) return ' '.join(i[0][0] for i in results)
python
def f2p(phrase, max_word_size=15, cutoff=3): """Convert a Finglish phrase to the most probable Persian phrase. """ results = f2p_list(phrase, max_word_size, cutoff) return ' '.join(i[0][0] for i in results)
[ "def", "f2p", "(", "phrase", ",", "max_word_size", "=", "15", ",", "cutoff", "=", "3", ")", ":", "results", "=", "f2p_list", "(", "phrase", ",", "max_word_size", ",", "cutoff", ")", "return", "' '", ".", "join", "(", "i", "[", "0", "]", "[", "0", ...
Convert a Finglish phrase to the most probable Persian phrase.
[ "Convert", "a", "Finglish", "phrase", "to", "the", "most", "probable", "Persian", "phrase", "." ]
3d6953d7ad385f860fac4b9110da4205326e4de5
https://github.com/elektito/finglish/blob/3d6953d7ad385f860fac4b9110da4205326e4de5/finglish/f2p.py#L196-L202
train
pytest-dev/apipkg
src/apipkg/__init__.py
distribution_version
def distribution_version(name): """try to get the version of the named distribution, returs None on failure""" from pkg_resources import get_distribution, DistributionNotFound try: dist = get_distribution(name) except DistributionNotFound: pass else: return dist.version
python
def distribution_version(name): """try to get the version of the named distribution, returs None on failure""" from pkg_resources import get_distribution, DistributionNotFound try: dist = get_distribution(name) except DistributionNotFound: pass else: return dist.version
[ "def", "distribution_version", "(", "name", ")", ":", "from", "pkg_resources", "import", "get_distribution", ",", "DistributionNotFound", "try", ":", "dist", "=", "get_distribution", "(", "name", ")", "except", "DistributionNotFound", ":", "pass", "else", ":", "re...
try to get the version of the named distribution, returs None on failure
[ "try", "to", "get", "the", "version", "of", "the", "named", "distribution", "returs", "None", "on", "failure" ]
e409195c52bab50e14745d0adf824b2a0390a50f
https://github.com/pytest-dev/apipkg/blob/e409195c52bab50e14745d0adf824b2a0390a50f/src/apipkg/__init__.py#L27-L36
train
pytest-dev/apipkg
src/apipkg/__init__.py
initpkg
def initpkg(pkgname, exportdefs, attr=None, eager=False): """ initialize given package from the export definitions. """ attr = attr or {} oldmod = sys.modules.get(pkgname) d = {} f = getattr(oldmod, '__file__', None) if f: f = _py_abspath(f) d['__file__'] = f if hasattr(oldmod, '__version__'): d['__version__'] = oldmod.__version__ if hasattr(oldmod, '__loader__'): d['__loader__'] = oldmod.__loader__ if hasattr(oldmod, '__path__'): d['__path__'] = [_py_abspath(p) for p in oldmod.__path__] if hasattr(oldmod, '__package__'): d['__package__'] = oldmod.__package__ if '__doc__' not in exportdefs and getattr(oldmod, '__doc__', None): d['__doc__'] = oldmod.__doc__ d.update(attr) if hasattr(oldmod, "__dict__"): oldmod.__dict__.update(d) mod = ApiModule(pkgname, exportdefs, implprefix=pkgname, attr=d) sys.modules[pkgname] = mod # eagerload in bypthon to avoid their monkeypatching breaking packages if 'bpython' in sys.modules or eager: for module in list(sys.modules.values()): if isinstance(module, ApiModule): module.__dict__
python
def initpkg(pkgname, exportdefs, attr=None, eager=False): """ initialize given package from the export definitions. """ attr = attr or {} oldmod = sys.modules.get(pkgname) d = {} f = getattr(oldmod, '__file__', None) if f: f = _py_abspath(f) d['__file__'] = f if hasattr(oldmod, '__version__'): d['__version__'] = oldmod.__version__ if hasattr(oldmod, '__loader__'): d['__loader__'] = oldmod.__loader__ if hasattr(oldmod, '__path__'): d['__path__'] = [_py_abspath(p) for p in oldmod.__path__] if hasattr(oldmod, '__package__'): d['__package__'] = oldmod.__package__ if '__doc__' not in exportdefs and getattr(oldmod, '__doc__', None): d['__doc__'] = oldmod.__doc__ d.update(attr) if hasattr(oldmod, "__dict__"): oldmod.__dict__.update(d) mod = ApiModule(pkgname, exportdefs, implprefix=pkgname, attr=d) sys.modules[pkgname] = mod # eagerload in bypthon to avoid their monkeypatching breaking packages if 'bpython' in sys.modules or eager: for module in list(sys.modules.values()): if isinstance(module, ApiModule): module.__dict__
[ "def", "initpkg", "(", "pkgname", ",", "exportdefs", ",", "attr", "=", "None", ",", "eager", "=", "False", ")", ":", "attr", "=", "attr", "or", "{", "}", "oldmod", "=", "sys", ".", "modules", ".", "get", "(", "pkgname", ")", "d", "=", "{", "}", ...
initialize given package from the export definitions.
[ "initialize", "given", "package", "from", "the", "export", "definitions", "." ]
e409195c52bab50e14745d0adf824b2a0390a50f
https://github.com/pytest-dev/apipkg/blob/e409195c52bab50e14745d0adf824b2a0390a50f/src/apipkg/__init__.py#L39-L67
train
pytest-dev/apipkg
src/apipkg/__init__.py
importobj
def importobj(modpath, attrname): """imports a module, then resolves the attrname on it""" module = __import__(modpath, None, None, ['__doc__']) if not attrname: return module retval = module names = attrname.split(".") for x in names: retval = getattr(retval, x) return retval
python
def importobj(modpath, attrname): """imports a module, then resolves the attrname on it""" module = __import__(modpath, None, None, ['__doc__']) if not attrname: return module retval = module names = attrname.split(".") for x in names: retval = getattr(retval, x) return retval
[ "def", "importobj", "(", "modpath", ",", "attrname", ")", ":", "module", "=", "__import__", "(", "modpath", ",", "None", ",", "None", ",", "[", "'__doc__'", "]", ")", "if", "not", "attrname", ":", "return", "module", "retval", "=", "module", "names", "...
imports a module, then resolves the attrname on it
[ "imports", "a", "module", "then", "resolves", "the", "attrname", "on", "it" ]
e409195c52bab50e14745d0adf824b2a0390a50f
https://github.com/pytest-dev/apipkg/blob/e409195c52bab50e14745d0adf824b2a0390a50f/src/apipkg/__init__.py#L70-L80
train
pytest-dev/apipkg
src/apipkg/__init__.py
ApiModule.__makeattr
def __makeattr(self, name): """lazily compute value for name or raise AttributeError if unknown.""" # print "makeattr", self.__name__, name target = None if '__onfirstaccess__' in self.__map__: target = self.__map__.pop('__onfirstaccess__') importobj(*target)() try: modpath, attrname = self.__map__[name] except KeyError: if target is not None and name != '__onfirstaccess__': # retry, onfirstaccess might have set attrs return getattr(self, name) raise AttributeError(name) else: result = importobj(modpath, attrname) setattr(self, name, result) try: del self.__map__[name] except KeyError: pass # in a recursive-import situation a double-del can happen return result
python
def __makeattr(self, name): """lazily compute value for name or raise AttributeError if unknown.""" # print "makeattr", self.__name__, name target = None if '__onfirstaccess__' in self.__map__: target = self.__map__.pop('__onfirstaccess__') importobj(*target)() try: modpath, attrname = self.__map__[name] except KeyError: if target is not None and name != '__onfirstaccess__': # retry, onfirstaccess might have set attrs return getattr(self, name) raise AttributeError(name) else: result = importobj(modpath, attrname) setattr(self, name, result) try: del self.__map__[name] except KeyError: pass # in a recursive-import situation a double-del can happen return result
[ "def", "__makeattr", "(", "self", ",", "name", ")", ":", "# print \"makeattr\", self.__name__, name", "target", "=", "None", "if", "'__onfirstaccess__'", "in", "self", ".", "__map__", ":", "target", "=", "self", ".", "__map__", ".", "pop", "(", "'__onfirstaccess...
lazily compute value for name or raise AttributeError if unknown.
[ "lazily", "compute", "value", "for", "name", "or", "raise", "AttributeError", "if", "unknown", "." ]
e409195c52bab50e14745d0adf824b2a0390a50f
https://github.com/pytest-dev/apipkg/blob/e409195c52bab50e14745d0adf824b2a0390a50f/src/apipkg/__init__.py#L137-L158
train
kimmobrunfeldt/nap
nap/url.py
Url._request
def _request(self, http_method, relative_url='', **kwargs): """Does actual HTTP request using requests library.""" # It could be possible to call api.resource.get('/index') # but it would be non-intuitive that the path would resolve # to root of domain relative_url = self._remove_leading_slash(relative_url) # Add default kwargs with possible custom kwargs returned by # before_request new_kwargs = self.default_kwargs().copy() custom_kwargs = self.before_request( http_method, relative_url, kwargs.copy() ) new_kwargs.update(custom_kwargs) response = requests.request( http_method, self._join_url(relative_url), **new_kwargs ) return self.after_request(response)
python
def _request(self, http_method, relative_url='', **kwargs): """Does actual HTTP request using requests library.""" # It could be possible to call api.resource.get('/index') # but it would be non-intuitive that the path would resolve # to root of domain relative_url = self._remove_leading_slash(relative_url) # Add default kwargs with possible custom kwargs returned by # before_request new_kwargs = self.default_kwargs().copy() custom_kwargs = self.before_request( http_method, relative_url, kwargs.copy() ) new_kwargs.update(custom_kwargs) response = requests.request( http_method, self._join_url(relative_url), **new_kwargs ) return self.after_request(response)
[ "def", "_request", "(", "self", ",", "http_method", ",", "relative_url", "=", "''", ",", "*", "*", "kwargs", ")", ":", "# It could be possible to call api.resource.get('/index')", "# but it would be non-intuitive that the path would resolve", "# to root of domain", "relative_ur...
Does actual HTTP request using requests library.
[ "Does", "actual", "HTTP", "request", "using", "requests", "library", "." ]
3ea7b41ef6b24b7e127bc87bb010d8a8bb18a4bd
https://github.com/kimmobrunfeldt/nap/blob/3ea7b41ef6b24b7e127bc87bb010d8a8bb18a4bd/nap/url.py#L109-L132
train
kimmobrunfeldt/nap
nap/url.py
Url._new_url
def _new_url(self, relative_url): """Create new Url which points to new url.""" return Url( urljoin(self._base_url, relative_url), **self._default_kwargs )
python
def _new_url(self, relative_url): """Create new Url which points to new url.""" return Url( urljoin(self._base_url, relative_url), **self._default_kwargs )
[ "def", "_new_url", "(", "self", ",", "relative_url", ")", ":", "return", "Url", "(", "urljoin", "(", "self", ".", "_base_url", ",", "relative_url", ")", ",", "*", "*", "self", ".", "_default_kwargs", ")" ]
Create new Url which points to new url.
[ "Create", "new", "Url", "which", "points", "to", "new", "url", "." ]
3ea7b41ef6b24b7e127bc87bb010d8a8bb18a4bd
https://github.com/kimmobrunfeldt/nap/blob/3ea7b41ef6b24b7e127bc87bb010d8a8bb18a4bd/nap/url.py#L142-L148
train
ourway/auth
auth/CAS/authorization.py
Authorization.roles
def roles(self): """gets user groups""" result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
python
def roles(self): """gets user groups""" result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
[ "def", "roles", "(", "self", ")", ":", "result", "=", "AuthGroup", ".", "objects", "(", "creator", "=", "self", ".", "client", ")", ".", "only", "(", "'role'", ")", "return", "json", ".", "loads", "(", "result", ".", "to_json", "(", ")", ")" ]
gets user groups
[ "gets", "user", "groups" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L25-L28
train
ourway/auth
auth/CAS/authorization.py
Authorization.get_permissions
def get_permissions(self, role): """gets permissions of role""" target_role = AuthGroup.objects(role=role, creator=self.client).first() if not target_role: return '[]' targets = AuthPermission.objects(groups=target_role, creator=self.client).only('name') return json.loads(targets.to_json())
python
def get_permissions(self, role): """gets permissions of role""" target_role = AuthGroup.objects(role=role, creator=self.client).first() if not target_role: return '[]' targets = AuthPermission.objects(groups=target_role, creator=self.client).only('name') return json.loads(targets.to_json())
[ "def", "get_permissions", "(", "self", ",", "role", ")", ":", "target_role", "=", "AuthGroup", ".", "objects", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", ".", "first", "(", ")", "if", "not", "target_role", ":", "return",...
gets permissions of role
[ "gets", "permissions", "of", "role" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L30-L36
train
ourway/auth
auth/CAS/authorization.py
Authorization.get_user_permissions
def get_user_permissions(self, user): """get permissions of a user""" memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups') results = [] for each in memberShipRecords: for group in each.groups: targetPermissionRecords = AuthPermission.objects(creator=self.client, groups=group).only('name') for each_permission in targetPermissionRecords: results.append({'name':each_permission.name}) return results
python
def get_user_permissions(self, user): """get permissions of a user""" memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups') results = [] for each in memberShipRecords: for group in each.groups: targetPermissionRecords = AuthPermission.objects(creator=self.client, groups=group).only('name') for each_permission in targetPermissionRecords: results.append({'name':each_permission.name}) return results
[ "def", "get_user_permissions", "(", "self", ",", "user", ")", ":", "memberShipRecords", "=", "AuthMembership", ".", "objects", "(", "creator", "=", "self", ".", "client", ",", "user", "=", "user", ")", ".", "only", "(", "'groups'", ")", "results", "=", "...
get permissions of a user
[ "get", "permissions", "of", "a", "user" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L39-L50
train
ourway/auth
auth/CAS/authorization.py
Authorization.get_user_roles
def get_user_roles(self, user): """get permissions of a user""" memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups') results = [] for each in memberShipRecords: for group in each.groups: results.append({'role':group.role}) return results
python
def get_user_roles(self, user): """get permissions of a user""" memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups') results = [] for each in memberShipRecords: for group in each.groups: results.append({'role':group.role}) return results
[ "def", "get_user_roles", "(", "self", ",", "user", ")", ":", "memberShipRecords", "=", "AuthMembership", ".", "objects", "(", "creator", "=", "self", ".", "client", ",", "user", "=", "user", ")", ".", "only", "(", "'groups'", ")", "results", "=", "[", ...
get permissions of a user
[ "get", "permissions", "of", "a", "user" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L52-L59
train
ourway/auth
auth/CAS/authorization.py
Authorization.get_role_members
def get_role_members(self, role): """get permissions of a user""" targetRoleDb = AuthGroup.objects(creator=self.client, role=role) members = AuthMembership.objects(groups__in=targetRoleDb).only('user') return json.loads(members.to_json())
python
def get_role_members(self, role): """get permissions of a user""" targetRoleDb = AuthGroup.objects(creator=self.client, role=role) members = AuthMembership.objects(groups__in=targetRoleDb).only('user') return json.loads(members.to_json())
[ "def", "get_role_members", "(", "self", ",", "role", ")", ":", "targetRoleDb", "=", "AuthGroup", ".", "objects", "(", "creator", "=", "self", ".", "client", ",", "role", "=", "role", ")", "members", "=", "AuthMembership", ".", "objects", "(", "groups__in",...
get permissions of a user
[ "get", "permissions", "of", "a", "user" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L62-L66
train
ourway/auth
auth/CAS/authorization.py
Authorization.which_roles_can
def which_roles_can(self, name): """Which role can SendMail? """ targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first() return [{'role': group.role} for group in targetPermissionRecords.groups]
python
def which_roles_can(self, name): """Which role can SendMail? """ targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first() return [{'role': group.role} for group in targetPermissionRecords.groups]
[ "def", "which_roles_can", "(", "self", ",", "name", ")", ":", "targetPermissionRecords", "=", "AuthPermission", ".", "objects", "(", "creator", "=", "self", ".", "client", ",", "name", "=", "name", ")", ".", "first", "(", ")", "return", "[", "{", "'role'...
Which role can SendMail?
[ "Which", "role", "can", "SendMail?" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L68-L71
train
ourway/auth
auth/CAS/authorization.py
Authorization.which_users_can
def which_users_can(self, name): """Which role can SendMail? """ _roles = self.which_roles_can(name) result = [self.get_role_members(i.get('role')) for i in _roles] return result
python
def which_users_can(self, name): """Which role can SendMail? """ _roles = self.which_roles_can(name) result = [self.get_role_members(i.get('role')) for i in _roles] return result
[ "def", "which_users_can", "(", "self", ",", "name", ")", ":", "_roles", "=", "self", ".", "which_roles_can", "(", "name", ")", "result", "=", "[", "self", ".", "get_role_members", "(", "i", ".", "get", "(", "'role'", ")", ")", "for", "i", "in", "_rol...
Which role can SendMail?
[ "Which", "role", "can", "SendMail?" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L73-L77
train
ourway/auth
auth/CAS/authorization.py
Authorization.get_role
def get_role(self, role): """Returns a role object """ role = AuthGroup.objects(role=role, creator=self.client).first() return role
python
def get_role(self, role): """Returns a role object """ role = AuthGroup.objects(role=role, creator=self.client).first() return role
[ "def", "get_role", "(", "self", ",", "role", ")", ":", "role", "=", "AuthGroup", ".", "objects", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", ".", "first", "(", ")", "return", "role" ]
Returns a role object
[ "Returns", "a", "role", "object" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L79-L83
train
ourway/auth
auth/CAS/authorization.py
Authorization.add_role
def add_role(self, role, description=None): """ Creates a new group """ new_group = AuthGroup(role=role, creator=self.client) try: new_group.save() return True except NotUniqueError: return False
python
def add_role(self, role, description=None): """ Creates a new group """ new_group = AuthGroup(role=role, creator=self.client) try: new_group.save() return True except NotUniqueError: return False
[ "def", "add_role", "(", "self", ",", "role", ",", "description", "=", "None", ")", ":", "new_group", "=", "AuthGroup", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", "try", ":", "new_group", ".", "save", "(", ")", "return"...
Creates a new group
[ "Creates", "a", "new", "group" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L85-L92
train
ourway/auth
auth/CAS/authorization.py
Authorization.del_role
def del_role(self, role): """ deletes a group """ target = AuthGroup.objects(role=role, creator=self.client).first() if target: target.delete() return True else: return False
python
def del_role(self, role): """ deletes a group """ target = AuthGroup.objects(role=role, creator=self.client).first() if target: target.delete() return True else: return False
[ "def", "del_role", "(", "self", ",", "role", ")", ":", "target", "=", "AuthGroup", ".", "objects", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", ".", "first", "(", ")", "if", "target", ":", "target", ".", "delete", "(",...
deletes a group
[ "deletes", "a", "group" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L94-L101
train
ourway/auth
auth/CAS/authorization.py
Authorization.add_membership
def add_membership(self, user, role): """ make user a member of a group """ targetGroup = AuthGroup.objects(role=role, creator=self.client).first() if not targetGroup: return False target = AuthMembership.objects(user=user, creator=self.client).first() if not target: target = AuthMembership(user=user, creator=self.client) if not role in [i.role for i in target.groups]: target.groups.append(targetGroup) target.save() return True
python
def add_membership(self, user, role): """ make user a member of a group """ targetGroup = AuthGroup.objects(role=role, creator=self.client).first() if not targetGroup: return False target = AuthMembership.objects(user=user, creator=self.client).first() if not target: target = AuthMembership(user=user, creator=self.client) if not role in [i.role for i in target.groups]: target.groups.append(targetGroup) target.save() return True
[ "def", "add_membership", "(", "self", ",", "user", ",", "role", ")", ":", "targetGroup", "=", "AuthGroup", ".", "objects", "(", "role", "=", "role", ",", "creator", "=", "self", ".", "client", ")", ".", "first", "(", ")", "if", "not", "targetGroup", ...
make user a member of a group
[ "make", "user", "a", "member", "of", "a", "group" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L103-L116
train
ourway/auth
auth/CAS/authorization.py
Authorization.del_membership
def del_membership(self, user, role): """ dismember user from a group """ if not self.has_membership(user, role): return True targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return True for group in targetRecord.groups: if group.role==role: targetRecord.groups.remove(group) targetRecord.save() return True
python
def del_membership(self, user, role): """ dismember user from a group """ if not self.has_membership(user, role): return True targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return True for group in targetRecord.groups: if group.role==role: targetRecord.groups.remove(group) targetRecord.save() return True
[ "def", "del_membership", "(", "self", ",", "user", ",", "role", ")", ":", "if", "not", "self", ".", "has_membership", "(", "user", ",", "role", ")", ":", "return", "True", "targetRecord", "=", "AuthMembership", ".", "objects", "(", "creator", "=", "self"...
dismember user from a group
[ "dismember", "user", "from", "a", "group" ]
f0d9676854dcec494add4fa086a9b2a3e4d8cea5
https://github.com/ourway/auth/blob/f0d9676854dcec494add4fa086a9b2a3e4d8cea5/auth/CAS/authorization.py#L119-L130
train