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 list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
ReindentFilter._flatten_up_to_token | (self, token) | Yields all tokens up to token but excluding current. | Yields all tokens up to token but excluding current. | def _flatten_up_to_token(self, token):
"""Yields all tokens up to token but excluding current."""
if token.is_group:
token = next(token.flatten())
for t in self._curr_stmt.flatten():
if t == token:
break
yield t | [
"def",
"_flatten_up_to_token",
"(",
"self",
",",
"token",
")",
":",
"if",
"token",
".",
"is_group",
":",
"token",
"=",
"next",
"(",
"token",
".",
"flatten",
"(",
")",
")",
"for",
"t",
"in",
"self",
".",
"_curr_stmt",
".",
"flatten",
"(",
")",
":",
... | [
27,
4
] | [
35,
19
] | python | en | ['en', 'en', 'en'] | True |
drf_reverse | (viewname, args=None, kwargs=None, request=None, format=None, **extra) |
Copy and monkey-patch `rest_framework.reverse.reverse` to prevent adding unwarranted
query string parameters.
|
Copy and monkey-patch `rest_framework.reverse.reverse` to prevent adding unwarranted
query string parameters.
| def drf_reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
"""
Copy and monkey-patch `rest_framework.reverse.reverse` to prevent adding unwarranted
query string parameters.
"""
scheme = getattr(request, 'versioning_scheme', None)
if scheme is not None:
try:
... | [
"def",
"drf_reverse",
"(",
"viewname",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"request",
"=",
"None",
",",
"format",
"=",
"None",
",",
"*",
"*",
"extra",
")",
":",
"scheme",
"=",
"getattr",
"(",
"request",
",",
"'versioning_scheme'"... | [
10,
0
] | [
26,
14
] | python | en | ['en', 'error', 'th'] | False |
plot_image | (text, index, adversarial_image, original_image, label_true, label_pred, limit, l2) |
TODO: Write Comment
|
TODO: Write Comment
| def plot_image(text, index, adversarial_image, original_image, label_true, label_pred, limit, l2):
"""
TODO: Write Comment
"""
def plot(index, image, label, label_type=""):
"""
TODO: Write Comment
"""
if image.ndim == 4 and image.shape[0] == 1: image = image[0]
... | [
"def",
"plot_image",
"(",
"text",
",",
"index",
",",
"adversarial_image",
",",
"original_image",
",",
"label_true",
",",
"label_pred",
",",
"limit",
",",
"l2",
")",
":",
"def",
"plot",
"(",
"index",
",",
"image",
",",
"label",
",",
"label_type",
"=",
"\"... | [
120,
0
] | [
145,
129
] | python | en | ['en', 'error', 'th'] | False |
PlotTraining.__init__ | (self, filepath="") |
TODO: Write Comment
|
TODO: Write Comment
| def __init__(self, filepath=""):
"""
TODO: Write Comment
"""
super(PlotTraining, self).__init__()
self.filepath = filepath
self.reset() | [
"def",
"__init__",
"(",
"self",
",",
"filepath",
"=",
"\"\"",
")",
":",
"super",
"(",
"PlotTraining",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"filepath",
"=",
"filepath",
"self",
".",
"reset",
"(",
")"
] | [
23,
4
] | [
31,
20
] | python | en | ['en', 'error', 'th'] | False |
PlotTraining.reset | (self) |
TODO: Write Comment
|
TODO: Write Comment
| def reset(self):
"""
TODO: Write Comment
"""
self.i = 0
self.x = []
self.losses = []
self.val_losses = []
self.acc = []
self.val_acc = []
self.logs = [] | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"i",
"=",
"0",
"self",
".",
"x",
"=",
"[",
"]",
"self",
".",
"losses",
"=",
"[",
"]",
"self",
".",
"val_losses",
"=",
"[",
"]",
"self",
".",
"acc",
"=",
"[",
"]",
"self",
".",
"val_acc",
"... | [
34,
4
] | [
45,
22
] | python | en | ['en', 'error', 'th'] | False |
PlotTraining.on_epoch_end | (self, epoch, logs={}) |
TODO: Write Comment
|
TODO: Write Comment
| def on_epoch_end(self, epoch, logs={}):
"""
TODO: Write Comment
"""
self.x.append(self.i+1)
self.logs.append(logs)
self.losses.append(logs.get('loss'))
self.val_losses.append(logs.get('val_loss'))
self.acc.append(logs.get('accuracy'))
self.val_acc... | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch",
",",
"logs",
"=",
"{",
"}",
")",
":",
"self",
".",
"x",
".",
"append",
"(",
"self",
".",
"i",
"+",
"1",
")",
"self",
".",
"logs",
".",
"append",
"(",
"logs",
")",
"self",
".",
"losses",
".",
"... | [
48,
4
] | [
80,
19
] | python | en | ['en', 'error', 'th'] | False |
bytes_to_text | (s, encoding) |
Converts basestring objects to unicode, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
Returns any non-basestring objects without change.
|
Converts basestring objects to unicode, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd). | def bytes_to_text(s, encoding):
"""
Converts basestring objects to unicode, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
Returns any non-basestring objects without change.
"""
if isinstance(s, bytes):
return six... | [
"def",
"bytes_to_text",
"(",
"s",
",",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"six",
".",
"text_type",
"(",
"s",
",",
"encoding",
",",
"'replace'",
")",
"else",
":",
"return",
"s"
] | [
526,
0
] | [
537,
16
] | python | en | ['en', 'error', 'th'] | False |
split_domain_port | (host) |
Return a (domain, port) tuple from a given host.
Returned domain is lower-cased. 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 lower-cased. 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 a... | [
"def",
"split_domain_port",
"(",
"host",
")",
":",
"host",
"=",
"host",
".",
"lower",
"(",
")",
"if",
"not",
"host_validation_re",
".",
"match",
"(",
"host",
")",
":",
"return",
"''",
",",
"''",
"if",
"host",
"[",
"-",
"1",
"]",
"==",
"']'",
":",
... | [
540,
0
] | [
559,
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), ``*`` mat... |
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
... | [
"def",
"validate_host",
"(",
"host",
",",
"allowed_hosts",
")",
":",
"for",
"pattern",
"in",
"allowed_hosts",
":",
"if",
"pattern",
"==",
"'*'",
"or",
"is_same_domain",
"(",
"host",
",",
"pattern",
")",
":",
"return",
"True",
"return",
"False"
] | [
562,
0
] | [
581,
16
] | python | en | ['en', 'error', 'th'] | False |
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 (
... | [
"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",
... | [
75,
4
] | [
92,
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:
... | [
"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",
"no... | [
94,
4
] | [
112,
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"... | [
114,
4
] | [
120,
24
] | python | en | ['en', 'en', 'en'] | True |
HttpRequest.get_signed_cookie | (self, key, default=RAISE_ERROR, salt='', max_age=None) |
Attempts to return a signed cookie. If the signature fails or the
cookie has expired, raises an exception... unless you provide the
default argument in which case that value will be returned instead.
|
Attempts to return a signed cookie. If the signature fails or the
cookie has expired, raises an exception... unless you provide the
default argument in which case that value will be returned instead.
| def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
"""
Attempts to return a signed cookie. If the signature fails or the
cookie has expired, raises an exception... unless you provide the
default argument in which case that value will be returned instead.
... | [
"def",
"get_signed_cookie",
"(",
"self",
",",
"key",
",",
"default",
"=",
"RAISE_ERROR",
",",
"salt",
"=",
"''",
",",
"max_age",
"=",
"None",
")",
":",
"try",
":",
"cookie_value",
"=",
"self",
".",
"COOKIES",
"[",
"key",
"]",
"except",
"KeyError",
":",... | [
131,
4
] | [
152,
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(),
p... | [
"def",
"get_raw_uri",
"(",
"self",
")",
":",
"return",
"'{scheme}://{host}{path}'",
".",
"format",
"(",
"scheme",
"=",
"self",
".",
"scheme",
",",
"host",
"=",
"self",
".",
"_get_raw_host",
"(",
")",
",",
"path",
"=",
"self",
".",
"get_full_path",
"(",
"... | [
154,
4
] | [
163,
9
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.build_absolute_uri | (self, location=None) |
Builds an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, the absolute URI is
built on ``request.get_full_path()``. Anyway, if the location is
absolute, it is simply converted to an RFC 3987 compliant URI and
returned ... |
Builds an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, the absolute URI is
built on ``request.get_full_path()``. Anyway, if the location is
absolute, it is simply converted to an RFC 3987 compliant URI and
returned ... | def build_absolute_uri(self, location=None):
"""
Builds an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, the absolute URI is
built on ``request.get_full_path()``. Anyway, if the location is
absolute, it is simply conv... | [
"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",... | [
165,
4
] | [
188,
35
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest._get_scheme | (self) |
Hook for subclasses like WSGIRequest to implement. Returns 'http' by
default.
|
Hook for subclasses like WSGIRequest to implement. Returns 'http' by
default.
| def _get_scheme(self):
"""
Hook for subclasses like WSGIRequest to implement. Returns 'http' by
default.
"""
return 'http' | [
"def",
"_get_scheme",
"(",
"self",
")",
":",
"return",
"'http'"
] | [
190,
4
] | [
195,
21
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.encoding | (self, val) |
Sets the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, it is removed and recreated on the
next access (so that it is decoded correctly).
|
Sets the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, it is removed and recreated on the
next access (so that it is decoded correctly).
| def encoding(self, val):
"""
Sets the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, it is removed and recreated on the
next access (so that it is decoded correctly).
"""
self._encoding = val
if hasattr(self, 'GET'):
... | [
"def",
"encoding",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"_encoding",
"=",
"val",
"if",
"hasattr",
"(",
"self",
",",
"'GET'",
")",
":",
"del",
"self",
".",
"GET",
"if",
"hasattr",
"(",
"self",
",",
"'_post'",
")",
":",
"del",
"self",
".... | [
221,
4
] | [
231,
26
] | python | en | ['en', 'error', 'th'] | False |
HttpRequest.parse_file_upload | (self, META, post_data) | Returns a tuple of (POST QueryDict, FILES MultiValueDict). | Returns a tuple of (POST QueryDict, FILES MultiValueDict). | def parse_file_upload(self, META, post_data):
"""Returns 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 = Mu... | [
"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.\"",
... | [
250,
4
] | [
257,
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'... | [
"def",
"_load_post_and_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"!=",
"'POST'",
":",
"self",
".",
"_post",
",",
"self",
".",
"_files",
"=",
"QueryDict",
"(",
"encoding",
"=",
"self",
".",
"_encoding",
")",
",",
"MultiValueDict",
"(",
... | [
282,
4
] | [
312,
90
] | 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)
... | [
"def",
"fromkeys",
"(",
"cls",
",",
"iterable",
",",
"value",
"=",
"''",
",",
"mutable",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"q",
"=",
"cls",
"(",
"''",
",",
"mutable",
"=",
"True",
",",
"encoding",
"=",
"encoding",
")",
"for",
... | [
406,
4
] | [
416,
16
] | python | en | ['en', 'error', 'th'] | False |
QueryDict.copy | (self) | Returns a mutable copy of this object. | Returns a mutable copy of this object. | def copy(self):
"""Returns a mutable copy of this object."""
return self.__deepcopy__({}) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__deepcopy__",
"(",
"{",
"}",
")"
] | [
489,
4
] | [
491,
36
] | python | en | ['en', 'en', 'en'] | True |
QueryDict.urlencode | (self, safe=None) |
Returns an encoded string of all query string arguments.
:arg safe: Used to specify characters which do not require quoting, for
example::
>>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'
>>> q.urlencode()
'next=%2Fa%2... |
Returns an encoded string of all query string arguments. | def urlencode(self, safe=None):
"""
Returns an encoded string of all query string arguments.
:arg safe: Used to specify characters which do not require quoting, for
example::
>>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'
>>>... | [
"def",
"urlencode",
"(",
"self",
",",
"safe",
"=",
"None",
")",
":",
"output",
"=",
"[",
"]",
"if",
"safe",
":",
"safe",
"=",
"force_bytes",
"(",
"safe",
",",
"self",
".",
"encoding",
")",
"def",
"encode",
"(",
"k",
",",
"v",
")",
":",
"return",
... | [
493,
4
] | [
520,
31
] | python | en | ['en', 'error', 'th'] | False |
PagesAdminAPIViewSet.get_root_page | (self) |
Returns the page that is used when the `&child_of=root` filter is used.
|
Returns the page that is used when the `&child_of=root` filter is used.
| def get_root_page(self):
"""
Returns the page that is used when the `&child_of=root` filter is used.
"""
return Page.get_first_root_node() | [
"def",
"get_root_page",
"(",
"self",
")",
":",
"return",
"Page",
".",
"get_first_root_node",
"(",
")"
] | [
61,
4
] | [
65,
41
] | python | en | ['en', 'error', 'th'] | False |
PagesAdminAPIViewSet.get_base_queryset | (self) |
Returns a queryset containing all pages that can be seen by this user.
This is used as the base for get_queryset and is also used to find the
parent pages when using the child_of and descendant_of filters as well.
|
Returns a queryset containing all pages that can be seen by this user. | def get_base_queryset(self):
"""
Returns a queryset containing all pages that can be seen by this user.
This is used as the base for get_queryset and is also used to find the
parent pages when using the child_of and descendant_of filters as well.
"""
return Page.objects.... | [
"def",
"get_base_queryset",
"(",
"self",
")",
":",
"return",
"Page",
".",
"objects",
".",
"all",
"(",
")"
] | [
67,
4
] | [
74,
33
] | python | en | ['en', 'error', 'th'] | False |
add_new_user_history | (user_profile: UserProfile, streams: Iterable[Stream]) | Give you the last ONBOARDING_TOTAL_MESSAGES messages on your public
streams, so you have something to look at in your home view once
you finish the tutorial. The most recent ONBOARDING_UNREAD_MESSAGES
are marked unread.
| Give you the last ONBOARDING_TOTAL_MESSAGES messages on your public
streams, so you have something to look at in your home view once
you finish the tutorial. The most recent ONBOARDING_UNREAD_MESSAGES
are marked unread.
| def add_new_user_history(user_profile: UserProfile, streams: Iterable[Stream]) -> None:
"""Give you the last ONBOARDING_TOTAL_MESSAGES messages on your public
streams, so you have something to look at in your home view once
you finish the tutorial. The most recent ONBOARDING_UNREAD_MESSAGES
are marked ... | [
"def",
"add_new_user_history",
"(",
"user_profile",
":",
"UserProfile",
",",
"streams",
":",
"Iterable",
"[",
"Stream",
"]",
")",
"->",
"None",
":",
"one_week_ago",
"=",
"timezone_now",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"weeks",
"=",
"1",
"... | [
406,
0
] | [
446,
60
] | python | en | ['en', 'en', 'en'] | True |
do_set_realm_property | (
realm: Realm, name: str, value: Any, *, acting_user: Optional[UserProfile]
) | Takes in a realm object, the name of an attribute to update, the
value to update and and the user who initiated the update.
| Takes in a realm object, the name of an attribute to update, the
value to update and and the user who initiated the update.
| def do_set_realm_property(
realm: Realm, name: str, value: Any, *, acting_user: Optional[UserProfile]
) -> None:
"""Takes in a realm object, the name of an attribute to update, the
value to update and and the user who initiated the update.
"""
property_type = Realm.property_types[name]
assert is... | [
"def",
"do_set_realm_property",
"(",
"realm",
":",
"Realm",
",",
"name",
":",
"str",
",",
"value",
":",
"Any",
",",
"*",
",",
"acting_user",
":",
"Optional",
"[",
"UserProfile",
"]",
")",
"->",
"None",
":",
"property_type",
"=",
"Realm",
".",
"property_t... | [
784,
0
] | [
838,
73
] | python | en | ['en', 'en', 'en'] | True |
do_deactivate_realm | (realm: Realm, *, acting_user: Optional[UserProfile]) |
Deactivate this realm. Do NOT deactivate the users -- we need to be able to
tell the difference between users that were intentionally deactivated,
e.g. by a realm admin, and users who can't currently use Zulip because their
realm has been deactivated.
|
Deactivate this realm. Do NOT deactivate the users -- we need to be able to
tell the difference between users that were intentionally deactivated,
e.g. by a realm admin, and users who can't currently use Zulip because their
realm has been deactivated.
| def do_deactivate_realm(realm: Realm, *, acting_user: Optional[UserProfile]) -> None:
"""
Deactivate this realm. Do NOT deactivate the users -- we need to be able to
tell the difference between users that were intentionally deactivated,
e.g. by a realm admin, and users who can't currently use Zulip beca... | [
"def",
"do_deactivate_realm",
"(",
"realm",
":",
"Realm",
",",
"*",
",",
"acting_user",
":",
"Optional",
"[",
"UserProfile",
"]",
")",
"->",
"None",
":",
"if",
"realm",
".",
"deactivated",
":",
"return",
"realm",
".",
"deactivated",
"=",
"True",
"realm",
... | [
985,
0
] | [
1028,
55
] | python | en | ['en', 'error', 'th'] | False |
change_user_is_active | (user_profile: UserProfile, value: bool) |
Helper function for changing the .is_active field. Not meant as a standalone function
in production code as properly activating/deactivating users requires more steps.
This changes the is_active value and saves it, while ensuring
Subscription.is_user_active values are updated in the same db transaction... |
Helper function for changing the .is_active field. Not meant as a standalone function
in production code as properly activating/deactivating users requires more steps.
This changes the is_active value and saves it, while ensuring
Subscription.is_user_active values are updated in the same db transaction... | def change_user_is_active(user_profile: UserProfile, value: bool) -> None:
"""
Helper function for changing the .is_active field. Not meant as a standalone function
in production code as properly activating/deactivating users requires more steps.
This changes the is_active value and saves it, while ensu... | [
"def",
"change_user_is_active",
"(",
"user_profile",
":",
"UserProfile",
",",
"value",
":",
"bool",
")",
"->",
"None",
":",
"with",
"transaction",
".",
"atomic",
"(",
"savepoint",
"=",
"False",
")",
":",
"user_profile",
".",
"is_active",
"=",
"value",
"user_... | [
1147,
0
] | [
1157,
91
] | python | en | ['en', 'error', 'th'] | False |
build_message_send_dict | (
message: Message,
stream: Optional[Stream] = None,
local_id: Optional[str] = None,
sender_queue_id: Optional[str] = None,
realm: Optional[Realm] = None,
widget_content_dict: Optional[Dict[str, Any]] = None,
email_gateway: bool = False,
) | Returns a dictionary that can be passed into do_send_messages. In
production, this is always called by check_message, but some
testing code paths call it directly.
| Returns a dictionary that can be passed into do_send_messages. In
production, this is always called by check_message, but some
testing code paths call it directly.
| def build_message_send_dict(
message: Message,
stream: Optional[Stream] = None,
local_id: Optional[str] = None,
sender_queue_id: Optional[str] = None,
realm: Optional[Realm] = None,
widget_content_dict: Optional[Dict[str, Any]] = None,
email_gateway: bool = False,
) -> SendMessageRequest:
... | [
"def",
"build_message_send_dict",
"(",
"message",
":",
"Message",
",",
"stream",
":",
"Optional",
"[",
"Stream",
"]",
"=",
"None",
",",
"local_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"sender_queue_id",
":",
"Optional",
"[",
"str",
"]",
"... | [
1741,
0
] | [
1841,
28
] | python | en | ['en', 'en', 'en'] | True |
do_send_messages | (
send_message_requests_maybe_none: Sequence[Optional[SendMessageRequest]],
email_gateway: bool = False,
mark_as_read: Sequence[int] = [],
) | See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem.
| See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem.
| def do_send_messages(
send_message_requests_maybe_none: Sequence[Optional[SendMessageRequest]],
email_gateway: bool = False,
mark_as_read: Sequence[int] = [],
) -> List[int]:
"""See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsy... | [
"def",
"do_send_messages",
"(",
"send_message_requests_maybe_none",
":",
"Sequence",
"[",
"Optional",
"[",
"SendMessageRequest",
"]",
"]",
",",
"email_gateway",
":",
"bool",
"=",
"False",
",",
"mark_as_read",
":",
"Sequence",
"[",
"int",
"]",
"=",
"[",
"]",
",... | [
1844,
0
] | [
2050,
78
] | python | en | ['en', 'en', 'ur'] | False |
bulk_insert_ums | (ums: List[UserMessageLite]) |
Doing bulk inserts this way is much faster than using Django,
since we don't have any ORM overhead. Profiling with 1000
users shows a speedup of 0.436 -> 0.027 seconds, so we're
talking about a 15x speedup.
|
Doing bulk inserts this way is much faster than using Django,
since we don't have any ORM overhead. Profiling with 1000
users shows a speedup of 0.436 -> 0.027 seconds, so we're
talking about a 15x speedup.
| def bulk_insert_ums(ums: List[UserMessageLite]) -> None:
"""
Doing bulk inserts this way is much faster than using Django,
since we don't have any ORM overhead. Profiling with 1000
users shows a speedup of 0.436 -> 0.027 seconds, so we're
talking about a 15x speedup.
"""
if not ums:
... | [
"def",
"bulk_insert_ums",
"(",
"ums",
":",
"List",
"[",
"UserMessageLite",
"]",
")",
"->",
"None",
":",
"if",
"not",
"ums",
":",
"return",
"vals",
"=",
"[",
"(",
"um",
".",
"user_profile_id",
",",
"um",
".",
"message_id",
",",
"um",
".",
"flags",
")"... | [
2140,
0
] | [
2160,
50
] | python | en | ['en', 'error', 'th'] | False |
verify_submessage_sender | (
*,
message_id: int,
message_sender_id: int,
submessage_sender_id: int,
) | Even though our submessage architecture is geared toward
collaboration among all message readers, we still enforce
the the first person to attach a submessage to the message
must be the original sender of the message.
| Even though our submessage architecture is geared toward
collaboration among all message readers, we still enforce
the the first person to attach a submessage to the message
must be the original sender of the message.
| def verify_submessage_sender(
*,
message_id: int,
message_sender_id: int,
submessage_sender_id: int,
) -> None:
"""Even though our submessage architecture is geared toward
collaboration among all message readers, we still enforce
the the first person to attach a submessage to the message
... | [
"def",
"verify_submessage_sender",
"(",
"*",
",",
"message_id",
":",
"int",
",",
"message_sender_id",
":",
"int",
",",
"submessage_sender_id",
":",
"int",
",",
")",
"->",
"None",
":",
"if",
"message_sender_id",
"==",
"submessage_sender_id",
":",
"return",
"if",
... | [
2163,
0
] | [
2184,
77
] | python | en | ['en', 'en', 'en'] | True |
do_add_submessage | (
realm: Realm,
sender_id: int,
message_id: int,
msg_type: str,
content: str,
) | Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
| Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
| def do_add_submessage(
realm: Realm,
sender_id: int,
message_id: int,
msg_type: str,
content: str,
) -> None:
"""Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
"""
submessag... | [
"def",
"do_add_submessage",
"(",
"realm",
":",
"Realm",
",",
"sender_id",
":",
"int",
",",
"message_id",
":",
"int",
",",
"msg_type",
":",
"str",
",",
"content",
":",
"str",
",",
")",
"->",
"None",
":",
"submessage",
"=",
"SubMessage",
"(",
"sender_id",
... | [
2187,
0
] | [
2217,
76
] | python | en | ['en', 'en', 'en'] | True |
do_add_reaction | (
user_profile: UserProfile,
message: Message,
emoji_name: str,
emoji_code: str,
reaction_type: str,
) | Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
| Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
| def do_add_reaction(
user_profile: UserProfile,
message: Message,
emoji_name: str,
emoji_code: str,
reaction_type: str,
) -> None:
"""Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
... | [
"def",
"do_add_reaction",
"(",
"user_profile",
":",
"UserProfile",
",",
"message",
":",
"Message",
",",
"emoji_name",
":",
"str",
",",
"emoji_code",
":",
"str",
",",
"reaction_type",
":",
"str",
",",
")",
"->",
"None",
":",
"reaction",
"=",
"Reaction",
"("... | [
2271,
0
] | [
2293,
66
] | python | en | ['en', 'en', 'en'] | True |
do_remove_reaction | (
user_profile: UserProfile, message: Message, emoji_code: str, reaction_type: str
) | Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
| Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
| def do_remove_reaction(
user_profile: UserProfile, message: Message, emoji_code: str, reaction_type: str
) -> None:
"""Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
"""
reaction = Reaction... | [
"def",
"do_remove_reaction",
"(",
"user_profile",
":",
"UserProfile",
",",
"message",
":",
"Message",
",",
"emoji_code",
":",
"str",
",",
"reaction_type",
":",
"str",
")",
"->",
"None",
":",
"reaction",
"=",
"Reaction",
".",
"objects",
".",
"filter",
"(",
... | [
2366,
0
] | [
2381,
69
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.pdf | (self, X, Y) | Conditional probability density function p(y|x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y)
Returns:
p(X|Y) conditional density... | Conditional probability density function p(y|x) of the underlying probability model | def pdf(self, X, Y):
""" Conditional probability density function p(y|x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y)
Returns:
... | [
"def",
"pdf",
"(",
"self",
",",
"X",
",",
"Y",
")",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",
",",
"Y",
")",
"mean",
"=",
"self",
".",
"_mean",
"(",
"X",
")",
"p",
"=",
"np",
".",
"squeeze",
"(",
"stats",
... | [
41,
2
] | [
55,
12
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.cdf | (self, X, Y) | Conditional cumulated probability density function P(Y < y | x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points, ndim_y)
Returns:
... | Conditional cumulated probability density function P(Y < y | x) of the underlying probability model | def cdf(self, X, Y):
""" Conditional cumulated probability density function P(Y < y | x) of the underlying probability model
Args:
X: x to be conditioned on - numpy array of shape (n_points, ndim_x)
Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points, n... | [
"def",
"cdf",
"(",
"self",
",",
"X",
",",
"Y",
")",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",
",",
"Y",
")",
"mean",
"=",
"self",
".",
"_mean",
"(",
"X",
")",
"return",
"np",
".",
"squeeze",
"(",
"stats",
"... | [
57,
2
] | [
69,
60
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.simulate_conditional | (self, X) | Draws random samples from the conditional distribution
Args:
X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)
Returns:
Conditional random samples y drawn from p(y|x) - numpy array of shape (n_samples, ndim_y)
| Draws random samples from the conditional distribution | def simulate_conditional(self, X):
""" Draws random samples from the conditional distribution
Args:
X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)
Returns:
Conditional random samples y drawn from p(y|x) - numpy array of shape (n_sampl... | [
"def",
"simulate_conditional",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",
")",
"n_samples",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"Y",
"=",
"self",
".",
"_mean",
"(",
"X",
")",
"+",
"self",
".... | [
71,
2
] | [
85,
15
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.simulate | (self, n_samples=1000) | Draws random samples from the joint distribution p(x,y)
Args:
n_samples: (int) number of samples to be drawn from the joint distribution
Returns:
(X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_x) and (n_samples, ndim_y)
| Draws random samples from the joint distribution p(x,y)
Args:
n_samples: (int) number of samples to be drawn from the joint distribution | def simulate(self, n_samples=1000):
""" Draws random samples from the joint distribution p(x,y)
Args:
n_samples: (int) number of samples to be drawn from the joint distribution
Returns:
(X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_x) and (n_samples, ndim_y)
... | [
"def",
"simulate",
"(",
"self",
",",
"n_samples",
"=",
"1000",
")",
":",
"assert",
"n_samples",
">",
"0",
"X",
"=",
"self",
".",
"random_state",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
",",
"size",
"=",
"(",
"n_samples",
",",
"self",
".",
"ndim_x"... | [
87,
2
] | [
99,
15
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.mean_ | (self, x_cond, n_samples=None) | Conditional mean of the distribution
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
| Conditional mean of the distribution
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x) | def mean_(self, x_cond, n_samples=None):
""" Conditional mean of the distribution
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
"""
assert x_cond.ndim == ... | [
"def",
"mean_",
"(",
"self",
",",
"x_cond",
",",
"n_samples",
"=",
"None",
")",
":",
"assert",
"x_cond",
".",
"ndim",
"==",
"2",
"and",
"x_cond",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"ndim_x",
"x_cond",
"=",
"self",
".",
"_handle_input_dim... | [
101,
2
] | [
111,
29
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.covariance | (self, x_cond, n_samples=None) | Covariance of the distribution conditioned on x_cond
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Covariances Cov[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y, ndim_y)
| Covariance of the distribution conditioned on x_cond | def covariance(self, x_cond, n_samples=None):
""" Covariance of the distribution conditioned on x_cond
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
Returns:
Covariances Cov[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim... | [
"def",
"covariance",
"(",
"self",
",",
"x_cond",
",",
"n_samples",
"=",
"None",
")",
":",
"assert",
"x_cond",
".",
"ndim",
"==",
"2",
"and",
"x_cond",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"ndim_x",
"x_cond",
"=",
"self",
".",
"_handle_inpu... | [
113,
2
] | [
125,
65
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.value_at_risk | (self, x_cond, alpha=0.01, **kwargs) | Computes the Value-at-Risk (VaR) of the fitted distribution. Only if ndim_y = 1
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
alpha: quantile percentage of the distribution
Returns:
VaR values for each x to condition on - numpy array of shape (n... | Computes the Value-at-Risk (VaR) of the fitted distribution. Only if ndim_y = 1 | def value_at_risk(self, x_cond, alpha=0.01, **kwargs):
""" Computes the Value-at-Risk (VaR) of the fitted distribution. Only if ndim_y = 1
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
alpha: quantile percentage of the distribution
Returns:
V... | [
"def",
"value_at_risk",
"(",
"self",
",",
"x_cond",
",",
"alpha",
"=",
"0.01",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"ndim_y",
"==",
"1",
",",
"\"Value at Risk can only be computed when ndim_y = 1\"",
"assert",
"x_cond",
".",
"ndim",
"==",
... | [
127,
2
] | [
142,
14
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.conditional_value_at_risk | (self, x_cond, alpha=0.01, **kwargs) | Computes the Conditional Value-at-Risk (CVaR) / Expected Shortfall of the fitted distribution. Only if ndim_y = 1
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
alpha: quantile percentage of the distribution
n_samples: number of samples for... | Computes the Conditional Value-at-Risk (CVaR) / Expected Shortfall of the fitted distribution. Only if ndim_y = 1 | def conditional_value_at_risk(self, x_cond, alpha=0.01, **kwargs):
""" Computes the Conditional Value-at-Risk (CVaR) / Expected Shortfall of the fitted distribution. Only if ndim_y = 1
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
alpha: quantil... | [
"def",
"conditional_value_at_risk",
"(",
"self",
",",
"x_cond",
",",
"alpha",
"=",
"0.01",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"ndim_y",
"==",
"1",
",",
"\"Value at Risk can only be computed when ndim_y = 1\"",
"x_cond",
"=",
"self",
".",
... | [
144,
2
] | [
163,
15
] | python | en | ['en', 'en', 'en'] | True |
LinearGaussian.tail_risk_measures | (self, x_cond, alpha=0.01, n_samples=10 ** 7) | Computes the Value-at-Risk (VaR) and Conditional Value-at-Risk (CVaR)
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
alpha: quantile percentage of the distribution
n_samples: number of samples for monte carlo model_fitting
Retu... | Computes the Value-at-Risk (VaR) and Conditional Value-at-Risk (CVaR) | def tail_risk_measures(self, x_cond, alpha=0.01, n_samples=10 ** 7):
""" Computes the Value-at-Risk (VaR) and Conditional Value-at-Risk (CVaR)
Args:
x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
alpha: quantile percentage of the distribution
... | [
"def",
"tail_risk_measures",
"(",
"self",
",",
"x_cond",
",",
"alpha",
"=",
"0.01",
",",
"n_samples",
"=",
"10",
"**",
"7",
")",
":",
"assert",
"self",
".",
"ndim_y",
"==",
"1",
",",
"\"Value at Risk can only be computed when ndim_y = 1\"",
"assert",
"x_cond",
... | [
165,
2
] | [
182,
22
] | python | en | ['en', 'en', 'en'] | True |
report_error | (
request: HttpRequest,
user_profile: UserProfile,
message: str = REQ(),
stacktrace: str = REQ(),
ui_message: bool = REQ(json_validator=check_bool),
user_agent: str = REQ(),
href: str = REQ(),
log: str = REQ(),
more_info: Mapping[str, Any] = REQ(json_validator=check_dict([]), default... | Accepts an error report and stores in a queue for processing. The
actual error reports are later handled by do_report_error | Accepts an error report and stores in a queue for processing. The
actual error reports are later handled by do_report_error | def report_error(
request: HttpRequest,
user_profile: UserProfile,
message: str = REQ(),
stacktrace: str = REQ(),
ui_message: bool = REQ(json_validator=check_bool),
user_agent: str = REQ(),
href: str = REQ(),
log: str = REQ(),
more_info: Mapping[str, Any] = REQ(json_validator=check_d... | [
"def",
"report_error",
"(",
"request",
":",
"HttpRequest",
",",
"user_profile",
":",
"UserProfile",
",",
"message",
":",
"str",
"=",
"REQ",
"(",
")",
",",
"stacktrace",
":",
"str",
"=",
"REQ",
"(",
")",
",",
"ui_message",
":",
"bool",
"=",
"REQ",
"(",
... | [
106,
0
] | [
173,
25
] | python | en | ['en', 'en', 'en'] | True |
execute_batch_async_pdf | (pdf_fun, X, Y, n_jobs=-1, batch_size=None) |
Executes pdf_fun in batches in multiple processes and concatenates results along axis 0
Args:
pdf_fun: callable with signature pdf(X, Y) returning a numpy array
X: ndarray with shape (n_queries, ndim_x)
Y: ndarray with shape (n_queries, ndim_y)
n_jobs: integer denoting the numb... |
Executes pdf_fun in batches in multiple processes and concatenates results along axis 0 | def execute_batch_async_pdf(pdf_fun, X, Y, n_jobs=-1, batch_size=None):
"""
Executes pdf_fun in batches in multiple processes and concatenates results along axis 0
Args:
pdf_fun: callable with signature pdf(X, Y) returning a numpy array
X: ndarray with shape (n_queries, ndim_x)
Y: n... | [
"def",
"execute_batch_async_pdf",
"(",
"pdf_fun",
",",
"X",
",",
"Y",
",",
"n_jobs",
"=",
"-",
"1",
",",
"batch_size",
"=",
"None",
")",
":",
"# split query arrays into batches",
"query_length",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"if",
"n_jobs",
"<",
... | [
54,
0
] | [
98,
18
] | python | en | ['en', 'error', 'th'] | False |
ZabbixHookTests.test_zabbix_alert_message | (self) |
Tests if zabbix alert is handled correctly
|
Tests if zabbix alert is handled correctly
| def test_zabbix_alert_message(self) -> None:
"""
Tests if zabbix alert is handled correctly
"""
expected_topic = "www.example.com"
expected_message = "PROBLEM (Average) alert on [www.example.com](https://zabbix.example.com/tr_events.php?triggerid=14032&eventid=10528):\n* Zabbix a... | [
"def",
"test_zabbix_alert_message",
"(",
"self",
")",
"->",
"None",
":",
"expected_topic",
"=",
"\"www.example.com\"",
"expected_message",
"=",
"\"PROBLEM (Average) alert on [www.example.com](https://zabbix.example.com/tr_events.php?triggerid=14032&eventid=10528):\\n* Zabbix agent on www.e... | [
11,
4
] | [
17,
76
] | python | en | ['en', 'error', 'th'] | False |
ZabbixHookTests.test_zabbix_invalid_payload_with_missing_data | (self) |
Tests if invalid Zabbix payloads are handled correctly
|
Tests if invalid Zabbix payloads are handled correctly
| def test_zabbix_invalid_payload_with_missing_data(self) -> None:
"""
Tests if invalid Zabbix payloads are handled correctly
"""
self.url = self.build_webhook_url()
payload = self.get_body("zabbix_invalid_payload_with_missing_data")
result = self.client_post(self.url, payl... | [
"def",
"test_zabbix_invalid_payload_with_missing_data",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"url",
"=",
"self",
".",
"build_webhook_url",
"(",
")",
"payload",
"=",
"self",
".",
"get_body",
"(",
"\"zabbix_invalid_payload_with_missing_data\"",
")",
"resu... | [
19,
4
] | [
35,
64
] | python | en | ['en', 'error', 'th'] | False |
loads_timestamp_w_microseconds | (dt_str) | Loads and returns timestamp with microsecond precission | Loads and returns timestamp with microsecond precission | def loads_timestamp_w_microseconds(dt_str):
"""Loads and returns timestamp with microsecond precission"""
return datetime.datetime.strptime(dt_str, dt_w_microsecond_format) | [
"def",
"loads_timestamp_w_microseconds",
"(",
"dt_str",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"dt_str",
",",
"dt_w_microsecond_format",
")"
] | [
15,
0
] | [
17,
70
] | python | en | ['en', 'en', 'en'] | True |
parse_to_dict | (config) | Loads the ConfigParser object as a nested dictionary.
Automatically converts strings representing ints and floats to their
respective types, through the magic of ast.literal_eval.
This functionality is extensible via the loads_methods list.
Each loads (load string) method is tested in turn to see i... | Loads the ConfigParser object as a nested dictionary.
Automatically converts strings representing ints and floats to their
respective types, through the magic of ast.literal_eval.
This functionality is extensible via the loads_methods list.
Each loads (load string) method is tested in turn to see i... | def parse_to_dict(config):
"""Loads the ConfigParser object as a nested dictionary.
Automatically converts strings representing ints and floats to their
respective types, through the magic of ast.literal_eval.
This functionality is extensible via the loads_methods list.
Each loads (load string)... | [
"def",
"parse_to_dict",
"(",
"config",
")",
":",
"pars",
"=",
"adict",
"(",
")",
"#'DEFAULT' section is not listed by ``sections()``,",
"# but we sometimes (ab)use it.",
"sections",
"=",
"config",
".",
"sections",
"(",
")",
"if",
"len",
"(",
"config",
".",
"items",
... | [
23,
0
] | [
70,
15
] | python | en | ['en', 'en', 'en'] | True |
BuildEnvironment.check_requirements | (self, reqs) | Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
| Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
| def check_requirements(self, reqs):
# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
"""Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = ... | [
"def",
"check_requirements",
"(",
"self",
",",
"reqs",
")",
":",
"# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]",
"missing",
"=",
"set",
"(",
")",
"conflicting",
"=",
"set",
"(",
")",
"if",
"reqs",
":",
"ws",
"=",
"WorkingSet",
"(",
"self",
".... | [
142,
4
] | [
159,
35
] | python | en | ['en', 'da', 'en'] | True |
loggers | () | get list of all loggers | get list of all loggers | def loggers():
""" get list of all loggers """
root = logging.root
existing = root.manager.loggerDict.keys()
return [logging.getLogger(name) for name in existing] | [
"def",
"loggers",
"(",
")",
":",
"root",
"=",
"logging",
".",
"root",
"existing",
"=",
"root",
".",
"manager",
".",
"loggerDict",
".",
"keys",
"(",
")",
"return",
"[",
"logging",
".",
"getLogger",
"(",
"name",
")",
"for",
"name",
"in",
"existing",
"]... | [
89,
0
] | [
93,
57
] | python | en | ['en', 'en', 'en'] | True |
Logger.atoms | (self, resp, req, environ, request_time) | Gets atoms for log formating.
| Gets atoms for log formating.
| def atoms(self, resp, req, environ, request_time):
""" Gets atoms for log formating.
"""
status = resp.status
if isinstance(status, str):
status = status.split(None, 1)[0]
atoms = {
'h': environ.get('REMOTE_ADDR', '-'),
'l': '-',
'u... | [
"def",
"atoms",
"(",
"self",
",",
"resp",
",",
"req",
",",
"environ",
",",
"request_time",
")",
":",
"status",
"=",
"resp",
".",
"status",
"if",
"isinstance",
"(",
"status",
",",
"str",
")",
":",
"status",
"=",
"status",
".",
"split",
"(",
"None",
... | [
274,
4
] | [
324,
20
] | python | en | ['en', 'da', 'en'] | True |
Logger.access | (self, resp, req, environ, request_time) | See http://httpd.apache.org/docs/2.0/logs.html#combined
for format details
| See http://httpd.apache.org/docs/2.0/logs.html#combined
for format details
| def access(self, resp, req, environ, request_time):
""" See http://httpd.apache.org/docs/2.0/logs.html#combined
for format details
"""
if not (self.cfg.accesslog or self.cfg.logconfig or
self.cfg.logconfig_dict or
(self.cfg.syslog and not self.cfg.disable_redirect_... | [
"def",
"access",
"(",
"self",
",",
"resp",
",",
"req",
",",
"environ",
",",
"request_time",
")",
":",
"if",
"not",
"(",
"self",
".",
"cfg",
".",
"accesslog",
"or",
"self",
".",
"cfg",
".",
"logconfig",
"or",
"self",
".",
"cfg",
".",
"logconfig_dict",... | [
326,
4
] | [
345,
46
] | python | en | ['en', 'en', 'en'] | False |
Logger.now | (self) | return date in Apache Common Log Format | return date in Apache Common Log Format | def now(self):
""" return date in Apache Common Log Format """
return time.strftime('[%d/%b/%Y:%H:%M:%S %z]') | [
"def",
"now",
"(",
"self",
")",
":",
"return",
"time",
".",
"strftime",
"(",
"'[%d/%b/%Y:%H:%M:%S %z]'",
")"
] | [
347,
4
] | [
349,
54
] | python | en | ['nl', 'en', 'en'] | True |
test_percentage_as_fraction_of_execution_nodes | () |
If an instance requests 50 percent of instances, then those should be 50 percent
of available execution nodes (1 out of 2), as opposed to 50 percent
of all available nodes (2 out of 4) which include unusable control nodes
|
If an instance requests 50 percent of instances, then those should be 50 percent
of available execution nodes (1 out of 2), as opposed to 50 percent
of all available nodes (2 out of 4) which include unusable control nodes
| def test_percentage_as_fraction_of_execution_nodes():
"""
If an instance requests 50 percent of instances, then those should be 50 percent
of available execution nodes (1 out of 2), as opposed to 50 percent
of all available nodes (2 out of 4) which include unusable control nodes
"""
ig = Instanc... | [
"def",
"test_percentage_as_fraction_of_execution_nodes",
"(",
")",
":",
"ig",
"=",
"InstanceGroup",
".",
"objects",
".",
"create",
"(",
"name",
"=",
"'bar'",
",",
"policy_instance_percentage",
"=",
"50",
")",
"for",
"i",
"in",
"range",
"(",
"2",
")",
":",
"I... | [
264,
0
] | [
277,
59
] | python | en | ['en', 'error', 'th'] | False |
MnistModel.__init__ | (self, args) |
TODO: Write Comment
|
TODO: Write Comment
| def __init__(self, args):
"""
TODO: Write Comment
"""
self.input_shape = (28, 28, 1)
Model.__init__(self, args) | [
"def",
"__init__",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"input_shape",
"=",
"(",
"28",
",",
"28",
",",
"1",
")",
"Model",
".",
"__init__",
"(",
"self",
",",
"args",
")"
] | [
11,
4
] | [
17,
34
] | python | en | ['en', 'error', 'th'] | False |
MnistModel.dataset | (self) |
TODO: Write Comment
|
TODO: Write Comment
| def dataset(self):
"""
TODO: Write Comment
"""
from tensorflow.keras import datasets, utils
import numpy as np
self.num_images = {'train': 60000, 'test': 10000}
self.mean = [0.]
self.std = [255.]
if self.USE_DATASET == 0:
... | [
"def",
"dataset",
"(",
"self",
")",
":",
"from",
"tensorflow",
".",
"keras",
"import",
"datasets",
",",
"utils",
"import",
"numpy",
"as",
"np",
"self",
".",
"num_images",
"=",
"{",
"'train'",
":",
"60000",
",",
"'test'",
":",
"10000",
"}",
"self",
".",... | [
19,
4
] | [
67,
81
] | python | en | ['en', 'error', 'th'] | False |
connect_to_daemon | (self_hostname: str, daemon_port: int, ssl_context: Optional[ssl.SSLContext]) |
Connect to the local daemon.
|
Connect to the local daemon.
| async def connect_to_daemon(self_hostname: str, daemon_port: int, ssl_context: Optional[ssl.SSLContext]) -> DaemonProxy:
"""
Connect to the local daemon.
"""
client = DaemonProxy(f"wss://{self_hostname}:{daemon_port}", ssl_context)
await client.start()
return client | [
"async",
"def",
"connect_to_daemon",
"(",
"self_hostname",
":",
"str",
",",
"daemon_port",
":",
"int",
",",
"ssl_context",
":",
"Optional",
"[",
"ssl",
".",
"SSLContext",
"]",
")",
"->",
"DaemonProxy",
":",
"client",
"=",
"DaemonProxy",
"(",
"f\"wss://{self_ho... | [
102,
0
] | [
109,
17
] | python | en | ['en', 'error', 'th'] | False |
connect_to_daemon_and_validate | (root_path: Path) |
Connect to the local daemon and do a ping to ensure that something is really
there and running.
|
Connect to the local daemon and do a ping to ensure that something is really
there and running.
| async def connect_to_daemon_and_validate(root_path: Path) -> Optional[DaemonProxy]:
"""
Connect to the local daemon and do a ping to ensure that something is really
there and running.
"""
try:
net_config = load_config(root_path, "config.yaml")
crt_path = root_path / net_config["daemo... | [
"async",
"def",
"connect_to_daemon_and_validate",
"(",
"root_path",
":",
"Path",
")",
"->",
"Optional",
"[",
"DaemonProxy",
"]",
":",
"try",
":",
"net_config",
"=",
"load_config",
"(",
"root_path",
",",
"\"config.yaml\"",
")",
"crt_path",
"=",
"root_path",
"/",
... | [
112,
0
] | [
132,
15
] | python | en | ['en', 'error', 'th'] | False |
KernelMixtureNetwork.fit | (self, X, Y, eval_set=None, verbose=True) | Fits the conditional density model with provided data
Args:
X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)
Y: numpy array of y targets - shape: (n_samples, n_dim_y)
eval_set: (tuple) eval/test set - tuple (X_test, Y_test)
verbose: (boolean) controls the verbosi... | Fits the conditional density model with provided data | def fit(self, X, Y, eval_set=None, verbose=True):
""" Fits the conditional density model with provided data
Args:
X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)
Y: numpy array of y targets - shape: (n_samples, n_dim_y)
eval_set: (tuple) eval/test set - tuple (X_test... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"Y",
",",
"eval_set",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",
",",
"Y",
",",
"fitting",
"=",
"True",
")",
"if",
"eval... | [
113,
2
] | [
148,
68
] | python | en | ['en', 'en', 'en'] | True |
KernelMixtureNetwork._build_model | (self) |
implementation of the KMN
|
implementation of the KMN
| def _build_model(self):
"""
implementation of the KMN
"""
with tf.variable_scope(self.name):
# add placeholders, data_normalization and data_noise if desired. Also sets up the placeholder for dropout prob
self.layer_in_x, self.layer_in_y = self._build_input_layers()
self.X_in = L.get_... | [
"def",
"_build_model",
"(",
"self",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"self",
".",
"name",
")",
":",
"# add placeholders, data_normalization and data_noise if desired. Also sets up the placeholder for dropout prob",
"self",
".",
"layer_in_x",
",",
"self",
... | [
150,
2
] | [
226,
111
] | python | en | ['en', 'error', 'th'] | False |
get_custom_form | (form_setting) | Return custom form class if defined and available | Return custom form class if defined and available | def get_custom_form(form_setting):
"""Return custom form class if defined and available"""
try:
return import_string(getattr(settings, form_setting))
except ImportError:
raise ImproperlyConfigured(
"%s refers to a form '%s' that is not available" %
(form_setting, geta... | [
"def",
"get_custom_form",
"(",
"form_setting",
")",
":",
"try",
":",
"return",
"import_string",
"(",
"getattr",
"(",
"settings",
",",
"form_setting",
")",
")",
"except",
"ImportError",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"%s refers to a form '%s' that is not ... | [
5,
0
] | [
13,
9
] | python | en | ['en', 'en', 'en'] | True |
ResourceFilesCollector.__init__ | (self, executor) |
:param executor: JMeterExecutor
|
:param executor: JMeterExecutor
| def __init__(self, executor):
"""
:param executor: JMeterExecutor
"""
super(ResourceFilesCollector, self).__init__()
self.executor = executor | [
"def",
"__init__",
"(",
"self",
",",
"executor",
")",
":",
"super",
"(",
"ResourceFilesCollector",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"executor",
"=",
"executor"
] | [
379,
4
] | [
384,
32
] | python | en | ['en', 'error', 'th'] | False |
stringfilter | (func) |
Decorator for filters which should only receive unicode objects. The object
passed as the first positional argument will be converted to a unicode
object.
|
Decorator for filters which should only receive unicode objects. The object
passed as the first positional argument will be converted to a unicode
object.
| def stringfilter(func):
"""
Decorator for filters which should only receive unicode objects. The object
passed as the first positional argument will be converted to a unicode
object.
"""
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_text(ar... | [
"def",
"stringfilter",
"(",
"func",
")",
":",
"def",
"_dec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"args",
"=",
"list",
"(",
"args",
")",
"args",
"[",
"0",
"]",
"=",
"force_text",
"(",
"args",
"[",
"0",
"]",
... | [
37,
0
] | [
57,
28
] | python | en | ['en', 'error', 'th'] | False |
addslashes | (value) |
Adds slashes before quotes. Useful for escaping strings in CSV, for
example. Less useful for escaping JavaScript; use the ``escapejs``
filter instead.
|
Adds slashes before quotes. Useful for escaping strings in CSV, for
example. Less useful for escaping JavaScript; use the ``escapejs``
filter instead.
| def addslashes(value):
"""
Adds slashes before quotes. Useful for escaping strings in CSV, for
example. Less useful for escaping JavaScript; use the ``escapejs``
filter instead.
"""
return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'") | [
"def",
"addslashes",
"(",
"value",
")",
":",
"return",
"value",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
".",
"replace",
"(",
"\"'\"",
",",
"\"\\\\'\"",
")"
] | [
66,
0
] | [
72,
78
] | python | en | ['en', 'error', 'th'] | False |
capfirst | (value) | Capitalizes the first character of the value. | Capitalizes the first character of the value. | def capfirst(value):
"""Capitalizes the first character of the value."""
return value and value[0].upper() + value[1:] | [
"def",
"capfirst",
"(",
"value",
")",
":",
"return",
"value",
"and",
"value",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"value",
"[",
"1",
":",
"]"
] | [
77,
0
] | [
79,
49
] | python | en | ['en', 'en', 'en'] | True |
escapejs_filter | (value) | Hex encodes characters for use in JavaScript strings. | Hex encodes characters for use in JavaScript strings. | def escapejs_filter(value):
"""Hex encodes characters for use in JavaScript strings."""
return escapejs(value) | [
"def",
"escapejs_filter",
"(",
"value",
")",
":",
"return",
"escapejs",
"(",
"value",
")"
] | [
84,
0
] | [
86,
26
] | python | en | ['en', 'en', 'en'] | True |
floatformat | (text, arg=-1) |
Displays a float to a specified number of decimal places.
If called without an argument, it displays the floating point number with
one decimal place -- but only if there's a decimal place to be displayed:
* num1 = 34.23234
* num2 = 34.00000
* num3 = 34.26000
* {{ num1|floatformat }} disp... |
Displays a float to a specified number of decimal places. | def floatformat(text, arg=-1):
"""
Displays a float to a specified number of decimal places.
If called without an argument, it displays the floating point number with
one decimal place -- but only if there's a decimal place to be displayed:
* num1 = 34.23234
* num2 = 34.00000
* num3 = 34.2... | [
"def",
"floatformat",
"(",
"text",
",",
"arg",
"=",
"-",
"1",
")",
":",
"try",
":",
"input_val",
"=",
"repr",
"(",
"text",
")",
"d",
"=",
"Decimal",
"(",
"input_val",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"''",
"except",
"InvalidOperation",... | [
103,
0
] | [
183,
24
] | python | en | ['en', 'error', 'th'] | False |
iriencode | (value) | Escapes an IRI value for use in a URL. | Escapes an IRI value for use in a URL. | def iriencode(value):
"""Escapes an IRI value for use in a URL."""
return force_text(iri_to_uri(value)) | [
"def",
"iriencode",
"(",
"value",
")",
":",
"return",
"force_text",
"(",
"iri_to_uri",
"(",
"value",
")",
")"
] | [
188,
0
] | [
190,
40
] | python | en | ['en', 'en', 'en'] | True |
linenumbers | (value, autoescape=True) | Displays text with line numbers. | Displays text with line numbers. | def linenumbers(value, autoescape=True):
"""Displays text with line numbers."""
lines = value.split('\n')
# Find the maximum width of the line count, for use with zero padding
# string format command
width = six.text_type(len(six.text_type(len(lines))))
if not autoescape or isinstance(value, Saf... | [
"def",
"linenumbers",
"(",
"value",
",",
"autoescape",
"=",
"True",
")",
":",
"lines",
"=",
"value",
".",
"split",
"(",
"'\\n'",
")",
"# Find the maximum width of the line count, for use with zero padding",
"# string format command",
"width",
"=",
"six",
".",
"text_ty... | [
195,
0
] | [
207,
38
] | python | en | ['en', 'en', 'en'] | True |
lower | (value) | Converts a string into all lowercase. | Converts a string into all lowercase. | def lower(value):
"""Converts a string into all lowercase."""
return value.lower() | [
"def",
"lower",
"(",
"value",
")",
":",
"return",
"value",
".",
"lower",
"(",
")"
] | [
212,
0
] | [
214,
24
] | python | en | ['en', 'en', 'en'] | True |
make_list | (value) |
Returns the value turned into a list.
For an integer, it's a list of digits.
For a string, it's a list of characters.
|
Returns the value turned into a list. | def make_list(value):
"""
Returns the value turned into a list.
For an integer, it's a list of digits.
For a string, it's a list of characters.
"""
return list(value) | [
"def",
"make_list",
"(",
"value",
")",
":",
"return",
"list",
"(",
"value",
")"
] | [
219,
0
] | [
226,
22
] | python | en | ['en', 'error', 'th'] | False |
slugify | (value) |
Converts to ASCII. Converts spaces to hyphens. Removes characters that
aren't alphanumerics, underscores, or hyphens. Converts to lowercase.
Also strips leading and trailing whitespace.
|
Converts to ASCII. Converts spaces to hyphens. Removes characters that
aren't alphanumerics, underscores, or hyphens. Converts to lowercase.
Also strips leading and trailing whitespace.
| def slugify(value):
"""
Converts to ASCII. Converts spaces to hyphens. Removes characters that
aren't alphanumerics, underscores, or hyphens. Converts to lowercase.
Also strips leading and trailing whitespace.
"""
return _slugify(value) | [
"def",
"slugify",
"(",
"value",
")",
":",
"return",
"_slugify",
"(",
"value",
")"
] | [
231,
0
] | [
237,
26
] | python | en | ['en', 'error', 'th'] | False |
stringformat | (value, arg) |
Formats the variable according to the arg, a string formatting specifier.
This specifier uses Python string formating syntax, with the exception that
the leading "%" is dropped.
See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
for documentation of Python string f... |
Formats the variable according to the arg, a string formatting specifier. | def stringformat(value, arg):
"""
Formats the variable according to the arg, a string formatting specifier.
This specifier uses Python string formating syntax, with the exception that
the leading "%" is dropped.
See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
... | [
"def",
"stringformat",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"return",
"(",
"\"%\"",
"+",
"six",
".",
"text_type",
"(",
"arg",
")",
")",
"%",
"value",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"\"\""
] | [
241,
0
] | [
254,
17
] | python | en | ['en', 'error', 'th'] | False |
title | (value) | Converts a string into titlecase. | Converts a string into titlecase. | def title(value):
"""Converts a string into titlecase."""
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
return re.sub(r"\d([A-Z])", lambda m: m.group(0).lower(), t) | [
"def",
"title",
"(",
"value",
")",
":",
"t",
"=",
"re",
".",
"sub",
"(",
"\"([a-z])'([A-Z])\"",
",",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"0",
")",
".",
"lower",
"(",
")",
",",
"value",
".",
"title",
"(",
")",
")",
"return",
"re",
".",
... | [
259,
0
] | [
262,
64
] | python | en | ['en', 'en', 'en'] | True |
truncatechars | (value, arg) |
Truncates a string after a certain number of characters.
Argument: Number of characters to truncate after.
|
Truncates a string after a certain number of characters. | def truncatechars(value, arg):
"""
Truncates a string after a certain number of characters.
Argument: Number of characters to truncate after.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
return Truncator(value).ch... | [
"def",
"truncatechars",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"length",
"=",
"int",
"(",
"arg",
")",
"except",
"ValueError",
":",
"# Invalid literal for int().",
"return",
"value",
"# Fail silently.",
"return",
"Truncator",
"(",
"value",
")",
".",
... | [
267,
0
] | [
277,
41
] | python | en | ['en', 'error', 'th'] | False |
truncatechars_html | (value, arg) |
Truncates HTML after a certain number of chars.
Argument: Number of chars to truncate after.
Newlines in the HTML are preserved.
|
Truncates HTML after a certain number of chars. | def truncatechars_html(value, arg):
"""
Truncates HTML after a certain number of chars.
Argument: Number of chars to truncate after.
Newlines in the HTML are preserved.
"""
try:
length = int(arg)
except ValueError: # invalid literal for int()
return value # Fail silently.... | [
"def",
"truncatechars_html",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"length",
"=",
"int",
"(",
"arg",
")",
"except",
"ValueError",
":",
"# invalid literal for int()",
"return",
"value",
"# Fail silently.",
"return",
"Truncator",
"(",
"value",
")",
"."... | [
282,
0
] | [
294,
52
] | python | en | ['en', 'error', 'th'] | False |
truncatewords | (value, arg) |
Truncates a string after a certain number of words.
Argument: Number of words to truncate after.
Newlines within the string are removed.
|
Truncates a string after a certain number of words. | def truncatewords(value, arg):
"""
Truncates a string after a certain number of words.
Argument: Number of words to truncate after.
Newlines within the string are removed.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silen... | [
"def",
"truncatewords",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"length",
"=",
"int",
"(",
"arg",
")",
"except",
"ValueError",
":",
"# Invalid literal for int().",
"return",
"value",
"# Fail silently.",
"return",
"Truncator",
"(",
"value",
")",
".",
... | [
299,
0
] | [
311,
58
] | python | en | ['en', 'error', 'th'] | False |
truncatewords_html | (value, arg) |
Truncates HTML after a certain number of words.
Argument: Number of words to truncate after.
Newlines in the HTML are preserved.
|
Truncates HTML after a certain number of words. | def truncatewords_html(value, arg):
"""
Truncates HTML after a certain number of words.
Argument: Number of words to truncate after.
Newlines in the HTML are preserved.
"""
try:
length = int(arg)
except ValueError: # invalid literal for int()
return value # Fail silently.... | [
"def",
"truncatewords_html",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"length",
"=",
"int",
"(",
"arg",
")",
"except",
"ValueError",
":",
"# invalid literal for int()",
"return",
"value",
"# Fail silently.",
"return",
"Truncator",
"(",
"value",
")",
"."... | [
316,
0
] | [
328,
69
] | python | en | ['en', 'error', 'th'] | False |
upper | (value) | Converts a string into all uppercase. | Converts a string into all uppercase. | def upper(value):
"""Converts a string into all uppercase."""
return value.upper() | [
"def",
"upper",
"(",
"value",
")",
":",
"return",
"value",
".",
"upper",
"(",
")"
] | [
333,
0
] | [
335,
24
] | python | en | ['en', 'en', 'en'] | True |
urlencode | (value, safe=None) |
Escapes a value for use in a URL.
Takes an optional ``safe`` parameter used to determine the characters which
should not be escaped by Django's ``urlquote`` method. If not provided, the
default safe characters will be used (but an empty string can be provided
when *all* characters should be escape... |
Escapes a value for use in a URL. | def urlencode(value, safe=None):
"""
Escapes a value for use in a URL.
Takes an optional ``safe`` parameter used to determine the characters which
should not be escaped by Django's ``urlquote`` method. If not provided, the
default safe characters will be used (but an empty string can be provided
... | [
"def",
"urlencode",
"(",
"value",
",",
"safe",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"safe",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'safe'",
"]",
"=",
"safe",
"return",
"urlquote",
"(",
"value",
",",
"*",
"*",
"kwargs",
")"
] | [
340,
0
] | [
352,
36
] | python | en | ['en', 'error', 'th'] | False |
urlize | (value, autoescape=True) | Converts URLs in plain text into clickable links. | Converts URLs in plain text into clickable links. | def urlize(value, autoescape=True):
"""Converts URLs in plain text into clickable links."""
return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape)) | [
"def",
"urlize",
"(",
"value",
",",
"autoescape",
"=",
"True",
")",
":",
"return",
"mark_safe",
"(",
"_urlize",
"(",
"value",
",",
"nofollow",
"=",
"True",
",",
"autoescape",
"=",
"autoescape",
")",
")"
] | [
357,
0
] | [
359,
74
] | python | en | ['en', 'en', 'en'] | True |
urlizetrunc | (value, limit, autoescape=True) |
Converts URLs into clickable links, truncating URLs to the given character
limit, and adding 'rel=nofollow' attribute to discourage spamming.
Argument: Length to truncate URLs to.
|
Converts URLs into clickable links, truncating URLs to the given character
limit, and adding 'rel=nofollow' attribute to discourage spamming. | def urlizetrunc(value, limit, autoescape=True):
"""
Converts URLs into clickable links, truncating URLs to the given character
limit, and adding 'rel=nofollow' attribute to discourage spamming.
Argument: Length to truncate URLs to.
"""
return mark_safe(_urlize(value, trim_url_limit=int(limit), ... | [
"def",
"urlizetrunc",
"(",
"value",
",",
"limit",
",",
"autoescape",
"=",
"True",
")",
":",
"return",
"mark_safe",
"(",
"_urlize",
"(",
"value",
",",
"trim_url_limit",
"=",
"int",
"(",
"limit",
")",
",",
"nofollow",
"=",
"True",
",",
"autoescape",
"=",
... | [
364,
0
] | [
371,
101
] | python | en | ['en', 'error', 'th'] | False |
wordcount | (value) | Returns the number of words. | Returns the number of words. | def wordcount(value):
"""Returns the number of words."""
return len(value.split()) | [
"def",
"wordcount",
"(",
"value",
")",
":",
"return",
"len",
"(",
"value",
".",
"split",
"(",
")",
")"
] | [
376,
0
] | [
378,
29
] | python | en | ['en', 'en', 'en'] | True |
wordwrap | (value, arg) |
Wraps words at specified line length.
Argument: number of characters to wrap the text at.
|
Wraps words at specified line length. | def wordwrap(value, arg):
"""
Wraps words at specified line length.
Argument: number of characters to wrap the text at.
"""
return wrap(value, int(arg)) | [
"def",
"wordwrap",
"(",
"value",
",",
"arg",
")",
":",
"return",
"wrap",
"(",
"value",
",",
"int",
"(",
"arg",
")",
")"
] | [
383,
0
] | [
389,
32
] | python | en | ['en', 'error', 'th'] | False |
ljust | (value, arg) |
Left-aligns the value in a field of a given width.
Argument: field size.
|
Left-aligns the value in a field of a given width. | def ljust(value, arg):
"""
Left-aligns the value in a field of a given width.
Argument: field size.
"""
return value.ljust(int(arg)) | [
"def",
"ljust",
"(",
"value",
",",
"arg",
")",
":",
"return",
"value",
".",
"ljust",
"(",
"int",
"(",
"arg",
")",
")"
] | [
394,
0
] | [
400,
32
] | python | en | ['en', 'error', 'th'] | False |
rjust | (value, arg) |
Right-aligns the value in a field of a given width.
Argument: field size.
|
Right-aligns the value in a field of a given width. | def rjust(value, arg):
"""
Right-aligns the value in a field of a given width.
Argument: field size.
"""
return value.rjust(int(arg)) | [
"def",
"rjust",
"(",
"value",
",",
"arg",
")",
":",
"return",
"value",
".",
"rjust",
"(",
"int",
"(",
"arg",
")",
")"
] | [
405,
0
] | [
411,
32
] | python | en | ['en', 'error', 'th'] | False |
center | (value, arg) | Centers the value in a field of a given width. | Centers the value in a field of a given width. | def center(value, arg):
"""Centers the value in a field of a given width."""
return value.center(int(arg)) | [
"def",
"center",
"(",
"value",
",",
"arg",
")",
":",
"return",
"value",
".",
"center",
"(",
"int",
"(",
"arg",
")",
")"
] | [
416,
0
] | [
418,
33
] | python | en | ['en', 'en', 'en'] | True |
cut | (value, arg) |
Removes all values of arg from the given string.
|
Removes all values of arg from the given string.
| def cut(value, arg):
"""
Removes all values of arg from the given string.
"""
safe = isinstance(value, SafeData)
value = value.replace(arg, '')
if safe and arg != ';':
return mark_safe(value)
return value | [
"def",
"cut",
"(",
"value",
",",
"arg",
")",
":",
"safe",
"=",
"isinstance",
"(",
"value",
",",
"SafeData",
")",
"value",
"=",
"value",
".",
"replace",
"(",
"arg",
",",
"''",
")",
"if",
"safe",
"and",
"arg",
"!=",
"';'",
":",
"return",
"mark_safe",... | [
423,
0
] | [
431,
16
] | python | en | ['en', 'error', 'th'] | False |
escape_filter | (value) |
Marks the value as a string that should be auto-escaped.
|
Marks the value as a string that should be auto-escaped.
| def escape_filter(value):
"""
Marks the value as a string that should be auto-escaped.
"""
with warnings.catch_warnings():
# Ignore mark_for_escaping deprecation -- this will use
# conditional_escape() in Django 2.0.
warnings.simplefilter('ignore', category=RemovedInDjango20Warni... | [
"def",
"escape_filter",
"(",
"value",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"# Ignore mark_for_escaping deprecation -- this will use",
"# conditional_escape() in Django 2.0.",
"warnings",
".",
"simplefilter",
"(",
"'ignore'",
",",
"category",
... | [
440,
0
] | [
448,
39
] | python | en | ['en', 'error', 'th'] | False |
force_escape | (value) |
Escapes a string's HTML. This returns a new string containing the escaped
characters (as opposed to "escape", which marks the content for later
possible escaping).
|
Escapes a string's HTML. This returns a new string containing the escaped
characters (as opposed to "escape", which marks the content for later
possible escaping).
| def force_escape(value):
"""
Escapes a string's HTML. This returns a new string containing the escaped
characters (as opposed to "escape", which marks the content for later
possible escaping).
"""
return escape(value) | [
"def",
"force_escape",
"(",
"value",
")",
":",
"return",
"escape",
"(",
"value",
")"
] | [
453,
0
] | [
459,
24
] | python | en | ['en', 'error', 'th'] | False |
linebreaks_filter | (value, autoescape=True) |
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br />``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).
|
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br />``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).
| def linebreaks_filter(value, autoescape=True):
"""
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br />``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).
"""
autoescape = autoescape and not isinstance(value... | [
"def",
"linebreaks_filter",
"(",
"value",
",",
"autoescape",
"=",
"True",
")",
":",
"autoescape",
"=",
"autoescape",
"and",
"not",
"isinstance",
"(",
"value",
",",
"SafeData",
")",
"return",
"mark_safe",
"(",
"linebreaks",
"(",
"value",
",",
"autoescape",
")... | [
464,
0
] | [
471,
51
] | python | en | ['en', 'error', 'th'] | False |
linebreaksbr | (value, autoescape=True) |
Converts all newlines in a piece of plain text to HTML line breaks
(``<br />``).
|
Converts all newlines in a piece of plain text to HTML line breaks
(``<br />``).
| def linebreaksbr(value, autoescape=True):
"""
Converts all newlines in a piece of plain text to HTML line breaks
(``<br />``).
"""
autoescape = autoescape and not isinstance(value, SafeData)
value = normalize_newlines(value)
if autoescape:
value = escape(value)
return mark_safe(v... | [
"def",
"linebreaksbr",
"(",
"value",
",",
"autoescape",
"=",
"True",
")",
":",
"autoescape",
"=",
"autoescape",
"and",
"not",
"isinstance",
"(",
"value",
",",
"SafeData",
")",
"value",
"=",
"normalize_newlines",
"(",
"value",
")",
"if",
"autoescape",
":",
... | [
476,
0
] | [
485,
51
] | python | en | ['en', 'error', 'th'] | False |
safe | (value) |
Marks the value as a string that should not be auto-escaped.
|
Marks the value as a string that should not be auto-escaped.
| def safe(value):
"""
Marks the value as a string that should not be auto-escaped.
"""
return mark_safe(value) | [
"def",
"safe",
"(",
"value",
")",
":",
"return",
"mark_safe",
"(",
"value",
")"
] | [
490,
0
] | [
494,
27
] | python | en | ['en', 'error', 'th'] | False |
safeseq | (value) |
A "safe" filter for sequences. Marks each element in the sequence,
individually, as safe, after converting them to unicode. Returns a list
with the results.
|
A "safe" filter for sequences. Marks each element in the sequence,
individually, as safe, after converting them to unicode. Returns a list
with the results.
| def safeseq(value):
"""
A "safe" filter for sequences. Marks each element in the sequence,
individually, as safe, after converting them to unicode. Returns a list
with the results.
"""
return [mark_safe(force_text(obj)) for obj in value] | [
"def",
"safeseq",
"(",
"value",
")",
":",
"return",
"[",
"mark_safe",
"(",
"force_text",
"(",
"obj",
")",
")",
"for",
"obj",
"in",
"value",
"]"
] | [
498,
0
] | [
504,
56
] | python | en | ['en', 'error', 'th'] | False |
striptags | (value) | Strips all [X]HTML tags. | Strips all [X]HTML tags. | def striptags(value):
"""Strips all [X]HTML tags."""
return strip_tags(value) | [
"def",
"striptags",
"(",
"value",
")",
":",
"return",
"strip_tags",
"(",
"value",
")"
] | [
509,
0
] | [
511,
28
] | python | en | ['en', 'en', 'en'] | True |
_property_resolver | (arg) |
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, behave like Variable(arg).resolve
>>> _property_resolver(1)('abc')
'b'
>>> _property_resolver('1')('abc')
Traceback (most recent call last):
...
TypeError: string indices must be integers
>>> class Fo... |
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, behave like Variable(arg).resolve | def _property_resolver(arg):
"""
When arg is convertible to float, behave like operator.itemgetter(arg)
Otherwise, behave like Variable(arg).resolve
>>> _property_resolver(1)('abc')
'b'
>>> _property_resolver('1')('abc')
Traceback (most recent call last):
...
TypeError: string indic... | [
"def",
"_property_resolver",
"(",
"arg",
")",
":",
"try",
":",
"float",
"(",
"arg",
")",
"except",
"ValueError",
":",
"return",
"Variable",
"(",
"arg",
")",
".",
"resolve",
"else",
":",
"return",
"itemgetter",
"(",
"arg",
")"
] | [
518,
0
] | [
541,
30
] | python | en | ['en', 'error', 'th'] | False |
dictsort | (value, arg) |
Takes a list of dicts, returns that list sorted by the property given in
the argument.
|
Takes a list of dicts, returns that list sorted by the property given in
the argument.
| def dictsort(value, arg):
"""
Takes a list of dicts, returns that list sorted by the property given in
the argument.
"""
try:
return sorted(value, key=_property_resolver(arg))
except (TypeError, VariableDoesNotExist):
return '' | [
"def",
"dictsort",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"return",
"sorted",
"(",
"value",
",",
"key",
"=",
"_property_resolver",
"(",
"arg",
")",
")",
"except",
"(",
"TypeError",
",",
"VariableDoesNotExist",
")",
":",
"return",
"''"
] | [
545,
0
] | [
553,
17
] | python | en | ['en', 'error', 'th'] | False |
dictsortreversed | (value, arg) |
Takes a list of dicts, returns that list sorted in reverse order by the
property given in the argument.
|
Takes a list of dicts, returns that list sorted in reverse order by the
property given in the argument.
| def dictsortreversed(value, arg):
"""
Takes a list of dicts, returns that list sorted in reverse order by the
property given in the argument.
"""
try:
return sorted(value, key=_property_resolver(arg), reverse=True)
except (TypeError, VariableDoesNotExist):
return '' | [
"def",
"dictsortreversed",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"return",
"sorted",
"(",
"value",
",",
"key",
"=",
"_property_resolver",
"(",
"arg",
")",
",",
"reverse",
"=",
"True",
")",
"except",
"(",
"TypeError",
",",
"VariableDoesNotExist",
... | [
557,
0
] | [
565,
17
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.