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 |
---|---|---|---|---|---|---|---|---|---|---|---|
_SixMetaPathImporter.get_code | (self, fullname) | Return None
Required, if is_package is implemented | Return None | def get_code(self, fullname):
"""Return None
Required, if is_package is implemented"""
self.__get_module(fullname) # eventually raises ImportError
return None | [
"def",
"get_code",
"(",
"self",
",",
"fullname",
")",
":",
"self",
".",
"__get_module",
"(",
"fullname",
")",
"# eventually raises ImportError",
"return",
"None"
] | [
217,
4
] | [
222,
19
] | python | en | ['en', 'co', 'en'] | False |
SingleObjectMixin.get_object | (self, queryset=None) |
Return the object the view is displaying.
Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
Subclasses can override this to return any object.
|
Return the object the view is displaying. | def get_object(self, queryset=None):
"""
Return the object the view is displaying.
Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
Subclasses can override this to return any object.
"""
# Use a custom queryset if provided; this is required for subclasses
# like DateDetailView
if queryset is None:
queryset = self.get_queryset()
# Next, try looking up by primary key.
pk = self.kwargs.get(self.pk_url_kwarg)
slug = self.kwargs.get(self.slug_url_kwarg)
if pk is not None:
queryset = queryset.filter(pk=pk)
# Next, try looking up by slug.
if slug is not None and (pk is None or self.query_pk_and_slug):
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})
# If none of those are defined, it's an error.
if pk is None and slug is None:
raise AttributeError(
"Generic detail view %s must be called with either an object "
"pk or a slug in the URLconf." % self.__class__.__name__
)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
return obj | [
"def",
"get_object",
"(",
"self",
",",
"queryset",
"=",
"None",
")",
":",
"# Use a custom queryset if provided; this is required for subclasses",
"# like DateDetailView",
"if",
"queryset",
"is",
"None",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"# Next, try looking up by primary key.",
"pk",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"self",
".",
"pk_url_kwarg",
")",
"slug",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"self",
".",
"slug_url_kwarg",
")",
"if",
"pk",
"is",
"not",
"None",
":",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"pk",
"=",
"pk",
")",
"# Next, try looking up by slug.",
"if",
"slug",
"is",
"not",
"None",
"and",
"(",
"pk",
"is",
"None",
"or",
"self",
".",
"query_pk_and_slug",
")",
":",
"slug_field",
"=",
"self",
".",
"get_slug_field",
"(",
")",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"*",
"*",
"{",
"slug_field",
":",
"slug",
"}",
")",
"# If none of those are defined, it's an error.",
"if",
"pk",
"is",
"None",
"and",
"slug",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"\"Generic detail view %s must be called with either an object \"",
"\"pk or a slug in the URLconf.\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"try",
":",
"# Get the single item from the filtered queryset",
"obj",
"=",
"queryset",
".",
"get",
"(",
")",
"except",
"queryset",
".",
"model",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"(",
"_",
"(",
"\"No %(verbose_name)s found matching the query\"",
")",
"%",
"{",
"'verbose_name'",
":",
"queryset",
".",
"model",
".",
"_meta",
".",
"verbose_name",
"}",
")",
"return",
"obj"
] | [
19,
4
] | [
55,
18
] | python | en | ['en', 'error', 'th'] | False |
SingleObjectMixin.get_queryset | (self) |
Return the `QuerySet` that will be used to look up the object.
This method is called by the default implementation of get_object() and
may not be called if get_object() is overridden.
|
Return the `QuerySet` that will be used to look up the object. | def get_queryset(self):
"""
Return the `QuerySet` that will be used to look up the object.
This method is called by the default implementation of get_object() and
may not be called if get_object() is overridden.
"""
if self.queryset is None:
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
return self.queryset.all() | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"if",
"self",
".",
"queryset",
"is",
"None",
":",
"if",
"self",
".",
"model",
":",
"return",
"self",
".",
"model",
".",
"_default_manager",
".",
"all",
"(",
")",
"else",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"%(cls)s is missing a QuerySet. Define \"",
"\"%(cls)s.model, %(cls)s.queryset, or override \"",
"\"%(cls)s.get_queryset().\"",
"%",
"{",
"'cls'",
":",
"self",
".",
"__class__",
".",
"__name__",
"}",
")",
"return",
"self",
".",
"queryset",
".",
"all",
"(",
")"
] | [
57,
4
] | [
75,
34
] | python | en | ['en', 'error', 'th'] | False |
SingleObjectMixin.get_slug_field | (self) | Get the name of a slug field to be used to look up by slug. | Get the name of a slug field to be used to look up by slug. | def get_slug_field(self):
"""Get the name of a slug field to be used to look up by slug."""
return self.slug_field | [
"def",
"get_slug_field",
"(",
"self",
")",
":",
"return",
"self",
".",
"slug_field"
] | [
77,
4
] | [
79,
30
] | python | en | ['en', 'en', 'en'] | True |
SingleObjectMixin.get_context_object_name | (self, obj) | Get the name to use for the object. | Get the name to use for the object. | def get_context_object_name(self, obj):
"""Get the name to use for the object."""
if self.context_object_name:
return self.context_object_name
elif isinstance(obj, models.Model):
return obj._meta.model_name
else:
return None | [
"def",
"get_context_object_name",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"context_object_name",
":",
"return",
"self",
".",
"context_object_name",
"elif",
"isinstance",
"(",
"obj",
",",
"models",
".",
"Model",
")",
":",
"return",
"obj",
".",
"_meta",
".",
"model_name",
"else",
":",
"return",
"None"
] | [
81,
4
] | [
88,
23
] | python | en | ['en', 'en', 'en'] | True |
SingleObjectMixin.get_context_data | (self, **kwargs) | Insert the single object into the context dict. | Insert the single object into the context dict. | def get_context_data(self, **kwargs):
"""Insert the single object into the context dict."""
context = {}
if self.object:
context['object'] = self.object
context_object_name = self.get_context_object_name(self.object)
if context_object_name:
context[context_object_name] = self.object
context.update(kwargs)
return super().get_context_data(**context) | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"{",
"}",
"if",
"self",
".",
"object",
":",
"context",
"[",
"'object'",
"]",
"=",
"self",
".",
"object",
"context_object_name",
"=",
"self",
".",
"get_context_object_name",
"(",
"self",
".",
"object",
")",
"if",
"context_object_name",
":",
"context",
"[",
"context_object_name",
"]",
"=",
"self",
".",
"object",
"context",
".",
"update",
"(",
"kwargs",
")",
"return",
"super",
"(",
")",
".",
"get_context_data",
"(",
"*",
"*",
"context",
")"
] | [
90,
4
] | [
99,
50
] | python | en | ['en', 'en', 'en'] | True |
SingleObjectTemplateResponseMixin.get_template_names | (self) |
Return a list of template names to be used for the request. May not be
called if render_to_response() is overridden. Return the following list:
* the value of ``template_name`` on the view (if provided)
* the contents of the ``template_name_field`` field on the
object instance that the view is operating upon (if available)
* ``<app_label>/<model_name><template_name_suffix>.html``
|
Return a list of template names to be used for the request. May not be
called if render_to_response() is overridden. Return the following list: | def get_template_names(self):
"""
Return a list of template names to be used for the request. May not be
called if render_to_response() is overridden. Return the following list:
* the value of ``template_name`` on the view (if provided)
* the contents of the ``template_name_field`` field on the
object instance that the view is operating upon (if available)
* ``<app_label>/<model_name><template_name_suffix>.html``
"""
try:
names = super().get_template_names()
except ImproperlyConfigured:
# If template_name isn't specified, it's not a problem --
# we just start with an empty list.
names = []
# If self.template_name_field is set, grab the value of the field
# of that name from the object; this is the most specific template
# name, if given.
if self.object and self.template_name_field:
name = getattr(self.object, self.template_name_field, None)
if name:
names.insert(0, name)
# The least-specific option is the default <app>/<model>_detail.html;
# only use this if the object in question is a model.
if isinstance(self.object, models.Model):
object_meta = self.object._meta
names.append("%s/%s%s.html" % (
object_meta.app_label,
object_meta.model_name,
self.template_name_suffix
))
elif getattr(self, 'model', None) is not None and issubclass(self.model, models.Model):
names.append("%s/%s%s.html" % (
self.model._meta.app_label,
self.model._meta.model_name,
self.template_name_suffix
))
# If we still haven't managed to find any template names, we should
# re-raise the ImproperlyConfigured to alert the user.
if not names:
raise
return names | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"try",
":",
"names",
"=",
"super",
"(",
")",
".",
"get_template_names",
"(",
")",
"except",
"ImproperlyConfigured",
":",
"# If template_name isn't specified, it's not a problem --",
"# we just start with an empty list.",
"names",
"=",
"[",
"]",
"# If self.template_name_field is set, grab the value of the field",
"# of that name from the object; this is the most specific template",
"# name, if given.",
"if",
"self",
".",
"object",
"and",
"self",
".",
"template_name_field",
":",
"name",
"=",
"getattr",
"(",
"self",
".",
"object",
",",
"self",
".",
"template_name_field",
",",
"None",
")",
"if",
"name",
":",
"names",
".",
"insert",
"(",
"0",
",",
"name",
")",
"# The least-specific option is the default <app>/<model>_detail.html;",
"# only use this if the object in question is a model.",
"if",
"isinstance",
"(",
"self",
".",
"object",
",",
"models",
".",
"Model",
")",
":",
"object_meta",
"=",
"self",
".",
"object",
".",
"_meta",
"names",
".",
"append",
"(",
"\"%s/%s%s.html\"",
"%",
"(",
"object_meta",
".",
"app_label",
",",
"object_meta",
".",
"model_name",
",",
"self",
".",
"template_name_suffix",
")",
")",
"elif",
"getattr",
"(",
"self",
",",
"'model'",
",",
"None",
")",
"is",
"not",
"None",
"and",
"issubclass",
"(",
"self",
".",
"model",
",",
"models",
".",
"Model",
")",
":",
"names",
".",
"append",
"(",
"\"%s/%s%s.html\"",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"model_name",
",",
"self",
".",
"template_name_suffix",
")",
")",
"# If we still haven't managed to find any template names, we should",
"# re-raise the ImproperlyConfigured to alert the user.",
"if",
"not",
"names",
":",
"raise",
"return",
"names"
] | [
114,
4
] | [
160,
20
] | python | en | ['en', 'error', 'th'] | False |
bytes_to_text | (s, encoding) |
Convert bytes objects to strings, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
Return any non-bytes objects without change.
|
Convert bytes objects to strings, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd). | def bytes_to_text(s, encoding):
"""
Convert bytes objects to strings, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
Return any non-bytes objects without change.
"""
if isinstance(s, bytes):
return str(s, encoding, 'replace')
else:
return s | [
"def",
"bytes_to_text",
"(",
"s",
",",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"str",
"(",
"s",
",",
"encoding",
",",
"'replace'",
")",
"else",
":",
"return",
"s"
] | [
639,
0
] | [
650,
16
] | python | en | ['en', 'error', 'th'] | False |
split_domain_port | (host) |
Return a (domain, port) tuple from a given host.
Returned domain is lowercased. If the host is invalid, the domain will be
empty.
|
Return a (domain, port) tuple from a given host. | def split_domain_port(host):
"""
Return a (domain, port) tuple from a given host.
Returned domain is lowercased. If the host is invalid, the domain will be
empty.
"""
host = host.lower()
if not host_validation_re.match(host):
return '', ''
if host[-1] == ']':
# It's an IPv6 address without a port.
return host, ''
bits = host.rsplit(':', 1)
domain, port = bits if len(bits) == 2 else (bits[0], '')
# Remove a trailing dot (if present) from the domain.
domain = domain[:-1] if domain.endswith('.') else domain
return domain, port | [
"def",
"split_domain_port",
"(",
"host",
")",
":",
"host",
"=",
"host",
".",
"lower",
"(",
")",
"if",
"not",
"host_validation_re",
".",
"match",
"(",
"host",
")",
":",
"return",
"''",
",",
"''",
"if",
"host",
"[",
"-",
"1",
"]",
"==",
"']'",
":",
"# It's an IPv6 address without a port.",
"return",
"host",
",",
"''",
"bits",
"=",
"host",
".",
"rsplit",
"(",
"':'",
",",
"1",
")",
"domain",
",",
"port",
"=",
"bits",
"if",
"len",
"(",
"bits",
")",
"==",
"2",
"else",
"(",
"bits",
"[",
"0",
"]",
",",
"''",
")",
"# Remove a trailing dot (if present) from the domain.",
"domain",
"=",
"domain",
"[",
":",
"-",
"1",
"]",
"if",
"domain",
".",
"endswith",
"(",
"'.'",
")",
"else",
"domain",
"return",
"domain",
",",
"port"
] | [
653,
0
] | [
672,
23
] | python | en | ['en', 'error', 'th'] | False |
validate_host | (host, allowed_hosts) |
Validate the given host for this site.
Check that the host looks valid and matches a host or host pattern in the
given list of ``allowed_hosts``. Any pattern beginning with a period
matches a domain and all its subdomains (e.g. ``.example.com`` matches
``example.com`` and any subdomain), ``*`` matches anything, and anything
else must match exactly.
Note: This function assumes that the given host is lowercased and has
already had the port, if any, stripped off.
Return ``True`` for a valid host, ``False`` otherwise.
|
Validate the given host for this site. | def validate_host(host, allowed_hosts):
"""
Validate the given host for this site.
Check that the host looks valid and matches a host or host pattern in the
given list of ``allowed_hosts``. Any pattern beginning with a period
matches a domain and all its subdomains (e.g. ``.example.com`` matches
``example.com`` and any subdomain), ``*`` matches anything, and anything
else must match exactly.
Note: This function assumes that the given host is lowercased and has
already had the port, if any, stripped off.
Return ``True`` for a valid host, ``False`` otherwise.
"""
return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts) | [
"def",
"validate_host",
"(",
"host",
",",
"allowed_hosts",
")",
":",
"return",
"any",
"(",
"pattern",
"==",
"'*'",
"or",
"is_same_domain",
"(",
"host",
",",
"pattern",
")",
"for",
"pattern",
"in",
"allowed_hosts",
")"
] | [
675,
0
] | [
690,
92
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.accepted_types | (self) | Return a list of MediaType instances. | Return a list of MediaType instances. | def accepted_types(self):
"""Return a list of MediaType instances."""
return parse_accept_header(self.headers.get('Accept', '*/*')) | [
"def",
"accepted_types",
"(",
"self",
")",
":",
"return",
"parse_accept_header",
"(",
"self",
".",
"headers",
".",
"get",
"(",
"'Accept'",
",",
"'*/*'",
")",
")"
] | [
90,
4
] | [
92,
69
] | python | en | ['en', 'en', 'en'] | True |
HttpRequest._set_content_type_params | (self, meta) | Set content_type, content_params, and encoding. | Set content_type, content_params, and encoding. | def _set_content_type_params(self, meta):
"""Set content_type, content_params, and encoding."""
self.content_type, self.content_params = cgi.parse_header(meta.get('CONTENT_TYPE', ''))
if 'charset' in self.content_params:
try:
codecs.lookup(self.content_params['charset'])
except LookupError:
pass
else:
self.encoding = self.content_params['charset'] | [
"def",
"_set_content_type_params",
"(",
"self",
",",
"meta",
")",
":",
"self",
".",
"content_type",
",",
"self",
".",
"content_params",
"=",
"cgi",
".",
"parse_header",
"(",
"meta",
".",
"get",
"(",
"'CONTENT_TYPE'",
",",
"''",
")",
")",
"if",
"'charset'",
"in",
"self",
".",
"content_params",
":",
"try",
":",
"codecs",
".",
"lookup",
"(",
"self",
".",
"content_params",
"[",
"'charset'",
"]",
")",
"except",
"LookupError",
":",
"pass",
"else",
":",
"self",
".",
"encoding",
"=",
"self",
".",
"content_params",
"[",
"'charset'",
"]"
] | [
100,
4
] | [
109,
62
] | python | en | ['en', 'en', 'en'] | True |
HttpRequest._get_raw_host | (self) |
Return the HTTP host using the environment or request headers. Skip
allowed hosts protection, so may return an insecure host.
|
Return the HTTP host using the environment or request headers. Skip
allowed hosts protection, so may return an insecure host.
| def _get_raw_host(self):
"""
Return the HTTP host using the environment or request headers. Skip
allowed hosts protection, so may return an insecure host.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = self.get_port()
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
return host | [
"def",
"_get_raw_host",
"(",
"self",
")",
":",
"# We try three options, in order of decreasing preference.",
"if",
"settings",
".",
"USE_X_FORWARDED_HOST",
"and",
"(",
"'HTTP_X_FORWARDED_HOST'",
"in",
"self",
".",
"META",
")",
":",
"host",
"=",
"self",
".",
"META",
"[",
"'HTTP_X_FORWARDED_HOST'",
"]",
"elif",
"'HTTP_HOST'",
"in",
"self",
".",
"META",
":",
"host",
"=",
"self",
".",
"META",
"[",
"'HTTP_HOST'",
"]",
"else",
":",
"# Reconstruct the host using the algorithm from PEP 333.",
"host",
"=",
"self",
".",
"META",
"[",
"'SERVER_NAME'",
"]",
"server_port",
"=",
"self",
".",
"get_port",
"(",
")",
"if",
"server_port",
"!=",
"(",
"'443'",
"if",
"self",
".",
"is_secure",
"(",
")",
"else",
"'80'",
")",
":",
"host",
"=",
"'%s:%s'",
"%",
"(",
"host",
",",
"server_port",
")",
"return",
"host"
] | [
111,
4
] | [
128,
19
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.get_host | (self) | Return the HTTP host using the environment or request headers. | Return the HTTP host using the environment or request headers. | def get_host(self):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
allowed_hosts = ['.localhost', '127.0.0.1', '[::1]']
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
else:
msg += " The domain name provided is not valid according to RFC 1034/1035."
raise DisallowedHost(msg) | [
"def",
"get_host",
"(",
"self",
")",
":",
"host",
"=",
"self",
".",
"_get_raw_host",
"(",
")",
"# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.",
"allowed_hosts",
"=",
"settings",
".",
"ALLOWED_HOSTS",
"if",
"settings",
".",
"DEBUG",
"and",
"not",
"allowed_hosts",
":",
"allowed_hosts",
"=",
"[",
"'.localhost'",
",",
"'127.0.0.1'",
",",
"'[::1]'",
"]",
"domain",
",",
"port",
"=",
"split_domain_port",
"(",
"host",
")",
"if",
"domain",
"and",
"validate_host",
"(",
"domain",
",",
"allowed_hosts",
")",
":",
"return",
"host",
"else",
":",
"msg",
"=",
"\"Invalid HTTP_HOST header: %r.\"",
"%",
"host",
"if",
"domain",
":",
"msg",
"+=",
"\" You may need to add %r to ALLOWED_HOSTS.\"",
"%",
"domain",
"else",
":",
"msg",
"+=",
"\" The domain name provided is not valid according to RFC 1034/1035.\"",
"raise",
"DisallowedHost",
"(",
"msg",
")"
] | [
130,
4
] | [
148,
37
] | python | en | ['en', 'en', 'en'] | True |
HttpRequest.get_port | (self) | Return the port number for the request as a string. | Return the port number for the request as a string. | def get_port(self):
"""Return the port number for the request as a string."""
if settings.USE_X_FORWARDED_PORT and 'HTTP_X_FORWARDED_PORT' in self.META:
port = self.META['HTTP_X_FORWARDED_PORT']
else:
port = self.META['SERVER_PORT']
return str(port) | [
"def",
"get_port",
"(",
"self",
")",
":",
"if",
"settings",
".",
"USE_X_FORWARDED_PORT",
"and",
"'HTTP_X_FORWARDED_PORT'",
"in",
"self",
".",
"META",
":",
"port",
"=",
"self",
".",
"META",
"[",
"'HTTP_X_FORWARDED_PORT'",
"]",
"else",
":",
"port",
"=",
"self",
".",
"META",
"[",
"'SERVER_PORT'",
"]",
"return",
"str",
"(",
"port",
")"
] | [
150,
4
] | [
156,
24
] | python | en | ['en', 'en', 'en'] | True |
HttpRequest.get_signed_cookie | (self, key, default=RAISE_ERROR, salt='', max_age=None) |
Attempt to return a signed cookie. If the signature fails or the
cookie has expired, raise an exception, unless the `default` argument
is provided, in which case return that value.
|
Attempt to return a signed cookie. If the signature fails or the
cookie has expired, raise an exception, unless the `default` argument
is provided, in which case return that value.
| def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
"""
Attempt to return a signed cookie. If the signature fails or the
cookie has expired, raise an exception, unless the `default` argument
is provided, in which case return that value.
"""
try:
cookie_value = self.COOKIES[key]
except KeyError:
if default is not RAISE_ERROR:
return default
else:
raise
try:
value = signing.get_cookie_signer(salt=key + salt).unsign(
cookie_value, max_age=max_age)
except signing.BadSignature:
if default is not RAISE_ERROR:
return default
else:
raise
return value | [
"def",
"get_signed_cookie",
"(",
"self",
",",
"key",
",",
"default",
"=",
"RAISE_ERROR",
",",
"salt",
"=",
"''",
",",
"max_age",
"=",
"None",
")",
":",
"try",
":",
"cookie_value",
"=",
"self",
".",
"COOKIES",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"not",
"RAISE_ERROR",
":",
"return",
"default",
"else",
":",
"raise",
"try",
":",
"value",
"=",
"signing",
".",
"get_cookie_signer",
"(",
"salt",
"=",
"key",
"+",
"salt",
")",
".",
"unsign",
"(",
"cookie_value",
",",
"max_age",
"=",
"max_age",
")",
"except",
"signing",
".",
"BadSignature",
":",
"if",
"default",
"is",
"not",
"RAISE_ERROR",
":",
"return",
"default",
"else",
":",
"raise",
"return",
"value"
] | [
173,
4
] | [
194,
20
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.get_raw_uri | (self) |
Return an absolute URI from variables available in this request. Skip
allowed hosts protection, so may return insecure URI.
|
Return an absolute URI from variables available in this request. Skip
allowed hosts protection, so may return insecure URI.
| def get_raw_uri(self):
"""
Return an absolute URI from variables available in this request. Skip
allowed hosts protection, so may return insecure URI.
"""
return '{scheme}://{host}{path}'.format(
scheme=self.scheme,
host=self._get_raw_host(),
path=self.get_full_path(),
) | [
"def",
"get_raw_uri",
"(",
"self",
")",
":",
"return",
"'{scheme}://{host}{path}'",
".",
"format",
"(",
"scheme",
"=",
"self",
".",
"scheme",
",",
"host",
"=",
"self",
".",
"_get_raw_host",
"(",
")",
",",
"path",
"=",
"self",
".",
"get_full_path",
"(",
")",
",",
")"
] | [
196,
4
] | [
205,
9
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.build_absolute_uri | (self, location=None) |
Build an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, build the absolute URI
using request.get_full_path(). If the location is absolute, convert it
to an RFC 3987 compliant URI and return it. If location is relative or
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
URL constructed from the request variables.
|
Build an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, build the absolute URI
using request.get_full_path(). If the location is absolute, convert it
to an RFC 3987 compliant URI and return it. If location is relative or
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
URL constructed from the request variables.
| def build_absolute_uri(self, location=None):
"""
Build an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, build the absolute URI
using request.get_full_path(). If the location is absolute, convert it
to an RFC 3987 compliant URI and return it. If location is relative or
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
URL constructed from the request variables.
"""
if location is None:
# Make it an absolute url (but schemeless and domainless) for the
# edge case that the path starts with '//'.
location = '//%s' % self.get_full_path()
else:
# Coerce lazy locations.
location = str(location)
bits = urlsplit(location)
if not (bits.scheme and bits.netloc):
# Handle the simple, most common case. If the location is absolute
# and a scheme or host (netloc) isn't provided, skip an expensive
# urljoin() as long as no path segments are '.' or '..'.
if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
'/./' not in bits.path and '/../' not in bits.path):
# If location starts with '//' but has no netloc, reuse the
# schema and netloc from the current request. Strip the double
# slashes and continue as if it wasn't specified.
if location.startswith('//'):
location = location[2:]
location = self._current_scheme_host + location
else:
# Join the constructed URL with the provided location, which
# allows the provided location to apply query strings to the
# base path.
location = urljoin(self._current_scheme_host + self.path, location)
return iri_to_uri(location) | [
"def",
"build_absolute_uri",
"(",
"self",
",",
"location",
"=",
"None",
")",
":",
"if",
"location",
"is",
"None",
":",
"# Make it an absolute url (but schemeless and domainless) for the",
"# edge case that the path starts with '//'.",
"location",
"=",
"'//%s'",
"%",
"self",
".",
"get_full_path",
"(",
")",
"else",
":",
"# Coerce lazy locations.",
"location",
"=",
"str",
"(",
"location",
")",
"bits",
"=",
"urlsplit",
"(",
"location",
")",
"if",
"not",
"(",
"bits",
".",
"scheme",
"and",
"bits",
".",
"netloc",
")",
":",
"# Handle the simple, most common case. If the location is absolute",
"# and a scheme or host (netloc) isn't provided, skip an expensive",
"# urljoin() as long as no path segments are '.' or '..'.",
"if",
"(",
"bits",
".",
"path",
".",
"startswith",
"(",
"'/'",
")",
"and",
"not",
"bits",
".",
"scheme",
"and",
"not",
"bits",
".",
"netloc",
"and",
"'/./'",
"not",
"in",
"bits",
".",
"path",
"and",
"'/../'",
"not",
"in",
"bits",
".",
"path",
")",
":",
"# If location starts with '//' but has no netloc, reuse the",
"# schema and netloc from the current request. Strip the double",
"# slashes and continue as if it wasn't specified.",
"if",
"location",
".",
"startswith",
"(",
"'//'",
")",
":",
"location",
"=",
"location",
"[",
"2",
":",
"]",
"location",
"=",
"self",
".",
"_current_scheme_host",
"+",
"location",
"else",
":",
"# Join the constructed URL with the provided location, which",
"# allows the provided location to apply query strings to the",
"# base path.",
"location",
"=",
"urljoin",
"(",
"self",
".",
"_current_scheme_host",
"+",
"self",
".",
"path",
",",
"location",
")",
"return",
"iri_to_uri",
"(",
"location",
")"
] | [
207,
4
] | [
241,
35
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest._get_scheme | (self) |
Hook for subclasses like WSGIRequest to implement. Return 'http' by
default.
|
Hook for subclasses like WSGIRequest to implement. Return 'http' by
default.
| def _get_scheme(self):
"""
Hook for subclasses like WSGIRequest to implement. Return 'http' by
default.
"""
return 'http' | [
"def",
"_get_scheme",
"(",
"self",
")",
":",
"return",
"'http'"
] | [
247,
4
] | [
252,
21
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.encoding | (self, val) |
Set the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, remove and recreate it on the
next access (so that it is decoded correctly).
|
Set the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, remove and recreate it on the
next access (so that it is decoded correctly).
| def encoding(self, val):
"""
Set the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, remove and recreate it on the
next access (so that it is decoded correctly).
"""
self._encoding = val
if hasattr(self, 'GET'):
del self.GET
if hasattr(self, '_post'):
del self._post | [
"def",
"encoding",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"_encoding",
"=",
"val",
"if",
"hasattr",
"(",
"self",
",",
"'GET'",
")",
":",
"del",
"self",
".",
"GET",
"if",
"hasattr",
"(",
"self",
",",
"'_post'",
")",
":",
"del",
"self",
".",
"_post"
] | [
285,
4
] | [
295,
26
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.parse_file_upload | (self, META, post_data) | Return a tuple of (POST QueryDict, FILES MultiValueDict). | Return a tuple of (POST QueryDict, FILES MultiValueDict). | def parse_file_upload(self, META, post_data):
"""Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
self.upload_handlers = ImmutableList(
self.upload_handlers,
warning="You cannot alter upload handlers after the upload has been processed."
)
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse() | [
"def",
"parse_file_upload",
"(",
"self",
",",
"META",
",",
"post_data",
")",
":",
"self",
".",
"upload_handlers",
"=",
"ImmutableList",
"(",
"self",
".",
"upload_handlers",
",",
"warning",
"=",
"\"You cannot alter upload handlers after the upload has been processed.\"",
")",
"parser",
"=",
"MultiPartParser",
"(",
"META",
",",
"post_data",
",",
"self",
".",
"upload_handlers",
",",
"self",
".",
"encoding",
")",
"return",
"parser",
".",
"parse",
"(",
")"
] | [
314,
4
] | [
321,
29
] | python | en | ['en', 'la', 'en'] | True |
HttpRequest._load_post_and_files | (self) | Populate self._post and self._files if the content-type is a form type | Populate self._post and self._files if the content-type is a form type | def _load_post_and_files(self):
"""Populate self._post and self._files if the content-type is a form type"""
if self.method != 'POST':
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
return
if self._read_started and not hasattr(self, '_body'):
self._mark_post_parse_error()
return
if self.content_type == 'multipart/form-data':
if hasattr(self, '_body'):
# Use already read data
data = BytesIO(self._body)
else:
data = self
try:
self._post, self._files = self.parse_file_upload(self.META, data)
except MultiPartParserError:
# An error occurred while parsing POST data. Since when
# formatting the error the request handler might access
# self.POST, set self._post and self._file to prevent
# attempts to parse POST data again.
self._mark_post_parse_error()
raise
elif self.content_type == 'application/x-www-form-urlencoded':
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
else:
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict() | [
"def",
"_load_post_and_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"!=",
"'POST'",
":",
"self",
".",
"_post",
",",
"self",
".",
"_files",
"=",
"QueryDict",
"(",
"encoding",
"=",
"self",
".",
"_encoding",
")",
",",
"MultiValueDict",
"(",
")",
"return",
"if",
"self",
".",
"_read_started",
"and",
"not",
"hasattr",
"(",
"self",
",",
"'_body'",
")",
":",
"self",
".",
"_mark_post_parse_error",
"(",
")",
"return",
"if",
"self",
".",
"content_type",
"==",
"'multipart/form-data'",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_body'",
")",
":",
"# Use already read data",
"data",
"=",
"BytesIO",
"(",
"self",
".",
"_body",
")",
"else",
":",
"data",
"=",
"self",
"try",
":",
"self",
".",
"_post",
",",
"self",
".",
"_files",
"=",
"self",
".",
"parse_file_upload",
"(",
"self",
".",
"META",
",",
"data",
")",
"except",
"MultiPartParserError",
":",
"# An error occurred while parsing POST data. Since when",
"# formatting the error the request handler might access",
"# self.POST, set self._post and self._file to prevent",
"# attempts to parse POST data again.",
"self",
".",
"_mark_post_parse_error",
"(",
")",
"raise",
"elif",
"self",
".",
"content_type",
"==",
"'application/x-www-form-urlencoded'",
":",
"self",
".",
"_post",
",",
"self",
".",
"_files",
"=",
"QueryDict",
"(",
"self",
".",
"body",
",",
"encoding",
"=",
"self",
".",
"_encoding",
")",
",",
"MultiValueDict",
"(",
")",
"else",
":",
"self",
".",
"_post",
",",
"self",
".",
"_files",
"=",
"QueryDict",
"(",
"encoding",
"=",
"self",
".",
"_encoding",
")",
",",
"MultiValueDict",
"(",
")"
] | [
345,
4
] | [
372,
90
] | python | en | ['en', 'en', 'en'] | True |
HttpHeaders.__getitem__ | (self, key) | Allow header lookup using underscores in place of hyphens. | Allow header lookup using underscores in place of hyphens. | def __getitem__(self, key):
"""Allow header lookup using underscores in place of hyphens."""
return super().__getitem__(key.replace('_', '-')) | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"super",
"(",
")",
".",
"__getitem__",
"(",
"key",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
")"
] | [
421,
4
] | [
423,
57
] | python | en | ['en', 'en', 'en'] | True |
QueryDict.fromkeys | (cls, iterable, value='', mutable=False, encoding=None) |
Return a new QueryDict with keys (may be repeated) from an iterable and
values from value.
|
Return a new QueryDict with keys (may be repeated) from an iterable and
values from value.
| def fromkeys(cls, iterable, value='', mutable=False, encoding=None):
"""
Return a new QueryDict with keys (may be repeated) from an iterable and
values from value.
"""
q = cls('', mutable=True, encoding=encoding)
for key in iterable:
q.appendlist(key, value)
if not mutable:
q._mutable = False
return q | [
"def",
"fromkeys",
"(",
"cls",
",",
"iterable",
",",
"value",
"=",
"''",
",",
"mutable",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"q",
"=",
"cls",
"(",
"''",
",",
"mutable",
"=",
"True",
",",
"encoding",
"=",
"encoding",
")",
"for",
"key",
"in",
"iterable",
":",
"q",
".",
"appendlist",
"(",
"key",
",",
"value",
")",
"if",
"not",
"mutable",
":",
"q",
".",
"_mutable",
"=",
"False",
"return",
"q"
] | [
485,
4
] | [
495,
16
] | python | en | ['en', 'error', 'th'] | False |
QueryDict.copy | (self) | Return a mutable copy of this object. | Return a mutable copy of this object. | def copy(self):
"""Return a mutable copy of this object."""
return self.__deepcopy__({}) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__deepcopy__",
"(",
"{",
"}",
")"
] | [
568,
4
] | [
570,
36
] | python | en | ['en', 'en', 'en'] | True |
QueryDict.urlencode | (self, safe=None) |
Return an encoded string of all query string arguments.
`safe` specifies characters which don't require quoting, for example::
>>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'
>>> q.urlencode()
'next=%2Fa%26b%2F'
>>> q.urlencode(safe='/')
'next=/a%26b/'
|
Return an encoded string of all query string arguments. | def urlencode(self, safe=None):
"""
Return an encoded string of all query string arguments.
`safe` specifies characters which don't require quoting, for example::
>>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'
>>> q.urlencode()
'next=%2Fa%26b%2F'
>>> q.urlencode(safe='/')
'next=/a%26b/'
"""
output = []
if safe:
safe = safe.encode(self.encoding)
def encode(k, v):
return '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
def encode(k, v):
return urlencode({k: v})
for k, list_ in self.lists():
output.extend(
encode(k.encode(self.encoding), str(v).encode(self.encoding))
for v in list_
)
return '&'.join(output) | [
"def",
"urlencode",
"(",
"self",
",",
"safe",
"=",
"None",
")",
":",
"output",
"=",
"[",
"]",
"if",
"safe",
":",
"safe",
"=",
"safe",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
"def",
"encode",
"(",
"k",
",",
"v",
")",
":",
"return",
"'%s=%s'",
"%",
"(",
"(",
"quote",
"(",
"k",
",",
"safe",
")",
",",
"quote",
"(",
"v",
",",
"safe",
")",
")",
")",
"else",
":",
"def",
"encode",
"(",
"k",
",",
"v",
")",
":",
"return",
"urlencode",
"(",
"{",
"k",
":",
"v",
"}",
")",
"for",
"k",
",",
"list_",
"in",
"self",
".",
"lists",
"(",
")",
":",
"output",
".",
"extend",
"(",
"encode",
"(",
"k",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
",",
"str",
"(",
"v",
")",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
")",
"for",
"v",
"in",
"list_",
")",
"return",
"'&'",
".",
"join",
"(",
"output",
")"
] | [
572,
4
] | [
599,
31
] | python | en | ['en', 'error', 'th'] | False |
register_range | (pgrange, pyrange, conn_or_curs, globally=False) | Create and register an adapter and the typecasters to convert between
a PostgreSQL |range|_ type and a PostgreSQL `Range` subclass.
:param pgrange: the name of the PostgreSQL |range| type. Can be
schema-qualified
:param pyrange: a `Range` strict subclass, or just a name to give to a new
class
:param conn_or_curs: a connection or cursor used to find the oid of the
range and its subtype; the typecaster is registered in a scope limited
to this object, unless *globally* is set to `!True`
:param globally: if `!False` (default) register the typecaster only on
*conn_or_curs*, otherwise register it globally
:return: `RangeCaster` instance responsible for the conversion
If a string is passed to *pyrange*, a new `Range` subclass is created
with such name and will be available as the `~RangeCaster.range` attribute
of the returned `RangeCaster` object.
The function queries the database on *conn_or_curs* to inspect the
*pgrange* type and raises `~psycopg2.ProgrammingError` if the type is not
found. If querying the database is not advisable, use directly the
`RangeCaster` class and register the adapter and typecasters using the
provided functions.
| Create and register an adapter and the typecasters to convert between
a PostgreSQL |range|_ type and a PostgreSQL `Range` subclass. | def register_range(pgrange, pyrange, conn_or_curs, globally=False):
"""Create and register an adapter and the typecasters to convert between
a PostgreSQL |range|_ type and a PostgreSQL `Range` subclass.
:param pgrange: the name of the PostgreSQL |range| type. Can be
schema-qualified
:param pyrange: a `Range` strict subclass, or just a name to give to a new
class
:param conn_or_curs: a connection or cursor used to find the oid of the
range and its subtype; the typecaster is registered in a scope limited
to this object, unless *globally* is set to `!True`
:param globally: if `!False` (default) register the typecaster only on
*conn_or_curs*, otherwise register it globally
:return: `RangeCaster` instance responsible for the conversion
If a string is passed to *pyrange*, a new `Range` subclass is created
with such name and will be available as the `~RangeCaster.range` attribute
of the returned `RangeCaster` object.
The function queries the database on *conn_or_curs* to inspect the
*pgrange* type and raises `~psycopg2.ProgrammingError` if the type is not
found. If querying the database is not advisable, use directly the
`RangeCaster` class and register the adapter and typecasters using the
provided functions.
"""
caster = RangeCaster._from_db(pgrange, pyrange, conn_or_curs)
caster._register(not globally and conn_or_curs or None)
return caster | [
"def",
"register_range",
"(",
"pgrange",
",",
"pyrange",
",",
"conn_or_curs",
",",
"globally",
"=",
"False",
")",
":",
"caster",
"=",
"RangeCaster",
".",
"_from_db",
"(",
"pgrange",
",",
"pyrange",
",",
"conn_or_curs",
")",
"caster",
".",
"_register",
"(",
"not",
"globally",
"and",
"conn_or_curs",
"or",
"None",
")",
"return",
"caster"
] | [
209,
0
] | [
237,
17
] | python | en | ['en', 'en', 'en'] | True |
Range.lower | (self) | The lower bound of the range. `!None` if empty or unbound. | The lower bound of the range. `!None` if empty or unbound. | def lower(self):
"""The lower bound of the range. `!None` if empty or unbound."""
return self._lower | [
"def",
"lower",
"(",
"self",
")",
":",
"return",
"self",
".",
"_lower"
] | [
78,
4
] | [
80,
26
] | python | en | ['en', 'en', 'en'] | True |
Range.upper | (self) | The upper bound of the range. `!None` if empty or unbound. | The upper bound of the range. `!None` if empty or unbound. | def upper(self):
"""The upper bound of the range. `!None` if empty or unbound."""
return self._upper | [
"def",
"upper",
"(",
"self",
")",
":",
"return",
"self",
".",
"_upper"
] | [
83,
4
] | [
85,
26
] | python | en | ['en', 'en', 'en'] | True |
Range.isempty | (self) | `!True` if the range is empty. | `!True` if the range is empty. | def isempty(self):
"""`!True` if the range is empty."""
return self._bounds is None | [
"def",
"isempty",
"(",
"self",
")",
":",
"return",
"self",
".",
"_bounds",
"is",
"None"
] | [
88,
4
] | [
90,
35
] | python | en | ['en', 'sr', 'en'] | True |
Range.lower_inf | (self) | `!True` if the range doesn't have a lower bound. | `!True` if the range doesn't have a lower bound. | def lower_inf(self):
"""`!True` if the range doesn't have a lower bound."""
if self._bounds is None:
return False
return self._lower is None | [
"def",
"lower_inf",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bounds",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"_lower",
"is",
"None"
] | [
93,
4
] | [
97,
34
] | python | en | ['en', 'en', 'en'] | True |
Range.upper_inf | (self) | `!True` if the range doesn't have an upper bound. | `!True` if the range doesn't have an upper bound. | def upper_inf(self):
"""`!True` if the range doesn't have an upper bound."""
if self._bounds is None:
return False
return self._upper is None | [
"def",
"upper_inf",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bounds",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"_upper",
"is",
"None"
] | [
100,
4
] | [
104,
34
] | python | en | ['en', 'en', 'en'] | True |
Range.lower_inc | (self) | `!True` if the lower bound is included in the range. | `!True` if the lower bound is included in the range. | def lower_inc(self):
"""`!True` if the lower bound is included in the range."""
if self._bounds is None or self._lower is None:
return False
return self._bounds[0] == '[' | [
"def",
"lower_inc",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bounds",
"is",
"None",
"or",
"self",
".",
"_lower",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"_bounds",
"[",
"0",
"]",
"==",
"'['"
] | [
107,
4
] | [
111,
37
] | python | en | ['en', 'en', 'en'] | True |
Range.upper_inc | (self) | `!True` if the upper bound is included in the range. | `!True` if the upper bound is included in the range. | def upper_inc(self):
"""`!True` if the upper bound is included in the range."""
if self._bounds is None or self._upper is None:
return False
return self._bounds[1] == ']' | [
"def",
"upper_inc",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bounds",
"is",
"None",
"or",
"self",
".",
"_upper",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"_bounds",
"[",
"1",
"]",
"==",
"']'"
] | [
114,
4
] | [
118,
37
] | python | en | ['en', 'en', 'en'] | True |
RangeCaster._create_ranges | (self, pgrange, pyrange) | Create Range and RangeAdapter classes if needed. | Create Range and RangeAdapter classes if needed. | def _create_ranges(self, pgrange, pyrange):
"""Create Range and RangeAdapter classes if needed."""
# if got a string create a new RangeAdapter concrete type (with a name)
# else take it as an adapter. Passing an adapter should be considered
# an implementation detail and is not documented. It is currently used
# for the numeric ranges.
self.adapter = None
if isinstance(pgrange, str):
self.adapter = type(pgrange, (RangeAdapter,), {})
self.adapter.name = pgrange
else:
try:
if issubclass(pgrange, RangeAdapter) \
and pgrange is not RangeAdapter:
self.adapter = pgrange
except TypeError:
pass
if self.adapter is None:
raise TypeError(
'pgrange must be a string or a RangeAdapter strict subclass')
self.range = None
try:
if isinstance(pyrange, str):
self.range = type(pyrange, (Range,), {})
if issubclass(pyrange, Range) and pyrange is not Range:
self.range = pyrange
except TypeError:
pass
if self.range is None:
raise TypeError(
'pyrange must be a type or a Range strict subclass') | [
"def",
"_create_ranges",
"(",
"self",
",",
"pgrange",
",",
"pyrange",
")",
":",
"# if got a string create a new RangeAdapter concrete type (with a name)",
"# else take it as an adapter. Passing an adapter should be considered",
"# an implementation detail and is not documented. It is currently used",
"# for the numeric ranges.",
"self",
".",
"adapter",
"=",
"None",
"if",
"isinstance",
"(",
"pgrange",
",",
"str",
")",
":",
"self",
".",
"adapter",
"=",
"type",
"(",
"pgrange",
",",
"(",
"RangeAdapter",
",",
")",
",",
"{",
"}",
")",
"self",
".",
"adapter",
".",
"name",
"=",
"pgrange",
"else",
":",
"try",
":",
"if",
"issubclass",
"(",
"pgrange",
",",
"RangeAdapter",
")",
"and",
"pgrange",
"is",
"not",
"RangeAdapter",
":",
"self",
".",
"adapter",
"=",
"pgrange",
"except",
"TypeError",
":",
"pass",
"if",
"self",
".",
"adapter",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'pgrange must be a string or a RangeAdapter strict subclass'",
")",
"self",
".",
"range",
"=",
"None",
"try",
":",
"if",
"isinstance",
"(",
"pyrange",
",",
"str",
")",
":",
"self",
".",
"range",
"=",
"type",
"(",
"pyrange",
",",
"(",
"Range",
",",
")",
",",
"{",
"}",
")",
"if",
"issubclass",
"(",
"pyrange",
",",
"Range",
")",
"and",
"pyrange",
"is",
"not",
"Range",
":",
"self",
".",
"range",
"=",
"pyrange",
"except",
"TypeError",
":",
"pass",
"if",
"self",
".",
"range",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'pyrange must be a type or a Range strict subclass'",
")"
] | [
309,
4
] | [
342,
68
] | python | en | ['en', 'sn', 'en'] | True |
RangeCaster._from_db | (self, name, pyrange, conn_or_curs) | Return a `RangeCaster` instance for the type *pgrange*.
Raise `ProgrammingError` if the type is not found.
| Return a `RangeCaster` instance for the type *pgrange*. | def _from_db(self, name, pyrange, conn_or_curs):
"""Return a `RangeCaster` instance for the type *pgrange*.
Raise `ProgrammingError` if the type is not found.
"""
from psycopg2.extensions import STATUS_IN_TRANSACTION
from psycopg2.extras import _solve_conn_curs
conn, curs = _solve_conn_curs(conn_or_curs)
if conn.info.server_version < 90200:
raise ProgrammingError("range types not available in version %s"
% conn.info.server_version)
# Store the transaction status of the connection to revert it after use
conn_status = conn.status
# Use the correct schema
if '.' in name:
schema, tname = name.split('.', 1)
else:
tname = name
schema = 'public'
# get the type oid and attributes
try:
curs.execute("""\
select rngtypid, rngsubtype,
(select typarray from pg_type where oid = rngtypid)
from pg_range r
join pg_type t on t.oid = rngtypid
join pg_namespace ns on ns.oid = typnamespace
where typname = %s and ns.nspname = %s;
""", (tname, schema))
except ProgrammingError:
if not conn.autocommit:
conn.rollback()
raise
else:
rec = curs.fetchone()
# revert the status of the connection as before the command
if (conn_status != STATUS_IN_TRANSACTION
and not conn.autocommit):
conn.rollback()
if not rec:
raise ProgrammingError(
f"PostgreSQL type '{name}' not found")
type, subtype, array = rec
return RangeCaster(name, pyrange,
oid=type, subtype_oid=subtype, array_oid=array) | [
"def",
"_from_db",
"(",
"self",
",",
"name",
",",
"pyrange",
",",
"conn_or_curs",
")",
":",
"from",
"psycopg2",
".",
"extensions",
"import",
"STATUS_IN_TRANSACTION",
"from",
"psycopg2",
".",
"extras",
"import",
"_solve_conn_curs",
"conn",
",",
"curs",
"=",
"_solve_conn_curs",
"(",
"conn_or_curs",
")",
"if",
"conn",
".",
"info",
".",
"server_version",
"<",
"90200",
":",
"raise",
"ProgrammingError",
"(",
"\"range types not available in version %s\"",
"%",
"conn",
".",
"info",
".",
"server_version",
")",
"# Store the transaction status of the connection to revert it after use",
"conn_status",
"=",
"conn",
".",
"status",
"# Use the correct schema",
"if",
"'.'",
"in",
"name",
":",
"schema",
",",
"tname",
"=",
"name",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"else",
":",
"tname",
"=",
"name",
"schema",
"=",
"'public'",
"# get the type oid and attributes",
"try",
":",
"curs",
".",
"execute",
"(",
"\"\"\"\\\nselect rngtypid, rngsubtype,\n (select typarray from pg_type where oid = rngtypid)\nfrom pg_range r\njoin pg_type t on t.oid = rngtypid\njoin pg_namespace ns on ns.oid = typnamespace\nwhere typname = %s and ns.nspname = %s;\n\"\"\"",
",",
"(",
"tname",
",",
"schema",
")",
")",
"except",
"ProgrammingError",
":",
"if",
"not",
"conn",
".",
"autocommit",
":",
"conn",
".",
"rollback",
"(",
")",
"raise",
"else",
":",
"rec",
"=",
"curs",
".",
"fetchone",
"(",
")",
"# revert the status of the connection as before the command",
"if",
"(",
"conn_status",
"!=",
"STATUS_IN_TRANSACTION",
"and",
"not",
"conn",
".",
"autocommit",
")",
":",
"conn",
".",
"rollback",
"(",
")",
"if",
"not",
"rec",
":",
"raise",
"ProgrammingError",
"(",
"f\"PostgreSQL type '{name}' not found\"",
")",
"type",
",",
"subtype",
",",
"array",
"=",
"rec",
"return",
"RangeCaster",
"(",
"name",
",",
"pyrange",
",",
"oid",
"=",
"type",
",",
"subtype_oid",
"=",
"subtype",
",",
"array_oid",
"=",
"array",
")"
] | [
345,
4
] | [
398,
59
] | python | en | ['en', 'no', 'en'] | True |
csrf_exempt | (view_func) | Mark a view function as being exempt from the CSRF view protection. | Mark a view function as being exempt from the CSRF view protection. | def csrf_exempt(view_func):
"""Mark a view function as being exempt from the CSRF view protection."""
# view_func.csrf_exempt = True would also work, but decorators are nicer
# if they don't have side effects, so return a new function.
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.csrf_exempt = True
return wraps(view_func)(wrapped_view) | [
"def",
"csrf_exempt",
"(",
"view_func",
")",
":",
"# view_func.csrf_exempt = True would also work, but decorators are nicer",
"# if they don't have side effects, so return a new function.",
"def",
"wrapped_view",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"view_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"wrapped_view",
".",
"csrf_exempt",
"=",
"True",
"return",
"wraps",
"(",
"view_func",
")",
"(",
"wrapped_view",
")"
] | [
48,
0
] | [
55,
41
] | python | en | ['en', 'en', 'en'] | True |
get_current_site | (request) |
Check if contrib.sites is installed and return either the current
``Site`` object or a ``RequestSite`` object based on the request.
|
Check if contrib.sites is installed and return either the current
``Site`` object or a ``RequestSite`` object based on the request.
| def get_current_site(request):
"""
Check if contrib.sites is installed and return either the current
``Site`` object or a ``RequestSite`` object based on the request.
"""
# Imports are inside the function because its point is to avoid importing
# the Site models when django.contrib.sites isn't installed.
if apps.is_installed('django.contrib.sites'):
from .models import Site
return Site.objects.get_current(request)
else:
from .requests import RequestSite
return RequestSite(request) | [
"def",
"get_current_site",
"(",
"request",
")",
":",
"# Imports are inside the function because its point is to avoid importing",
"# the Site models when django.contrib.sites isn't installed.",
"if",
"apps",
".",
"is_installed",
"(",
"'django.contrib.sites'",
")",
":",
"from",
".",
"models",
"import",
"Site",
"return",
"Site",
".",
"objects",
".",
"get_current",
"(",
"request",
")",
"else",
":",
"from",
".",
"requests",
"import",
"RequestSite",
"return",
"RequestSite",
"(",
"request",
")"
] | [
3,
0
] | [
15,
35
] | python | en | ['en', 'error', 'th'] | False |
scaled_dot_product_attention | (q, k, v) | Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be broadcastable for addition.
Args:
q: query shape == (..., seq_len_q, depth)
k: key shape == (..., seq_len_k, depth)
v: value shape == (..., seq_len_v, depth_v)
Returns:
output, attention_weights
from : https://www.tensorflow.org/tutorials/text/transformer
| Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be broadcastable for addition. | def scaled_dot_product_attention(q, k, v):
"""Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be broadcastable for addition.
Args:
q: query shape == (..., seq_len_q, depth)
k: key shape == (..., seq_len_k, depth)
v: value shape == (..., seq_len_v, depth_v)
Returns:
output, attention_weights
from : https://www.tensorflow.org/tutorials/text/transformer
"""
matmul_qk = tf.matmul(q, k, transpose_b=True) # (..., seq_len_q, seq_len_k)
# scale matmul_qk
dk = tf.cast(tf.shape(k)[-1], tf.float32)
scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
# softmax is normalized on the last axis (seq_len_k) so that the scores
# add up to 1.
attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, seq_len_k)
output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v)
return output, attention_weights | [
"def",
"scaled_dot_product_attention",
"(",
"q",
",",
"k",
",",
"v",
")",
":",
"matmul_qk",
"=",
"tf",
".",
"matmul",
"(",
"q",
",",
"k",
",",
"transpose_b",
"=",
"True",
")",
"# (..., seq_len_q, seq_len_k)",
"# scale matmul_qk",
"dk",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"shape",
"(",
"k",
")",
"[",
"-",
"1",
"]",
",",
"tf",
".",
"float32",
")",
"scaled_attention_logits",
"=",
"matmul_qk",
"/",
"tf",
".",
"math",
".",
"sqrt",
"(",
"dk",
")",
"# softmax is normalized on the last axis (seq_len_k) so that the scores",
"# add up to 1.",
"attention_weights",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"scaled_attention_logits",
",",
"axis",
"=",
"-",
"1",
")",
"# (..., seq_len_q, seq_len_k)",
"output",
"=",
"tf",
".",
"matmul",
"(",
"attention_weights",
",",
"v",
")",
"# (..., seq_len_q, depth_v)",
"return",
"output",
",",
"attention_weights"
] | [
58,
0
] | [
88,
36
] | python | en | ['en', 'en', 'en'] | True |
SelfAttention.__init__ | (self, d_model, spatial_dims, positional_encoding=True, name="self_attention") |
d_model : number of output channels
spatial_dim : spatial dimensions of input tensor (x , y)
if positional_encoding: depth must correspond to input channel number
adapted from: https://www.tensorflow.org/tutorials/text/transformer
|
d_model : number of output channels
spatial_dim : spatial dimensions of input tensor (x , y)
if positional_encoding: depth must correspond to input channel number
adapted from: https://www.tensorflow.org/tutorials/text/transformer
| def __init__(self, d_model, spatial_dims, positional_encoding=True, name="self_attention"):
'''
d_model : number of output channels
spatial_dim : spatial dimensions of input tensor (x , y)
if positional_encoding: depth must correspond to input channel number
adapted from: https://www.tensorflow.org/tutorials/text/transformer
'''
super().__init__(name=name)
self.d_model = d_model
self.spatial_dims=spatial_dims
self.spatial_dim = np.prod(spatial_dims)
self.wq = Dense(self.d_model, name=name+"_q")
self.wk = Dense(self.d_model, name=name+"_k")
self.wv = Dense(self.d_model, name=name+"_w")
self.positional_encoding=positional_encoding
if positional_encoding:
self.pos_embedding = Embedding(self.spatial_dim, d_model, name=name+"pos_enc") | [
"def",
"__init__",
"(",
"self",
",",
"d_model",
",",
"spatial_dims",
",",
"positional_encoding",
"=",
"True",
",",
"name",
"=",
"\"self_attention\"",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"name",
"=",
"name",
")",
"self",
".",
"d_model",
"=",
"d_model",
"self",
".",
"spatial_dims",
"=",
"spatial_dims",
"self",
".",
"spatial_dim",
"=",
"np",
".",
"prod",
"(",
"spatial_dims",
")",
"self",
".",
"wq",
"=",
"Dense",
"(",
"self",
".",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"_q\"",
")",
"self",
".",
"wk",
"=",
"Dense",
"(",
"self",
".",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"_k\"",
")",
"self",
".",
"wv",
"=",
"Dense",
"(",
"self",
".",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"_w\"",
")",
"self",
".",
"positional_encoding",
"=",
"positional_encoding",
"if",
"positional_encoding",
":",
"self",
".",
"pos_embedding",
"=",
"Embedding",
"(",
"self",
".",
"spatial_dim",
",",
"d_model",
",",
"name",
"=",
"name",
"+",
"\"pos_enc\"",
")"
] | [
6,
4
] | [
22,
90
] | python | en | ['en', 'error', 'th'] | False |
SelfAttention.call | (self, x) |
x : tensor with shape (batch_size, y, x, channels)
|
x : tensor with shape (batch_size, y, x, channels)
| def call(self, x):
'''
x : tensor with shape (batch_size, y, x, channels)
'''
shape = tf.shape(x)
batch_size = shape[0]
#spatial_dims = shape[1:-1]
#spatial_dim = tf.reduce_prod(spatial_dims)
depth_dim = shape[3]
if self.positional_encoding:
x_index = tf.range(self.spatial_dim, dtype=tf.int32)
pos_emb = self.pos_embedding(x_index) # (spa_dim, d_model)
pos_emb = tf.reshape(pos_emb, (self.spatial_dims[0], self.spatial_dims[1], self.d_model)) #for broadcasting purpose
x = x + pos_emb # broadcast
q = self.wq(x) # (batch_size, *spa_dims, d_model)
k = self.wk(x) # (batch_size, *spa_dims, d_model)
v = self.wv(x) # (batch_size, *spa_dims, d_model)
q = tf.reshape(q, (batch_size, -1, depth_dim)) # (batch_size, spa_dim, d_model)
k = tf.reshape(k, (batch_size, -1, depth_dim))
v = tf.reshape(v, (batch_size, -1, depth_dim))
# scaled_attention.shape == (batch_size, spa_dims, depth)
# attention_weights.shape == (batch_size, spa_dims, spa_dims)
scaled_attention, attention_weights = scaled_dot_product_attention(q, k, v)
output = tf.reshape(scaled_attention, (batch_size, self.spatial_dims[0], self.spatial_dims[1], self.d_model))
tf.identity(attention_weights, name=self.name+"_attention_weights")
return output, attention_weights | [
"def",
"call",
"(",
"self",
",",
"x",
")",
":",
"shape",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"batch_size",
"=",
"shape",
"[",
"0",
"]",
"#spatial_dims = shape[1:-1]",
"#spatial_dim = tf.reduce_prod(spatial_dims)",
"depth_dim",
"=",
"shape",
"[",
"3",
"]",
"if",
"self",
".",
"positional_encoding",
":",
"x_index",
"=",
"tf",
".",
"range",
"(",
"self",
".",
"spatial_dim",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"pos_emb",
"=",
"self",
".",
"pos_embedding",
"(",
"x_index",
")",
"# (spa_dim, d_model)",
"pos_emb",
"=",
"tf",
".",
"reshape",
"(",
"pos_emb",
",",
"(",
"self",
".",
"spatial_dims",
"[",
"0",
"]",
",",
"self",
".",
"spatial_dims",
"[",
"1",
"]",
",",
"self",
".",
"d_model",
")",
")",
"#for broadcasting purpose",
"x",
"=",
"x",
"+",
"pos_emb",
"# broadcast",
"q",
"=",
"self",
".",
"wq",
"(",
"x",
")",
"# (batch_size, *spa_dims, d_model)",
"k",
"=",
"self",
".",
"wk",
"(",
"x",
")",
"# (batch_size, *spa_dims, d_model)",
"v",
"=",
"self",
".",
"wv",
"(",
"x",
")",
"# (batch_size, *spa_dims, d_model)",
"q",
"=",
"tf",
".",
"reshape",
"(",
"q",
",",
"(",
"batch_size",
",",
"-",
"1",
",",
"depth_dim",
")",
")",
"# (batch_size, spa_dim, d_model)",
"k",
"=",
"tf",
".",
"reshape",
"(",
"k",
",",
"(",
"batch_size",
",",
"-",
"1",
",",
"depth_dim",
")",
")",
"v",
"=",
"tf",
".",
"reshape",
"(",
"v",
",",
"(",
"batch_size",
",",
"-",
"1",
",",
"depth_dim",
")",
")",
"# scaled_attention.shape == (batch_size, spa_dims, depth)",
"# attention_weights.shape == (batch_size, spa_dims, spa_dims)",
"scaled_attention",
",",
"attention_weights",
"=",
"scaled_dot_product_attention",
"(",
"q",
",",
"k",
",",
"v",
")",
"output",
"=",
"tf",
".",
"reshape",
"(",
"scaled_attention",
",",
"(",
"batch_size",
",",
"self",
".",
"spatial_dims",
"[",
"0",
"]",
",",
"self",
".",
"spatial_dims",
"[",
"1",
"]",
",",
"self",
".",
"d_model",
")",
")",
"tf",
".",
"identity",
"(",
"attention_weights",
",",
"name",
"=",
"self",
".",
"name",
"+",
"\"_attention_weights\"",
")",
"return",
"output",
",",
"attention_weights"
] | [
24,
4
] | [
53,
40
] | python | en | ['en', 'error', 'th'] | False |
MigrationRecorder.Migration | (cls) |
Lazy load to avoid AppRegistryNotReady if installed apps import
MigrationRecorder.
|
Lazy load to avoid AppRegistryNotReady if installed apps import
MigrationRecorder.
| def Migration(cls):
"""
Lazy load to avoid AppRegistryNotReady if installed apps import
MigrationRecorder.
"""
if cls._migration_class is None:
class Migration(models.Model):
app = models.CharField(max_length=255)
name = models.CharField(max_length=255)
applied = models.DateTimeField(default=now)
class Meta:
apps = Apps()
app_label = 'migrations'
db_table = 'django_migrations'
def __str__(self):
return 'Migration %s for %s' % (self.name, self.app)
cls._migration_class = Migration
return cls._migration_class | [
"def",
"Migration",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_migration_class",
"is",
"None",
":",
"class",
"Migration",
"(",
"models",
".",
"Model",
")",
":",
"app",
"=",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
"name",
"=",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
"applied",
"=",
"models",
".",
"DateTimeField",
"(",
"default",
"=",
"now",
")",
"class",
"Meta",
":",
"apps",
"=",
"Apps",
"(",
")",
"app_label",
"=",
"'migrations'",
"db_table",
"=",
"'django_migrations'",
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"'Migration %s for %s'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"app",
")",
"cls",
".",
"_migration_class",
"=",
"Migration",
"return",
"cls",
".",
"_migration_class"
] | [
23,
4
] | [
43,
35
] | python | en | ['en', 'error', 'th'] | False |
MigrationRecorder.has_table | (self) | Return True if the django_migrations table exists. | Return True if the django_migrations table exists. | def has_table(self):
"""Return True if the django_migrations table exists."""
with self.connection.cursor() as cursor:
tables = self.connection.introspection.table_names(cursor)
return self.Migration._meta.db_table in tables | [
"def",
"has_table",
"(",
"self",
")",
":",
"with",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"tables",
"=",
"self",
".",
"connection",
".",
"introspection",
".",
"table_names",
"(",
"cursor",
")",
"return",
"self",
".",
"Migration",
".",
"_meta",
".",
"db_table",
"in",
"tables"
] | [
52,
4
] | [
56,
54
] | python | en | ['en', 'ca', 'en'] | True |
MigrationRecorder.ensure_schema | (self) | Ensure the table exists and has the correct schema. | Ensure the table exists and has the correct schema. | def ensure_schema(self):
"""Ensure the table exists and has the correct schema."""
# If the table's there, that's fine - we've never changed its schema
# in the codebase.
if self.has_table():
return
# Make the table
try:
with self.connection.schema_editor() as editor:
editor.create_model(self.Migration)
except DatabaseError as exc:
raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) | [
"def",
"ensure_schema",
"(",
"self",
")",
":",
"# If the table's there, that's fine - we've never changed its schema",
"# in the codebase.",
"if",
"self",
".",
"has_table",
"(",
")",
":",
"return",
"# Make the table",
"try",
":",
"with",
"self",
".",
"connection",
".",
"schema_editor",
"(",
")",
"as",
"editor",
":",
"editor",
".",
"create_model",
"(",
"self",
".",
"Migration",
")",
"except",
"DatabaseError",
"as",
"exc",
":",
"raise",
"MigrationSchemaMissing",
"(",
"\"Unable to create the django_migrations table (%s)\"",
"%",
"exc",
")"
] | [
58,
4
] | [
69,
99
] | python | en | ['en', 'en', 'en'] | True |
MigrationRecorder.applied_migrations | (self) |
Return a dict mapping (app_name, migration_name) to Migration instances
for all applied migrations.
|
Return a dict mapping (app_name, migration_name) to Migration instances
for all applied migrations.
| def applied_migrations(self):
"""
Return a dict mapping (app_name, migration_name) to Migration instances
for all applied migrations.
"""
if self.has_table():
return {(migration.app, migration.name): migration for migration in self.migration_qs}
else:
# If the django_migrations table doesn't exist, then no migrations
# are applied.
return {} | [
"def",
"applied_migrations",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_table",
"(",
")",
":",
"return",
"{",
"(",
"migration",
".",
"app",
",",
"migration",
".",
"name",
")",
":",
"migration",
"for",
"migration",
"in",
"self",
".",
"migration_qs",
"}",
"else",
":",
"# If the django_migrations table doesn't exist, then no migrations",
"# are applied.",
"return",
"{",
"}"
] | [
71,
4
] | [
81,
21
] | python | en | ['en', 'error', 'th'] | False |
MigrationRecorder.record_applied | (self, app, name) | Record that a migration was applied. | Record that a migration was applied. | def record_applied(self, app, name):
"""Record that a migration was applied."""
self.ensure_schema()
self.migration_qs.create(app=app, name=name) | [
"def",
"record_applied",
"(",
"self",
",",
"app",
",",
"name",
")",
":",
"self",
".",
"ensure_schema",
"(",
")",
"self",
".",
"migration_qs",
".",
"create",
"(",
"app",
"=",
"app",
",",
"name",
"=",
"name",
")"
] | [
83,
4
] | [
86,
52
] | python | en | ['en', 'en', 'en'] | True |
MigrationRecorder.record_unapplied | (self, app, name) | Record that a migration was unapplied. | Record that a migration was unapplied. | def record_unapplied(self, app, name):
"""Record that a migration was unapplied."""
self.ensure_schema()
self.migration_qs.filter(app=app, name=name).delete() | [
"def",
"record_unapplied",
"(",
"self",
",",
"app",
",",
"name",
")",
":",
"self",
".",
"ensure_schema",
"(",
")",
"self",
".",
"migration_qs",
".",
"filter",
"(",
"app",
"=",
"app",
",",
"name",
"=",
"name",
")",
".",
"delete",
"(",
")"
] | [
88,
4
] | [
91,
61
] | python | en | ['en', 'en', 'en'] | True |
MigrationRecorder.flush | (self) | Delete all migration records. Useful for testing migrations. | Delete all migration records. Useful for testing migrations. | def flush(self):
"""Delete all migration records. Useful for testing migrations."""
self.migration_qs.all().delete() | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"migration_qs",
".",
"all",
"(",
")",
".",
"delete",
"(",
")"
] | [
93,
4
] | [
95,
40
] | python | en | ['en', 'en', 'en'] | True |
command_randomnumber | (bot, user, channel, args) | Prints a random number. | Prints a random number. | def command_randomnumber(bot, user, channel, args):
"Prints a random number."
return bot.say(channel, "5") | [
"def",
"command_randomnumber",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"5\"",
")"
] | [
3,
0
] | [
5,
32
] | python | en | ['en', 'ca', 'en'] | True |
command_roll | (bot, user, channel, args) | Roll the dice! Usage: roll [<count>] [<sides>]. | Roll the dice! Usage: roll [<count>] [<sides>]. | def command_roll(bot, user, channel, args):
"Roll the dice! Usage: roll [<count>] [<sides>]."
if not args:
return bot.say(channel, "Usage: roll [<count>] [<sides>].")
args = args.split()
if len(args) > 2:
return
elif len(args) == 2:
count, sides = args[0], args[1]
else:
count, sides = args[0], 6
try:
count = int(count)
sides = int(sides)
except ValueError:
return bot.say(channel, "Need integers, {}".format(get_nick(user)))
rolls = [random.randrange(1, sides + 1) for _ in range(count)]
total = sum(rolls)
bot.say(channel, "{} = {}".format(rolls, total)) | [
"def",
"command_roll",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Usage: roll [<count>] [<sides>].\"",
")",
"args",
"=",
"args",
".",
"split",
"(",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"return",
"elif",
"len",
"(",
"args",
")",
"==",
"2",
":",
"count",
",",
"sides",
"=",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
"else",
":",
"count",
",",
"sides",
"=",
"args",
"[",
"0",
"]",
",",
"6",
"try",
":",
"count",
"=",
"int",
"(",
"count",
")",
"sides",
"=",
"int",
"(",
"sides",
")",
"except",
"ValueError",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Need integers, {}\"",
".",
"format",
"(",
"get_nick",
"(",
"user",
")",
")",
")",
"rolls",
"=",
"[",
"random",
".",
"randrange",
"(",
"1",
",",
"sides",
"+",
"1",
")",
"for",
"_",
"in",
"range",
"(",
"count",
")",
"]",
"total",
"=",
"sum",
"(",
"rolls",
")",
"bot",
".",
"say",
"(",
"channel",
",",
"\"{} = {}\"",
".",
"format",
"(",
"rolls",
",",
"total",
")",
")"
] | [
8,
0
] | [
31,
52
] | python | en | ['en', 'en', 'en'] | True |
command_range | (bot, user, channel, args) | Returns a random number in a range. Usage: range <max>. | Returns a random number in a range. Usage: range <max>. | def command_range(bot, user, channel, args):
"Returns a random number in a range. Usage: range <max>."
if not args or not args.isdigit():
return bot.say(channel, "Usage: range <max>.")
return bot.say(channel, "{}".format(random.randrange(int(args)))) | [
"def",
"command_range",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"if",
"not",
"args",
"or",
"not",
"args",
".",
"isdigit",
"(",
")",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Usage: range <max>.\"",
")",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"{}\"",
".",
"format",
"(",
"random",
".",
"randrange",
"(",
"int",
"(",
"args",
")",
")",
")",
")"
] | [
34,
0
] | [
40,
69
] | python | en | ['en', 'da', 'en'] | True |
command_8ball | (bot, user, channel, args) | Ask the magic 8ball anything and he will tell you what to do. | Ask the magic 8ball anything and he will tell you what to do. | def command_8ball(bot, user, channel, args):
"Ask the magic 8ball anything and he will tell you what to do."
phrases = ["It is certain", "It is decidedly so", "Without a doubt",
"Yes definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes",
"Reply hazy, try again", "Ask again later", "Very doubtful",
"Better not tell you now", "Concentrate and ask again",
"Don't count on it", "My reply is no", "My sources say no",
"Outlook not so good", "Cannot predict now"]
nick = get_nick(user)
if "?" not in args:
return bot.say(channel, "Need a question, {}!".format(nick))
bot.say(channel, "{}, {}.".format(random.choice(phrases), nick)) | [
"def",
"command_8ball",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"phrases",
"=",
"[",
"\"It is certain\"",
",",
"\"It is decidedly so\"",
",",
"\"Without a doubt\"",
",",
"\"Yes definitely\"",
",",
"\"You may rely on it\"",
",",
"\"As I see it, yes\"",
",",
"\"Most likely\"",
",",
"\"Outlook good\"",
",",
"\"Signs point to yes\"",
",",
"\"Reply hazy, try again\"",
",",
"\"Ask again later\"",
",",
"\"Very doubtful\"",
",",
"\"Better not tell you now\"",
",",
"\"Concentrate and ask again\"",
",",
"\"Don't count on it\"",
",",
"\"My reply is no\"",
",",
"\"My sources say no\"",
",",
"\"Outlook not so good\"",
",",
"\"Cannot predict now\"",
"]",
"nick",
"=",
"get_nick",
"(",
"user",
")",
"if",
"\"?\"",
"not",
"in",
"args",
":",
"return",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Need a question, {}!\"",
".",
"format",
"(",
"nick",
")",
")",
"bot",
".",
"say",
"(",
"channel",
",",
"\"{}, {}.\"",
".",
"format",
"(",
"random",
".",
"choice",
"(",
"phrases",
")",
",",
"nick",
")",
")"
] | [
43,
0
] | [
56,
68
] | python | en | ['en', 'en', 'en'] | True |
command_cointoss | (bot, user, channel, args) | Flip a coin! | Flip a coin! | def command_cointoss(bot, user, channel, args):
"Flip a coin!"
if random.random() > 0.5:
bot.say(channel, "Heads!")
else:
bot.say(channel, "Tails!") | [
"def",
"command_cointoss",
"(",
"bot",
",",
"user",
",",
"channel",
",",
"args",
")",
":",
"if",
"random",
".",
"random",
"(",
")",
">",
"0.5",
":",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Heads!\"",
")",
"else",
":",
"bot",
".",
"say",
"(",
"channel",
",",
"\"Tails!\"",
")"
] | [
59,
0
] | [
64,
34
] | python | en | ['es', 'gl', 'en'] | False |
call | () | Responds to incoming calls using Twilio Add-ons | Responds to incoming calls using Twilio Add-ons | def call():
"""Responds to incoming calls using Twilio Add-ons"""
# Start our TwiML response
response = twiml.Response()
# Decode the JSON included in the 'AddOns' field
add_ons = json.loads(request.values['AddOns'])
# If the Whitepages add-on found nothing, return immediately
if 'whitepages_pro_caller_id' not in add_ons['results']:
response.say('Sorry, I could not learn anything about you.')
response.hangup()
return str(response)
# Otherwise, extract the Whitepages data
whitepages = add_ons['results']['whitepages_pro_caller_id']
# Grab the result Whitepages gave us
# (see the "Documentation" tab on the Whitepages add-on for more details)
caller_id = whitepages['result']
# See if we can get the caller's name
try:
first_name = caller_id['belongs_to'][0]['firstname']
except (IndexError, KeyError):
first_name = 'a mystery'
# And what city the caller lives in
try:
city = caller_id['current_addresses'][0]['city']
except (IndexError, KeyError):
city = 'a mystery'
# Tell the caller what we think their name and city are
response.say('Hello. Your name is {}.'.format(first_name))
response.say('And I think you live in {}.'.format(city))
# Then end the call
response.hangup()
return str(response) | [
"def",
"call",
"(",
")",
":",
"# Start our TwiML response",
"response",
"=",
"twiml",
".",
"Response",
"(",
")",
"# Decode the JSON included in the 'AddOns' field",
"add_ons",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"values",
"[",
"'AddOns'",
"]",
")",
"# If the Whitepages add-on found nothing, return immediately",
"if",
"'whitepages_pro_caller_id'",
"not",
"in",
"add_ons",
"[",
"'results'",
"]",
":",
"response",
".",
"say",
"(",
"'Sorry, I could not learn anything about you.'",
")",
"response",
".",
"hangup",
"(",
")",
"return",
"str",
"(",
"response",
")",
"# Otherwise, extract the Whitepages data",
"whitepages",
"=",
"add_ons",
"[",
"'results'",
"]",
"[",
"'whitepages_pro_caller_id'",
"]",
"# Grab the result Whitepages gave us",
"# (see the \"Documentation\" tab on the Whitepages add-on for more details)",
"caller_id",
"=",
"whitepages",
"[",
"'result'",
"]",
"# See if we can get the caller's name",
"try",
":",
"first_name",
"=",
"caller_id",
"[",
"'belongs_to'",
"]",
"[",
"0",
"]",
"[",
"'firstname'",
"]",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"first_name",
"=",
"'a mystery'",
"# And what city the caller lives in",
"try",
":",
"city",
"=",
"caller_id",
"[",
"'current_addresses'",
"]",
"[",
"0",
"]",
"[",
"'city'",
"]",
"except",
"(",
"IndexError",
",",
"KeyError",
")",
":",
"city",
"=",
"'a mystery'",
"# Tell the caller what we think their name and city are",
"response",
".",
"say",
"(",
"'Hello. Your name is {}.'",
".",
"format",
"(",
"first_name",
")",
")",
"response",
".",
"say",
"(",
"'And I think you live in {}.'",
".",
"format",
"(",
"city",
")",
")",
"# Then end the call",
"response",
".",
"hangup",
"(",
")",
"return",
"str",
"(",
"response",
")"
] | [
9,
0
] | [
50,
24
] | python | en | ['en', 'en', 'en'] | True |
ScriptMaker._build_shebang | (self, executable, post_interp) |
Build a shebang line. In the simple case (on Windows, or a shebang line
which is not too long or contains spaces) use a simple formulation for
the shebang. Otherwise, use /bin/sh as the executable, with a contrived
shebang which allows the script to run either under Python or sh, using
suitable quoting. Thanks to Harald Nordgren for his input.
See also: http://www.in-ulm.de/~mascheck/various/shebang/#length
https://hg.mozilla.org/mozilla-central/file/tip/mach
|
Build a shebang line. In the simple case (on Windows, or a shebang line
which is not too long or contains spaces) use a simple formulation for
the shebang. Otherwise, use /bin/sh as the executable, with a contrived
shebang which allows the script to run either under Python or sh, using
suitable quoting. Thanks to Harald Nordgren for his input. | def _build_shebang(self, executable, post_interp):
"""
Build a shebang line. In the simple case (on Windows, or a shebang line
which is not too long or contains spaces) use a simple formulation for
the shebang. Otherwise, use /bin/sh as the executable, with a contrived
shebang which allows the script to run either under Python or sh, using
suitable quoting. Thanks to Harald Nordgren for his input.
See also: http://www.in-ulm.de/~mascheck/various/shebang/#length
https://hg.mozilla.org/mozilla-central/file/tip/mach
"""
if os.name != 'posix':
simple_shebang = True
else:
# Add 3 for '#!' prefix and newline suffix.
shebang_length = len(executable) + len(post_interp) + 3
if sys.platform == 'darwin':
max_shebang_length = 512
else:
max_shebang_length = 127
simple_shebang = ((b' ' not in executable) and
(shebang_length <= max_shebang_length))
if simple_shebang:
result = b'#!' + executable + post_interp + b'\n'
else:
result = b'#!/bin/sh\n'
result += b"'''exec' " + executable + post_interp + b' "$0" "$@"\n'
result += b"' '''"
return result | [
"def",
"_build_shebang",
"(",
"self",
",",
"executable",
",",
"post_interp",
")",
":",
"if",
"os",
".",
"name",
"!=",
"'posix'",
":",
"simple_shebang",
"=",
"True",
"else",
":",
"# Add 3 for '#!' prefix and newline suffix.",
"shebang_length",
"=",
"len",
"(",
"executable",
")",
"+",
"len",
"(",
"post_interp",
")",
"+",
"3",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"max_shebang_length",
"=",
"512",
"else",
":",
"max_shebang_length",
"=",
"127",
"simple_shebang",
"=",
"(",
"(",
"b' '",
"not",
"in",
"executable",
")",
"and",
"(",
"shebang_length",
"<=",
"max_shebang_length",
")",
")",
"if",
"simple_shebang",
":",
"result",
"=",
"b'#!'",
"+",
"executable",
"+",
"post_interp",
"+",
"b'\\n'",
"else",
":",
"result",
"=",
"b'#!/bin/sh\\n'",
"result",
"+=",
"b\"'''exec' \"",
"+",
"executable",
"+",
"post_interp",
"+",
"b' \"$0\" \"$@\"\\n'",
"result",
"+=",
"b\"' '''\"",
"return",
"result"
] | [
126,
4
] | [
155,
21
] | python | en | ['en', 'error', 'th'] | False |
ScriptMaker.make | (self, specification, options=None) |
Make a script.
:param specification: The specification, which is either a valid export
entry specification (to make a script from a
callable) or a filename (to make a script by
copying from a source location).
:param options: A dictionary of options controlling script generation.
:return: A list of all absolute pathnames written to.
|
Make a script. | def make(self, specification, options=None):
"""
Make a script.
:param specification: The specification, which is either a valid export
entry specification (to make a script from a
callable) or a filename (to make a script by
copying from a source location).
:param options: A dictionary of options controlling script generation.
:return: A list of all absolute pathnames written to.
"""
filenames = []
entry = get_export_entry(specification)
if entry is None:
self._copy_script(specification, filenames)
else:
self._make_script(entry, filenames, options=options)
return filenames | [
"def",
"make",
"(",
"self",
",",
"specification",
",",
"options",
"=",
"None",
")",
":",
"filenames",
"=",
"[",
"]",
"entry",
"=",
"get_export_entry",
"(",
"specification",
")",
"if",
"entry",
"is",
"None",
":",
"self",
".",
"_copy_script",
"(",
"specification",
",",
"filenames",
")",
"else",
":",
"self",
".",
"_make_script",
"(",
"entry",
",",
"filenames",
",",
"options",
"=",
"options",
")",
"return",
"filenames"
] | [
394,
4
] | [
411,
24
] | python | en | ['en', 'error', 'th'] | False |
ScriptMaker.make_multiple | (self, specifications, options=None) |
Take a list of specifications and make scripts from them,
:param specifications: A list of specifications.
:return: A list of all absolute pathnames written to,
|
Take a list of specifications and make scripts from them,
:param specifications: A list of specifications.
:return: A list of all absolute pathnames written to,
| def make_multiple(self, specifications, options=None):
"""
Take a list of specifications and make scripts from them,
:param specifications: A list of specifications.
:return: A list of all absolute pathnames written to,
"""
filenames = []
for specification in specifications:
filenames.extend(self.make(specification, options))
return filenames | [
"def",
"make_multiple",
"(",
"self",
",",
"specifications",
",",
"options",
"=",
"None",
")",
":",
"filenames",
"=",
"[",
"]",
"for",
"specification",
"in",
"specifications",
":",
"filenames",
".",
"extend",
"(",
"self",
".",
"make",
"(",
"specification",
",",
"options",
")",
")",
"return",
"filenames"
] | [
413,
4
] | [
422,
24
] | python | en | ['en', 'error', 'th'] | False |
Widget.format_value | (self, value) |
Return a value as it should appear when rendered in a template.
|
Return a value as it should appear when rendered in a template.
| def format_value(self, value):
"""
Return a value as it should appear when rendered in a template.
"""
if value == '' or value is None:
return None
if self.is_localized:
return formats.localize_input(value)
return str(value) | [
"def",
"format_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"''",
"or",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"is_localized",
":",
"return",
"formats",
".",
"localize_input",
"(",
"value",
")",
"return",
"str",
"(",
"value",
")"
] | [
221,
4
] | [
229,
25
] | python | en | ['en', 'error', 'th'] | False |
Widget.render | (self, name, value, attrs=None, renderer=None) | Render the widget as an HTML string. | Render the widget as an HTML string. | def render(self, name, value, attrs=None, renderer=None):
"""Render the widget as an HTML string."""
context = self.get_context(name, value, attrs)
return self._render(self.template_name, context, renderer) | [
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"renderer",
"=",
"None",
")",
":",
"context",
"=",
"self",
".",
"get_context",
"(",
"name",
",",
"value",
",",
"attrs",
")",
"return",
"self",
".",
"_render",
"(",
"self",
".",
"template_name",
",",
"context",
",",
"renderer",
")"
] | [
243,
4
] | [
246,
66
] | python | en | ['en', 'lb', 'en'] | True |
Widget.build_attrs | (self, base_attrs, extra_attrs=None) | Build an attribute dictionary. | Build an attribute dictionary. | def build_attrs(self, base_attrs, extra_attrs=None):
"""Build an attribute dictionary."""
return {**base_attrs, **(extra_attrs or {})} | [
"def",
"build_attrs",
"(",
"self",
",",
"base_attrs",
",",
"extra_attrs",
"=",
"None",
")",
":",
"return",
"{",
"*",
"*",
"base_attrs",
",",
"*",
"*",
"(",
"extra_attrs",
"or",
"{",
"}",
")",
"}"
] | [
253,
4
] | [
255,
52
] | python | en | ['en', 'en', 'en'] | True |
Widget.value_from_datadict | (self, data, files, name) |
Given a dictionary of data and this widget's name, return the value
of this widget or None if it's not provided.
|
Given a dictionary of data and this widget's name, return the value
of this widget or None if it's not provided.
| def value_from_datadict(self, data, files, name):
"""
Given a dictionary of data and this widget's name, return the value
of this widget or None if it's not provided.
"""
return data.get(name) | [
"def",
"value_from_datadict",
"(",
"self",
",",
"data",
",",
"files",
",",
"name",
")",
":",
"return",
"data",
".",
"get",
"(",
"name",
")"
] | [
257,
4
] | [
262,
29
] | python | en | ['en', 'error', 'th'] | False |
Widget.id_for_label | (self, id_) |
Return the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Return None if no ID is available.
This hook is necessary because some widgets have multiple HTML
elements and, thus, multiple IDs. In that case, this method should
return an ID value that corresponds to the first ID in the widget's
tags.
|
Return the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Return None if no ID is available. | def id_for_label(self, id_):
"""
Return the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Return None if no ID is available.
This hook is necessary because some widgets have multiple HTML
elements and, thus, multiple IDs. In that case, this method should
return an ID value that corresponds to the first ID in the widget's
tags.
"""
return id_ | [
"def",
"id_for_label",
"(",
"self",
",",
"id_",
")",
":",
"return",
"id_"
] | [
267,
4
] | [
277,
18
] | python | en | ['en', 'error', 'th'] | False |
FileInput.format_value | (self, value) | File input never renders a value. | File input never renders a value. | def format_value(self, value):
"""File input never renders a value."""
return | [
"def",
"format_value",
"(",
"self",
",",
"value",
")",
":",
"return"
] | [
383,
4
] | [
385,
14
] | python | en | ['hu', 'en', 'en'] | True |
FileInput.value_from_datadict | (self, data, files, name) | File widgets take data from FILES, not POST | File widgets take data from FILES, not POST | def value_from_datadict(self, data, files, name):
"File widgets take data from FILES, not POST"
return files.get(name) | [
"def",
"value_from_datadict",
"(",
"self",
",",
"data",
",",
"files",
",",
"name",
")",
":",
"return",
"files",
".",
"get",
"(",
"name",
")"
] | [
387,
4
] | [
389,
30
] | python | en | ['en', 'en', 'en'] | True |
ClearableFileInput.clear_checkbox_name | (self, name) |
Given the name of the file input, return the name of the clear checkbox
input.
|
Given the name of the file input, return the name of the clear checkbox
input.
| def clear_checkbox_name(self, name):
"""
Given the name of the file input, return the name of the clear checkbox
input.
"""
return name + '-clear' | [
"def",
"clear_checkbox_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"name",
"+",
"'-clear'"
] | [
407,
4
] | [
412,
30
] | python | en | ['en', 'error', 'th'] | False |
ClearableFileInput.clear_checkbox_id | (self, name) |
Given the name of the clear checkbox input, return the HTML id for it.
|
Given the name of the clear checkbox input, return the HTML id for it.
| def clear_checkbox_id(self, name):
"""
Given the name of the clear checkbox input, return the HTML id for it.
"""
return name + '_id' | [
"def",
"clear_checkbox_id",
"(",
"self",
",",
"name",
")",
":",
"return",
"name",
"+",
"'_id'"
] | [
414,
4
] | [
418,
27
] | python | en | ['en', 'error', 'th'] | False |
ClearableFileInput.is_initial | (self, value) |
Return whether value is considered to be initial value.
|
Return whether value is considered to be initial value.
| def is_initial(self, value):
"""
Return whether value is considered to be initial value.
"""
return bool(value and getattr(value, 'url', False)) | [
"def",
"is_initial",
"(",
"self",
",",
"value",
")",
":",
"return",
"bool",
"(",
"value",
"and",
"getattr",
"(",
"value",
",",
"'url'",
",",
"False",
")",
")"
] | [
420,
4
] | [
424,
59
] | python | en | ['en', 'error', 'th'] | False |
ClearableFileInput.format_value | (self, value) |
Return the file object if it has a defined url attribute.
|
Return the file object if it has a defined url attribute.
| def format_value(self, value):
"""
Return the file object if it has a defined url attribute.
"""
if self.is_initial(value):
return value | [
"def",
"format_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"is_initial",
"(",
"value",
")",
":",
"return",
"value"
] | [
426,
4
] | [
431,
24
] | python | en | ['en', 'error', 'th'] | False |
CheckboxInput.format_value | (self, value) | Only return the 'value' attribute if value isn't empty. | Only return the 'value' attribute if value isn't empty. | def format_value(self, value):
"""Only return the 'value' attribute if value isn't empty."""
if value is True or value is False or value is None or value == '':
return
return str(value) | [
"def",
"format_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"True",
"or",
"value",
"is",
"False",
"or",
"value",
"is",
"None",
"or",
"value",
"==",
"''",
":",
"return",
"return",
"str",
"(",
"value",
")"
] | [
521,
4
] | [
525,
25
] | python | en | ['en', 'en', 'en'] | True |
ChoiceWidget.subwidgets | (self, name, value, attrs=None) |
Yield all "subwidgets" of this widget. Used to enable iterating
options from a BoundField for choice widgets.
|
Yield all "subwidgets" of this widget. Used to enable iterating
options from a BoundField for choice widgets.
| def subwidgets(self, name, value, attrs=None):
"""
Yield all "subwidgets" of this widget. Used to enable iterating
options from a BoundField for choice widgets.
"""
value = self.format_value(value)
yield from self.options(name, value, attrs) | [
"def",
"subwidgets",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"format_value",
"(",
"value",
")",
"yield",
"from",
"self",
".",
"options",
"(",
"name",
",",
"value",
",",
"attrs",
")"
] | [
573,
4
] | [
579,
51
] | python | en | ['en', 'error', 'th'] | False |
ChoiceWidget.options | (self, name, value, attrs=None) | Yield a flat list of options for this widgets. | Yield a flat list of options for this widgets. | def options(self, name, value, attrs=None):
"""Yield a flat list of options for this widgets."""
for group in self.optgroups(name, value, attrs):
yield from group[1] | [
"def",
"options",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"for",
"group",
"in",
"self",
".",
"optgroups",
"(",
"name",
",",
"value",
",",
"attrs",
")",
":",
"yield",
"from",
"group",
"[",
"1",
"]"
] | [
581,
4
] | [
584,
31
] | python | en | ['en', 'en', 'en'] | True |
ChoiceWidget.optgroups | (self, name, value, attrs=None) | Return a list of optgroups for this widget. | Return a list of optgroups for this widget. | def optgroups(self, name, value, attrs=None):
"""Return a list of optgroups for this widget."""
groups = []
has_selected = False
for index, (option_value, option_label) in enumerate(self.choices):
if option_value is None:
option_value = ''
subgroup = []
if isinstance(option_label, (list, tuple)):
group_name = option_value
subindex = 0
choices = option_label
else:
group_name = None
subindex = None
choices = [(option_value, option_label)]
groups.append((group_name, subgroup, index))
for subvalue, sublabel in choices:
selected = (
str(subvalue) in value and
(not has_selected or self.allow_multiple_selected)
)
has_selected |= selected
subgroup.append(self.create_option(
name, subvalue, sublabel, selected, index,
subindex=subindex, attrs=attrs,
))
if subindex is not None:
subindex += 1
return groups | [
"def",
"optgroups",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"groups",
"=",
"[",
"]",
"has_selected",
"=",
"False",
"for",
"index",
",",
"(",
"option_value",
",",
"option_label",
")",
"in",
"enumerate",
"(",
"self",
".",
"choices",
")",
":",
"if",
"option_value",
"is",
"None",
":",
"option_value",
"=",
"''",
"subgroup",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"option_label",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"group_name",
"=",
"option_value",
"subindex",
"=",
"0",
"choices",
"=",
"option_label",
"else",
":",
"group_name",
"=",
"None",
"subindex",
"=",
"None",
"choices",
"=",
"[",
"(",
"option_value",
",",
"option_label",
")",
"]",
"groups",
".",
"append",
"(",
"(",
"group_name",
",",
"subgroup",
",",
"index",
")",
")",
"for",
"subvalue",
",",
"sublabel",
"in",
"choices",
":",
"selected",
"=",
"(",
"str",
"(",
"subvalue",
")",
"in",
"value",
"and",
"(",
"not",
"has_selected",
"or",
"self",
".",
"allow_multiple_selected",
")",
")",
"has_selected",
"|=",
"selected",
"subgroup",
".",
"append",
"(",
"self",
".",
"create_option",
"(",
"name",
",",
"subvalue",
",",
"sublabel",
",",
"selected",
",",
"index",
",",
"subindex",
"=",
"subindex",
",",
"attrs",
"=",
"attrs",
",",
")",
")",
"if",
"subindex",
"is",
"not",
"None",
":",
"subindex",
"+=",
"1",
"return",
"groups"
] | [
586,
4
] | [
618,
21
] | python | en | ['en', 'en', 'en'] | True |
ChoiceWidget.id_for_label | (self, id_, index='0') |
Use an incremented id for each option where the main widget
references the zero index.
|
Use an incremented id for each option where the main widget
references the zero index.
| def id_for_label(self, id_, index='0'):
"""
Use an incremented id for each option where the main widget
references the zero index.
"""
if id_ and self.add_id_index:
id_ = '%s_%s' % (id_, index)
return id_ | [
"def",
"id_for_label",
"(",
"self",
",",
"id_",
",",
"index",
"=",
"'0'",
")",
":",
"if",
"id_",
"and",
"self",
".",
"add_id_index",
":",
"id_",
"=",
"'%s_%s'",
"%",
"(",
"id_",
",",
"index",
")",
"return",
"id_"
] | [
646,
4
] | [
653,
18
] | python | en | ['en', 'error', 'th'] | False |
ChoiceWidget.format_value | (self, value) | Return selected values as a list. | Return selected values as a list. | def format_value(self, value):
"""Return selected values as a list."""
if value is None and self.allow_multiple_selected:
return []
if not isinstance(value, (tuple, list)):
value = [value]
return [str(v) if v is not None else '' for v in value] | [
"def",
"format_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"self",
".",
"allow_multiple_selected",
":",
"return",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
"[",
"str",
"(",
"v",
")",
"if",
"v",
"is",
"not",
"None",
"else",
"''",
"for",
"v",
"in",
"value",
"]"
] | [
664,
4
] | [
670,
63
] | python | en | ['en', 'en', 'en'] | True |
Select._choice_has_empty_value | (choice) | Return True if the choice's value is empty string or None. | Return True if the choice's value is empty string or None. | def _choice_has_empty_value(choice):
"""Return True if the choice's value is empty string or None."""
value, _ = choice
return value is None or value == '' | [
"def",
"_choice_has_empty_value",
"(",
"choice",
")",
":",
"value",
",",
"_",
"=",
"choice",
"return",
"value",
"is",
"None",
"or",
"value",
"==",
"''"
] | [
688,
4
] | [
691,
43
] | python | en | ['en', 'en', 'en'] | True |
Select.use_required_attribute | (self, initial) |
Don't render 'required' if the first <option> has a value, as that's
invalid HTML.
|
Don't render 'required' if the first <option> has a value, as that's
invalid HTML.
| def use_required_attribute(self, initial):
"""
Don't render 'required' if the first <option> has a value, as that's
invalid HTML.
"""
use_required_attribute = super().use_required_attribute(initial)
# 'required' is always okay for <select multiple>.
if self.allow_multiple_selected:
return use_required_attribute
first_choice = next(iter(self.choices), None)
return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) | [
"def",
"use_required_attribute",
"(",
"self",
",",
"initial",
")",
":",
"use_required_attribute",
"=",
"super",
"(",
")",
".",
"use_required_attribute",
"(",
"initial",
")",
"# 'required' is always okay for <select multiple>.",
"if",
"self",
".",
"allow_multiple_selected",
":",
"return",
"use_required_attribute",
"first_choice",
"=",
"next",
"(",
"iter",
"(",
"self",
".",
"choices",
")",
",",
"None",
")",
"return",
"use_required_attribute",
"and",
"first_choice",
"is",
"not",
"None",
"and",
"self",
".",
"_choice_has_empty_value",
"(",
"first_choice",
")"
] | [
693,
4
] | [
704,
113
] | python | en | ['en', 'error', 'th'] | False |
CheckboxSelectMultiple.id_for_label | (self, id_, index=None) |
Don't include for="field_0" in <label> because clicking such a label
would toggle the first checkbox.
|
Don't include for="field_0" in <label> because clicking such a label
would toggle the first checkbox.
| def id_for_label(self, id_, index=None):
"""
Don't include for="field_0" in <label> because clicking such a label
would toggle the first checkbox.
"""
if index is None:
return ''
return super().id_for_label(id_, index) | [
"def",
"id_for_label",
"(",
"self",
",",
"id_",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"return",
"''",
"return",
"super",
"(",
")",
".",
"id_for_label",
"(",
"id_",
",",
"index",
")"
] | [
783,
4
] | [
790,
47
] | python | en | ['en', 'error', 'th'] | False |
MultiWidget.decompress | (self, value) |
Return a list of decompressed values for the given compressed value.
The given value can be assumed to be valid, but not necessarily
non-empty.
|
Return a list of decompressed values for the given compressed value.
The given value can be assumed to be valid, but not necessarily
non-empty.
| def decompress(self, value):
"""
Return a list of decompressed values for the given compressed value.
The given value can be assumed to be valid, but not necessarily
non-empty.
"""
raise NotImplementedError('Subclasses must implement this method.') | [
"def",
"decompress",
"(",
"self",
",",
"value",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Subclasses must implement this method.'",
")"
] | [
868,
4
] | [
874,
75
] | python | en | ['en', 'error', 'th'] | False |
MultiWidget._get_media | (self) |
Media for a multiwidget is the combination of all media of the
subwidgets.
|
Media for a multiwidget is the combination of all media of the
subwidgets.
| def _get_media(self):
"""
Media for a multiwidget is the combination of all media of the
subwidgets.
"""
media = Media()
for w in self.widgets:
media = media + w.media
return media | [
"def",
"_get_media",
"(",
"self",
")",
":",
"media",
"=",
"Media",
"(",
")",
"for",
"w",
"in",
"self",
".",
"widgets",
":",
"media",
"=",
"media",
"+",
"w",
".",
"media",
"return",
"media"
] | [
876,
4
] | [
884,
20
] | python | en | ['en', 'error', 'th'] | False |
SelectDateWidget.format_value | (self, value) |
Return a dict containing the year, month, and day of the current value.
Use dict instead of a datetime to allow invalid dates such as February
31 to display correctly.
|
Return a dict containing the year, month, and day of the current value.
Use dict instead of a datetime to allow invalid dates such as February
31 to display correctly.
| def format_value(self, value):
"""
Return a dict containing the year, month, and day of the current value.
Use dict instead of a datetime to allow invalid dates such as February
31 to display correctly.
"""
year, month, day = None, None, None
if isinstance(value, (datetime.date, datetime.datetime)):
year, month, day = value.year, value.month, value.day
elif isinstance(value, str):
match = self.date_re.match(value)
if match:
# Convert any zeros in the date to empty strings to match the
# empty option value.
year, month, day = [int(val) or '' for val in match.groups()]
else:
input_format = get_format('DATE_INPUT_FORMATS')[0]
try:
d = datetime.datetime.strptime(value, input_format)
except ValueError:
pass
else:
year, month, day = d.year, d.month, d.day
return {'year': year, 'month': month, 'day': day} | [
"def",
"format_value",
"(",
"self",
",",
"value",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"None",
",",
"None",
",",
"None",
"if",
"isinstance",
"(",
"value",
",",
"(",
"datetime",
".",
"date",
",",
"datetime",
".",
"datetime",
")",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"value",
".",
"year",
",",
"value",
".",
"month",
",",
"value",
".",
"day",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"match",
"=",
"self",
".",
"date_re",
".",
"match",
"(",
"value",
")",
"if",
"match",
":",
"# Convert any zeros in the date to empty strings to match the",
"# empty option value.",
"year",
",",
"month",
",",
"day",
"=",
"[",
"int",
"(",
"val",
")",
"or",
"''",
"for",
"val",
"in",
"match",
".",
"groups",
"(",
")",
"]",
"else",
":",
"input_format",
"=",
"get_format",
"(",
"'DATE_INPUT_FORMATS'",
")",
"[",
"0",
"]",
"try",
":",
"d",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"value",
",",
"input_format",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"year",
",",
"month",
",",
"day",
"=",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
"return",
"{",
"'year'",
":",
"year",
",",
"'month'",
":",
"month",
",",
"'day'",
":",
"day",
"}"
] | [
1020,
4
] | [
1043,
57
] | python | en | ['en', 'error', 'th'] | False |
Result.output | (self) | The (standard) output as unicode string. | The (standard) output as unicode string. | def output(self):
"""The (standard) output as unicode string."""
return self.stdout | [
"def",
"output",
"(",
"self",
")",
":",
"return",
"self",
".",
"stdout"
] | [
91,
4
] | [
93,
26
] | python | en | ['en', 'en', 'en'] | True |
Result.stdout | (self) | The standard output as unicode string. | The standard output as unicode string. | def stdout(self):
"""The standard output as unicode string."""
return self.stdout_bytes.decode(self.runner.charset, 'replace') \
.replace('\r\n', '\n') | [
"def",
"stdout",
"(",
"self",
")",
":",
"return",
"self",
".",
"stdout_bytes",
".",
"decode",
"(",
"self",
".",
"runner",
".",
"charset",
",",
"'replace'",
")",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")"
] | [
96,
4
] | [
99,
34
] | python | en | ['en', 'en', 'en'] | True |
Result.stderr | (self) | The standard error as unicode string. | The standard error as unicode string. | def stderr(self):
"""The standard error as unicode string."""
if not self.stderr_bytes:
raise ValueError("stderr not separately captured")
return self.stderr_bytes.decode(self.runner.charset, 'replace') \
.replace('\r\n', '\n') | [
"def",
"stderr",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"stderr_bytes",
":",
"raise",
"ValueError",
"(",
"\"stderr not separately captured\"",
")",
"return",
"self",
".",
"stderr_bytes",
".",
"decode",
"(",
"self",
".",
"runner",
".",
"charset",
",",
"'replace'",
")",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")"
] | [
102,
4
] | [
107,
34
] | python | en | ['en', 'en', 'en'] | True |
CliRunner.get_default_prog_name | (self, cli) | Given a command object it will return the default program name
for it. The default is the `name` attribute or ``"root"`` if not
set.
| Given a command object it will return the default program name
for it. The default is the `name` attribute or ``"root"`` if not
set.
| def get_default_prog_name(self, cli):
"""Given a command object it will return the default program name
for it. The default is the `name` attribute or ``"root"`` if not
set.
"""
return cli.name or 'root' | [
"def",
"get_default_prog_name",
"(",
"self",
",",
"cli",
")",
":",
"return",
"cli",
".",
"name",
"or",
"'root'"
] | [
147,
4
] | [
152,
33
] | python | en | ['en', 'en', 'en'] | True |
CliRunner.make_env | (self, overrides=None) | Returns the environment overrides for invoking a script. | Returns the environment overrides for invoking a script. | def make_env(self, overrides=None):
"""Returns the environment overrides for invoking a script."""
rv = dict(self.env)
if overrides:
rv.update(overrides)
return rv | [
"def",
"make_env",
"(",
"self",
",",
"overrides",
"=",
"None",
")",
":",
"rv",
"=",
"dict",
"(",
"self",
".",
"env",
")",
"if",
"overrides",
":",
"rv",
".",
"update",
"(",
"overrides",
")",
"return",
"rv"
] | [
154,
4
] | [
159,
17
] | python | en | ['en', 'en', 'en'] | True |
CliRunner.isolation | (self, input=None, env=None, color=False) | A context manager that sets up the isolation for invoking of a
command line tool. This sets up stdin with the given input data
and `os.environ` with the overrides from the given dictionary.
This also rebinds some internals in Click to be mocked (like the
prompt functionality).
This is automatically done in the :meth:`invoke` method.
.. versionadded:: 4.0
The ``color`` parameter was added.
:param input: the input stream to put into sys.stdin.
:param env: the environment overrides as dictionary.
:param color: whether the output should contain color codes. The
application can still override this explicitly.
| A context manager that sets up the isolation for invoking of a
command line tool. This sets up stdin with the given input data
and `os.environ` with the overrides from the given dictionary.
This also rebinds some internals in Click to be mocked (like the
prompt functionality). | def isolation(self, input=None, env=None, color=False):
"""A context manager that sets up the isolation for invoking of a
command line tool. This sets up stdin with the given input data
and `os.environ` with the overrides from the given dictionary.
This also rebinds some internals in Click to be mocked (like the
prompt functionality).
This is automatically done in the :meth:`invoke` method.
.. versionadded:: 4.0
The ``color`` parameter was added.
:param input: the input stream to put into sys.stdin.
:param env: the environment overrides as dictionary.
:param color: whether the output should contain color codes. The
application can still override this explicitly.
"""
input = make_input_stream(input, self.charset)
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
old_forced_width = clickpkg.formatting.FORCED_WIDTH
clickpkg.formatting.FORCED_WIDTH = 80
env = self.make_env(env)
if PY2:
bytes_output = StringIO()
if self.echo_stdin:
input = EchoingStdin(input, bytes_output)
sys.stdout = bytes_output
if not self.mix_stderr:
bytes_error = StringIO()
sys.stderr = bytes_error
else:
bytes_output = io.BytesIO()
if self.echo_stdin:
input = EchoingStdin(input, bytes_output)
input = io.TextIOWrapper(input, encoding=self.charset)
sys.stdout = io.TextIOWrapper(
bytes_output, encoding=self.charset)
if not self.mix_stderr:
bytes_error = io.BytesIO()
sys.stderr = io.TextIOWrapper(
bytes_error, encoding=self.charset)
if self.mix_stderr:
sys.stderr = sys.stdout
sys.stdin = input
def visible_input(prompt=None):
sys.stdout.write(prompt or '')
val = input.readline().rstrip('\r\n')
sys.stdout.write(val + '\n')
sys.stdout.flush()
return val
def hidden_input(prompt=None):
sys.stdout.write((prompt or '') + '\n')
sys.stdout.flush()
return input.readline().rstrip('\r\n')
def _getchar(echo):
char = sys.stdin.read(1)
if echo:
sys.stdout.write(char)
sys.stdout.flush()
return char
default_color = color
def should_strip_ansi(stream=None, color=None):
if color is None:
return not default_color
return not color
old_visible_prompt_func = clickpkg.termui.visible_prompt_func
old_hidden_prompt_func = clickpkg.termui.hidden_prompt_func
old__getchar_func = clickpkg.termui._getchar
old_should_strip_ansi = clickpkg.utils.should_strip_ansi
clickpkg.termui.visible_prompt_func = visible_input
clickpkg.termui.hidden_prompt_func = hidden_input
clickpkg.termui._getchar = _getchar
clickpkg.utils.should_strip_ansi = should_strip_ansi
old_env = {}
try:
for key, value in iteritems(env):
old_env[key] = os.environ.get(key)
if value is None:
try:
del os.environ[key]
except Exception:
pass
else:
os.environ[key] = value
yield (bytes_output, not self.mix_stderr and bytes_error)
finally:
for key, value in iteritems(old_env):
if value is None:
try:
del os.environ[key]
except Exception:
pass
else:
os.environ[key] = value
sys.stdout = old_stdout
sys.stderr = old_stderr
sys.stdin = old_stdin
clickpkg.termui.visible_prompt_func = old_visible_prompt_func
clickpkg.termui.hidden_prompt_func = old_hidden_prompt_func
clickpkg.termui._getchar = old__getchar_func
clickpkg.utils.should_strip_ansi = old_should_strip_ansi
clickpkg.formatting.FORCED_WIDTH = old_forced_width | [
"def",
"isolation",
"(",
"self",
",",
"input",
"=",
"None",
",",
"env",
"=",
"None",
",",
"color",
"=",
"False",
")",
":",
"input",
"=",
"make_input_stream",
"(",
"input",
",",
"self",
".",
"charset",
")",
"old_stdin",
"=",
"sys",
".",
"stdin",
"old_stdout",
"=",
"sys",
".",
"stdout",
"old_stderr",
"=",
"sys",
".",
"stderr",
"old_forced_width",
"=",
"clickpkg",
".",
"formatting",
".",
"FORCED_WIDTH",
"clickpkg",
".",
"formatting",
".",
"FORCED_WIDTH",
"=",
"80",
"env",
"=",
"self",
".",
"make_env",
"(",
"env",
")",
"if",
"PY2",
":",
"bytes_output",
"=",
"StringIO",
"(",
")",
"if",
"self",
".",
"echo_stdin",
":",
"input",
"=",
"EchoingStdin",
"(",
"input",
",",
"bytes_output",
")",
"sys",
".",
"stdout",
"=",
"bytes_output",
"if",
"not",
"self",
".",
"mix_stderr",
":",
"bytes_error",
"=",
"StringIO",
"(",
")",
"sys",
".",
"stderr",
"=",
"bytes_error",
"else",
":",
"bytes_output",
"=",
"io",
".",
"BytesIO",
"(",
")",
"if",
"self",
".",
"echo_stdin",
":",
"input",
"=",
"EchoingStdin",
"(",
"input",
",",
"bytes_output",
")",
"input",
"=",
"io",
".",
"TextIOWrapper",
"(",
"input",
",",
"encoding",
"=",
"self",
".",
"charset",
")",
"sys",
".",
"stdout",
"=",
"io",
".",
"TextIOWrapper",
"(",
"bytes_output",
",",
"encoding",
"=",
"self",
".",
"charset",
")",
"if",
"not",
"self",
".",
"mix_stderr",
":",
"bytes_error",
"=",
"io",
".",
"BytesIO",
"(",
")",
"sys",
".",
"stderr",
"=",
"io",
".",
"TextIOWrapper",
"(",
"bytes_error",
",",
"encoding",
"=",
"self",
".",
"charset",
")",
"if",
"self",
".",
"mix_stderr",
":",
"sys",
".",
"stderr",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdin",
"=",
"input",
"def",
"visible_input",
"(",
"prompt",
"=",
"None",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"prompt",
"or",
"''",
")",
"val",
"=",
"input",
".",
"readline",
"(",
")",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"val",
"+",
"'\\n'",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"return",
"val",
"def",
"hidden_input",
"(",
"prompt",
"=",
"None",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"prompt",
"or",
"''",
")",
"+",
"'\\n'",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"return",
"input",
".",
"readline",
"(",
")",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"def",
"_getchar",
"(",
"echo",
")",
":",
"char",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
"1",
")",
"if",
"echo",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"char",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"return",
"char",
"default_color",
"=",
"color",
"def",
"should_strip_ansi",
"(",
"stream",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"if",
"color",
"is",
"None",
":",
"return",
"not",
"default_color",
"return",
"not",
"color",
"old_visible_prompt_func",
"=",
"clickpkg",
".",
"termui",
".",
"visible_prompt_func",
"old_hidden_prompt_func",
"=",
"clickpkg",
".",
"termui",
".",
"hidden_prompt_func",
"old__getchar_func",
"=",
"clickpkg",
".",
"termui",
".",
"_getchar",
"old_should_strip_ansi",
"=",
"clickpkg",
".",
"utils",
".",
"should_strip_ansi",
"clickpkg",
".",
"termui",
".",
"visible_prompt_func",
"=",
"visible_input",
"clickpkg",
".",
"termui",
".",
"hidden_prompt_func",
"=",
"hidden_input",
"clickpkg",
".",
"termui",
".",
"_getchar",
"=",
"_getchar",
"clickpkg",
".",
"utils",
".",
"should_strip_ansi",
"=",
"should_strip_ansi",
"old_env",
"=",
"{",
"}",
"try",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"env",
")",
":",
"old_env",
"[",
"key",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"try",
":",
"del",
"os",
".",
"environ",
"[",
"key",
"]",
"except",
"Exception",
":",
"pass",
"else",
":",
"os",
".",
"environ",
"[",
"key",
"]",
"=",
"value",
"yield",
"(",
"bytes_output",
",",
"not",
"self",
".",
"mix_stderr",
"and",
"bytes_error",
")",
"finally",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"old_env",
")",
":",
"if",
"value",
"is",
"None",
":",
"try",
":",
"del",
"os",
".",
"environ",
"[",
"key",
"]",
"except",
"Exception",
":",
"pass",
"else",
":",
"os",
".",
"environ",
"[",
"key",
"]",
"=",
"value",
"sys",
".",
"stdout",
"=",
"old_stdout",
"sys",
".",
"stderr",
"=",
"old_stderr",
"sys",
".",
"stdin",
"=",
"old_stdin",
"clickpkg",
".",
"termui",
".",
"visible_prompt_func",
"=",
"old_visible_prompt_func",
"clickpkg",
".",
"termui",
".",
"hidden_prompt_func",
"=",
"old_hidden_prompt_func",
"clickpkg",
".",
"termui",
".",
"_getchar",
"=",
"old__getchar_func",
"clickpkg",
".",
"utils",
".",
"should_strip_ansi",
"=",
"old_should_strip_ansi",
"clickpkg",
".",
"formatting",
".",
"FORCED_WIDTH",
"=",
"old_forced_width"
] | [
162,
4
] | [
277,
63
] | python | en | ['en', 'en', 'en'] | True |
CliRunner.invoke | (self, cli, args=None, input=None, env=None,
catch_exceptions=True, color=False, mix_stderr=False, **extra) | Invokes a command in an isolated environment. The arguments are
forwarded directly to the command line script, the `extra` keyword
arguments are passed to the :meth:`~clickpkg.Command.main` function of
the command.
This returns a :class:`Result` object.
.. versionadded:: 3.0
The ``catch_exceptions`` parameter was added.
.. versionchanged:: 3.0
The result object now has an `exc_info` attribute with the
traceback if available.
.. versionadded:: 4.0
The ``color`` parameter was added.
:param cli: the command to invoke
:param args: the arguments to invoke. It may be given as an iterable
or a string. When given as string it will be interpreted
as a Unix shell command. More details at
:func:`shlex.split`.
:param input: the input data for `sys.stdin`.
:param env: the environment overrides.
:param catch_exceptions: Whether to catch any other exceptions than
``SystemExit``.
:param extra: the keyword arguments to pass to :meth:`main`.
:param color: whether the output should contain color codes. The
application can still override this explicitly.
| Invokes a command in an isolated environment. The arguments are
forwarded directly to the command line script, the `extra` keyword
arguments are passed to the :meth:`~clickpkg.Command.main` function of
the command. | def invoke(self, cli, args=None, input=None, env=None,
catch_exceptions=True, color=False, mix_stderr=False, **extra):
"""Invokes a command in an isolated environment. The arguments are
forwarded directly to the command line script, the `extra` keyword
arguments are passed to the :meth:`~clickpkg.Command.main` function of
the command.
This returns a :class:`Result` object.
.. versionadded:: 3.0
The ``catch_exceptions`` parameter was added.
.. versionchanged:: 3.0
The result object now has an `exc_info` attribute with the
traceback if available.
.. versionadded:: 4.0
The ``color`` parameter was added.
:param cli: the command to invoke
:param args: the arguments to invoke. It may be given as an iterable
or a string. When given as string it will be interpreted
as a Unix shell command. More details at
:func:`shlex.split`.
:param input: the input data for `sys.stdin`.
:param env: the environment overrides.
:param catch_exceptions: Whether to catch any other exceptions than
``SystemExit``.
:param extra: the keyword arguments to pass to :meth:`main`.
:param color: whether the output should contain color codes. The
application can still override this explicitly.
"""
exc_info = None
with self.isolation(input=input, env=env, color=color) as outstreams:
exception = None
exit_code = 0
if isinstance(args, string_types):
args = shlex.split(args)
try:
prog_name = extra.pop("prog_name")
except KeyError:
prog_name = self.get_default_prog_name(cli)
try:
cli.main(args=args or (), prog_name=prog_name, **extra)
except SystemExit as e:
exc_info = sys.exc_info()
exit_code = e.code
if exit_code is None:
exit_code = 0
if exit_code != 0:
exception = e
if not isinstance(exit_code, int):
sys.stdout.write(str(exit_code))
sys.stdout.write('\n')
exit_code = 1
except Exception as e:
if not catch_exceptions:
raise
exception = e
exit_code = 1
exc_info = sys.exc_info()
finally:
sys.stdout.flush()
stdout = outstreams[0].getvalue()
stderr = outstreams[1] and outstreams[1].getvalue()
return Result(runner=self,
stdout_bytes=stdout,
stderr_bytes=stderr,
exit_code=exit_code,
exception=exception,
exc_info=exc_info) | [
"def",
"invoke",
"(",
"self",
",",
"cli",
",",
"args",
"=",
"None",
",",
"input",
"=",
"None",
",",
"env",
"=",
"None",
",",
"catch_exceptions",
"=",
"True",
",",
"color",
"=",
"False",
",",
"mix_stderr",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"exc_info",
"=",
"None",
"with",
"self",
".",
"isolation",
"(",
"input",
"=",
"input",
",",
"env",
"=",
"env",
",",
"color",
"=",
"color",
")",
"as",
"outstreams",
":",
"exception",
"=",
"None",
"exit_code",
"=",
"0",
"if",
"isinstance",
"(",
"args",
",",
"string_types",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"args",
")",
"try",
":",
"prog_name",
"=",
"extra",
".",
"pop",
"(",
"\"prog_name\"",
")",
"except",
"KeyError",
":",
"prog_name",
"=",
"self",
".",
"get_default_prog_name",
"(",
"cli",
")",
"try",
":",
"cli",
".",
"main",
"(",
"args",
"=",
"args",
"or",
"(",
")",
",",
"prog_name",
"=",
"prog_name",
",",
"*",
"*",
"extra",
")",
"except",
"SystemExit",
"as",
"e",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"exit_code",
"=",
"e",
".",
"code",
"if",
"exit_code",
"is",
"None",
":",
"exit_code",
"=",
"0",
"if",
"exit_code",
"!=",
"0",
":",
"exception",
"=",
"e",
"if",
"not",
"isinstance",
"(",
"exit_code",
",",
"int",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"exit_code",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"exit_code",
"=",
"1",
"except",
"Exception",
"as",
"e",
":",
"if",
"not",
"catch_exceptions",
":",
"raise",
"exception",
"=",
"e",
"exit_code",
"=",
"1",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"finally",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"stdout",
"=",
"outstreams",
"[",
"0",
"]",
".",
"getvalue",
"(",
")",
"stderr",
"=",
"outstreams",
"[",
"1",
"]",
"and",
"outstreams",
"[",
"1",
"]",
".",
"getvalue",
"(",
")",
"return",
"Result",
"(",
"runner",
"=",
"self",
",",
"stdout_bytes",
"=",
"stdout",
",",
"stderr_bytes",
"=",
"stderr",
",",
"exit_code",
"=",
"exit_code",
",",
"exception",
"=",
"exception",
",",
"exc_info",
"=",
"exc_info",
")"
] | [
279,
4
] | [
356,
40
] | python | en | ['en', 'en', 'en'] | True |
CliRunner.isolated_filesystem | (self) | A context manager that creates a temporary folder and changes
the current working directory to it for isolated filesystem tests.
| A context manager that creates a temporary folder and changes
the current working directory to it for isolated filesystem tests.
| def isolated_filesystem(self):
"""A context manager that creates a temporary folder and changes
the current working directory to it for isolated filesystem tests.
"""
cwd = os.getcwd()
t = tempfile.mkdtemp()
os.chdir(t)
try:
yield t
finally:
os.chdir(cwd)
try:
shutil.rmtree(t)
except (OSError, IOError):
pass | [
"def",
"isolated_filesystem",
"(",
"self",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"t",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"os",
".",
"chdir",
"(",
"t",
")",
"try",
":",
"yield",
"t",
"finally",
":",
"os",
".",
"chdir",
"(",
"cwd",
")",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"t",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"pass"
] | [
359,
4
] | [
373,
20
] | python | en | ['en', 'en', 'en'] | True |
infCallUtil.callmethod | (self, val, fname, args) | make method in fname on the obj ref 'val | make method in fname on the obj ref 'val | def callmethod(self, val, fname, args):
"make method in fname on the obj ref 'val'"
methodcall = "( (" + str(val.type) + ")" + "(" + str(val).split()[0] + ") )" + "->" + fname + "("
cnt = 0
for arg in args:
if (cnt):
methodcall += ","
try:
methodcall += "( (" + str(arg.type) + ")" + "(" + str(arg).split()[0] + ") )"
except AttributeError:
methodcall += "(" + str(arg).split()[0] + ")"
cnt+=1
methodcall += ")"
#print ("methodcall = ", methodcall)
return gdb.parse_and_eval(methodcall) | [
"def",
"callmethod",
"(",
"self",
",",
"val",
",",
"fname",
",",
"args",
")",
":",
"methodcall",
"=",
"\"( (\"",
"+",
"str",
"(",
"val",
".",
"type",
")",
"+",
"\")\"",
"+",
"\"(\"",
"+",
"str",
"(",
"val",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
"+",
"\") )\"",
"+",
"\"->\"",
"+",
"fname",
"+",
"\"(\"",
"cnt",
"=",
"0",
"for",
"arg",
"in",
"args",
":",
"if",
"(",
"cnt",
")",
":",
"methodcall",
"+=",
"\",\"",
"try",
":",
"methodcall",
"+=",
"\"( (\"",
"+",
"str",
"(",
"arg",
".",
"type",
")",
"+",
"\")\"",
"+",
"\"(\"",
"+",
"str",
"(",
"arg",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
"+",
"\") )\"",
"except",
"AttributeError",
":",
"methodcall",
"+=",
"\"(\"",
"+",
"str",
"(",
"arg",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
"+",
"\")\"",
"cnt",
"+=",
"1",
"methodcall",
"+=",
"\")\"",
"#print (\"methodcall = \", methodcall)",
"return",
"gdb",
".",
"parse_and_eval",
"(",
"methodcall",
")"
] | [
10,
1
] | [
26,
39
] | python | en | ['en', 'da', 'en'] | True |
infCallUtil.callfunc | (self, fname, args) | make call fname(args) | make call fname(args) | def callfunc(self, fname, args):
"make call fname(args)"
funccall = fname + "("
cnt = 0
for val in args:
if (cnt):
funccall += ","
funccall += "( (" + str(val.type) + ")" + "(" + str(val).split()[0] + ") )"
cnt+=1
funccall += ")"
#print ("funccall = ", funccall)
return gdb.parse_and_eval(funccall) | [
"def",
"callfunc",
"(",
"self",
",",
"fname",
",",
"args",
")",
":",
"funccall",
"=",
"fname",
"+",
"\"(\"",
"cnt",
"=",
"0",
"for",
"val",
"in",
"args",
":",
"if",
"(",
"cnt",
")",
":",
"funccall",
"+=",
"\",\"",
"funccall",
"+=",
"\"( (\"",
"+",
"str",
"(",
"val",
".",
"type",
")",
"+",
"\")\"",
"+",
"\"(\"",
"+",
"str",
"(",
"val",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
"+",
"\") )\"",
"cnt",
"+=",
"1",
"funccall",
"+=",
"\")\"",
"#print (\"funccall = \", funccall)",
"return",
"gdb",
".",
"parse_and_eval",
"(",
"funccall",
")"
] | [
28,
1
] | [
39,
37
] | python | en | ['en', 'ceb', 'en'] | True |
_parse_arguments | (argv) | Parses command-line arguments. | Parses command-line arguments. | def _parse_arguments(argv):
"""Parses command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--game',
help='Which open ai gym game to play',
type=str,
default='CartPole-v0')
parser.add_argument(
'--episodes',
help='The number of episodes to simulate',
type=int,
default=2000)
parser.add_argument(
'--learning_rate',
help='Learning rate for the nueral network',
type=float,
default=0.0005)
parser.add_argument(
'--critic_weight',
help='Learning rate for the nueral network',
type=float,
default=0.95)
parser.add_argument(
'--hidden_neurons',
help='The number of nuerons to use per layer',
type=int,
default=128)
parser.add_argument(
'--gamma',
help='The gamma or "discount" factor to discount future states',
type=float,
default=0.995)
parser.add_argument(
'--batch_size',
help='How often to print the score, 0 if never',
type=int,
default=32)
parser.add_argument(
'--entropy',
help='How often to print the score, 0 if never',
type=float,
default=0.0001)
parser.add_argument(
'--print_rate',
help='How often to print the score, 0 if never',
type=int,
default=0)
parser.add_argument(
'--job-dir',
help='Directory where to save the given model',
type=str,
default='models/')
parser.add_argument(
'--eval_rate',
help="""While training, perform an on-policy simulation and record
metrics to tensorboard every <record_rate> steps, 0 if never. Use
higher values to avoid hyperparameter tuning "too many metrics"
error""",
type=int,
default=50)
return parser.parse_known_args(argv) | [
"def",
"_parse_arguments",
"(",
"argv",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--game'",
",",
"help",
"=",
"'Which open ai gym game to play'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'CartPole-v0'",
")",
"parser",
".",
"add_argument",
"(",
"'--episodes'",
",",
"help",
"=",
"'The number of episodes to simulate'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"2000",
")",
"parser",
".",
"add_argument",
"(",
"'--learning_rate'",
",",
"help",
"=",
"'Learning rate for the nueral network'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.0005",
")",
"parser",
".",
"add_argument",
"(",
"'--critic_weight'",
",",
"help",
"=",
"'Learning rate for the nueral network'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.95",
")",
"parser",
".",
"add_argument",
"(",
"'--hidden_neurons'",
",",
"help",
"=",
"'The number of nuerons to use per layer'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"128",
")",
"parser",
".",
"add_argument",
"(",
"'--gamma'",
",",
"help",
"=",
"'The gamma or \"discount\" factor to discount future states'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.995",
")",
"parser",
".",
"add_argument",
"(",
"'--batch_size'",
",",
"help",
"=",
"'How often to print the score, 0 if never'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"32",
")",
"parser",
".",
"add_argument",
"(",
"'--entropy'",
",",
"help",
"=",
"'How often to print the score, 0 if never'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.0001",
")",
"parser",
".",
"add_argument",
"(",
"'--print_rate'",
",",
"help",
"=",
"'How often to print the score, 0 if never'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
")",
"parser",
".",
"add_argument",
"(",
"'--job-dir'",
",",
"help",
"=",
"'Directory where to save the given model'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'models/'",
")",
"parser",
".",
"add_argument",
"(",
"'--eval_rate'",
",",
"help",
"=",
"\"\"\"While training, perform an on-policy simulation and record\n metrics to tensorboard every <record_rate> steps, 0 if never. Use\n higher values to avoid hyperparameter tuning \"too many metrics\"\n error\"\"\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"50",
")",
"return",
"parser",
".",
"parse_known_args",
"(",
"argv",
")"
] | [
33,
0
] | [
94,
40
] | python | en | ['en', 'fr', 'en'] | True |
_run | (game, network_params, memory_params, ops) | Sets up and runs the gaming simulation.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
args: The arguments from the command line parsed by_parse_arguments.
| Sets up and runs the gaming simulation. | def _run(game, network_params, memory_params, ops):
"""Sets up and runs the gaming simulation.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
args: The arguments from the command line parsed by_parse_arguments.
"""
# Setup TensorBoard Writer.
trial_id = json.loads(
os.environ.get('TF_CONFIG', '{}')).get('task', {}).get('trial', '')
output_path = ops.job_dir if not trial_id else ops.job_dir + '/'
tensorboard = TensorBoard(log_dir=output_path)
hpt = hypertune.HyperTune()
graph = tf.Graph()
with graph.as_default():
env = gym.make(game)
agent = _create_agent(env, network_params, memory_params)
rewards = []
tensorboard.set_model(agent.policy)
def _train_or_evaluate(print_score, training=False):
"""Runs a gaming simulation and writes results for tensorboard.
Args:
print_score (bool): True to print a score to the console.
training (bool): True if the agent is training, False to eval.
Returns:
loss if training, else reward for evaluating.
"""
reward = _play(agent, env, training)
if print_score:
print(
'Train - ',
'Episode: {}'.format(episode),
'Total reward: {}'.format(reward),
)
return reward
for episode in range(1, ops.episodes+1):
print_score = ops.print_rate and episode % ops.print_rate == 0
get_summary = ops.eval_rate and episode % ops.eval_rate == 0
rewards.append(_train_or_evaluate(print_score, training=True))
if get_summary:
avg_reward = sum(rewards) / len(rewards)
summary = {'eval_reward': avg_reward}
tensorboard.on_epoch_end(episode, summary)
hpt.report_hyperparameter_tuning_metric(
hyperparameter_metric_tag='avg_reward',
metric_value=avg_reward,
global_step=episode)
print(
'Eval - ',
'Episode: {}'.format(episode),
'Average Reward: {}'.format(avg_reward),
)
rewards = []
tensorboard.on_train_end(None)
_record_video(env, agent, output_path)
agent.policy.save(output_path, save_format='tf') | [
"def",
"_run",
"(",
"game",
",",
"network_params",
",",
"memory_params",
",",
"ops",
")",
":",
"# Setup TensorBoard Writer.",
"trial_id",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'TF_CONFIG'",
",",
"'{}'",
")",
")",
".",
"get",
"(",
"'task'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'trial'",
",",
"''",
")",
"output_path",
"=",
"ops",
".",
"job_dir",
"if",
"not",
"trial_id",
"else",
"ops",
".",
"job_dir",
"+",
"'/'",
"tensorboard",
"=",
"TensorBoard",
"(",
"log_dir",
"=",
"output_path",
")",
"hpt",
"=",
"hypertune",
".",
"HyperTune",
"(",
")",
"graph",
"=",
"tf",
".",
"Graph",
"(",
")",
"with",
"graph",
".",
"as_default",
"(",
")",
":",
"env",
"=",
"gym",
".",
"make",
"(",
"game",
")",
"agent",
"=",
"_create_agent",
"(",
"env",
",",
"network_params",
",",
"memory_params",
")",
"rewards",
"=",
"[",
"]",
"tensorboard",
".",
"set_model",
"(",
"agent",
".",
"policy",
")",
"def",
"_train_or_evaluate",
"(",
"print_score",
",",
"training",
"=",
"False",
")",
":",
"\"\"\"Runs a gaming simulation and writes results for tensorboard.\n\n Args:\n print_score (bool): True to print a score to the console.\n training (bool): True if the agent is training, False to eval.\n\n Returns:\n loss if training, else reward for evaluating.\n \"\"\"",
"reward",
"=",
"_play",
"(",
"agent",
",",
"env",
",",
"training",
")",
"if",
"print_score",
":",
"print",
"(",
"'Train - '",
",",
"'Episode: {}'",
".",
"format",
"(",
"episode",
")",
",",
"'Total reward: {}'",
".",
"format",
"(",
"reward",
")",
",",
")",
"return",
"reward",
"for",
"episode",
"in",
"range",
"(",
"1",
",",
"ops",
".",
"episodes",
"+",
"1",
")",
":",
"print_score",
"=",
"ops",
".",
"print_rate",
"and",
"episode",
"%",
"ops",
".",
"print_rate",
"==",
"0",
"get_summary",
"=",
"ops",
".",
"eval_rate",
"and",
"episode",
"%",
"ops",
".",
"eval_rate",
"==",
"0",
"rewards",
".",
"append",
"(",
"_train_or_evaluate",
"(",
"print_score",
",",
"training",
"=",
"True",
")",
")",
"if",
"get_summary",
":",
"avg_reward",
"=",
"sum",
"(",
"rewards",
")",
"/",
"len",
"(",
"rewards",
")",
"summary",
"=",
"{",
"'eval_reward'",
":",
"avg_reward",
"}",
"tensorboard",
".",
"on_epoch_end",
"(",
"episode",
",",
"summary",
")",
"hpt",
".",
"report_hyperparameter_tuning_metric",
"(",
"hyperparameter_metric_tag",
"=",
"'avg_reward'",
",",
"metric_value",
"=",
"avg_reward",
",",
"global_step",
"=",
"episode",
")",
"print",
"(",
"'Eval - '",
",",
"'Episode: {}'",
".",
"format",
"(",
"episode",
")",
",",
"'Average Reward: {}'",
".",
"format",
"(",
"avg_reward",
")",
",",
")",
"rewards",
"=",
"[",
"]",
"tensorboard",
".",
"on_train_end",
"(",
"None",
")",
"_record_video",
"(",
"env",
",",
"agent",
",",
"output_path",
")",
"agent",
".",
"policy",
".",
"save",
"(",
"output_path",
",",
"save_format",
"=",
"'tf'",
")"
] | [
97,
0
] | [
162,
56
] | python | en | ['en', 'fil', 'en'] | True |
_play | (agent, env, training, recorder=None) | Plays through one episode of the game.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
agent: The actor learning to play in the given environment.
env: The environment for the agent to act in. This code is intended for
use with OpenAI Gym, but the user can alter the code to provide their
own environment.
training (bool): True if the agent is training.
recorder (optional): A gym video recorder object to save the simulation
to a movie.
| Plays through one episode of the game. | def _play(agent, env, training, recorder=None):
"""Plays through one episode of the game.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
agent: The actor learning to play in the given environment.
env: The environment for the agent to act in. This code is intended for
use with OpenAI Gym, but the user can alter the code to provide their
own environment.
training (bool): True if the agent is training.
recorder (optional): A gym video recorder object to save the simulation
to a movie.
"""
episode_reward = 0 # The total reward for an episode.
state = env.reset().tolist() # Set up Environment and get start state.
done = False
if recorder:
recorder.capture_frame()
while not done:
action = agent.act(state)
state_prime, reward, done, _ = env.step(action)
episode_reward += reward
next_value = agent.critic.predict([[state_prime]])
agent.memory.add((state, action, reward, done, next_value))
if training and agent.memory.check_full():
agent.learn()
if recorder:
recorder.capture_frame()
state = state_prime # st+1 is now our current state.
return episode_reward | [
"def",
"_play",
"(",
"agent",
",",
"env",
",",
"training",
",",
"recorder",
"=",
"None",
")",
":",
"episode_reward",
"=",
"0",
"# The total reward for an episode.",
"state",
"=",
"env",
".",
"reset",
"(",
")",
".",
"tolist",
"(",
")",
"# Set up Environment and get start state.",
"done",
"=",
"False",
"if",
"recorder",
":",
"recorder",
".",
"capture_frame",
"(",
")",
"while",
"not",
"done",
":",
"action",
"=",
"agent",
".",
"act",
"(",
"state",
")",
"state_prime",
",",
"reward",
",",
"done",
",",
"_",
"=",
"env",
".",
"step",
"(",
"action",
")",
"episode_reward",
"+=",
"reward",
"next_value",
"=",
"agent",
".",
"critic",
".",
"predict",
"(",
"[",
"[",
"state_prime",
"]",
"]",
")",
"agent",
".",
"memory",
".",
"add",
"(",
"(",
"state",
",",
"action",
",",
"reward",
",",
"done",
",",
"next_value",
")",
")",
"if",
"training",
"and",
"agent",
".",
"memory",
".",
"check_full",
"(",
")",
":",
"agent",
".",
"learn",
"(",
")",
"if",
"recorder",
":",
"recorder",
".",
"capture_frame",
"(",
")",
"state",
"=",
"state_prime",
"# st+1 is now our current state.",
"return",
"episode_reward"
] | [
165,
0
] | [
201,
25
] | python | en | ['en', 'en', 'en'] | True |
_create_agent | (env, network_params, memory_params) | Creates a Reinforcement Learning agent.
Args:
env: The environment for the agent to act in.
network_params: Parameters to build actor-critic neural networks.
memory_params: Parameters to an actor-critic memory buffer.
Returns:
An RL agent.
| Creates a Reinforcement Learning agent. | def _create_agent(env, network_params, memory_params):
"""Creates a Reinforcement Learning agent.
Args:
env: The environment for the agent to act in.
network_params: Parameters to build actor-critic neural networks.
memory_params: Parameters to an actor-critic memory buffer.
Returns:
An RL agent.
"""
space_shape = env.observation_space.shape[0]
action_size = env.action_space.n
actor, critic, policy = model.build_networks(
space_shape, action_size, *network_params)
memory = model.Memory(*memory_params)
return model.Agent(actor, critic, policy, memory, action_size) | [
"def",
"_create_agent",
"(",
"env",
",",
"network_params",
",",
"memory_params",
")",
":",
"space_shape",
"=",
"env",
".",
"observation_space",
".",
"shape",
"[",
"0",
"]",
"action_size",
"=",
"env",
".",
"action_space",
".",
"n",
"actor",
",",
"critic",
",",
"policy",
"=",
"model",
".",
"build_networks",
"(",
"space_shape",
",",
"action_size",
",",
"*",
"network_params",
")",
"memory",
"=",
"model",
".",
"Memory",
"(",
"*",
"memory_params",
")",
"return",
"model",
".",
"Agent",
"(",
"actor",
",",
"critic",
",",
"policy",
",",
"memory",
",",
"action_size",
")"
] | [
204,
0
] | [
220,
66
] | python | en | ['en', 'en', 'en'] | True |
_record_video | (env, agent, output_path) | Records a video of an agent playing a gaming simulation.
Args:
env: The environment for the agent to act in.
agent: An RL agent created by _create_agent.
output_path (str): The directory path of where to save the recording.
| Records a video of an agent playing a gaming simulation. | def _record_video(env, agent, output_path):
"""Records a video of an agent playing a gaming simulation.
Args:
env: The environment for the agent to act in.
agent: An RL agent created by _create_agent.
output_path (str): The directory path of where to save the recording.
"""
video_recorder = VideoRecorder(env, RECORDING_NAME)
_play(agent, env, False, recorder=video_recorder)
video_recorder.close()
env.close()
# Check if output directory is google cloud and save there if so.
if output_path.startswith("gs://"):
[bucket_name, blob_path] = output_path[5:].split("/", 1)
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_path + RECORDING_NAME)
blob.upload_from_filename(RECORDING_NAME) | [
"def",
"_record_video",
"(",
"env",
",",
"agent",
",",
"output_path",
")",
":",
"video_recorder",
"=",
"VideoRecorder",
"(",
"env",
",",
"RECORDING_NAME",
")",
"_play",
"(",
"agent",
",",
"env",
",",
"False",
",",
"recorder",
"=",
"video_recorder",
")",
"video_recorder",
".",
"close",
"(",
")",
"env",
".",
"close",
"(",
")",
"# Check if output directory is google cloud and save there if so.",
"if",
"output_path",
".",
"startswith",
"(",
"\"gs://\"",
")",
":",
"[",
"bucket_name",
",",
"blob_path",
"]",
"=",
"output_path",
"[",
"5",
":",
"]",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"storage_client",
"=",
"storage",
".",
"Client",
"(",
")",
"bucket",
"=",
"storage_client",
".",
"get_bucket",
"(",
"bucket_name",
")",
"blob",
"=",
"bucket",
".",
"blob",
"(",
"blob_path",
"+",
"RECORDING_NAME",
")",
"blob",
".",
"upload_from_filename",
"(",
"RECORDING_NAME",
")"
] | [
223,
0
] | [
242,
49
] | python | en | ['en', 'en', 'en'] | True |
main | () | Parses command line arguments and kicks off the gaming simulation. | Parses command line arguments and kicks off the gaming simulation. | def main():
"""Parses command line arguments and kicks off the gaming simulation."""
args = _parse_arguments(sys.argv[1:])[0]
network_params = (
args.learning_rate, args.critic_weight, args.hidden_neurons, args.entropy)
memory_params = (args.gamma, args.batch_size)
ops = argparse.Namespace(**{
'job_dir': args.job_dir,
'episodes': args.episodes,
'print_rate': args.print_rate,
'eval_rate': args.eval_rate
})
_run(args.game, network_params, memory_params, ops) | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"_parse_arguments",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"[",
"0",
"]",
"network_params",
"=",
"(",
"args",
".",
"learning_rate",
",",
"args",
".",
"critic_weight",
",",
"args",
".",
"hidden_neurons",
",",
"args",
".",
"entropy",
")",
"memory_params",
"=",
"(",
"args",
".",
"gamma",
",",
"args",
".",
"batch_size",
")",
"ops",
"=",
"argparse",
".",
"Namespace",
"(",
"*",
"*",
"{",
"'job_dir'",
":",
"args",
".",
"job_dir",
",",
"'episodes'",
":",
"args",
".",
"episodes",
",",
"'print_rate'",
":",
"args",
".",
"print_rate",
",",
"'eval_rate'",
":",
"args",
".",
"eval_rate",
"}",
")",
"_run",
"(",
"args",
".",
"game",
",",
"network_params",
",",
"memory_params",
",",
"ops",
")"
] | [
245,
0
] | [
257,
55
] | python | en | ['en', 'en', 'en'] | True |
ResponseHeaders.__init__ | (self, data) |
Populate the initial data using __setitem__ to ensure values are
correctly encoded.
|
Populate the initial data using __setitem__ to ensure values are
correctly encoded.
| def __init__(self, data):
"""
Populate the initial data using __setitem__ to ensure values are
correctly encoded.
"""
if not isinstance(data, Mapping):
data = {k: v for k, v in _destruct_iterable_mapping_values(data)}
self._store = {}
for header, value in data.items():
self[header] = value | [
"def",
"__init__",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Mapping",
")",
":",
"data",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"_destruct_iterable_mapping_values",
"(",
"data",
")",
"}",
"self",
".",
"_store",
"=",
"{",
"}",
"for",
"header",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"self",
"[",
"header",
"]",
"=",
"value"
] | [
29,
4
] | [
38,
32
] | python | en | ['en', 'error', 'th'] | False |
ResponseHeaders._convert_to_charset | (self, value, charset, mime_encode=False) |
Convert headers key/value to ascii/latin-1 native strings.
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
`value` can't be represented in the given charset, apply MIME-encoding.
|
Convert headers key/value to ascii/latin-1 native strings.
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
`value` can't be represented in the given charset, apply MIME-encoding.
| def _convert_to_charset(self, value, charset, mime_encode=False):
"""
Convert headers key/value to ascii/latin-1 native strings.
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
`value` can't be represented in the given charset, apply MIME-encoding.
"""
if not isinstance(value, (bytes, str)):
value = str(value)
if (
(isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
(isinstance(value, str) and ('\n' in value or '\r' in value))
):
raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
try:
if isinstance(value, str):
# Ensure string is valid in given charset
value.encode(charset)
else:
# Convert bytestring using given charset
value = value.decode(charset)
except UnicodeError as e:
if mime_encode:
value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
else:
e.reason += ', HTTP response headers must be in %s format' % charset
raise
return value | [
"def",
"_convert_to_charset",
"(",
"self",
",",
"value",
",",
"charset",
",",
"mime_encode",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"bytes",
",",
"str",
")",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"(",
"(",
"isinstance",
"(",
"value",
",",
"bytes",
")",
"and",
"(",
"b'\\n'",
"in",
"value",
"or",
"b'\\r'",
"in",
"value",
")",
")",
"or",
"(",
"isinstance",
"(",
"value",
",",
"str",
")",
"and",
"(",
"'\\n'",
"in",
"value",
"or",
"'\\r'",
"in",
"value",
")",
")",
")",
":",
"raise",
"BadHeaderError",
"(",
"\"Header values can't contain newlines (got %r)\"",
"%",
"value",
")",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# Ensure string is valid in given charset",
"value",
".",
"encode",
"(",
"charset",
")",
"else",
":",
"# Convert bytestring using given charset",
"value",
"=",
"value",
".",
"decode",
"(",
"charset",
")",
"except",
"UnicodeError",
"as",
"e",
":",
"if",
"mime_encode",
":",
"value",
"=",
"Header",
"(",
"value",
",",
"'utf-8'",
",",
"maxlinelen",
"=",
"sys",
".",
"maxsize",
")",
".",
"encode",
"(",
")",
"else",
":",
"e",
".",
"reason",
"+=",
"', HTTP response headers must be in %s format'",
"%",
"charset",
"raise",
"return",
"value"
] | [
40,
4
] | [
66,
20
] | python | en | ['en', 'error', 'th'] | False |
HttpResponseBase.serialize_headers | (self) | HTTP headers as a bytestring. | HTTP headers as a bytestring. | def serialize_headers(self):
"""HTTP headers as a bytestring."""
def to_bytes(val, encoding):
return val if isinstance(val, bytes) else val.encode(encoding)
headers = [
(to_bytes(key, 'ascii') + b': ' + to_bytes(value, 'latin-1'))
for key, value in self.headers.items()
]
return b'\r\n'.join(headers) | [
"def",
"serialize_headers",
"(",
"self",
")",
":",
"def",
"to_bytes",
"(",
"val",
",",
"encoding",
")",
":",
"return",
"val",
"if",
"isinstance",
"(",
"val",
",",
"bytes",
")",
"else",
"val",
".",
"encode",
"(",
"encoding",
")",
"headers",
"=",
"[",
"(",
"to_bytes",
"(",
"key",
",",
"'ascii'",
")",
"+",
"b': '",
"+",
"to_bytes",
"(",
"value",
",",
"'latin-1'",
")",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"headers",
".",
"items",
"(",
")",
"]",
"return",
"b'\\r\\n'",
".",
"join",
"(",
"headers",
")"
] | [
153,
4
] | [
162,
36
] | python | en | ['en', 'sv', 'en'] | True |
HttpResponseBase.has_header | (self, header) | Case-insensitive check for a header. | Case-insensitive check for a header. | def has_header(self, header):
"""Case-insensitive check for a header."""
return header in self.headers | [
"def",
"has_header",
"(",
"self",
",",
"header",
")",
":",
"return",
"header",
"in",
"self",
".",
"headers"
] | [
179,
4
] | [
181,
37
] | 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.