Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
get_cached_http | () | Return an HTTP object which caches results returned.
This is intended to be used in methods like
oauth2client.client.verify_id_token(), which calls to the same URI
to retrieve certs.
Returns:
httplib2.Http, an HTTP object with a MemoryCache
| Return an HTTP object which caches results returned. | def get_cached_http():
"""Return an HTTP object which caches results returned.
This is intended to be used in methods like
oauth2client.client.verify_id_token(), which calls to the same URI
to retrieve certs.
Returns:
httplib2.Http, an HTTP object with a MemoryCache
"""
return _CACHED_HTTP | [
"def",
"get_cached_http",
"(",
")",
":",
"return",
"_CACHED_HTTP"
] | [
47,
0
] | [
57,
23
] | python | en | ['en', 'en', 'en'] | True |
get_http_object | (*args, **kwargs) | Return a new HTTP object.
Args:
*args: tuple, The positional arguments to be passed when
contructing a new HTTP object.
**kwargs: dict, The keyword arguments to be passed when
contructing a new HTTP object.
Returns:
httplib2.Http, an HTTP object.
| Return a new HTTP object. | def get_http_object(*args, **kwargs):
"""Return a new HTTP object.
Args:
*args: tuple, The positional arguments to be passed when
contructing a new HTTP object.
**kwargs: dict, The keyword arguments to be passed when
contructing a new HTTP object.
Returns:
httplib2.Http, an HTTP object.
"""
return httplib2.Http(*args, **kwargs) | [
"def",
"get_http_object",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"httplib2",
".",
"Http",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
60,
0
] | [
72,
41
] | python | en | ['en', 'en', 'en'] | True |
_initialize_headers | (headers) | Creates a copy of the headers.
Args:
headers: dict, request headers to copy.
Returns:
dict, the copied headers or a new dictionary if the headers
were None.
| Creates a copy of the headers. | def _initialize_headers(headers):
"""Creates a copy of the headers.
Args:
headers: dict, request headers to copy.
Returns:
dict, the copied headers or a new dictionary if the headers
were None.
"""
return {} if headers is None else dict(headers) | [
"def",
"_initialize_headers",
"(",
"headers",
")",
":",
"return",
"{",
"}",
"if",
"headers",
"is",
"None",
"else",
"dict",
"(",
"headers",
")"
] | [
75,
0
] | [
85,
51
] | python | en | ['en', 'en', 'en'] | True |
_apply_user_agent | (headers, user_agent) | Adds a user-agent to the headers.
Args:
headers: dict, request headers to add / modify user
agent within.
user_agent: str, the user agent to add.
Returns:
dict, the original headers passed in, but modified if the
user agent is not None.
| Adds a user-agent to the headers. | def _apply_user_agent(headers, user_agent):
"""Adds a user-agent to the headers.
Args:
headers: dict, request headers to add / modify user
agent within.
user_agent: str, the user agent to add.
Returns:
dict, the original headers passed in, but modified if the
user agent is not None.
"""
if user_agent is not None:
if 'user-agent' in headers:
headers['user-agent'] = (user_agent + ' ' + headers['user-agent'])
else:
headers['user-agent'] = user_agent
return headers | [
"def",
"_apply_user_agent",
"(",
"headers",
",",
"user_agent",
")",
":",
"if",
"user_agent",
"is",
"not",
"None",
":",
"if",
"'user-agent'",
"in",
"headers",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"(",
"user_agent",
"+",
"' '",
"+",
"headers",
"[",
"'user-agent'",
"]",
")",
"else",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"user_agent",
"return",
"headers"
] | [
88,
0
] | [
106,
18
] | python | en | ['en', 'en', 'en'] | True |
clean_headers | (headers) | Forces header keys and values to be strings, i.e not unicode.
The httplib module just concats the header keys and values in a way that
may make the message header a unicode string, which, if it then tries to
contatenate to a binary request body may result in a unicode decode error.
Args:
headers: dict, A dictionary of headers.
Returns:
The same dictionary but with all the keys converted to strings.
| Forces header keys and values to be strings, i.e not unicode. | def clean_headers(headers):
"""Forces header keys and values to be strings, i.e not unicode.
The httplib module just concats the header keys and values in a way that
may make the message header a unicode string, which, if it then tries to
contatenate to a binary request body may result in a unicode decode error.
Args:
headers: dict, A dictionary of headers.
Returns:
The same dictionary but with all the keys converted to strings.
"""
clean = {}
try:
for k, v in six.iteritems(headers):
if not isinstance(k, six.binary_type):
k = str(k)
if not isinstance(v, six.binary_type):
v = str(v)
clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v)
except UnicodeEncodeError:
from oauth2client.client import NonAsciiHeaderError
raise NonAsciiHeaderError(k, ': ', v)
return clean | [
"def",
"clean_headers",
"(",
"headers",
")",
":",
"clean",
"=",
"{",
"}",
"try",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"headers",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"six",
".",
"binary_type",
")",
":",
"k",
"=",
"str",
"(",
"k",
")",
"if",
"not",
"isinstance",
"(",
"v",
",",
"six",
".",
"binary_type",
")",
":",
"v",
"=",
"str",
"(",
"v",
")",
"clean",
"[",
"_helpers",
".",
"_to_bytes",
"(",
"k",
")",
"]",
"=",
"_helpers",
".",
"_to_bytes",
"(",
"v",
")",
"except",
"UnicodeEncodeError",
":",
"from",
"oauth2client",
".",
"client",
"import",
"NonAsciiHeaderError",
"raise",
"NonAsciiHeaderError",
"(",
"k",
",",
"': '",
",",
"v",
")",
"return",
"clean"
] | [
109,
0
] | [
133,
16
] | python | en | ['en', 'en', 'en'] | True |
wrap_http_for_auth | (credentials, http) | Prepares an HTTP object's request method for auth.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
Args:
credentials: Credentials, the credentials used to identify
the authenticated user.
http: httplib2.Http, an http object to be used to make
auth requests.
| Prepares an HTTP object's request method for auth. | def wrap_http_for_auth(credentials, http):
"""Prepares an HTTP object's request method for auth.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
Args:
credentials: Credentials, the credentials used to identify
the authenticated user.
http: httplib2.Http, an http object to be used to make
auth requests.
"""
orig_request_method = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
if not credentials.access_token:
_LOGGER.info('Attempting refresh to obtain '
'initial access_token')
credentials._refresh(orig_request_method)
# Clone and modify the request headers to add the appropriate
# Authorization header.
headers = _initialize_headers(headers)
credentials.apply(headers)
_apply_user_agent(headers, credentials.user_agent)
body_stream_position = None
# Check if the body is a file-like stream.
if all(getattr(body, stream_prop, None) for stream_prop in
_STREAM_PROPERTIES):
body_stream_position = body.tell()
resp, content = request(orig_request_method, uri, method, body,
clean_headers(headers),
redirections, connection_type)
# A stored token may expire between the time it is retrieved and
# the time the request is made, so we may need to try twice.
max_refresh_attempts = 2
for refresh_attempt in range(max_refresh_attempts):
if resp.status not in REFRESH_STATUS_CODES:
break
_LOGGER.info('Refreshing due to a %s (attempt %s/%s)',
resp.status, refresh_attempt + 1,
max_refresh_attempts)
credentials._refresh(orig_request_method)
credentials.apply(headers)
if body_stream_position is not None:
body.seek(body_stream_position)
resp, content = request(orig_request_method, uri, method, body,
clean_headers(headers),
redirections, connection_type)
return resp, content
# Replace the request method with our own closure.
http.request = new_request
# Set credentials as a property of the request method.
http.request.credentials = credentials | [
"def",
"wrap_http_for_auth",
"(",
"credentials",
",",
"http",
")",
":",
"orig_request_method",
"=",
"http",
".",
"request",
"# The closure that will replace 'httplib2.Http.request'.",
"def",
"new_request",
"(",
"uri",
",",
"method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"redirections",
"=",
"httplib2",
".",
"DEFAULT_MAX_REDIRECTS",
",",
"connection_type",
"=",
"None",
")",
":",
"if",
"not",
"credentials",
".",
"access_token",
":",
"_LOGGER",
".",
"info",
"(",
"'Attempting refresh to obtain '",
"'initial access_token'",
")",
"credentials",
".",
"_refresh",
"(",
"orig_request_method",
")",
"# Clone and modify the request headers to add the appropriate",
"# Authorization header.",
"headers",
"=",
"_initialize_headers",
"(",
"headers",
")",
"credentials",
".",
"apply",
"(",
"headers",
")",
"_apply_user_agent",
"(",
"headers",
",",
"credentials",
".",
"user_agent",
")",
"body_stream_position",
"=",
"None",
"# Check if the body is a file-like stream.",
"if",
"all",
"(",
"getattr",
"(",
"body",
",",
"stream_prop",
",",
"None",
")",
"for",
"stream_prop",
"in",
"_STREAM_PROPERTIES",
")",
":",
"body_stream_position",
"=",
"body",
".",
"tell",
"(",
")",
"resp",
",",
"content",
"=",
"request",
"(",
"orig_request_method",
",",
"uri",
",",
"method",
",",
"body",
",",
"clean_headers",
"(",
"headers",
")",
",",
"redirections",
",",
"connection_type",
")",
"# A stored token may expire between the time it is retrieved and",
"# the time the request is made, so we may need to try twice.",
"max_refresh_attempts",
"=",
"2",
"for",
"refresh_attempt",
"in",
"range",
"(",
"max_refresh_attempts",
")",
":",
"if",
"resp",
".",
"status",
"not",
"in",
"REFRESH_STATUS_CODES",
":",
"break",
"_LOGGER",
".",
"info",
"(",
"'Refreshing due to a %s (attempt %s/%s)'",
",",
"resp",
".",
"status",
",",
"refresh_attempt",
"+",
"1",
",",
"max_refresh_attempts",
")",
"credentials",
".",
"_refresh",
"(",
"orig_request_method",
")",
"credentials",
".",
"apply",
"(",
"headers",
")",
"if",
"body_stream_position",
"is",
"not",
"None",
":",
"body",
".",
"seek",
"(",
"body_stream_position",
")",
"resp",
",",
"content",
"=",
"request",
"(",
"orig_request_method",
",",
"uri",
",",
"method",
",",
"body",
",",
"clean_headers",
"(",
"headers",
")",
",",
"redirections",
",",
"connection_type",
")",
"return",
"resp",
",",
"content",
"# Replace the request method with our own closure.",
"http",
".",
"request",
"=",
"new_request",
"# Set credentials as a property of the request method.",
"http",
".",
"request",
".",
"credentials",
"=",
"credentials"
] | [
136,
0
] | [
200,
42
] | python | en | ['en', 'en', 'en'] | True |
wrap_http_for_jwt_access | (credentials, http) | Prepares an HTTP object's request method for JWT access.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
Args:
credentials: _JWTAccessCredentials, the credentials used to identify
a service account that uses JWT access tokens.
http: httplib2.Http, an http object to be used to make
auth requests.
| Prepares an HTTP object's request method for JWT access. | def wrap_http_for_jwt_access(credentials, http):
"""Prepares an HTTP object's request method for JWT access.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
Args:
credentials: _JWTAccessCredentials, the credentials used to identify
a service account that uses JWT access tokens.
http: httplib2.Http, an http object to be used to make
auth requests.
"""
orig_request_method = http.request
wrap_http_for_auth(credentials, http)
# The new value of ``http.request`` set by ``wrap_http_for_auth``.
authenticated_request_method = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
if 'aud' in credentials._kwargs:
# Preemptively refresh token, this is not done for OAuth2
if (credentials.access_token is None or
credentials.access_token_expired):
credentials.refresh(None)
return request(authenticated_request_method, uri,
method, body, headers, redirections,
connection_type)
else:
# If we don't have an 'aud' (audience) claim,
# create a 1-time token with the uri root as the audience
headers = _initialize_headers(headers)
_apply_user_agent(headers, credentials.user_agent)
uri_root = uri.split('?', 1)[0]
token, unused_expiry = credentials._create_token({'aud': uri_root})
headers['Authorization'] = 'Bearer ' + token
return request(orig_request_method, uri, method, body,
clean_headers(headers),
redirections, connection_type)
# Replace the request method with our own closure.
http.request = new_request
# Set credentials as a property of the request method.
http.request.credentials = credentials | [
"def",
"wrap_http_for_jwt_access",
"(",
"credentials",
",",
"http",
")",
":",
"orig_request_method",
"=",
"http",
".",
"request",
"wrap_http_for_auth",
"(",
"credentials",
",",
"http",
")",
"# The new value of ``http.request`` set by ``wrap_http_for_auth``.",
"authenticated_request_method",
"=",
"http",
".",
"request",
"# The closure that will replace 'httplib2.Http.request'.",
"def",
"new_request",
"(",
"uri",
",",
"method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"redirections",
"=",
"httplib2",
".",
"DEFAULT_MAX_REDIRECTS",
",",
"connection_type",
"=",
"None",
")",
":",
"if",
"'aud'",
"in",
"credentials",
".",
"_kwargs",
":",
"# Preemptively refresh token, this is not done for OAuth2",
"if",
"(",
"credentials",
".",
"access_token",
"is",
"None",
"or",
"credentials",
".",
"access_token_expired",
")",
":",
"credentials",
".",
"refresh",
"(",
"None",
")",
"return",
"request",
"(",
"authenticated_request_method",
",",
"uri",
",",
"method",
",",
"body",
",",
"headers",
",",
"redirections",
",",
"connection_type",
")",
"else",
":",
"# If we don't have an 'aud' (audience) claim,",
"# create a 1-time token with the uri root as the audience",
"headers",
"=",
"_initialize_headers",
"(",
"headers",
")",
"_apply_user_agent",
"(",
"headers",
",",
"credentials",
".",
"user_agent",
")",
"uri_root",
"=",
"uri",
".",
"split",
"(",
"'?'",
",",
"1",
")",
"[",
"0",
"]",
"token",
",",
"unused_expiry",
"=",
"credentials",
".",
"_create_token",
"(",
"{",
"'aud'",
":",
"uri_root",
"}",
")",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'Bearer '",
"+",
"token",
"return",
"request",
"(",
"orig_request_method",
",",
"uri",
",",
"method",
",",
"body",
",",
"clean_headers",
"(",
"headers",
")",
",",
"redirections",
",",
"connection_type",
")",
"# Replace the request method with our own closure.",
"http",
".",
"request",
"=",
"new_request",
"# Set credentials as a property of the request method.",
"http",
".",
"request",
".",
"credentials",
"=",
"credentials"
] | [
203,
0
] | [
250,
42
] | python | en | ['en', 'en', 'en'] | True |
request | (http, uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None) | Make an HTTP request with an HTTP object and arguments.
Args:
http: httplib2.Http, an http object to be used to make requests.
uri: string, The URI to be requested.
method: string, The HTTP method to use for the request. Defaults
to 'GET'.
body: string, The payload / body in HTTP request. By default
there is no payload.
headers: dict, Key-value pairs of request headers. By default
there are no headers.
redirections: int, The number of allowed 203 redirects for
the request. Defaults to 5.
connection_type: httplib.HTTPConnection, a subclass to be used for
establishing connection. If not set, the type
will be determined from the ``uri``.
Returns:
tuple, a pair of a httplib2.Response with the status code and other
headers and the bytes of the content returned.
| Make an HTTP request with an HTTP object and arguments. | def request(http, uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Make an HTTP request with an HTTP object and arguments.
Args:
http: httplib2.Http, an http object to be used to make requests.
uri: string, The URI to be requested.
method: string, The HTTP method to use for the request. Defaults
to 'GET'.
body: string, The payload / body in HTTP request. By default
there is no payload.
headers: dict, Key-value pairs of request headers. By default
there are no headers.
redirections: int, The number of allowed 203 redirects for
the request. Defaults to 5.
connection_type: httplib.HTTPConnection, a subclass to be used for
establishing connection. If not set, the type
will be determined from the ``uri``.
Returns:
tuple, a pair of a httplib2.Response with the status code and other
headers and the bytes of the content returned.
"""
# NOTE: Allowing http or http.request is temporary (See Issue 601).
http_callable = getattr(http, 'request', http)
return http_callable(uri, method=method, body=body, headers=headers,
redirections=redirections,
connection_type=connection_type) | [
"def",
"request",
"(",
"http",
",",
"uri",
",",
"method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"redirections",
"=",
"httplib2",
".",
"DEFAULT_MAX_REDIRECTS",
",",
"connection_type",
"=",
"None",
")",
":",
"# NOTE: Allowing http or http.request is temporary (See Issue 601).",
"http_callable",
"=",
"getattr",
"(",
"http",
",",
"'request'",
",",
"http",
")",
"return",
"http_callable",
"(",
"uri",
",",
"method",
"=",
"method",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"headers",
",",
"redirections",
"=",
"redirections",
",",
"connection_type",
"=",
"connection_type",
")"
] | [
253,
0
] | [
281,
57
] | python | en | ['en', 'en', 'en'] | True |
_items | (mappingorseq) | Wrapper for efficient iteration over mappings represented by dicts
or sequences::
>>> for k, v in _items((i, i*i) for i in xrange(5)):
... assert k*k == v
>>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
... assert k*k == v
| Wrapper for efficient iteration over mappings represented by dicts
or sequences:: | def _items(mappingorseq):
"""Wrapper for efficient iteration over mappings represented by dicts
or sequences::
>>> for k, v in _items((i, i*i) for i in xrange(5)):
... assert k*k == v
>>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
... assert k*k == v
"""
if hasattr(mappingorseq, "items"):
return iteritems(mappingorseq)
return mappingorseq | [
"def",
"_items",
"(",
"mappingorseq",
")",
":",
"if",
"hasattr",
"(",
"mappingorseq",
",",
"\"items\"",
")",
":",
"return",
"iteritems",
"(",
"mappingorseq",
")",
"return",
"mappingorseq"
] | [
88,
0
] | [
101,
23
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.get | (self, key) | Look up key in the cache and return the value for it.
:param key: the key to be looked up.
:returns: The value if it exists and is readable, else ``None``.
| Look up key in the cache and return the value for it. | def get(self, key):
"""Look up key in the cache and return the value for it.
:param key: the key to be looked up.
:returns: The value if it exists and is readable, else ``None``.
"""
return None | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"return",
"None"
] | [
121,
4
] | [
127,
19
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.delete | (self, key) | Delete `key` from the cache.
:param key: the key to delete.
:returns: Whether the key existed and has been deleted.
:rtype: boolean
| Delete `key` from the cache. | def delete(self, key):
"""Delete `key` from the cache.
:param key: the key to delete.
:returns: Whether the key existed and has been deleted.
:rtype: boolean
"""
return True | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"return",
"True"
] | [
129,
4
] | [
136,
19
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.get_many | (self, *keys) | Returns a list of values for the given keys.
For each key an item in the list is created::
foo, bar = cache.get_many("foo", "bar")
Has the same error handling as :meth:`get`.
:param keys: The function accepts multiple keys as positional
arguments.
| Returns a list of values for the given keys.
For each key an item in the list is created:: | def get_many(self, *keys):
"""Returns a list of values for the given keys.
For each key an item in the list is created::
foo, bar = cache.get_many("foo", "bar")
Has the same error handling as :meth:`get`.
:param keys: The function accepts multiple keys as positional
arguments.
"""
return [self.get(k) for k in keys] | [
"def",
"get_many",
"(",
"self",
",",
"*",
"keys",
")",
":",
"return",
"[",
"self",
".",
"get",
"(",
"k",
")",
"for",
"k",
"in",
"keys",
"]"
] | [
138,
4
] | [
149,
42
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.get_dict | (self, *keys) | Like :meth:`get_many` but return a dict::
d = cache.get_dict("foo", "bar")
foo = d["foo"]
bar = d["bar"]
:param keys: The function accepts multiple keys as positional
arguments.
| Like :meth:`get_many` but return a dict:: | def get_dict(self, *keys):
"""Like :meth:`get_many` but return a dict::
d = cache.get_dict("foo", "bar")
foo = d["foo"]
bar = d["bar"]
:param keys: The function accepts multiple keys as positional
arguments.
"""
return dict(zip(keys, self.get_many(*keys))) | [
"def",
"get_dict",
"(",
"self",
",",
"*",
"keys",
")",
":",
"return",
"dict",
"(",
"zip",
"(",
"keys",
",",
"self",
".",
"get_many",
"(",
"*",
"keys",
")",
")",
")"
] | [
151,
4
] | [
161,
52
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.set | (self, key, value, timeout=None) | Add a new key/value to the cache (overwrites value, if key already
exists in the cache).
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key in seconds (if not
specified, it uses the default timeout). A timeout of
0 idicates that the cache never expires.
:returns: ``True`` if key has been updated, ``False`` for backend
errors. Pickling errors, however, will raise a subclass of
``pickle.PickleError``.
:rtype: boolean
| Add a new key/value to the cache (overwrites value, if key already
exists in the cache). | def set(self, key, value, timeout=None):
"""Add a new key/value to the cache (overwrites value, if key already
exists in the cache).
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key in seconds (if not
specified, it uses the default timeout). A timeout of
0 idicates that the cache never expires.
:returns: ``True`` if key has been updated, ``False`` for backend
errors. Pickling errors, however, will raise a subclass of
``pickle.PickleError``.
:rtype: boolean
"""
return True | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"True"
] | [
163,
4
] | [
177,
19
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.add | (self, key, value, timeout=None) | Works like :meth:`set` but does not overwrite the values of already
existing keys.
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key in seconds (if not
specified, it uses the default timeout). A timeout of
0 idicates that the cache never expires.
:returns: Same as :meth:`set`, but also ``False`` for already
existing keys.
:rtype: boolean
| Works like :meth:`set` but does not overwrite the values of already
existing keys. | def add(self, key, value, timeout=None):
"""Works like :meth:`set` but does not overwrite the values of already
existing keys.
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key in seconds (if not
specified, it uses the default timeout). A timeout of
0 idicates that the cache never expires.
:returns: Same as :meth:`set`, but also ``False`` for already
existing keys.
:rtype: boolean
"""
return True | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"True"
] | [
179,
4
] | [
192,
19
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.set_many | (self, mapping, timeout=None) | Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key in seconds (if not
specified, it uses the default timeout). A timeout of
0 idicates that the cache never expires.
:returns: Whether all given keys have been set.
:rtype: boolean
| Sets multiple keys and values from a mapping. | def set_many(self, mapping, timeout=None):
"""Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key in seconds (if not
specified, it uses the default timeout). A timeout of
0 idicates that the cache never expires.
:returns: Whether all given keys have been set.
:rtype: boolean
"""
rv = True
for key, value in _items(mapping):
if not self.set(key, value, timeout):
rv = False
return rv | [
"def",
"set_many",
"(",
"self",
",",
"mapping",
",",
"timeout",
"=",
"None",
")",
":",
"rv",
"=",
"True",
"for",
"key",
",",
"value",
"in",
"_items",
"(",
"mapping",
")",
":",
"if",
"not",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"timeout",
")",
":",
"rv",
"=",
"False",
"return",
"rv"
] | [
194,
4
] | [
208,
17
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.delete_many | (self, *keys) | Deletes multiple keys at once.
:param keys: The function accepts multiple keys as positional
arguments.
:returns: Whether all given keys have been deleted.
:rtype: boolean
| Deletes multiple keys at once. | def delete_many(self, *keys):
"""Deletes multiple keys at once.
:param keys: The function accepts multiple keys as positional
arguments.
:returns: Whether all given keys have been deleted.
:rtype: boolean
"""
return all(self.delete(key) for key in keys) | [
"def",
"delete_many",
"(",
"self",
",",
"*",
"keys",
")",
":",
"return",
"all",
"(",
"self",
".",
"delete",
"(",
"key",
")",
"for",
"key",
"in",
"keys",
")"
] | [
210,
4
] | [
218,
52
] | python | en | ['en', 'da', 'en'] | True |
BaseCache.has | (self, key) | Checks if a key exists in the cache without returning it. This is a
cheap operation that bypasses loading the actual data on the backend.
This method is optional and may not be implemented on all caches.
:param key: the key to check
| Checks if a key exists in the cache without returning it. This is a
cheap operation that bypasses loading the actual data on the backend. | def has(self, key):
"""Checks if a key exists in the cache without returning it. This is a
cheap operation that bypasses loading the actual data on the backend.
This method is optional and may not be implemented on all caches.
:param key: the key to check
"""
raise NotImplementedError(
"%s doesn't have an efficient implementation of `has`. That "
"means it is impossible to check whether a key exists without "
"fully loading the key's data. Consider using `self.get` "
"explicitly if you don't care about performance."
) | [
"def",
"has",
"(",
"self",
",",
"key",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"%s doesn't have an efficient implementation of `has`. That \"",
"\"means it is impossible to check whether a key exists without \"",
"\"fully loading the key's data. Consider using `self.get` \"",
"\"explicitly if you don't care about performance.\"",
")"
] | [
220,
4
] | [
233,
9
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.clear | (self) | Clears the cache. Keep in mind that not all caches support
completely clearing the cache.
:returns: Whether the cache has been cleared.
:rtype: boolean
| Clears the cache. Keep in mind that not all caches support
completely clearing the cache. | def clear(self):
"""Clears the cache. Keep in mind that not all caches support
completely clearing the cache.
:returns: Whether the cache has been cleared.
:rtype: boolean
"""
return True | [
"def",
"clear",
"(",
"self",
")",
":",
"return",
"True"
] | [
235,
4
] | [
242,
19
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.inc | (self, key, delta=1) | Increments the value of a key by `delta`. If the key does
not yet exist it is initialized with `delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to add.
:returns: The new value or ``None`` for backend errors.
| Increments the value of a key by `delta`. If the key does
not yet exist it is initialized with `delta`. | def inc(self, key, delta=1):
"""Increments the value of a key by `delta`. If the key does
not yet exist it is initialized with `delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to add.
:returns: The new value or ``None`` for backend errors.
"""
value = (self.get(key) or 0) + delta
return value if self.set(key, value) else None | [
"def",
"inc",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
")",
":",
"value",
"=",
"(",
"self",
".",
"get",
"(",
"key",
")",
"or",
"0",
")",
"+",
"delta",
"return",
"value",
"if",
"self",
".",
"set",
"(",
"key",
",",
"value",
")",
"else",
"None"
] | [
244,
4
] | [
255,
54
] | python | en | ['en', 'en', 'en'] | True |
BaseCache.dec | (self, key, delta=1) | Decrements the value of a key by `delta`. If the key does
not yet exist it is initialized with `-delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to subtract.
:returns: The new value or `None` for backend errors.
| Decrements the value of a key by `delta`. If the key does
not yet exist it is initialized with `-delta`. | def dec(self, key, delta=1):
"""Decrements the value of a key by `delta`. If the key does
not yet exist it is initialized with `-delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to subtract.
:returns: The new value or `None` for backend errors.
"""
value = (self.get(key) or 0) - delta
return value if self.set(key, value) else None | [
"def",
"dec",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
")",
":",
"value",
"=",
"(",
"self",
".",
"get",
"(",
"key",
")",
"or",
"0",
")",
"-",
"delta",
"return",
"value",
"if",
"self",
".",
"set",
"(",
"key",
",",
"value",
")",
"else",
"None"
] | [
257,
4
] | [
268,
54
] | python | en | ['en', 'en', 'en'] | True |
MemcachedCache.import_preferred_memcache_lib | (self, servers) | Returns an initialized memcache client. Used by the constructor. | Returns an initialized memcache client. Used by the constructor. | def import_preferred_memcache_lib(self, servers):
"""Returns an initialized memcache client. Used by the constructor."""
try:
import pylibmc
except ImportError:
pass
else:
return pylibmc.Client(servers)
try:
from google.appengine.api import memcache
except ImportError:
pass
else:
return memcache.Client()
try:
import memcache
except ImportError:
pass
else:
return memcache.Client(servers)
try:
import libmc
except ImportError:
pass
else:
return libmc.Client(servers) | [
"def",
"import_preferred_memcache_lib",
"(",
"self",
",",
"servers",
")",
":",
"try",
":",
"import",
"pylibmc",
"except",
"ImportError",
":",
"pass",
"else",
":",
"return",
"pylibmc",
".",
"Client",
"(",
"servers",
")",
"try",
":",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"memcache",
"except",
"ImportError",
":",
"pass",
"else",
":",
"return",
"memcache",
".",
"Client",
"(",
")",
"try",
":",
"import",
"memcache",
"except",
"ImportError",
":",
"pass",
"else",
":",
"return",
"memcache",
".",
"Client",
"(",
"servers",
")",
"try",
":",
"import",
"libmc",
"except",
"ImportError",
":",
"pass",
"else",
":",
"return",
"libmc",
".",
"Client",
"(",
"servers",
")"
] | [
499,
4
] | [
527,
40
] | python | en | ['en', 'en', 'en'] | True |
RedisCache.dump_object | (self, value) | Dumps an object into a string for redis. By default it serializes
integers as regular string and pickle dumps everything else.
| Dumps an object into a string for redis. By default it serializes
integers as regular string and pickle dumps everything else.
| def dump_object(self, value):
"""Dumps an object into a string for redis. By default it serializes
integers as regular string and pickle dumps everything else.
"""
t = type(value)
if t in integer_types:
return str(value).encode("ascii")
return b"!" + pickle.dumps(value) | [
"def",
"dump_object",
"(",
"self",
",",
"value",
")",
":",
"t",
"=",
"type",
"(",
"value",
")",
"if",
"t",
"in",
"integer_types",
":",
"return",
"str",
"(",
"value",
")",
".",
"encode",
"(",
"\"ascii\"",
")",
"return",
"b\"!\"",
"+",
"pickle",
".",
"dumps",
"(",
"value",
")"
] | [
603,
4
] | [
610,
41
] | python | en | ['en', 'en', 'en'] | True |
RedisCache.load_object | (self, value) | The reversal of :meth:`dump_object`. This might be called with
None.
| The reversal of :meth:`dump_object`. This might be called with
None.
| def load_object(self, value):
"""The reversal of :meth:`dump_object`. This might be called with
None.
"""
if value is None:
return None
if value.startswith(b"!"):
try:
return pickle.loads(value[1:])
except pickle.PickleError:
return None
try:
return int(value)
except ValueError:
# before 0.8 we did not have serialization. Still support that.
return value | [
"def",
"load_object",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"value",
".",
"startswith",
"(",
"b\"!\"",
")",
":",
"try",
":",
"return",
"pickle",
".",
"loads",
"(",
"value",
"[",
"1",
":",
"]",
")",
"except",
"pickle",
".",
"PickleError",
":",
"return",
"None",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"# before 0.8 we did not have serialization. Still support that.",
"return",
"value"
] | [
612,
4
] | [
627,
24
] | python | en | ['en', 'en', 'en'] | True |
FileSystemCache._list_dir | (self) | return a list of (fully qualified) cache filenames
| return a list of (fully qualified) cache filenames
| def _list_dir(self):
"""return a list of (fully qualified) cache filenames
"""
mgmt_files = [
self._get_filename(name).split("/")[-1] for name in (self._fs_count_file,)
]
return [
os.path.join(self._path, fn)
for fn in os.listdir(self._path)
if not fn.endswith(self._fs_transaction_suffix) and fn not in mgmt_files
] | [
"def",
"_list_dir",
"(",
"self",
")",
":",
"mgmt_files",
"=",
"[",
"self",
".",
"_get_filename",
"(",
"name",
")",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"for",
"name",
"in",
"(",
"self",
".",
"_fs_count_file",
",",
")",
"]",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"fn",
")",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"_path",
")",
"if",
"not",
"fn",
".",
"endswith",
"(",
"self",
".",
"_fs_transaction_suffix",
")",
"and",
"fn",
"not",
"in",
"mgmt_files",
"]"
] | [
755,
4
] | [
765,
9
] | python | en | ['en', 'en', 'en'] | True |
MatrixFactorization.__init__ | (self, train_file=None, test_file=None, output_file=None, factors=10, learn_rate=0.01, epochs=30,
delta=0.015, init_mean=0.1, init_stdev=0.1, baseline=False, bias_learn_rate=0.005, delta_bias=0.002,
stop_criteria=0.009, sep='\t', output_sep='\t', random_seed=None) |
Matrix Factorization for rating prediction
Matrix factorization models map both users and items to a joint latent factor space of dimensionality f,
such that user-item interactions are modeled as inner products in that space.
Usage::
>> MatrixFactorization(train, test).compute()
:param train_file: File which contains the train set. This file needs to have at least 3 columns
(user item feedback_value).
:type train_file: str
:param test_file: File which contains the test set. This file needs to have at least 3 columns
(user item feedback_value).
:type test_file: str, default None
:param output_file: File with dir to write the final predictions
:type output_file: str, default None
:param factors: Number of latent factors per user/item
:type factors: int, default 10
:param learn_rate: Learning rate (alpha)
:type learn_rate: float, default 0.05
:param epochs: Number of epochs over the training data
:type epochs: int, default 30
:param delta: Regularization value
:type delta: float, default 0.015
:param init_mean: Mean of the normal distribution used to initialize the latent factors
:type init_mean: float, default 0
:param init_stdev: Standard deviation of the normal distribution used to initialize the latent factors
:type init_stdev: float, default 0.1
:param baseline: Use the train data to build baselines (SVD Algorithm); else: Use only the mean
:type baseline: bool, default False
:param bias_learn_rate: Learning rate for baselines
:type bias_learn_rate: float, default 0.005
:param delta_bias: Regularization value for baselines
:type delta_bias: float, default 0.002
:param stop_criteria: Difference between errors for stopping criteria
:type stop_criteria: float, default 0.001
:param sep: Delimiter for input files
:type sep: str, default'\t'
:param output_sep: Delimiter for output file
:type output_sep: str, default '\t'
:param random_seed: Number of seed. Lock random numbers for reproducibility of experiments.
:type random_seed: int, default None
|
Matrix Factorization for rating prediction | def __init__(self, train_file=None, test_file=None, output_file=None, factors=10, learn_rate=0.01, epochs=30,
delta=0.015, init_mean=0.1, init_stdev=0.1, baseline=False, bias_learn_rate=0.005, delta_bias=0.002,
stop_criteria=0.009, sep='\t', output_sep='\t', random_seed=None):
"""
Matrix Factorization for rating prediction
Matrix factorization models map both users and items to a joint latent factor space of dimensionality f,
such that user-item interactions are modeled as inner products in that space.
Usage::
>> MatrixFactorization(train, test).compute()
:param train_file: File which contains the train set. This file needs to have at least 3 columns
(user item feedback_value).
:type train_file: str
:param test_file: File which contains the test set. This file needs to have at least 3 columns
(user item feedback_value).
:type test_file: str, default None
:param output_file: File with dir to write the final predictions
:type output_file: str, default None
:param factors: Number of latent factors per user/item
:type factors: int, default 10
:param learn_rate: Learning rate (alpha)
:type learn_rate: float, default 0.05
:param epochs: Number of epochs over the training data
:type epochs: int, default 30
:param delta: Regularization value
:type delta: float, default 0.015
:param init_mean: Mean of the normal distribution used to initialize the latent factors
:type init_mean: float, default 0
:param init_stdev: Standard deviation of the normal distribution used to initialize the latent factors
:type init_stdev: float, default 0.1
:param baseline: Use the train data to build baselines (SVD Algorithm); else: Use only the mean
:type baseline: bool, default False
:param bias_learn_rate: Learning rate for baselines
:type bias_learn_rate: float, default 0.005
:param delta_bias: Regularization value for baselines
:type delta_bias: float, default 0.002
:param stop_criteria: Difference between errors for stopping criteria
:type stop_criteria: float, default 0.001
:param sep: Delimiter for input files
:type sep: str, default'\t'
:param output_sep: Delimiter for output file
:type output_sep: str, default '\t'
:param random_seed: Number of seed. Lock random numbers for reproducibility of experiments.
:type random_seed: int, default None
"""
super(MatrixFactorization, self).__init__(train_file=train_file, test_file=test_file, output_file=output_file,
sep=sep, output_sep=output_sep)
self.recommender_name = 'Matrix Factorization'
self.epochs = epochs
self.learn_rate = learn_rate
self.delta = delta
self.factors = factors
self.init_mean = init_mean
self.init_stdev = init_stdev
self.baseline = baseline
self.bias_learn_rate = bias_learn_rate
self.delta_bias = delta_bias
self.stop_criteria = stop_criteria
if random_seed is not None:
np.random.seed(random_seed)
# internal vars
self.feedback_triples = None
self.p = None
self.q = None
self.bu = None
self.bi = None | [
"def",
"__init__",
"(",
"self",
",",
"train_file",
"=",
"None",
",",
"test_file",
"=",
"None",
",",
"output_file",
"=",
"None",
",",
"factors",
"=",
"10",
",",
"learn_rate",
"=",
"0.01",
",",
"epochs",
"=",
"30",
",",
"delta",
"=",
"0.015",
",",
"init_mean",
"=",
"0.1",
",",
"init_stdev",
"=",
"0.1",
",",
"baseline",
"=",
"False",
",",
"bias_learn_rate",
"=",
"0.005",
",",
"delta_bias",
"=",
"0.002",
",",
"stop_criteria",
"=",
"0.009",
",",
"sep",
"=",
"'\\t'",
",",
"output_sep",
"=",
"'\\t'",
",",
"random_seed",
"=",
"None",
")",
":",
"super",
"(",
"MatrixFactorization",
",",
"self",
")",
".",
"__init__",
"(",
"train_file",
"=",
"train_file",
",",
"test_file",
"=",
"test_file",
",",
"output_file",
"=",
"output_file",
",",
"sep",
"=",
"sep",
",",
"output_sep",
"=",
"output_sep",
")",
"self",
".",
"recommender_name",
"=",
"'Matrix Factorization'",
"self",
".",
"epochs",
"=",
"epochs",
"self",
".",
"learn_rate",
"=",
"learn_rate",
"self",
".",
"delta",
"=",
"delta",
"self",
".",
"factors",
"=",
"factors",
"self",
".",
"init_mean",
"=",
"init_mean",
"self",
".",
"init_stdev",
"=",
"init_stdev",
"self",
".",
"baseline",
"=",
"baseline",
"self",
".",
"bias_learn_rate",
"=",
"bias_learn_rate",
"self",
".",
"delta_bias",
"=",
"delta_bias",
"self",
".",
"stop_criteria",
"=",
"stop_criteria",
"if",
"random_seed",
"is",
"not",
"None",
":",
"np",
".",
"random",
".",
"seed",
"(",
"random_seed",
")",
"# internal vars",
"self",
".",
"feedback_triples",
"=",
"None",
"self",
".",
"p",
"=",
"None",
"self",
".",
"q",
"=",
"None",
"self",
".",
"bu",
"=",
"None",
"self",
".",
"bi",
"=",
"None"
] | [
24,
4
] | [
112,
22
] | python | en | ['en', 'error', 'th'] | False |
MatrixFactorization.init_model | (self) |
Method to treat and initialize the model
|
Method to treat and initialize the model | def init_model(self):
"""
Method to treat and initialize the model
"""
self.feedback_triples = []
# Map interaction with ids
for user in self.train_set['feedback']:
for item in self.train_set['feedback'][user]:
self.feedback_triples.append((self.user_to_user_id[user], self.item_to_item_id[item],
self.train_set['feedback'][user][item]))
# Initialize factors
self.create_factors() | [
"def",
"init_model",
"(",
"self",
")",
":",
"self",
".",
"feedback_triples",
"=",
"[",
"]",
"# Map interaction with ids",
"for",
"user",
"in",
"self",
".",
"train_set",
"[",
"'feedback'",
"]",
":",
"for",
"item",
"in",
"self",
".",
"train_set",
"[",
"'feedback'",
"]",
"[",
"user",
"]",
":",
"self",
".",
"feedback_triples",
".",
"append",
"(",
"(",
"self",
".",
"user_to_user_id",
"[",
"user",
"]",
",",
"self",
".",
"item_to_item_id",
"[",
"item",
"]",
",",
"self",
".",
"train_set",
"[",
"'feedback'",
"]",
"[",
"user",
"]",
"[",
"item",
"]",
")",
")",
"# Initialize factors",
"self",
".",
"create_factors",
"(",
")"
] | [
114,
4
] | [
128,
29
] | python | en | ['en', 'error', 'th'] | False |
MatrixFactorization.fit | (self) |
This method performs iterations of stochastic gradient ascent over the training data.
|
This method performs iterations of stochastic gradient ascent over the training data. | def fit(self):
"""
This method performs iterations of stochastic gradient ascent over the training data.
"""
rmse_old = .0
for epoch in range(self.epochs):
error_final = .0
for user, item, feedback in self.feedback_triples:
eui = feedback - self._predict_score(user, item, False)
error_final += (eui ** 2.0)
# Adjust the factors
u_f = self.p[user]
i_f = self.q[item]
# Compute factor updates
delta_u = np.subtract(np.multiply(eui, i_f), np.multiply(self.delta, u_f))
delta_i = np.subtract(np.multiply(eui, u_f), np.multiply(self.delta, i_f))
# apply updates
self.p[user] += np.multiply(self.learn_rate, delta_u)
self.q[item] += np.multiply(self.learn_rate, delta_i)
if self.baseline:
self.bu[user] += self.bias_learn_rate * (eui - self.delta_bias * self.bu[user])
self.bi[item] += self.bias_learn_rate * (eui - self.delta_bias * self.bi[item])
rmse_new = np.sqrt(error_final / self.train_set["number_interactions"])
if np.fabs(rmse_new - rmse_old) <= self.stop_criteria:
break
else:
rmse_old = rmse_new | [
"def",
"fit",
"(",
"self",
")",
":",
"rmse_old",
"=",
".0",
"for",
"epoch",
"in",
"range",
"(",
"self",
".",
"epochs",
")",
":",
"error_final",
"=",
".0",
"for",
"user",
",",
"item",
",",
"feedback",
"in",
"self",
".",
"feedback_triples",
":",
"eui",
"=",
"feedback",
"-",
"self",
".",
"_predict_score",
"(",
"user",
",",
"item",
",",
"False",
")",
"error_final",
"+=",
"(",
"eui",
"**",
"2.0",
")",
"# Adjust the factors",
"u_f",
"=",
"self",
".",
"p",
"[",
"user",
"]",
"i_f",
"=",
"self",
".",
"q",
"[",
"item",
"]",
"# Compute factor updates",
"delta_u",
"=",
"np",
".",
"subtract",
"(",
"np",
".",
"multiply",
"(",
"eui",
",",
"i_f",
")",
",",
"np",
".",
"multiply",
"(",
"self",
".",
"delta",
",",
"u_f",
")",
")",
"delta_i",
"=",
"np",
".",
"subtract",
"(",
"np",
".",
"multiply",
"(",
"eui",
",",
"u_f",
")",
",",
"np",
".",
"multiply",
"(",
"self",
".",
"delta",
",",
"i_f",
")",
")",
"# apply updates",
"self",
".",
"p",
"[",
"user",
"]",
"+=",
"np",
".",
"multiply",
"(",
"self",
".",
"learn_rate",
",",
"delta_u",
")",
"self",
".",
"q",
"[",
"item",
"]",
"+=",
"np",
".",
"multiply",
"(",
"self",
".",
"learn_rate",
",",
"delta_i",
")",
"if",
"self",
".",
"baseline",
":",
"self",
".",
"bu",
"[",
"user",
"]",
"+=",
"self",
".",
"bias_learn_rate",
"*",
"(",
"eui",
"-",
"self",
".",
"delta_bias",
"*",
"self",
".",
"bu",
"[",
"user",
"]",
")",
"self",
".",
"bi",
"[",
"item",
"]",
"+=",
"self",
".",
"bias_learn_rate",
"*",
"(",
"eui",
"-",
"self",
".",
"delta_bias",
"*",
"self",
".",
"bi",
"[",
"item",
"]",
")",
"rmse_new",
"=",
"np",
".",
"sqrt",
"(",
"error_final",
"/",
"self",
".",
"train_set",
"[",
"\"number_interactions\"",
"]",
")",
"if",
"np",
".",
"fabs",
"(",
"rmse_new",
"-",
"rmse_old",
")",
"<=",
"self",
".",
"stop_criteria",
":",
"break",
"else",
":",
"rmse_old",
"=",
"rmse_new"
] | [
130,
4
] | [
167,
35
] | python | en | ['en', 'error', 'th'] | False |
MatrixFactorization.create_factors | (self) |
This method create factors for users, items and bias
|
This method create factors for users, items and bias | def create_factors(self):
"""
This method create factors for users, items and bias
"""
self.p = np.random.normal(self.init_mean, self.init_stdev, (len(self.users), self.factors))
self.q = np.random.normal(self.init_mean, self.init_stdev, (len(self.items), self.factors))
if self.baseline:
self.bu = np.zeros(len(self.users), np.double)
self.bi = np.zeros(len(self.items), np.double) | [
"def",
"create_factors",
"(",
"self",
")",
":",
"self",
".",
"p",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"self",
".",
"init_mean",
",",
"self",
".",
"init_stdev",
",",
"(",
"len",
"(",
"self",
".",
"users",
")",
",",
"self",
".",
"factors",
")",
")",
"self",
".",
"q",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"self",
".",
"init_mean",
",",
"self",
".",
"init_stdev",
",",
"(",
"len",
"(",
"self",
".",
"items",
")",
",",
"self",
".",
"factors",
")",
")",
"if",
"self",
".",
"baseline",
":",
"self",
".",
"bu",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"self",
".",
"users",
")",
",",
"np",
".",
"double",
")",
"self",
".",
"bi",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"self",
".",
"items",
")",
",",
"np",
".",
"double",
")"
] | [
169,
4
] | [
180,
58
] | python | en | ['en', 'error', 'th'] | False |
MatrixFactorization._predict_score | (self, u, i, cond=True) |
Method to predict a single score for a pair (user, item)
:param u: User ID
:type u: int
:param i: Item ID
:type i: int
:param cond: Use max and min values of train set to limit score
:type cond: bool, default True
:return: Score generate for pair (user, item)
:rtype: float
|
Method to predict a single score for a pair (user, item) | def _predict_score(self, u, i, cond=True):
"""
Method to predict a single score for a pair (user, item)
:param u: User ID
:type u: int
:param i: Item ID
:type i: int
:param cond: Use max and min values of train set to limit score
:type cond: bool, default True
:return: Score generate for pair (user, item)
:rtype: float
"""
if self.baseline:
rui = self.train_set["mean_value"] + self.bu[u] + self.bi[i] + np.dot(self.p[u], self.q[i])
else:
rui = self.train_set['mean_value'] + np.dot(self.p[u], self.q[i])
if cond:
if rui > self.train_set["max_value"]:
rui = self.train_set["max_value"]
elif rui < self.train_set["min_value"]:
rui = self.train_set["min_value"]
return rui | [
"def",
"_predict_score",
"(",
"self",
",",
"u",
",",
"i",
",",
"cond",
"=",
"True",
")",
":",
"if",
"self",
".",
"baseline",
":",
"rui",
"=",
"self",
".",
"train_set",
"[",
"\"mean_value\"",
"]",
"+",
"self",
".",
"bu",
"[",
"u",
"]",
"+",
"self",
".",
"bi",
"[",
"i",
"]",
"+",
"np",
".",
"dot",
"(",
"self",
".",
"p",
"[",
"u",
"]",
",",
"self",
".",
"q",
"[",
"i",
"]",
")",
"else",
":",
"rui",
"=",
"self",
".",
"train_set",
"[",
"'mean_value'",
"]",
"+",
"np",
".",
"dot",
"(",
"self",
".",
"p",
"[",
"u",
"]",
",",
"self",
".",
"q",
"[",
"i",
"]",
")",
"if",
"cond",
":",
"if",
"rui",
">",
"self",
".",
"train_set",
"[",
"\"max_value\"",
"]",
":",
"rui",
"=",
"self",
".",
"train_set",
"[",
"\"max_value\"",
"]",
"elif",
"rui",
"<",
"self",
".",
"train_set",
"[",
"\"min_value\"",
"]",
":",
"rui",
"=",
"self",
".",
"train_set",
"[",
"\"min_value\"",
"]",
"return",
"rui"
] | [
182,
4
] | [
211,
18
] | python | en | ['en', 'error', 'th'] | False |
MatrixFactorization.predict | (self) |
This method computes a final rating for unknown pairs (user, item)
|
This method computes a final rating for unknown pairs (user, item) | def predict(self):
"""
This method computes a final rating for unknown pairs (user, item)
"""
if self.test_file is not None:
for user in self.test_set['users']:
for item in self.test_set['feedback'][user]:
self.predictions.append((user, item, self._predict_score(self.user_to_user_id[user],
self.item_to_item_id[item], True)))
else:
raise NotImplemented | [
"def",
"predict",
"(",
"self",
")",
":",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"for",
"user",
"in",
"self",
".",
"test_set",
"[",
"'users'",
"]",
":",
"for",
"item",
"in",
"self",
".",
"test_set",
"[",
"'feedback'",
"]",
"[",
"user",
"]",
":",
"self",
".",
"predictions",
".",
"append",
"(",
"(",
"user",
",",
"item",
",",
"self",
".",
"_predict_score",
"(",
"self",
".",
"user_to_user_id",
"[",
"user",
"]",
",",
"self",
".",
"item_to_item_id",
"[",
"item",
"]",
",",
"True",
")",
")",
")",
"else",
":",
"raise",
"NotImplemented"
] | [
213,
4
] | [
225,
32
] | python | en | ['en', 'error', 'th'] | False |
MatrixFactorization.compute | (self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t') |
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm
:param verbose: Print recommender and database information
:type verbose: bool, default True
:param metrics: List of evaluation measures
:type metrics: list, default None
:param verbose_evaluation: Print the evaluation results
:type verbose_evaluation: bool, default True
:param as_table: Print the evaluation results as table
:type as_table: bool, default False
:param table_sep: Delimiter for print results (only work with verbose=True and as_table=True)
:type table_sep: str, default '\t'
|
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm | def compute(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t'):
"""
Extends compute method from BaseRatingPrediction. Method to run recommender algorithm
:param verbose: Print recommender and database information
:type verbose: bool, default True
:param metrics: List of evaluation measures
:type metrics: list, default None
:param verbose_evaluation: Print the evaluation results
:type verbose_evaluation: bool, default True
:param as_table: Print the evaluation results as table
:type as_table: bool, default False
:param table_sep: Delimiter for print results (only work with verbose=True and as_table=True)
:type table_sep: str, default '\t'
"""
super(MatrixFactorization, self).compute(verbose=verbose)
if verbose:
self.init_model()
print("training_time:: %4f sec" % timed(self.fit))
if self.extra_info_header is not None:
print(self.extra_info_header)
print("prediction_time:: %4f sec" % timed(self.predict))
print('\n')
else:
# Execute all in silence without prints
self.init_model()
self.fit()
self.predict()
self.write_predictions()
if self.test_file is not None:
self.evaluate(metrics, verbose_evaluation, as_table=as_table, table_sep=table_sep) | [
"def",
"compute",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"metrics",
"=",
"None",
",",
"verbose_evaluation",
"=",
"True",
",",
"as_table",
"=",
"False",
",",
"table_sep",
"=",
"'\\t'",
")",
":",
"super",
"(",
"MatrixFactorization",
",",
"self",
")",
".",
"compute",
"(",
"verbose",
"=",
"verbose",
")",
"if",
"verbose",
":",
"self",
".",
"init_model",
"(",
")",
"print",
"(",
"\"training_time:: %4f sec\"",
"%",
"timed",
"(",
"self",
".",
"fit",
")",
")",
"if",
"self",
".",
"extra_info_header",
"is",
"not",
"None",
":",
"print",
"(",
"self",
".",
"extra_info_header",
")",
"print",
"(",
"\"prediction_time:: %4f sec\"",
"%",
"timed",
"(",
"self",
".",
"predict",
")",
")",
"print",
"(",
"'\\n'",
")",
"else",
":",
"# Execute all in silence without prints",
"self",
".",
"init_model",
"(",
")",
"self",
".",
"fit",
"(",
")",
"self",
".",
"predict",
"(",
")",
"self",
".",
"write_predictions",
"(",
")",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"self",
".",
"evaluate",
"(",
"metrics",
",",
"verbose_evaluation",
",",
"as_table",
"=",
"as_table",
",",
"table_sep",
"=",
"table_sep",
")"
] | [
227,
4
] | [
269,
94
] | python | en | ['en', 'error', 'th'] | False |
fast_exit | (code) | Exit without garbage collection, this speeds up exit by about 10ms for
things like bash completion.
| Exit without garbage collection, this speeds up exit by about 10ms for
things like bash completion.
| def fast_exit(code):
"""Exit without garbage collection, this speeds up exit by about 10ms for
things like bash completion.
"""
sys.stdout.flush()
sys.stderr.flush()
os._exit(code) | [
"def",
"fast_exit",
"(",
"code",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"os",
".",
"_exit",
"(",
"code",
")"
] | [
38,
0
] | [
44,
18
] | python | en | ['en', 'en', 'en'] | True |
_bashcomplete | (cmd, prog_name, complete_var=None) | Internal handler for the bash completion support. | Internal handler for the bash completion support. | def _bashcomplete(cmd, prog_name, complete_var=None):
"""Internal handler for the bash completion support."""
if complete_var is None:
complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
from ._bashcomplete import bashcomplete
if bashcomplete(cmd, prog_name, complete_var, complete_instr):
fast_exit(1) | [
"def",
"_bashcomplete",
"(",
"cmd",
",",
"prog_name",
",",
"complete_var",
"=",
"None",
")",
":",
"if",
"complete_var",
"is",
"None",
":",
"complete_var",
"=",
"'_%s_COMPLETE'",
"%",
"(",
"prog_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
".",
"upper",
"(",
")",
"complete_instr",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"complete_var",
")",
"if",
"not",
"complete_instr",
":",
"return",
"from",
".",
"_bashcomplete",
"import",
"bashcomplete",
"if",
"bashcomplete",
"(",
"cmd",
",",
"prog_name",
",",
"complete_var",
",",
"complete_instr",
")",
":",
"fast_exit",
"(",
"1",
")"
] | [
47,
0
] | [
57,
20
] | python | en | ['en', 'da', 'en'] | True |
augment_usage_errors | (ctx, param=None) | Context manager that attaches extra information to exceptions that
fly.
| Context manager that attaches extra information to exceptions that
fly.
| def augment_usage_errors(ctx, param=None):
"""Context manager that attaches extra information to exceptions that
fly.
"""
try:
yield
except BadParameter as e:
if e.ctx is None:
e.ctx = ctx
if param is not None and e.param is None:
e.param = param
raise
except UsageError as e:
if e.ctx is None:
e.ctx = ctx
raise | [
"def",
"augment_usage_errors",
"(",
"ctx",
",",
"param",
"=",
"None",
")",
":",
"try",
":",
"yield",
"except",
"BadParameter",
"as",
"e",
":",
"if",
"e",
".",
"ctx",
"is",
"None",
":",
"e",
".",
"ctx",
"=",
"ctx",
"if",
"param",
"is",
"not",
"None",
"and",
"e",
".",
"param",
"is",
"None",
":",
"e",
".",
"param",
"=",
"param",
"raise",
"except",
"UsageError",
"as",
"e",
":",
"if",
"e",
".",
"ctx",
"is",
"None",
":",
"e",
".",
"ctx",
"=",
"ctx",
"raise"
] | [
99,
0
] | [
114,
13
] | python | en | ['en', 'en', 'en'] | True |
iter_params_for_processing | (invocation_order, declaration_order) | Given a sequence of parameters in the order as should be considered
for processing and an iterable of parameters that exist, this returns
a list in the correct order as they should be processed.
| Given a sequence of parameters in the order as should be considered
for processing and an iterable of parameters that exist, this returns
a list in the correct order as they should be processed.
| def iter_params_for_processing(invocation_order, declaration_order):
"""Given a sequence of parameters in the order as should be considered
for processing and an iterable of parameters that exist, this returns
a list in the correct order as they should be processed.
"""
def sort_key(item):
try:
idx = invocation_order.index(item)
except ValueError:
idx = float('inf')
return (not item.is_eager, idx)
return sorted(declaration_order, key=sort_key) | [
"def",
"iter_params_for_processing",
"(",
"invocation_order",
",",
"declaration_order",
")",
":",
"def",
"sort_key",
"(",
"item",
")",
":",
"try",
":",
"idx",
"=",
"invocation_order",
".",
"index",
"(",
"item",
")",
"except",
"ValueError",
":",
"idx",
"=",
"float",
"(",
"'inf'",
")",
"return",
"(",
"not",
"item",
".",
"is_eager",
",",
"idx",
")",
"return",
"sorted",
"(",
"declaration_order",
",",
"key",
"=",
"sort_key",
")"
] | [
117,
0
] | [
129,
50
] | python | en | ['en', 'en', 'en'] | True |
Context.scope | (self, cleanup=True) | This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. The cleanup
functions are typically used for things such as closing file handles.
If the cleanup is intended the context object can also be directly
used as a context manager.
Example usage::
with ctx.scope():
assert get_current_context() is ctx
This is equivalent::
with ctx:
assert get_current_context() is ctx
.. versionadded:: 5.0
:param cleanup: controls if the cleanup functions should be run or
not. The default is to run these functions. In
some situations the context only wants to be
temporarily pushed in which case this can be disabled.
Nested pushes automatically defer the cleanup.
| This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. The cleanup
functions are typically used for things such as closing file handles. | def scope(self, cleanup=True):
"""This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. The cleanup
functions are typically used for things such as closing file handles.
If the cleanup is intended the context object can also be directly
used as a context manager.
Example usage::
with ctx.scope():
assert get_current_context() is ctx
This is equivalent::
with ctx:
assert get_current_context() is ctx
.. versionadded:: 5.0
:param cleanup: controls if the cleanup functions should be run or
not. The default is to run these functions. In
some situations the context only wants to be
temporarily pushed in which case this can be disabled.
Nested pushes automatically defer the cleanup.
"""
if not cleanup:
self._depth += 1
try:
with self as rv:
yield rv
finally:
if not cleanup:
self._depth -= 1 | [
"def",
"scope",
"(",
"self",
",",
"cleanup",
"=",
"True",
")",
":",
"if",
"not",
"cleanup",
":",
"self",
".",
"_depth",
"+=",
"1",
"try",
":",
"with",
"self",
"as",
"rv",
":",
"yield",
"rv",
"finally",
":",
"if",
"not",
"cleanup",
":",
"self",
".",
"_depth",
"-=",
"1"
] | [
354,
4
] | [
389,
32
] | python | en | ['en', 'en', 'en'] | True |
Context.meta | (self) | This is a dictionary which is shared with all the contexts
that are nested. It exists so that click utilities can store some
state here if they need to. It is however the responsibility of
that code to manage this dictionary well.
The keys are supposed to be unique dotted strings. For instance
module paths are a good choice for it. What is stored in there is
irrelevant for the operation of click. However what is important is
that code that places data here adheres to the general semantics of
the system.
Example usage::
LANG_KEY = __name__ + '.lang'
def set_language(value):
ctx = get_current_context()
ctx.meta[LANG_KEY] = value
def get_language():
return get_current_context().meta.get(LANG_KEY, 'en_US')
.. versionadded:: 5.0
| This is a dictionary which is shared with all the contexts
that are nested. It exists so that click utilities can store some
state here if they need to. It is however the responsibility of
that code to manage this dictionary well. | def meta(self):
"""This is a dictionary which is shared with all the contexts
that are nested. It exists so that click utilities can store some
state here if they need to. It is however the responsibility of
that code to manage this dictionary well.
The keys are supposed to be unique dotted strings. For instance
module paths are a good choice for it. What is stored in there is
irrelevant for the operation of click. However what is important is
that code that places data here adheres to the general semantics of
the system.
Example usage::
LANG_KEY = __name__ + '.lang'
def set_language(value):
ctx = get_current_context()
ctx.meta[LANG_KEY] = value
def get_language():
return get_current_context().meta.get(LANG_KEY, 'en_US')
.. versionadded:: 5.0
"""
return self._meta | [
"def",
"meta",
"(",
"self",
")",
":",
"return",
"self",
".",
"_meta"
] | [
392,
4
] | [
417,
25
] | python | en | ['en', 'en', 'en'] | True |
Context.make_formatter | (self) | Creates the formatter for the help and usage output. | Creates the formatter for the help and usage output. | def make_formatter(self):
"""Creates the formatter for the help and usage output."""
return HelpFormatter(width=self.terminal_width,
max_width=self.max_content_width) | [
"def",
"make_formatter",
"(",
"self",
")",
":",
"return",
"HelpFormatter",
"(",
"width",
"=",
"self",
".",
"terminal_width",
",",
"max_width",
"=",
"self",
".",
"max_content_width",
")"
] | [
419,
4
] | [
422,
62
] | python | en | ['en', 'en', 'en'] | True |
Context.call_on_close | (self, f) | This decorator remembers a function as callback that should be
executed when the context tears down. This is most useful to bind
resource handling to the script execution. For instance, file objects
opened by the :class:`File` type will register their close callbacks
here.
:param f: the function to execute on teardown.
| This decorator remembers a function as callback that should be
executed when the context tears down. This is most useful to bind
resource handling to the script execution. For instance, file objects
opened by the :class:`File` type will register their close callbacks
here. | def call_on_close(self, f):
"""This decorator remembers a function as callback that should be
executed when the context tears down. This is most useful to bind
resource handling to the script execution. For instance, file objects
opened by the :class:`File` type will register their close callbacks
here.
:param f: the function to execute on teardown.
"""
self._close_callbacks.append(f)
return f | [
"def",
"call_on_close",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"_close_callbacks",
".",
"append",
"(",
"f",
")",
"return",
"f"
] | [
424,
4
] | [
434,
16
] | python | en | ['en', 'en', 'en'] | True |
Context.close | (self) | Invokes all close callbacks. | Invokes all close callbacks. | def close(self):
"""Invokes all close callbacks."""
for cb in self._close_callbacks:
cb()
self._close_callbacks = [] | [
"def",
"close",
"(",
"self",
")",
":",
"for",
"cb",
"in",
"self",
".",
"_close_callbacks",
":",
"cb",
"(",
")",
"self",
".",
"_close_callbacks",
"=",
"[",
"]"
] | [
436,
4
] | [
440,
34
] | python | en | ['en', 'sm', 'en'] | True |
Context.command_path | (self) | The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root.
| The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root.
| def command_path(self):
"""The computed command path. This is used for the ``usage``
information on the help page. It's automatically created by
combining the info names of the chain of contexts to the root.
"""
rv = ''
if self.info_name is not None:
rv = self.info_name
if self.parent is not None:
rv = self.parent.command_path + ' ' + rv
return rv.lstrip() | [
"def",
"command_path",
"(",
"self",
")",
":",
"rv",
"=",
"''",
"if",
"self",
".",
"info_name",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"info_name",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"parent",
".",
"command_path",
"+",
"' '",
"+",
"rv",
"return",
"rv",
".",
"lstrip",
"(",
")"
] | [
443,
4
] | [
453,
26
] | python | en | ['en', 'en', 'en'] | True |
Context.find_root | (self) | Finds the outermost context. | Finds the outermost context. | def find_root(self):
"""Finds the outermost context."""
node = self
while node.parent is not None:
node = node.parent
return node | [
"def",
"find_root",
"(",
"self",
")",
":",
"node",
"=",
"self",
"while",
"node",
".",
"parent",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"parent",
"return",
"node"
] | [
455,
4
] | [
460,
19
] | python | en | ['en', 'en', 'en'] | True |
Context.find_object | (self, object_type) | Finds the closest object of a given type. | Finds the closest object of a given type. | def find_object(self, object_type):
"""Finds the closest object of a given type."""
node = self
while node is not None:
if isinstance(node.obj, object_type):
return node.obj
node = node.parent | [
"def",
"find_object",
"(",
"self",
",",
"object_type",
")",
":",
"node",
"=",
"self",
"while",
"node",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"node",
".",
"obj",
",",
"object_type",
")",
":",
"return",
"node",
".",
"obj",
"node",
"=",
"node",
".",
"parent"
] | [
462,
4
] | [
468,
30
] | python | en | ['en', 'en', 'en'] | True |
Context.ensure_object | (self, object_type) | Like :meth:`find_object` but sets the innermost object to a
new instance of `object_type` if it does not exist.
| Like :meth:`find_object` but sets the innermost object to a
new instance of `object_type` if it does not exist.
| def ensure_object(self, object_type):
"""Like :meth:`find_object` but sets the innermost object to a
new instance of `object_type` if it does not exist.
"""
rv = self.find_object(object_type)
if rv is None:
self.obj = rv = object_type()
return rv | [
"def",
"ensure_object",
"(",
"self",
",",
"object_type",
")",
":",
"rv",
"=",
"self",
".",
"find_object",
"(",
"object_type",
")",
"if",
"rv",
"is",
"None",
":",
"self",
".",
"obj",
"=",
"rv",
"=",
"object_type",
"(",
")",
"return",
"rv"
] | [
470,
4
] | [
477,
17
] | python | en | ['en', 'en', 'en'] | True |
Context.lookup_default | (self, name) | Looks up the default for a parameter name. This by default
looks into the :attr:`default_map` if available.
| Looks up the default for a parameter name. This by default
looks into the :attr:`default_map` if available.
| def lookup_default(self, name):
"""Looks up the default for a parameter name. This by default
looks into the :attr:`default_map` if available.
"""
if self.default_map is not None:
rv = self.default_map.get(name)
if callable(rv):
rv = rv()
return rv | [
"def",
"lookup_default",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"default_map",
"is",
"not",
"None",
":",
"rv",
"=",
"self",
".",
"default_map",
".",
"get",
"(",
"name",
")",
"if",
"callable",
"(",
"rv",
")",
":",
"rv",
"=",
"rv",
"(",
")",
"return",
"rv"
] | [
479,
4
] | [
487,
21
] | python | en | ['en', 'en', 'en'] | True |
Context.fail | (self, message) | Aborts the execution of the program with a specific error
message.
:param message: the error message to fail with.
| Aborts the execution of the program with a specific error
message. | def fail(self, message):
"""Aborts the execution of the program with a specific error
message.
:param message: the error message to fail with.
"""
raise UsageError(message, self) | [
"def",
"fail",
"(",
"self",
",",
"message",
")",
":",
"raise",
"UsageError",
"(",
"message",
",",
"self",
")"
] | [
489,
4
] | [
495,
39
] | python | en | ['en', 'en', 'en'] | True |
Context.abort | (self) | Aborts the script. | Aborts the script. | def abort(self):
"""Aborts the script."""
raise Abort() | [
"def",
"abort",
"(",
"self",
")",
":",
"raise",
"Abort",
"(",
")"
] | [
497,
4
] | [
499,
21
] | python | en | ['en', 'it', 'en'] | True |
Context.exit | (self, code=0) | Exits the application with a given exit code. | Exits the application with a given exit code. | def exit(self, code=0):
"""Exits the application with a given exit code."""
raise Exit(code) | [
"def",
"exit",
"(",
"self",
",",
"code",
"=",
"0",
")",
":",
"raise",
"Exit",
"(",
"code",
")"
] | [
501,
4
] | [
503,
24
] | python | en | ['en', 'en', 'en'] | True |
Context.get_usage | (self) | Helper method to get formatted usage string for the current
context and command.
| Helper method to get formatted usage string for the current
context and command.
| def get_usage(self):
"""Helper method to get formatted usage string for the current
context and command.
"""
return self.command.get_usage(self) | [
"def",
"get_usage",
"(",
"self",
")",
":",
"return",
"self",
".",
"command",
".",
"get_usage",
"(",
"self",
")"
] | [
505,
4
] | [
509,
43
] | python | en | ['en', 'en', 'en'] | True |
Context.get_help | (self) | Helper method to get formatted help page for the current
context and command.
| Helper method to get formatted help page for the current
context and command.
| def get_help(self):
"""Helper method to get formatted help page for the current
context and command.
"""
return self.command.get_help(self) | [
"def",
"get_help",
"(",
"self",
")",
":",
"return",
"self",
".",
"command",
".",
"get_help",
"(",
"self",
")"
] | [
511,
4
] | [
515,
42
] | python | en | ['en', 'en', 'en'] | True |
Context.invoke | (*args, **kwargs) | Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first argument is a click command object. In that case all
arguments are forwarded as well but proper click parameters
(options and click arguments) must be keyword arguments and Click
will fill in defaults.
Note that before Click 3.2 keyword arguments were not properly filled
in against the intention of this code and no context was created. For
more information about this change and why it was done in a bugfix
release see :ref:`upgrade-to-3.2`.
| Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method: | def invoke(*args, **kwargs):
"""Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first argument is a click command object. In that case all
arguments are forwarded as well but proper click parameters
(options and click arguments) must be keyword arguments and Click
will fill in defaults.
Note that before Click 3.2 keyword arguments were not properly filled
in against the intention of this code and no context was created. For
more information about this change and why it was done in a bugfix
release see :ref:`upgrade-to-3.2`.
"""
self, callback = args[:2]
ctx = self
# It's also possible to invoke another command which might or
# might not have a callback. In that case we also fill
# in defaults and make a new context for this command.
if isinstance(callback, Command):
other_cmd = callback
callback = other_cmd.callback
ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)
if callback is None:
raise TypeError('The given command does not have a '
'callback that can be invoked.')
for param in other_cmd.params:
if param.name not in kwargs and param.expose_value:
kwargs[param.name] = param.get_default(ctx)
args = args[2:]
with augment_usage_errors(self):
with ctx:
return callback(*args, **kwargs) | [
"def",
"invoke",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
",",
"callback",
"=",
"args",
"[",
":",
"2",
"]",
"ctx",
"=",
"self",
"# It's also possible to invoke another command which might or",
"# might not have a callback. In that case we also fill",
"# in defaults and make a new context for this command.",
"if",
"isinstance",
"(",
"callback",
",",
"Command",
")",
":",
"other_cmd",
"=",
"callback",
"callback",
"=",
"other_cmd",
".",
"callback",
"ctx",
"=",
"Context",
"(",
"other_cmd",
",",
"info_name",
"=",
"other_cmd",
".",
"name",
",",
"parent",
"=",
"self",
")",
"if",
"callback",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'The given command does not have a '",
"'callback that can be invoked.'",
")",
"for",
"param",
"in",
"other_cmd",
".",
"params",
":",
"if",
"param",
".",
"name",
"not",
"in",
"kwargs",
"and",
"param",
".",
"expose_value",
":",
"kwargs",
"[",
"param",
".",
"name",
"]",
"=",
"param",
".",
"get_default",
"(",
"ctx",
")",
"args",
"=",
"args",
"[",
"2",
":",
"]",
"with",
"augment_usage_errors",
"(",
"self",
")",
":",
"with",
"ctx",
":",
"return",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
517,
4
] | [
554,
48
] | python | en | ['en', 'en', 'en'] | True |
Context.forward | (*args, **kwargs) | Similar to :meth:`invoke` but fills in default keyword
arguments from the current context if the other command expects
it. This cannot invoke callbacks directly, only other commands.
| Similar to :meth:`invoke` but fills in default keyword
arguments from the current context if the other command expects
it. This cannot invoke callbacks directly, only other commands.
| def forward(*args, **kwargs):
"""Similar to :meth:`invoke` but fills in default keyword
arguments from the current context if the other command expects
it. This cannot invoke callbacks directly, only other commands.
"""
self, cmd = args[:2]
# It's also possible to invoke another command which might or
# might not have a callback.
if not isinstance(cmd, Command):
raise TypeError('Callback is not a command.')
for param in self.params:
if param not in kwargs:
kwargs[param] = self.params[param]
return self.invoke(cmd, **kwargs) | [
"def",
"forward",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
",",
"cmd",
"=",
"args",
"[",
":",
"2",
"]",
"# It's also possible to invoke another command which might or",
"# might not have a callback.",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"Command",
")",
":",
"raise",
"TypeError",
"(",
"'Callback is not a command.'",
")",
"for",
"param",
"in",
"self",
".",
"params",
":",
"if",
"param",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"param",
"]",
"=",
"self",
".",
"params",
"[",
"param",
"]",
"return",
"self",
".",
"invoke",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")"
] | [
556,
4
] | [
572,
41
] | python | en | ['en', 'id', 'en'] | True |
BaseCommand.make_context | (self, info_name, args, parent=None, **extra) | This function when given an info name and arguments will kick
off the parsing and create a new :class:`Context`. It does not
invoke the actual command callback though.
:param info_name: the info name for this invokation. Generally this
is the most descriptive name for the script or
command. For the toplevel script it's usually
the name of the script, for commands below it it's
the name of the script.
:param args: the arguments to parse as list of strings.
:param parent: the parent context if available.
:param extra: extra keyword arguments forwarded to the context
constructor.
| This function when given an info name and arguments will kick
off the parsing and create a new :class:`Context`. It does not
invoke the actual command callback though. | def make_context(self, info_name, args, parent=None, **extra):
"""This function when given an info name and arguments will kick
off the parsing and create a new :class:`Context`. It does not
invoke the actual command callback though.
:param info_name: the info name for this invokation. Generally this
is the most descriptive name for the script or
command. For the toplevel script it's usually
the name of the script, for commands below it it's
the name of the script.
:param args: the arguments to parse as list of strings.
:param parent: the parent context if available.
:param extra: extra keyword arguments forwarded to the context
constructor.
"""
for key, value in iteritems(self.context_settings):
if key not in extra:
extra[key] = value
ctx = Context(self, info_name=info_name, parent=parent, **extra)
with ctx.scope(cleanup=False):
self.parse_args(ctx, args)
return ctx | [
"def",
"make_context",
"(",
"self",
",",
"info_name",
",",
"args",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"context_settings",
")",
":",
"if",
"key",
"not",
"in",
"extra",
":",
"extra",
"[",
"key",
"]",
"=",
"value",
"ctx",
"=",
"Context",
"(",
"self",
",",
"info_name",
"=",
"info_name",
",",
"parent",
"=",
"parent",
",",
"*",
"*",
"extra",
")",
"with",
"ctx",
".",
"scope",
"(",
"cleanup",
"=",
"False",
")",
":",
"self",
".",
"parse_args",
"(",
"ctx",
",",
"args",
")",
"return",
"ctx"
] | [
620,
4
] | [
641,
18
] | python | en | ['en', 'en', 'en'] | True |
BaseCommand.parse_args | (self, ctx, args) | Given a context and a list of arguments this creates the parser
and parses the arguments, then modifies the context as necessary.
This is automatically invoked by :meth:`make_context`.
| Given a context and a list of arguments this creates the parser
and parses the arguments, then modifies the context as necessary.
This is automatically invoked by :meth:`make_context`.
| def parse_args(self, ctx, args):
"""Given a context and a list of arguments this creates the parser
and parses the arguments, then modifies the context as necessary.
This is automatically invoked by :meth:`make_context`.
"""
raise NotImplementedError('Base commands do not know how to parse '
'arguments.') | [
"def",
"parse_args",
"(",
"self",
",",
"ctx",
",",
"args",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Base commands do not know how to parse '",
"'arguments.'",
")"
] | [
643,
4
] | [
649,
47
] | python | en | ['en', 'en', 'en'] | True |
BaseCommand.invoke | (self, ctx) | Given a context, this invokes the command. The default
implementation is raising a not implemented error.
| Given a context, this invokes the command. The default
implementation is raising a not implemented error.
| def invoke(self, ctx):
"""Given a context, this invokes the command. The default
implementation is raising a not implemented error.
"""
raise NotImplementedError('Base commands are not invokable by default') | [
"def",
"invoke",
"(",
"self",
",",
"ctx",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Base commands are not invokable by default'",
")"
] | [
651,
4
] | [
655,
79
] | python | en | ['en', 'en', 'en'] | True |
BaseCommand.main | (self, args=None, prog_name=None, complete_var=None,
standalone_mode=True, **extra) | This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, ``SystemExit``
needs to be caught.
This method is also available by directly calling the instance of
a :class:`Command`.
.. versionadded:: 3.0
Added the `standalone_mode` flag to control the standalone mode.
:param args: the arguments that should be used for parsing. If not
provided, ``sys.argv[1:]`` is used.
:param prog_name: the program name that should be used. By default
the program name is constructed by taking the file
name from ``sys.argv[0]``.
:param complete_var: the environment variable that controls the
bash completion support. The default is
``"_<prog_name>_COMPLETE"`` with prog_name in
uppercase.
:param standalone_mode: the default behavior is to invoke the script
in standalone mode. Click will then
handle exceptions and convert them into
error messages and the function will never
return but shut down the interpreter. If
this is set to `False` they will be
propagated to the caller and the return
value of this function is the return value
of :meth:`invoke`.
:param extra: extra keyword arguments are forwarded to the context
constructor. See :class:`Context` for more information.
| This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, ``SystemExit``
needs to be caught. | def main(self, args=None, prog_name=None, complete_var=None,
standalone_mode=True, **extra):
"""This is the way to invoke a script with all the bells and
whistles as a command line application. This will always terminate
the application after a call. If this is not wanted, ``SystemExit``
needs to be caught.
This method is also available by directly calling the instance of
a :class:`Command`.
.. versionadded:: 3.0
Added the `standalone_mode` flag to control the standalone mode.
:param args: the arguments that should be used for parsing. If not
provided, ``sys.argv[1:]`` is used.
:param prog_name: the program name that should be used. By default
the program name is constructed by taking the file
name from ``sys.argv[0]``.
:param complete_var: the environment variable that controls the
bash completion support. The default is
``"_<prog_name>_COMPLETE"`` with prog_name in
uppercase.
:param standalone_mode: the default behavior is to invoke the script
in standalone mode. Click will then
handle exceptions and convert them into
error messages and the function will never
return but shut down the interpreter. If
this is set to `False` they will be
propagated to the caller and the return
value of this function is the return value
of :meth:`invoke`.
:param extra: extra keyword arguments are forwarded to the context
constructor. See :class:`Context` for more information.
"""
# If we are in Python 3, we will verify that the environment is
# sane at this point or reject further execution to avoid a
# broken script.
if not PY2:
_verify_python3_env()
else:
_check_for_unicode_literals()
if args is None:
args = get_os_args()
else:
args = list(args)
if prog_name is None:
prog_name = make_str(os.path.basename(
sys.argv and sys.argv[0] or __file__))
# Hook for the Bash completion. This only activates if the Bash
# completion is actually enabled, otherwise this is quite a fast
# noop.
_bashcomplete(self, prog_name, complete_var)
try:
try:
with self.make_context(prog_name, args, **extra) as ctx:
rv = self.invoke(ctx)
if not standalone_mode:
return rv
# it's not safe to `ctx.exit(rv)` here!
# note that `rv` may actually contain data like "1" which
# has obvious effects
# more subtle case: `rv=[None, None]` can come out of
# chained commands which all returned `None` -- so it's not
# even always obvious that `rv` indicates success/failure
# by its truthiness/falsiness
ctx.exit()
except (EOFError, KeyboardInterrupt):
echo(file=sys.stderr)
raise Abort()
except ClickException as e:
if not standalone_mode:
raise
e.show()
sys.exit(e.exit_code)
except IOError as e:
if e.errno == errno.EPIPE:
sys.stdout = PacifyFlushWrapper(sys.stdout)
sys.stderr = PacifyFlushWrapper(sys.stderr)
sys.exit(1)
else:
raise
except Exit as e:
if standalone_mode:
sys.exit(e.exit_code)
else:
# in non-standalone mode, return the exit code
# note that this is only reached if `self.invoke` above raises
# an Exit explicitly -- thus bypassing the check there which
# would return its result
# the results of non-standalone execution may therefore be
# somewhat ambiguous: if there are codepaths which lead to
# `ctx.exit(1)` and to `return 1`, the caller won't be able to
# tell the difference between the two
return e.exit_code
except Abort:
if not standalone_mode:
raise
echo('Aborted!', file=sys.stderr)
sys.exit(1) | [
"def",
"main",
"(",
"self",
",",
"args",
"=",
"None",
",",
"prog_name",
"=",
"None",
",",
"complete_var",
"=",
"None",
",",
"standalone_mode",
"=",
"True",
",",
"*",
"*",
"extra",
")",
":",
"# If we are in Python 3, we will verify that the environment is",
"# sane at this point or reject further execution to avoid a",
"# broken script.",
"if",
"not",
"PY2",
":",
"_verify_python3_env",
"(",
")",
"else",
":",
"_check_for_unicode_literals",
"(",
")",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"get_os_args",
"(",
")",
"else",
":",
"args",
"=",
"list",
"(",
"args",
")",
"if",
"prog_name",
"is",
"None",
":",
"prog_name",
"=",
"make_str",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"and",
"sys",
".",
"argv",
"[",
"0",
"]",
"or",
"__file__",
")",
")",
"# Hook for the Bash completion. This only activates if the Bash",
"# completion is actually enabled, otherwise this is quite a fast",
"# noop.",
"_bashcomplete",
"(",
"self",
",",
"prog_name",
",",
"complete_var",
")",
"try",
":",
"try",
":",
"with",
"self",
".",
"make_context",
"(",
"prog_name",
",",
"args",
",",
"*",
"*",
"extra",
")",
"as",
"ctx",
":",
"rv",
"=",
"self",
".",
"invoke",
"(",
"ctx",
")",
"if",
"not",
"standalone_mode",
":",
"return",
"rv",
"# it's not safe to `ctx.exit(rv)` here!",
"# note that `rv` may actually contain data like \"1\" which",
"# has obvious effects",
"# more subtle case: `rv=[None, None]` can come out of",
"# chained commands which all returned `None` -- so it's not",
"# even always obvious that `rv` indicates success/failure",
"# by its truthiness/falsiness",
"ctx",
".",
"exit",
"(",
")",
"except",
"(",
"EOFError",
",",
"KeyboardInterrupt",
")",
":",
"echo",
"(",
"file",
"=",
"sys",
".",
"stderr",
")",
"raise",
"Abort",
"(",
")",
"except",
"ClickException",
"as",
"e",
":",
"if",
"not",
"standalone_mode",
":",
"raise",
"e",
".",
"show",
"(",
")",
"sys",
".",
"exit",
"(",
"e",
".",
"exit_code",
")",
"except",
"IOError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EPIPE",
":",
"sys",
".",
"stdout",
"=",
"PacifyFlushWrapper",
"(",
"sys",
".",
"stdout",
")",
"sys",
".",
"stderr",
"=",
"PacifyFlushWrapper",
"(",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"else",
":",
"raise",
"except",
"Exit",
"as",
"e",
":",
"if",
"standalone_mode",
":",
"sys",
".",
"exit",
"(",
"e",
".",
"exit_code",
")",
"else",
":",
"# in non-standalone mode, return the exit code",
"# note that this is only reached if `self.invoke` above raises",
"# an Exit explicitly -- thus bypassing the check there which",
"# would return its result",
"# the results of non-standalone execution may therefore be",
"# somewhat ambiguous: if there are codepaths which lead to",
"# `ctx.exit(1)` and to `return 1`, the caller won't be able to",
"# tell the difference between the two",
"return",
"e",
".",
"exit_code",
"except",
"Abort",
":",
"if",
"not",
"standalone_mode",
":",
"raise",
"echo",
"(",
"'Aborted!'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | [
657,
4
] | [
759,
23
] | python | en | ['en', 'en', 'en'] | True |
BaseCommand.__call__ | (self, *args, **kwargs) | Alias for :meth:`main`. | Alias for :meth:`main`. | def __call__(self, *args, **kwargs):
"""Alias for :meth:`main`."""
return self.main(*args, **kwargs) | [
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"main",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
761,
4
] | [
763,
41
] | python | en | ['es', 'hmn', 'en'] | False |
Command.format_usage | (self, ctx, formatter) | Writes the usage line into the formatter. | Writes the usage line into the formatter. | def format_usage(self, ctx, formatter):
"""Writes the usage line into the formatter."""
pieces = self.collect_usage_pieces(ctx)
formatter.write_usage(ctx.command_path, ' '.join(pieces)) | [
"def",
"format_usage",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"pieces",
"=",
"self",
".",
"collect_usage_pieces",
"(",
"ctx",
")",
"formatter",
".",
"write_usage",
"(",
"ctx",
".",
"command_path",
",",
"' '",
".",
"join",
"(",
"pieces",
")",
")"
] | [
829,
4
] | [
832,
65
] | python | en | ['en', 'en', 'en'] | True |
Command.collect_usage_pieces | (self, ctx) | Returns all the pieces that go into the usage line and returns
it as a list of strings.
| Returns all the pieces that go into the usage line and returns
it as a list of strings.
| def collect_usage_pieces(self, ctx):
"""Returns all the pieces that go into the usage line and returns
it as a list of strings.
"""
rv = [self.options_metavar]
for param in self.get_params(ctx):
rv.extend(param.get_usage_pieces(ctx))
return rv | [
"def",
"collect_usage_pieces",
"(",
"self",
",",
"ctx",
")",
":",
"rv",
"=",
"[",
"self",
".",
"options_metavar",
"]",
"for",
"param",
"in",
"self",
".",
"get_params",
"(",
"ctx",
")",
":",
"rv",
".",
"extend",
"(",
"param",
".",
"get_usage_pieces",
"(",
"ctx",
")",
")",
"return",
"rv"
] | [
834,
4
] | [
841,
17
] | python | en | ['en', 'en', 'en'] | True |
Command.get_help_option_names | (self, ctx) | Returns the names for the help option. | Returns the names for the help option. | def get_help_option_names(self, ctx):
"""Returns the names for the help option."""
all_names = set(ctx.help_option_names)
for param in self.params:
all_names.difference_update(param.opts)
all_names.difference_update(param.secondary_opts)
return all_names | [
"def",
"get_help_option_names",
"(",
"self",
",",
"ctx",
")",
":",
"all_names",
"=",
"set",
"(",
"ctx",
".",
"help_option_names",
")",
"for",
"param",
"in",
"self",
".",
"params",
":",
"all_names",
".",
"difference_update",
"(",
"param",
".",
"opts",
")",
"all_names",
".",
"difference_update",
"(",
"param",
".",
"secondary_opts",
")",
"return",
"all_names"
] | [
843,
4
] | [
849,
24
] | python | en | ['en', 'en', 'en'] | True |
Command.get_help_option | (self, ctx) | Returns the help option object. | Returns the help option object. | def get_help_option(self, ctx):
"""Returns the help option object."""
help_options = self.get_help_option_names(ctx)
if not help_options or not self.add_help_option:
return
def show_help(ctx, param, value):
if value and not ctx.resilient_parsing:
echo(ctx.get_help(), color=ctx.color)
ctx.exit()
return Option(help_options, is_flag=True,
is_eager=True, expose_value=False,
callback=show_help,
help='Show this message and exit.') | [
"def",
"get_help_option",
"(",
"self",
",",
"ctx",
")",
":",
"help_options",
"=",
"self",
".",
"get_help_option_names",
"(",
"ctx",
")",
"if",
"not",
"help_options",
"or",
"not",
"self",
".",
"add_help_option",
":",
"return",
"def",
"show_help",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"value",
"and",
"not",
"ctx",
".",
"resilient_parsing",
":",
"echo",
"(",
"ctx",
".",
"get_help",
"(",
")",
",",
"color",
"=",
"ctx",
".",
"color",
")",
"ctx",
".",
"exit",
"(",
")",
"return",
"Option",
"(",
"help_options",
",",
"is_flag",
"=",
"True",
",",
"is_eager",
"=",
"True",
",",
"expose_value",
"=",
"False",
",",
"callback",
"=",
"show_help",
",",
"help",
"=",
"'Show this message and exit.'",
")"
] | [
851,
4
] | [
864,
57
] | python | en | ['en', 'en', 'en'] | True |
Command.make_parser | (self, ctx) | Creates the underlying option parser for this command. | Creates the underlying option parser for this command. | def make_parser(self, ctx):
"""Creates the underlying option parser for this command."""
parser = OptionParser(ctx)
for param in self.get_params(ctx):
param.add_to_parser(parser, ctx)
return parser | [
"def",
"make_parser",
"(",
"self",
",",
"ctx",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"ctx",
")",
"for",
"param",
"in",
"self",
".",
"get_params",
"(",
"ctx",
")",
":",
"param",
".",
"add_to_parser",
"(",
"parser",
",",
"ctx",
")",
"return",
"parser"
] | [
866,
4
] | [
871,
21
] | python | en | ['en', 'en', 'en'] | True |
Command.get_help | (self, ctx) | Formats the help into a string and returns it. This creates a
formatter and will call into the following formatting methods:
| Formats the help into a string and returns it. This creates a
formatter and will call into the following formatting methods:
| def get_help(self, ctx):
"""Formats the help into a string and returns it. This creates a
formatter and will call into the following formatting methods:
"""
formatter = ctx.make_formatter()
self.format_help(ctx, formatter)
return formatter.getvalue().rstrip('\n') | [
"def",
"get_help",
"(",
"self",
",",
"ctx",
")",
":",
"formatter",
"=",
"ctx",
".",
"make_formatter",
"(",
")",
"self",
".",
"format_help",
"(",
"ctx",
",",
"formatter",
")",
"return",
"formatter",
".",
"getvalue",
"(",
")",
".",
"rstrip",
"(",
"'\\n'",
")"
] | [
873,
4
] | [
879,
48
] | python | en | ['en', 'en', 'en'] | True |
Command.get_short_help_str | (self, limit=45) | Gets short help for the command or makes it by shortening the long help string. | Gets short help for the command or makes it by shortening the long help string. | def get_short_help_str(self, limit=45):
"""Gets short help for the command or makes it by shortening the long help string."""
return self.short_help or self.help and make_default_short_help(self.help, limit) or '' | [
"def",
"get_short_help_str",
"(",
"self",
",",
"limit",
"=",
"45",
")",
":",
"return",
"self",
".",
"short_help",
"or",
"self",
".",
"help",
"and",
"make_default_short_help",
"(",
"self",
".",
"help",
",",
"limit",
")",
"or",
"''"
] | [
881,
4
] | [
883,
95
] | python | en | ['en', 'en', 'en'] | True |
Command.format_help | (self, ctx, formatter) | Writes the help into the formatter if it exists.
This calls into the following methods:
- :meth:`format_usage`
- :meth:`format_help_text`
- :meth:`format_options`
- :meth:`format_epilog`
| Writes the help into the formatter if it exists. | def format_help(self, ctx, formatter):
"""Writes the help into the formatter if it exists.
This calls into the following methods:
- :meth:`format_usage`
- :meth:`format_help_text`
- :meth:`format_options`
- :meth:`format_epilog`
"""
self.format_usage(ctx, formatter)
self.format_help_text(ctx, formatter)
self.format_options(ctx, formatter)
self.format_epilog(ctx, formatter) | [
"def",
"format_help",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"self",
".",
"format_usage",
"(",
"ctx",
",",
"formatter",
")",
"self",
".",
"format_help_text",
"(",
"ctx",
",",
"formatter",
")",
"self",
".",
"format_options",
"(",
"ctx",
",",
"formatter",
")",
"self",
".",
"format_epilog",
"(",
"ctx",
",",
"formatter",
")"
] | [
885,
4
] | [
898,
42
] | python | en | ['en', 'en', 'en'] | True |
Command.format_help_text | (self, ctx, formatter) | Writes the help text to the formatter if it exists. | Writes the help text to the formatter if it exists. | def format_help_text(self, ctx, formatter):
"""Writes the help text to the formatter if it exists."""
if self.help:
formatter.write_paragraph()
with formatter.indentation():
help_text = self.help
if self.deprecated:
help_text += DEPRECATED_HELP_NOTICE
formatter.write_text(help_text)
elif self.deprecated:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(DEPRECATED_HELP_NOTICE) | [
"def",
"format_help_text",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"if",
"self",
".",
"help",
":",
"formatter",
".",
"write_paragraph",
"(",
")",
"with",
"formatter",
".",
"indentation",
"(",
")",
":",
"help_text",
"=",
"self",
".",
"help",
"if",
"self",
".",
"deprecated",
":",
"help_text",
"+=",
"DEPRECATED_HELP_NOTICE",
"formatter",
".",
"write_text",
"(",
"help_text",
")",
"elif",
"self",
".",
"deprecated",
":",
"formatter",
".",
"write_paragraph",
"(",
")",
"with",
"formatter",
".",
"indentation",
"(",
")",
":",
"formatter",
".",
"write_text",
"(",
"DEPRECATED_HELP_NOTICE",
")"
] | [
900,
4
] | [
912,
60
] | python | en | ['en', 'en', 'en'] | True |
Command.format_options | (self, ctx, formatter) | Writes all the options into the formatter if they exist. | Writes all the options into the formatter if they exist. | def format_options(self, ctx, formatter):
"""Writes all the options into the formatter if they exist."""
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
opts.append(rv)
if opts:
with formatter.section('Options'):
formatter.write_dl(opts) | [
"def",
"format_options",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"opts",
"=",
"[",
"]",
"for",
"param",
"in",
"self",
".",
"get_params",
"(",
"ctx",
")",
":",
"rv",
"=",
"param",
".",
"get_help_record",
"(",
"ctx",
")",
"if",
"rv",
"is",
"not",
"None",
":",
"opts",
".",
"append",
"(",
"rv",
")",
"if",
"opts",
":",
"with",
"formatter",
".",
"section",
"(",
"'Options'",
")",
":",
"formatter",
".",
"write_dl",
"(",
"opts",
")"
] | [
914,
4
] | [
924,
40
] | python | en | ['en', 'en', 'en'] | True |
Command.format_epilog | (self, ctx, formatter) | Writes the epilog into the formatter if it exists. | Writes the epilog into the formatter if it exists. | def format_epilog(self, ctx, formatter):
"""Writes the epilog into the formatter if it exists."""
if self.epilog:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(self.epilog) | [
"def",
"format_epilog",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"if",
"self",
".",
"epilog",
":",
"formatter",
".",
"write_paragraph",
"(",
")",
"with",
"formatter",
".",
"indentation",
"(",
")",
":",
"formatter",
".",
"write_text",
"(",
"self",
".",
"epilog",
")"
] | [
926,
4
] | [
931,
49
] | python | en | ['en', 'en', 'en'] | True |
Command.invoke | (self, ctx) | Given a context, this invokes the attached callback (if it exists)
in the right way.
| Given a context, this invokes the attached callback (if it exists)
in the right way.
| def invoke(self, ctx):
"""Given a context, this invokes the attached callback (if it exists)
in the right way.
"""
_maybe_show_deprecated_notice(self)
if self.callback is not None:
return ctx.invoke(self.callback, **ctx.params) | [
"def",
"invoke",
"(",
"self",
",",
"ctx",
")",
":",
"_maybe_show_deprecated_notice",
"(",
"self",
")",
"if",
"self",
".",
"callback",
"is",
"not",
"None",
":",
"return",
"ctx",
".",
"invoke",
"(",
"self",
".",
"callback",
",",
"*",
"*",
"ctx",
".",
"params",
")"
] | [
949,
4
] | [
955,
58
] | python | en | ['en', 'en', 'en'] | True |
MultiCommand.resultcallback | (self, replace=False) | Adds a result callback to the chain command. By default if a
result callback is already registered this will chain them but
this can be disabled with the `replace` parameter. The result
callback is invoked with the return value of the subcommand
(or the list of return values from all subcommands if chaining
is enabled) as well as the parameters as they would be passed
to the main callback.
Example::
@click.group()
@click.option('-i', '--input', default=23)
def cli(input):
return 42
@cli.resultcallback()
def process_result(result, input):
return result + input
.. versionadded:: 3.0
:param replace: if set to `True` an already existing result
callback will be removed.
| Adds a result callback to the chain command. By default if a
result callback is already registered this will chain them but
this can be disabled with the `replace` parameter. The result
callback is invoked with the return value of the subcommand
(or the list of return values from all subcommands if chaining
is enabled) as well as the parameters as they would be passed
to the main callback. | def resultcallback(self, replace=False):
"""Adds a result callback to the chain command. By default if a
result callback is already registered this will chain them but
this can be disabled with the `replace` parameter. The result
callback is invoked with the return value of the subcommand
(or the list of return values from all subcommands if chaining
is enabled) as well as the parameters as they would be passed
to the main callback.
Example::
@click.group()
@click.option('-i', '--input', default=23)
def cli(input):
return 42
@cli.resultcallback()
def process_result(result, input):
return result + input
.. versionadded:: 3.0
:param replace: if set to `True` an already existing result
callback will be removed.
"""
def decorator(f):
old_callback = self.result_callback
if old_callback is None or replace:
self.result_callback = f
return f
def function(__value, *args, **kwargs):
return f(old_callback(__value, *args, **kwargs),
*args, **kwargs)
self.result_callback = rv = update_wrapper(function, f)
return rv
return decorator | [
"def",
"resultcallback",
"(",
"self",
",",
"replace",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"old_callback",
"=",
"self",
".",
"result_callback",
"if",
"old_callback",
"is",
"None",
"or",
"replace",
":",
"self",
".",
"result_callback",
"=",
"f",
"return",
"f",
"def",
"function",
"(",
"__value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"f",
"(",
"old_callback",
"(",
"__value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"result_callback",
"=",
"rv",
"=",
"update_wrapper",
"(",
"function",
",",
"f",
")",
"return",
"rv",
"return",
"decorator"
] | [
1018,
4
] | [
1053,
24
] | python | en | ['en', 'en', 'en'] | True |
MultiCommand.format_commands | (self, ctx, formatter) | Extra format methods for multi methods that adds all the commands
after the options.
| Extra format methods for multi methods that adds all the commands
after the options.
| def format_commands(self, ctx, formatter):
"""Extra format methods for multi methods that adds all the commands
after the options.
"""
commands = []
for subcommand in self.list_commands(ctx):
cmd = self.get_command(ctx, subcommand)
# What is this, the tool lied about a command. Ignore it
if cmd is None:
continue
if cmd.hidden:
continue
commands.append((subcommand, cmd))
# allow for 3 times the default spacing
if len(commands):
limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)
rows = []
for subcommand, cmd in commands:
help = cmd.get_short_help_str(limit)
rows.append((subcommand, help))
if rows:
with formatter.section('Commands'):
formatter.write_dl(rows) | [
"def",
"format_commands",
"(",
"self",
",",
"ctx",
",",
"formatter",
")",
":",
"commands",
"=",
"[",
"]",
"for",
"subcommand",
"in",
"self",
".",
"list_commands",
"(",
"ctx",
")",
":",
"cmd",
"=",
"self",
".",
"get_command",
"(",
"ctx",
",",
"subcommand",
")",
"# What is this, the tool lied about a command. Ignore it",
"if",
"cmd",
"is",
"None",
":",
"continue",
"if",
"cmd",
".",
"hidden",
":",
"continue",
"commands",
".",
"append",
"(",
"(",
"subcommand",
",",
"cmd",
")",
")",
"# allow for 3 times the default spacing",
"if",
"len",
"(",
"commands",
")",
":",
"limit",
"=",
"formatter",
".",
"width",
"-",
"6",
"-",
"max",
"(",
"len",
"(",
"cmd",
"[",
"0",
"]",
")",
"for",
"cmd",
"in",
"commands",
")",
"rows",
"=",
"[",
"]",
"for",
"subcommand",
",",
"cmd",
"in",
"commands",
":",
"help",
"=",
"cmd",
".",
"get_short_help_str",
"(",
"limit",
")",
"rows",
".",
"append",
"(",
"(",
"subcommand",
",",
"help",
")",
")",
"if",
"rows",
":",
"with",
"formatter",
".",
"section",
"(",
"'Commands'",
")",
":",
"formatter",
".",
"write_dl",
"(",
"rows",
")"
] | [
1055,
4
] | [
1081,
44
] | python | en | ['en', 'en', 'en'] | True |
MultiCommand.get_command | (self, ctx, cmd_name) | Given a context and a command name, this returns a
:class:`Command` object if it exists or returns `None`.
| Given a context and a command name, this returns a
:class:`Command` object if it exists or returns `None`.
| def get_command(self, ctx, cmd_name):
"""Given a context and a command name, this returns a
:class:`Command` object if it exists or returns `None`.
"""
raise NotImplementedError() | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
1191,
4
] | [
1195,
35
] | python | en | ['en', 'en', 'en'] | True |
MultiCommand.list_commands | (self, ctx) | Returns a list of subcommand names in the order they should
appear.
| Returns a list of subcommand names in the order they should
appear.
| def list_commands(self, ctx):
"""Returns a list of subcommand names in the order they should
appear.
"""
return [] | [
"def",
"list_commands",
"(",
"self",
",",
"ctx",
")",
":",
"return",
"[",
"]"
] | [
1197,
4
] | [
1201,
17
] | python | en | ['en', 'en', 'en'] | True |
Group.add_command | (self, cmd, name=None) | Registers another :class:`Command` with this group. If the name
is not provided, the name of the command is used.
| Registers another :class:`Command` with this group. If the name
is not provided, the name of the command is used.
| def add_command(self, cmd, name=None):
"""Registers another :class:`Command` with this group. If the name
is not provided, the name of the command is used.
"""
name = name or cmd.name
if name is None:
raise TypeError('Command has no name.')
_check_multicommand(self, name, cmd, register=True)
self.commands[name] = cmd | [
"def",
"add_command",
"(",
"self",
",",
"cmd",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"cmd",
".",
"name",
"if",
"name",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Command has no name.'",
")",
"_check_multicommand",
"(",
"self",
",",
"name",
",",
"cmd",
",",
"register",
"=",
"True",
")",
"self",
".",
"commands",
"[",
"name",
"]",
"=",
"cmd"
] | [
1216,
4
] | [
1224,
33
] | python | en | ['en', 'en', 'en'] | True |
Group.command | (self, *args, **kwargs) | A shortcut decorator for declaring and attaching a command to
the group. This takes the same arguments as :func:`command` but
immediately registers the created command with this instance by
calling into :meth:`add_command`.
| A shortcut decorator for declaring and attaching a command to
the group. This takes the same arguments as :func:`command` but
immediately registers the created command with this instance by
calling into :meth:`add_command`.
| def command(self, *args, **kwargs):
"""A shortcut decorator for declaring and attaching a command to
the group. This takes the same arguments as :func:`command` but
immediately registers the created command with this instance by
calling into :meth:`add_command`.
"""
def decorator(f):
cmd = command(*args, **kwargs)(f)
self.add_command(cmd)
return cmd
return decorator | [
"def",
"command",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"cmd",
"=",
"command",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"(",
"f",
")",
"self",
".",
"add_command",
"(",
"cmd",
")",
"return",
"cmd",
"return",
"decorator"
] | [
1226,
4
] | [
1236,
24
] | python | en | ['en', 'en', 'en'] | True |
Group.group | (self, *args, **kwargs) | A shortcut decorator for declaring and attaching a group to
the group. This takes the same arguments as :func:`group` but
immediately registers the created command with this instance by
calling into :meth:`add_command`.
| A shortcut decorator for declaring and attaching a group to
the group. This takes the same arguments as :func:`group` but
immediately registers the created command with this instance by
calling into :meth:`add_command`.
| def group(self, *args, **kwargs):
"""A shortcut decorator for declaring and attaching a group to
the group. This takes the same arguments as :func:`group` but
immediately registers the created command with this instance by
calling into :meth:`add_command`.
"""
def decorator(f):
cmd = group(*args, **kwargs)(f)
self.add_command(cmd)
return cmd
return decorator | [
"def",
"group",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"cmd",
"=",
"group",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"(",
"f",
")",
"self",
".",
"add_command",
"(",
"cmd",
")",
"return",
"cmd",
"return",
"decorator"
] | [
1238,
4
] | [
1248,
24
] | python | en | ['en', 'en', 'en'] | True |
CommandCollection.add_source | (self, multi_cmd) | Adds a new multi command to the chain dispatcher. | Adds a new multi command to the chain dispatcher. | def add_source(self, multi_cmd):
"""Adds a new multi command to the chain dispatcher."""
self.sources.append(multi_cmd) | [
"def",
"add_source",
"(",
"self",
",",
"multi_cmd",
")",
":",
"self",
".",
"sources",
".",
"append",
"(",
"multi_cmd",
")"
] | [
1269,
4
] | [
1271,
38
] | python | en | ['en', 'en', 'en'] | True |
Parameter.human_readable_name | (self) | Returns the human readable name of this parameter. This is the
same as the name for options, but the metavar for arguments.
| Returns the human readable name of this parameter. This is the
same as the name for options, but the metavar for arguments.
| def human_readable_name(self):
"""Returns the human readable name of this parameter. This is the
same as the name for options, but the metavar for arguments.
"""
return self.name | [
"def",
"human_readable_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"name"
] | [
1361,
4
] | [
1365,
24
] | python | en | ['en', 'en', 'en'] | True |
Parameter.get_default | (self, ctx) | Given a context variable this calculates the default value. | Given a context variable this calculates the default value. | def get_default(self, ctx):
"""Given a context variable this calculates the default value."""
# Otherwise go with the regular default.
if callable(self.default):
rv = self.default()
else:
rv = self.default
return self.type_cast_value(ctx, rv) | [
"def",
"get_default",
"(",
"self",
",",
"ctx",
")",
":",
"# Otherwise go with the regular default.",
"if",
"callable",
"(",
"self",
".",
"default",
")",
":",
"rv",
"=",
"self",
".",
"default",
"(",
")",
"else",
":",
"rv",
"=",
"self",
".",
"default",
"return",
"self",
".",
"type_cast_value",
"(",
"ctx",
",",
"rv",
")"
] | [
1377,
4
] | [
1384,
44
] | python | en | ['en', 'en', 'en'] | True |
Parameter.type_cast_value | (self, ctx, value) | Given a value this runs it properly through the type system.
This automatically handles things like `nargs` and `multiple` as
well as composite types.
| Given a value this runs it properly through the type system.
This automatically handles things like `nargs` and `multiple` as
well as composite types.
| def type_cast_value(self, ctx, value):
"""Given a value this runs it properly through the type system.
This automatically handles things like `nargs` and `multiple` as
well as composite types.
"""
if self.type.is_composite:
if self.nargs <= 1:
raise TypeError('Attempted to invoke composite type '
'but nargs has been set to %s. This is '
'not supported; nargs needs to be set to '
'a fixed value > 1.' % self.nargs)
if self.multiple:
return tuple(self.type(x or (), self, ctx) for x in value or ())
return self.type(value or (), self, ctx)
def _convert(value, level):
if level == 0:
return self.type(value, self, ctx)
return tuple(_convert(x, level - 1) for x in value or ())
return _convert(value, (self.nargs != 1) + bool(self.multiple)) | [
"def",
"type_cast_value",
"(",
"self",
",",
"ctx",
",",
"value",
")",
":",
"if",
"self",
".",
"type",
".",
"is_composite",
":",
"if",
"self",
".",
"nargs",
"<=",
"1",
":",
"raise",
"TypeError",
"(",
"'Attempted to invoke composite type '",
"'but nargs has been set to %s. This is '",
"'not supported; nargs needs to be set to '",
"'a fixed value > 1.'",
"%",
"self",
".",
"nargs",
")",
"if",
"self",
".",
"multiple",
":",
"return",
"tuple",
"(",
"self",
".",
"type",
"(",
"x",
"or",
"(",
")",
",",
"self",
",",
"ctx",
")",
"for",
"x",
"in",
"value",
"or",
"(",
")",
")",
"return",
"self",
".",
"type",
"(",
"value",
"or",
"(",
")",
",",
"self",
",",
"ctx",
")",
"def",
"_convert",
"(",
"value",
",",
"level",
")",
":",
"if",
"level",
"==",
"0",
":",
"return",
"self",
".",
"type",
"(",
"value",
",",
"self",
",",
"ctx",
")",
"return",
"tuple",
"(",
"_convert",
"(",
"x",
",",
"level",
"-",
"1",
")",
"for",
"x",
"in",
"value",
"or",
"(",
")",
")",
"return",
"_convert",
"(",
"value",
",",
"(",
"self",
".",
"nargs",
"!=",
"1",
")",
"+",
"bool",
"(",
"self",
".",
"multiple",
")",
")"
] | [
1397,
4
] | [
1416,
71
] | python | en | ['en', 'en', 'en'] | True |
Parameter.process_value | (self, ctx, value) | Given a value and context this runs the logic to convert the
value as necessary.
| Given a value and context this runs the logic to convert the
value as necessary.
| def process_value(self, ctx, value):
"""Given a value and context this runs the logic to convert the
value as necessary.
"""
# If the value we were given is None we do nothing. This way
# code that calls this can easily figure out if something was
# not provided. Otherwise it would be converted into an empty
# tuple for multiple invocations which is inconvenient.
if value is not None:
return self.type_cast_value(ctx, value) | [
"def",
"process_value",
"(",
"self",
",",
"ctx",
",",
"value",
")",
":",
"# If the value we were given is None we do nothing. This way",
"# code that calls this can easily figure out if something was",
"# not provided. Otherwise it would be converted into an empty",
"# tuple for multiple invocations which is inconvenient.",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"self",
".",
"type_cast_value",
"(",
"ctx",
",",
"value",
")"
] | [
1418,
4
] | [
1427,
51
] | python | en | ['en', 'en', 'en'] | True |
Parameter.get_error_hint | (self, ctx) | Get a stringified version of the param for use in error messages to
indicate which param caused the error.
| Get a stringified version of the param for use in error messages to
indicate which param caused the error.
| def get_error_hint(self, ctx):
"""Get a stringified version of the param for use in error messages to
indicate which param caused the error.
"""
hint_list = self.opts or [self.human_readable_name]
return ' / '.join('"%s"' % x for x in hint_list) | [
"def",
"get_error_hint",
"(",
"self",
",",
"ctx",
")",
":",
"hint_list",
"=",
"self",
".",
"opts",
"or",
"[",
"self",
".",
"human_readable_name",
"]",
"return",
"' / '",
".",
"join",
"(",
"'\"%s\"'",
"%",
"x",
"for",
"x",
"in",
"hint_list",
")"
] | [
1491,
4
] | [
1496,
56
] | python | en | ['en', 'en', 'en'] | True |
Option.prompt_for_value | (self, ctx) | This is an alternative flow that can be activated in the full
value processing if a value does not exist. It will prompt the
user until a valid value exists and then returns the processed
value as result.
| This is an alternative flow that can be activated in the full
value processing if a value does not exist. It will prompt the
user until a valid value exists and then returns the processed
value as result.
| def prompt_for_value(self, ctx):
"""This is an alternative flow that can be activated in the full
value processing if a value does not exist. It will prompt the
user until a valid value exists and then returns the processed
value as result.
"""
# Calculate the default before prompting anything to be stable.
default = self.get_default(ctx)
# If this is a prompt for a flag we need to handle this
# differently.
if self.is_bool_flag:
return confirm(self.prompt, default)
return prompt(self.prompt, default=default, type=self.type,
hide_input=self.hide_input, show_choices=self.show_choices,
confirmation_prompt=self.confirmation_prompt,
value_proc=lambda x: self.process_value(ctx, x)) | [
"def",
"prompt_for_value",
"(",
"self",
",",
"ctx",
")",
":",
"# Calculate the default before prompting anything to be stable.",
"default",
"=",
"self",
".",
"get_default",
"(",
"ctx",
")",
"# If this is a prompt for a flag we need to handle this",
"# differently.",
"if",
"self",
".",
"is_bool_flag",
":",
"return",
"confirm",
"(",
"self",
".",
"prompt",
",",
"default",
")",
"return",
"prompt",
"(",
"self",
".",
"prompt",
",",
"default",
"=",
"default",
",",
"type",
"=",
"self",
".",
"type",
",",
"hide_input",
"=",
"self",
".",
"hide_input",
",",
"show_choices",
"=",
"self",
".",
"show_choices",
",",
"confirmation_prompt",
"=",
"self",
".",
"confirmation_prompt",
",",
"value_proc",
"=",
"lambda",
"x",
":",
"self",
".",
"process_value",
"(",
"ctx",
",",
"x",
")",
")"
] | [
1746,
4
] | [
1763,
70
] | python | en | ['en', 'en', 'en'] | True |
transform_hits | (hits: List[Dict[str, str]]) |
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
|
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
| def transform_hits(hits: List[Dict[str, str]]) -> List["TransformedHit"]:
"""
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
"""
packages: Dict[str, "TransformedHit"] = OrderedDict()
for hit in hits:
name = hit['name']
summary = hit['summary']
version = hit['version']
if name not in packages.keys():
packages[name] = {
'name': name,
'summary': summary,
'versions': [version],
}
else:
packages[name]['versions'].append(version)
# if this is the highest version, replace summary and score
if version == highest_version(packages[name]['versions']):
packages[name]['summary'] = summary
return list(packages.values()) | [
"def",
"transform_hits",
"(",
"hits",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"\"TransformedHit\"",
"]",
":",
"packages",
":",
"Dict",
"[",
"str",
",",
"\"TransformedHit\"",
"]",
"=",
"OrderedDict",
"(",
")",
"for",
"hit",
"in",
"hits",
":",
"name",
"=",
"hit",
"[",
"'name'",
"]",
"summary",
"=",
"hit",
"[",
"'summary'",
"]",
"version",
"=",
"hit",
"[",
"'version'",
"]",
"if",
"name",
"not",
"in",
"packages",
".",
"keys",
"(",
")",
":",
"packages",
"[",
"name",
"]",
"=",
"{",
"'name'",
":",
"name",
",",
"'summary'",
":",
"summary",
",",
"'versions'",
":",
"[",
"version",
"]",
",",
"}",
"else",
":",
"packages",
"[",
"name",
"]",
"[",
"'versions'",
"]",
".",
"append",
"(",
"version",
")",
"# if this is the highest version, replace summary and score",
"if",
"version",
"==",
"highest_version",
"(",
"packages",
"[",
"name",
"]",
"[",
"'versions'",
"]",
")",
":",
"packages",
"[",
"name",
"]",
"[",
"'summary'",
"]",
"=",
"summary",
"return",
"list",
"(",
"packages",
".",
"values",
"(",
")",
")"
] | [
84,
0
] | [
109,
34
] | python | en | ['en', 'error', 'th'] | False |
dispatch_hook | (key, hooks, hook_data, **kwargs) | Dispatches a hook dictionary on a given piece of data. | Dispatches a hook dictionary on a given piece of data. | def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data | [
"def",
"dispatch_hook",
"(",
"key",
",",
"hooks",
",",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
":",
"hooks",
"=",
"hooks",
"or",
"{",
"}",
"hooks",
"=",
"hooks",
".",
"get",
"(",
"key",
")",
"if",
"hooks",
":",
"if",
"hasattr",
"(",
"hooks",
",",
"'__call__'",
")",
":",
"hooks",
"=",
"[",
"hooks",
"]",
"for",
"hook",
"in",
"hooks",
":",
"_hook_data",
"=",
"hook",
"(",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
"if",
"_hook_data",
"is",
"not",
"None",
":",
"hook_data",
"=",
"_hook_data",
"return",
"hook_data"
] | [
22,
0
] | [
33,
20
] | python | en | ['en', 'en', 'en'] | True |
_error | (msg) | Print msg and optionally exit with return code exit_. | Print msg and optionally exit with return code exit_. | def _error(msg):
"""Print msg and optionally exit with return code exit_."""
sys.stderr.write('[ERROR] {}\n'.format(msg))
return 1 | [
"def",
"_error",
"(",
"msg",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'[ERROR] {}\\n'",
".",
"format",
"(",
"msg",
")",
")",
"return",
"1"
] | [
150,
0
] | [
153,
12
] | python | en | ['en', 'en', 'en'] | True |
normalize_eols | (raw_contents) |
Take a block of raw text that will be passed through str.splitlines() to
get universal newlines treatment.
Return the resulting block of text with normalized `\n` EOL sequences ready
to be written to disk using current platform's native EOLs.
|
Take a block of raw text that will be passed through str.splitlines() to
get universal newlines treatment. | def normalize_eols(raw_contents):
"""
Take a block of raw text that will be passed through str.splitlines() to
get universal newlines treatment.
Return the resulting block of text with normalized `\n` EOL sequences ready
to be written to disk using current platform's native EOLs.
"""
lines_list = raw_contents.splitlines()
# Ensure last line has its EOL
if lines_list and lines_list[-1]:
lines_list.append('')
return '\n'.join(lines_list) | [
"def",
"normalize_eols",
"(",
"raw_contents",
")",
":",
"lines_list",
"=",
"raw_contents",
".",
"splitlines",
"(",
")",
"# Ensure last line has its EOL",
"if",
"lines_list",
"and",
"lines_list",
"[",
"-",
"1",
"]",
":",
"lines_list",
".",
"append",
"(",
"''",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines_list",
")"
] | [
154,
0
] | [
166,
32
] | python | en | ['en', 'error', 'th'] | False |
write_pot_file | (potfile, msgs) |
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
|
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
| def write_pot_file(potfile, msgs):
"""
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
"""
pot_lines = msgs.splitlines()
if os.path.exists(potfile):
# Strip the header
lines = dropwhile(len, pot_lines)
else:
lines = []
found, header_read = False, False
for line in pot_lines:
if not found and not header_read:
if 'charset=CHARSET' in line:
found = True
line = line.replace('charset=CHARSET', 'charset=UTF-8')
if not line and not found:
header_read = True
lines.append(line)
msgs = '\n'.join(lines)
# Force newlines of POT files to '\n' to work around
# https://savannah.gnu.org/bugs/index.php?52395
with open(potfile, 'a', encoding='utf-8', newline='\n') as fp:
fp.write(msgs) | [
"def",
"write_pot_file",
"(",
"potfile",
",",
"msgs",
")",
":",
"pot_lines",
"=",
"msgs",
".",
"splitlines",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"potfile",
")",
":",
"# Strip the header",
"lines",
"=",
"dropwhile",
"(",
"len",
",",
"pot_lines",
")",
"else",
":",
"lines",
"=",
"[",
"]",
"found",
",",
"header_read",
"=",
"False",
",",
"False",
"for",
"line",
"in",
"pot_lines",
":",
"if",
"not",
"found",
"and",
"not",
"header_read",
":",
"if",
"'charset=CHARSET'",
"in",
"line",
":",
"found",
"=",
"True",
"line",
"=",
"line",
".",
"replace",
"(",
"'charset=CHARSET'",
",",
"'charset=UTF-8'",
")",
"if",
"not",
"line",
"and",
"not",
"found",
":",
"header_read",
"=",
"True",
"lines",
".",
"append",
"(",
"line",
")",
"msgs",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"# Force newlines of POT files to '\\n' to work around",
"# https://savannah.gnu.org/bugs/index.php?52395",
"with",
"open",
"(",
"potfile",
",",
"'a'",
",",
"encoding",
"=",
"'utf-8'",
",",
"newline",
"=",
"'\\n'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"msgs",
")"
] | [
169,
0
] | [
193,
22
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.work_path | (self) |
Path to a file which is being fed into GNU gettext pipeline. This may
be either a translatable or its preprocessed version.
|
Path to a file which is being fed into GNU gettext pipeline. This may
be either a translatable or its preprocessed version.
| def work_path(self):
"""
Path to a file which is being fed into GNU gettext pipeline. This may
be either a translatable or its preprocessed version.
"""
if not self.is_templatized:
return self.path
extension = {
'djangojs': 'c',
'django': 'py',
}.get(self.domain)
filename = '%s.%s' % (self.translatable.file, extension)
return os.path.join(self.translatable.dirpath, filename) | [
"def",
"work_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_templatized",
":",
"return",
"self",
".",
"path",
"extension",
"=",
"{",
"'djangojs'",
":",
"'c'",
",",
"'django'",
":",
"'py'",
",",
"}",
".",
"get",
"(",
"self",
".",
"domain",
")",
"filename",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"translatable",
".",
"file",
",",
"extension",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"translatable",
".",
"dirpath",
",",
"filename",
")"
] | [
83,
4
] | [
95,
64
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.preprocess | (self) |
Preprocess (if necessary) a translatable file before passing it to
xgettext GNU gettext utility.
|
Preprocess (if necessary) a translatable file before passing it to
xgettext GNU gettext utility.
| def preprocess(self):
"""
Preprocess (if necessary) a translatable file before passing it to
xgettext GNU gettext utility.
"""
if not self.is_templatized:
return
with open(self.path, encoding='utf-8') as fp:
src_data = fp.read()
if self.domain == 'djangojs':
content = prepare_js_for_gettext(src_data)
elif self.domain == 'django':
content = templatize(src_data, origin=self.path[2:])
with open(self.work_path, 'w', encoding='utf-8') as fp:
fp.write(content) | [
"def",
"preprocess",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_templatized",
":",
"return",
"with",
"open",
"(",
"self",
".",
"path",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"src_data",
"=",
"fp",
".",
"read",
"(",
")",
"if",
"self",
".",
"domain",
"==",
"'djangojs'",
":",
"content",
"=",
"prepare_js_for_gettext",
"(",
"src_data",
")",
"elif",
"self",
".",
"domain",
"==",
"'django'",
":",
"content",
"=",
"templatize",
"(",
"src_data",
",",
"origin",
"=",
"self",
".",
"path",
"[",
"2",
":",
"]",
")",
"with",
"open",
"(",
"self",
".",
"work_path",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"content",
")"
] | [
97,
4
] | [
114,
29
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.postprocess_messages | (self, msgs) |
Postprocess messages generated by xgettext GNU gettext utility.
Transform paths as if these messages were generated from original
translatable files rather than from preprocessed versions.
|
Postprocess messages generated by xgettext GNU gettext utility. | def postprocess_messages(self, msgs):
"""
Postprocess messages generated by xgettext GNU gettext utility.
Transform paths as if these messages were generated from original
translatable files rather than from preprocessed versions.
"""
if not self.is_templatized:
return msgs
# Remove '.py' suffix
if os.name == 'nt':
# Preserve '.\' prefix on Windows to respect gettext behavior
old_path = self.work_path
new_path = self.path
else:
old_path = self.work_path[2:]
new_path = self.path[2:]
return re.sub(
r'^(#: .*)(' + re.escape(old_path) + r')',
lambda match: match[0].replace(old_path, new_path),
msgs,
flags=re.MULTILINE
) | [
"def",
"postprocess_messages",
"(",
"self",
",",
"msgs",
")",
":",
"if",
"not",
"self",
".",
"is_templatized",
":",
"return",
"msgs",
"# Remove '.py' suffix",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# Preserve '.\\' prefix on Windows to respect gettext behavior",
"old_path",
"=",
"self",
".",
"work_path",
"new_path",
"=",
"self",
".",
"path",
"else",
":",
"old_path",
"=",
"self",
".",
"work_path",
"[",
"2",
":",
"]",
"new_path",
"=",
"self",
".",
"path",
"[",
"2",
":",
"]",
"return",
"re",
".",
"sub",
"(",
"r'^(#: .*)('",
"+",
"re",
".",
"escape",
"(",
"old_path",
")",
"+",
"r')'",
",",
"lambda",
"match",
":",
"match",
"[",
"0",
"]",
".",
"replace",
"(",
"old_path",
",",
"new_path",
")",
",",
"msgs",
",",
"flags",
"=",
"re",
".",
"MULTILINE",
")"
] | [
116,
4
] | [
140,
9
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.cleanup | (self) |
Remove a preprocessed copy of a translatable file (if any).
|
Remove a preprocessed copy of a translatable file (if any).
| def cleanup(self):
"""
Remove a preprocessed copy of a translatable file (if any).
"""
if self.is_templatized:
# This check is needed for the case of a symlinked file and its
# source being processed inside a single group (locale dir);
# removing either of those two removes both.
if os.path.exists(self.work_path):
os.unlink(self.work_path) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_templatized",
":",
"# This check is needed for the case of a symlinked file and its",
"# source being processed inside a single group (locale dir);",
"# removing either of those two removes both.",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"work_path",
")",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"work_path",
")"
] | [
142,
4
] | [
151,
41
] | python | en | ['en', 'error', 'th'] | False |
Command.build_potfiles | (self) |
Build pot files and apply msguniq to them.
|
Build pot files and apply msguniq to them.
| def build_potfiles(self):
"""
Build pot files and apply msguniq to them.
"""
file_list = self.find_files(".")
self.remove_potfiles()
self.process_files(file_list)
potfiles = []
for path in self.locale_paths:
potfile = os.path.join(path, '%s.pot' % self.domain)
if not os.path.exists(potfile):
continue
args = ['msguniq'] + self.msguniq_options + [potfile]
msgs, errors, status = popen_wrapper(args)
if errors:
if status != STATUS_OK:
raise CommandError(
"errors happened while running msguniq\n%s" % errors)
elif self.verbosity > 0:
self.stdout.write(errors)
msgs = normalize_eols(msgs)
with open(potfile, 'w', encoding='utf-8') as fp:
fp.write(msgs)
potfiles.append(potfile)
return potfiles | [
"def",
"build_potfiles",
"(",
"self",
")",
":",
"file_list",
"=",
"self",
".",
"find_files",
"(",
"\".\"",
")",
"self",
".",
"remove_potfiles",
"(",
")",
"self",
".",
"process_files",
"(",
"file_list",
")",
"potfiles",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"locale_paths",
":",
"potfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'%s.pot'",
"%",
"self",
".",
"domain",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"potfile",
")",
":",
"continue",
"args",
"=",
"[",
"'msguniq'",
"]",
"+",
"self",
".",
"msguniq_options",
"+",
"[",
"potfile",
"]",
"msgs",
",",
"errors",
",",
"status",
"=",
"popen_wrapper",
"(",
"args",
")",
"if",
"errors",
":",
"if",
"status",
"!=",
"STATUS_OK",
":",
"raise",
"CommandError",
"(",
"\"errors happened while running msguniq\\n%s\"",
"%",
"errors",
")",
"elif",
"self",
".",
"verbosity",
">",
"0",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"errors",
")",
"msgs",
"=",
"normalize_eols",
"(",
"msgs",
")",
"with",
"open",
"(",
"potfile",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"msgs",
")",
"potfiles",
".",
"append",
"(",
"potfile",
")",
"return",
"potfiles"
] | [
425,
4
] | [
449,
23
] | python | en | ['en', 'error', 'th'] | False |
Command.find_files | (self, root) |
Get all files in the given root. Also check that there is a matching
locale dir for each file.
|
Get all files in the given root. Also check that there is a matching
locale dir for each file.
| def find_files(self, root):
"""
Get all files in the given root. Also check that there is a matching
locale dir for each file.
"""
all_files = []
ignored_roots = []
if self.settings_available:
ignored_roots = [os.path.normpath(p) for p in (settings.MEDIA_ROOT, settings.STATIC_ROOT) if p]
for dirpath, dirnames, filenames in os.walk(root, topdown=True, followlinks=self.symlinks):
for dirname in dirnames[:]:
if (is_ignored_path(os.path.normpath(os.path.join(dirpath, dirname)), self.ignore_patterns) or
os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots):
dirnames.remove(dirname)
if self.verbosity > 1:
self.stdout.write('ignoring directory %s' % dirname)
elif dirname == 'locale':
dirnames.remove(dirname)
self.locale_paths.insert(0, os.path.join(os.path.abspath(dirpath), dirname))
for filename in filenames:
file_path = os.path.normpath(os.path.join(dirpath, filename))
file_ext = os.path.splitext(filename)[1]
if file_ext not in self.extensions or is_ignored_path(file_path, self.ignore_patterns):
if self.verbosity > 1:
self.stdout.write('ignoring file %s in %s' % (filename, dirpath))
else:
locale_dir = None
for path in self.locale_paths:
if os.path.abspath(dirpath).startswith(os.path.dirname(path)):
locale_dir = path
break
locale_dir = locale_dir or self.default_locale_path or NO_LOCALE_DIR
all_files.append(self.translatable_file_class(dirpath, filename, locale_dir))
return sorted(all_files) | [
"def",
"find_files",
"(",
"self",
",",
"root",
")",
":",
"all_files",
"=",
"[",
"]",
"ignored_roots",
"=",
"[",
"]",
"if",
"self",
".",
"settings_available",
":",
"ignored_roots",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"p",
")",
"for",
"p",
"in",
"(",
"settings",
".",
"MEDIA_ROOT",
",",
"settings",
".",
"STATIC_ROOT",
")",
"if",
"p",
"]",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"root",
",",
"topdown",
"=",
"True",
",",
"followlinks",
"=",
"self",
".",
"symlinks",
")",
":",
"for",
"dirname",
"in",
"dirnames",
"[",
":",
"]",
":",
"if",
"(",
"is_ignored_path",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"dirname",
")",
")",
",",
"self",
".",
"ignore_patterns",
")",
"or",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"dirpath",
")",
",",
"dirname",
")",
"in",
"ignored_roots",
")",
":",
"dirnames",
".",
"remove",
"(",
"dirname",
")",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'ignoring directory %s'",
"%",
"dirname",
")",
"elif",
"dirname",
"==",
"'locale'",
":",
"dirnames",
".",
"remove",
"(",
"dirname",
")",
"self",
".",
"locale_paths",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"dirpath",
")",
",",
"dirname",
")",
")",
"for",
"filename",
"in",
"filenames",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"filename",
")",
")",
"file_ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"if",
"file_ext",
"not",
"in",
"self",
".",
"extensions",
"or",
"is_ignored_path",
"(",
"file_path",
",",
"self",
".",
"ignore_patterns",
")",
":",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'ignoring file %s in %s'",
"%",
"(",
"filename",
",",
"dirpath",
")",
")",
"else",
":",
"locale_dir",
"=",
"None",
"for",
"path",
"in",
"self",
".",
"locale_paths",
":",
"if",
"os",
".",
"path",
".",
"abspath",
"(",
"dirpath",
")",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
":",
"locale_dir",
"=",
"path",
"break",
"locale_dir",
"=",
"locale_dir",
"or",
"self",
".",
"default_locale_path",
"or",
"NO_LOCALE_DIR",
"all_files",
".",
"append",
"(",
"self",
".",
"translatable_file_class",
"(",
"dirpath",
",",
"filename",
",",
"locale_dir",
")",
")",
"return",
"sorted",
"(",
"all_files",
")"
] | [
457,
4
] | [
490,
32
] | python | en | ['en', 'error', 'th'] | False |
Command.process_files | (self, file_list) |
Group translatable files by locale directory and run pot file build
process for each group.
|
Group translatable files by locale directory and run pot file build
process for each group.
| def process_files(self, file_list):
"""
Group translatable files by locale directory and run pot file build
process for each group.
"""
file_groups = {}
for translatable in file_list:
file_group = file_groups.setdefault(translatable.locale_dir, [])
file_group.append(translatable)
for locale_dir, files in file_groups.items():
self.process_locale_dir(locale_dir, files) | [
"def",
"process_files",
"(",
"self",
",",
"file_list",
")",
":",
"file_groups",
"=",
"{",
"}",
"for",
"translatable",
"in",
"file_list",
":",
"file_group",
"=",
"file_groups",
".",
"setdefault",
"(",
"translatable",
".",
"locale_dir",
",",
"[",
"]",
")",
"file_group",
".",
"append",
"(",
"translatable",
")",
"for",
"locale_dir",
",",
"files",
"in",
"file_groups",
".",
"items",
"(",
")",
":",
"self",
".",
"process_locale_dir",
"(",
"locale_dir",
",",
"files",
")"
] | [
492,
4
] | [
502,
54
] | python | en | ['en', 'error', 'th'] | False |
Command.process_locale_dir | (self, locale_dir, files) |
Extract translatable literals from the specified files, creating or
updating the POT file for a given locale directory.
Use the xgettext GNU gettext utility.
|
Extract translatable literals from the specified files, creating or
updating the POT file for a given locale directory. | def process_locale_dir(self, locale_dir, files):
"""
Extract translatable literals from the specified files, creating or
updating the POT file for a given locale directory.
Use the xgettext GNU gettext utility.
"""
build_files = []
for translatable in files:
if self.verbosity > 1:
self.stdout.write('processing file %s in %s' % (
translatable.file, translatable.dirpath
))
if self.domain not in ('djangojs', 'django'):
continue
build_file = self.build_file_class(self, self.domain, translatable)
try:
build_file.preprocess()
except UnicodeDecodeError as e:
self.stdout.write(
'UnicodeDecodeError: skipped file %s in %s (reason: %s)' % (
translatable.file, translatable.dirpath, e,
)
)
continue
build_files.append(build_file)
if self.domain == 'djangojs':
is_templatized = build_file.is_templatized
args = [
'xgettext',
'-d', self.domain,
'--language=%s' % ('C' if is_templatized else 'JavaScript',),
'--keyword=gettext_noop',
'--keyword=gettext_lazy',
'--keyword=ngettext_lazy:1,2',
'--keyword=pgettext:1c,2',
'--keyword=npgettext:1c,2,3',
'--output=-',
]
elif self.domain == 'django':
args = [
'xgettext',
'-d', self.domain,
'--language=Python',
'--keyword=gettext_noop',
'--keyword=gettext_lazy',
'--keyword=ngettext_lazy:1,2',
'--keyword=ugettext_noop',
'--keyword=ugettext_lazy',
'--keyword=ungettext_lazy:1,2',
'--keyword=pgettext:1c,2',
'--keyword=npgettext:1c,2,3',
'--keyword=pgettext_lazy:1c,2',
'--keyword=npgettext_lazy:1c,2,3',
'--output=-',
]
else:
return
input_files = [bf.work_path for bf in build_files]
with NamedTemporaryFile(mode='w+') as input_files_list:
input_files_list.write('\n'.join(input_files))
input_files_list.flush()
args.extend(['--files-from', input_files_list.name])
args.extend(self.xgettext_options)
msgs, errors, status = popen_wrapper(args)
if errors:
if status != STATUS_OK:
for build_file in build_files:
build_file.cleanup()
raise CommandError(
'errors happened while running xgettext on %s\n%s' %
('\n'.join(input_files), errors)
)
elif self.verbosity > 0:
# Print warnings
self.stdout.write(errors)
if msgs:
if locale_dir is NO_LOCALE_DIR:
file_path = os.path.normpath(build_files[0].path)
raise CommandError(
'Unable to find a locale path to store translations for '
'file %s' % file_path
)
for build_file in build_files:
msgs = build_file.postprocess_messages(msgs)
potfile = os.path.join(locale_dir, '%s.pot' % self.domain)
write_pot_file(potfile, msgs)
for build_file in build_files:
build_file.cleanup() | [
"def",
"process_locale_dir",
"(",
"self",
",",
"locale_dir",
",",
"files",
")",
":",
"build_files",
"=",
"[",
"]",
"for",
"translatable",
"in",
"files",
":",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'processing file %s in %s'",
"%",
"(",
"translatable",
".",
"file",
",",
"translatable",
".",
"dirpath",
")",
")",
"if",
"self",
".",
"domain",
"not",
"in",
"(",
"'djangojs'",
",",
"'django'",
")",
":",
"continue",
"build_file",
"=",
"self",
".",
"build_file_class",
"(",
"self",
",",
"self",
".",
"domain",
",",
"translatable",
")",
"try",
":",
"build_file",
".",
"preprocess",
"(",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'UnicodeDecodeError: skipped file %s in %s (reason: %s)'",
"%",
"(",
"translatable",
".",
"file",
",",
"translatable",
".",
"dirpath",
",",
"e",
",",
")",
")",
"continue",
"build_files",
".",
"append",
"(",
"build_file",
")",
"if",
"self",
".",
"domain",
"==",
"'djangojs'",
":",
"is_templatized",
"=",
"build_file",
".",
"is_templatized",
"args",
"=",
"[",
"'xgettext'",
",",
"'-d'",
",",
"self",
".",
"domain",
",",
"'--language=%s'",
"%",
"(",
"'C'",
"if",
"is_templatized",
"else",
"'JavaScript'",
",",
")",
",",
"'--keyword=gettext_noop'",
",",
"'--keyword=gettext_lazy'",
",",
"'--keyword=ngettext_lazy:1,2'",
",",
"'--keyword=pgettext:1c,2'",
",",
"'--keyword=npgettext:1c,2,3'",
",",
"'--output=-'",
",",
"]",
"elif",
"self",
".",
"domain",
"==",
"'django'",
":",
"args",
"=",
"[",
"'xgettext'",
",",
"'-d'",
",",
"self",
".",
"domain",
",",
"'--language=Python'",
",",
"'--keyword=gettext_noop'",
",",
"'--keyword=gettext_lazy'",
",",
"'--keyword=ngettext_lazy:1,2'",
",",
"'--keyword=ugettext_noop'",
",",
"'--keyword=ugettext_lazy'",
",",
"'--keyword=ungettext_lazy:1,2'",
",",
"'--keyword=pgettext:1c,2'",
",",
"'--keyword=npgettext:1c,2,3'",
",",
"'--keyword=pgettext_lazy:1c,2'",
",",
"'--keyword=npgettext_lazy:1c,2,3'",
",",
"'--output=-'",
",",
"]",
"else",
":",
"return",
"input_files",
"=",
"[",
"bf",
".",
"work_path",
"for",
"bf",
"in",
"build_files",
"]",
"with",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w+'",
")",
"as",
"input_files_list",
":",
"input_files_list",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"input_files",
")",
")",
"input_files_list",
".",
"flush",
"(",
")",
"args",
".",
"extend",
"(",
"[",
"'--files-from'",
",",
"input_files_list",
".",
"name",
"]",
")",
"args",
".",
"extend",
"(",
"self",
".",
"xgettext_options",
")",
"msgs",
",",
"errors",
",",
"status",
"=",
"popen_wrapper",
"(",
"args",
")",
"if",
"errors",
":",
"if",
"status",
"!=",
"STATUS_OK",
":",
"for",
"build_file",
"in",
"build_files",
":",
"build_file",
".",
"cleanup",
"(",
")",
"raise",
"CommandError",
"(",
"'errors happened while running xgettext on %s\\n%s'",
"%",
"(",
"'\\n'",
".",
"join",
"(",
"input_files",
")",
",",
"errors",
")",
")",
"elif",
"self",
".",
"verbosity",
">",
"0",
":",
"# Print warnings",
"self",
".",
"stdout",
".",
"write",
"(",
"errors",
")",
"if",
"msgs",
":",
"if",
"locale_dir",
"is",
"NO_LOCALE_DIR",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"build_files",
"[",
"0",
"]",
".",
"path",
")",
"raise",
"CommandError",
"(",
"'Unable to find a locale path to store translations for '",
"'file %s'",
"%",
"file_path",
")",
"for",
"build_file",
"in",
"build_files",
":",
"msgs",
"=",
"build_file",
".",
"postprocess_messages",
"(",
"msgs",
")",
"potfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"locale_dir",
",",
"'%s.pot'",
"%",
"self",
".",
"domain",
")",
"write_pot_file",
"(",
"potfile",
",",
"msgs",
")",
"for",
"build_file",
"in",
"build_files",
":",
"build_file",
".",
"cleanup",
"(",
")"
] | [
504,
4
] | [
597,
32
] | python | en | ['en', 'error', 'th'] | False |
Command.write_po_file | (self, potfile, locale) |
Create or update the PO file for self.domain and `locale`.
Use contents of the existing `potfile`.
Use msgmerge and msgattrib GNU gettext utilities.
|
Create or update the PO file for self.domain and `locale`.
Use contents of the existing `potfile`. | def write_po_file(self, potfile, locale):
"""
Create or update the PO file for self.domain and `locale`.
Use contents of the existing `potfile`.
Use msgmerge and msgattrib GNU gettext utilities.
"""
basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
os.makedirs(basedir, exist_ok=True)
pofile = os.path.join(basedir, '%s.po' % self.domain)
if os.path.exists(pofile):
args = ['msgmerge'] + self.msgmerge_options + [pofile, potfile]
msgs, errors, status = popen_wrapper(args)
if errors:
if status != STATUS_OK:
raise CommandError(
"errors happened while running msgmerge\n%s" % errors)
elif self.verbosity > 0:
self.stdout.write(errors)
else:
with open(potfile, encoding='utf-8') as fp:
msgs = fp.read()
if not self.invoked_for_django:
msgs = self.copy_plural_forms(msgs, locale)
msgs = normalize_eols(msgs)
msgs = msgs.replace(
"#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % self.domain, "")
with open(pofile, 'w', encoding='utf-8') as fp:
fp.write(msgs)
if self.no_obsolete:
args = ['msgattrib'] + self.msgattrib_options + ['-o', pofile, pofile]
msgs, errors, status = popen_wrapper(args)
if errors:
if status != STATUS_OK:
raise CommandError(
"errors happened while running msgattrib\n%s" % errors)
elif self.verbosity > 0:
self.stdout.write(errors) | [
"def",
"write_po_file",
"(",
"self",
",",
"potfile",
",",
"locale",
")",
":",
"basedir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"potfile",
")",
",",
"locale",
",",
"'LC_MESSAGES'",
")",
"os",
".",
"makedirs",
"(",
"basedir",
",",
"exist_ok",
"=",
"True",
")",
"pofile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"'%s.po'",
"%",
"self",
".",
"domain",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pofile",
")",
":",
"args",
"=",
"[",
"'msgmerge'",
"]",
"+",
"self",
".",
"msgmerge_options",
"+",
"[",
"pofile",
",",
"potfile",
"]",
"msgs",
",",
"errors",
",",
"status",
"=",
"popen_wrapper",
"(",
"args",
")",
"if",
"errors",
":",
"if",
"status",
"!=",
"STATUS_OK",
":",
"raise",
"CommandError",
"(",
"\"errors happened while running msgmerge\\n%s\"",
"%",
"errors",
")",
"elif",
"self",
".",
"verbosity",
">",
"0",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"errors",
")",
"else",
":",
"with",
"open",
"(",
"potfile",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"msgs",
"=",
"fp",
".",
"read",
"(",
")",
"if",
"not",
"self",
".",
"invoked_for_django",
":",
"msgs",
"=",
"self",
".",
"copy_plural_forms",
"(",
"msgs",
",",
"locale",
")",
"msgs",
"=",
"normalize_eols",
"(",
"msgs",
")",
"msgs",
"=",
"msgs",
".",
"replace",
"(",
"\"#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\\n\"",
"%",
"self",
".",
"domain",
",",
"\"\"",
")",
"with",
"open",
"(",
"pofile",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"msgs",
")",
"if",
"self",
".",
"no_obsolete",
":",
"args",
"=",
"[",
"'msgattrib'",
"]",
"+",
"self",
".",
"msgattrib_options",
"+",
"[",
"'-o'",
",",
"pofile",
",",
"pofile",
"]",
"msgs",
",",
"errors",
",",
"status",
"=",
"popen_wrapper",
"(",
"args",
")",
"if",
"errors",
":",
"if",
"status",
"!=",
"STATUS_OK",
":",
"raise",
"CommandError",
"(",
"\"errors happened while running msgattrib\\n%s\"",
"%",
"errors",
")",
"elif",
"self",
".",
"verbosity",
">",
"0",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"errors",
")"
] | [
599,
4
] | [
638,
45
] | python | en | ['en', 'error', 'th'] | False |
Command.copy_plural_forms | (self, msgs, locale) |
Copy plural forms header contents from a Django catalog of locale to
the msgs string, inserting it at the right place. msgs should be the
contents of a newly created .po file.
|
Copy plural forms header contents from a Django catalog of locale to
the msgs string, inserting it at the right place. msgs should be the
contents of a newly created .po file.
| def copy_plural_forms(self, msgs, locale):
"""
Copy plural forms header contents from a Django catalog of locale to
the msgs string, inserting it at the right place. msgs should be the
contents of a newly created .po file.
"""
django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__)))
if self.domain == 'djangojs':
domains = ('djangojs', 'django')
else:
domains = ('django',)
for domain in domains:
django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain)
if os.path.exists(django_po):
with open(django_po, encoding='utf-8') as fp:
m = plural_forms_re.search(fp.read())
if m:
plural_form_line = m['value']
if self.verbosity > 1:
self.stdout.write('copying plural forms: %s' % plural_form_line)
lines = []
found = False
for line in msgs.splitlines():
if not found and (not line or plural_forms_re.search(line)):
line = plural_form_line
found = True
lines.append(line)
msgs = '\n'.join(lines)
break
return msgs | [
"def",
"copy_plural_forms",
"(",
"self",
",",
"msgs",
",",
"locale",
")",
":",
"django_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"django",
".",
"__file__",
")",
")",
")",
"if",
"self",
".",
"domain",
"==",
"'djangojs'",
":",
"domains",
"=",
"(",
"'djangojs'",
",",
"'django'",
")",
"else",
":",
"domains",
"=",
"(",
"'django'",
",",
")",
"for",
"domain",
"in",
"domains",
":",
"django_po",
"=",
"os",
".",
"path",
".",
"join",
"(",
"django_dir",
",",
"'conf'",
",",
"'locale'",
",",
"locale",
",",
"'LC_MESSAGES'",
",",
"'%s.po'",
"%",
"domain",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"django_po",
")",
":",
"with",
"open",
"(",
"django_po",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"m",
"=",
"plural_forms_re",
".",
"search",
"(",
"fp",
".",
"read",
"(",
")",
")",
"if",
"m",
":",
"plural_form_line",
"=",
"m",
"[",
"'value'",
"]",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'copying plural forms: %s'",
"%",
"plural_form_line",
")",
"lines",
"=",
"[",
"]",
"found",
"=",
"False",
"for",
"line",
"in",
"msgs",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"found",
"and",
"(",
"not",
"line",
"or",
"plural_forms_re",
".",
"search",
"(",
"line",
")",
")",
":",
"line",
"=",
"plural_form_line",
"found",
"=",
"True",
"lines",
".",
"append",
"(",
"line",
")",
"msgs",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"break",
"return",
"msgs"
] | [
640,
4
] | [
669,
19
] | python | en | ['en', 'error', 'th'] | False |
get_intersect_with_zero | (o, g) | Intersects a given gaze ray (origin o and direction g) with z = 0. | Intersects a given gaze ray (origin o and direction g) with z = 0. | def get_intersect_with_zero(o, g):
"""Intersects a given gaze ray (origin o and direction g) with z = 0."""
global nn_plane_normal, nn_plane_other
if nn_plane_normal is None:
nn_plane_normal = torch.tensor([0, 0, 1], dtype=torch.float32, device=device).view(1, 3, 1)
nn_plane_other = torch.tensor([1, 0, 0], dtype=torch.float32, device=device).view(1, 3, 1)
# Define plane to intersect with
n = nn_plane_normal
a = nn_plane_other
g = g.view(-1, 3, 1)
o = o.view(-1, 3, 1)
numer = torch.sum(torch.mul(a - o, n), dim=1)
# Intersect with plane using provided 3D origin
denom = torch.sum(torch.mul(g, n), dim=1) + 1e-7
t = torch.div(numer, denom).view(-1, 1, 1)
return (o + torch.mul(t, g))[:, :2, 0] | [
"def",
"get_intersect_with_zero",
"(",
"o",
",",
"g",
")",
":",
"global",
"nn_plane_normal",
",",
"nn_plane_other",
"if",
"nn_plane_normal",
"is",
"None",
":",
"nn_plane_normal",
"=",
"torch",
".",
"tensor",
"(",
"[",
"0",
",",
"0",
",",
"1",
"]",
",",
"dtype",
"=",
"torch",
".",
"float32",
",",
"device",
"=",
"device",
")",
".",
"view",
"(",
"1",
",",
"3",
",",
"1",
")",
"nn_plane_other",
"=",
"torch",
".",
"tensor",
"(",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"dtype",
"=",
"torch",
".",
"float32",
",",
"device",
"=",
"device",
")",
".",
"view",
"(",
"1",
",",
"3",
",",
"1",
")",
"# Define plane to intersect with",
"n",
"=",
"nn_plane_normal",
"a",
"=",
"nn_plane_other",
"g",
"=",
"g",
".",
"view",
"(",
"-",
"1",
",",
"3",
",",
"1",
")",
"o",
"=",
"o",
".",
"view",
"(",
"-",
"1",
",",
"3",
",",
"1",
")",
"numer",
"=",
"torch",
".",
"sum",
"(",
"torch",
".",
"mul",
"(",
"a",
"-",
"o",
",",
"n",
")",
",",
"dim",
"=",
"1",
")",
"# Intersect with plane using provided 3D origin",
"denom",
"=",
"torch",
".",
"sum",
"(",
"torch",
".",
"mul",
"(",
"g",
",",
"n",
")",
",",
"dim",
"=",
"1",
")",
"+",
"1e-7",
"t",
"=",
"torch",
".",
"div",
"(",
"numer",
",",
"denom",
")",
".",
"view",
"(",
"-",
"1",
",",
"1",
",",
"1",
")",
"return",
"(",
"o",
"+",
"torch",
".",
"mul",
"(",
"t",
",",
"g",
")",
")",
"[",
":",
",",
":",
"2",
",",
"0",
"]"
] | [
108,
0
] | [
125,
42
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.