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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
add_metaclass | (metaclass) | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slo... | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"... | [
863,
0
] | [
878,
18
] | python | en | ['en', 'en', 'en'] | True |
ensure_binary | (s, encoding='utf-8', errors='strict') | Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
| Coerce **s** to six.binary_type. | def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.enc... | [
"def",
"ensure_binary",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isinstanc... | [
881,
0
] | [
897,
60
] | python | en | ['en', 'sn', 'en'] | True |
ensure_str | (s, encoding='utf-8', errors='strict') | Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
| Coerce *s* to `str`. | def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeEr... | [
"def",
"ensure_str",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"text_type",
",",
"binary_type",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%s'\"... | [
900,
0
] | [
917,
12
] | python | en | ['en', 'sl', 'en'] | True |
ensure_text | (s, encoding='utf-8', errors='strict') | Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
| Coerce *s* to six.text_type. | def ensure_text(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encodin... | [
"def",
"ensure_text",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isinstanc... | [
920,
0
] | [
936,
60
] | python | en | ['en', 'sr', 'en'] | True |
python_2_unicode_compatible | (klass) |
A class decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
|
A class decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing. | def python_2_unicode_compatible(klass):
"""
A class decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if ... | [
"def",
"python_2_unicode_compatible",
"(",
"klass",
")",
":",
"if",
"PY2",
":",
"if",
"'__str__'",
"not",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"@python_2_unicode_compatible cannot be applied \"",
"\"to %s because it doesn't define __str__().\""... | [
939,
0
] | [
954,
16
] | python | en | ['en', 'error', 'th'] | False |
_SixMetaPathImporter.is_package | (self, fullname) |
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
|
Return true, if the named module is a package. | def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__") | [
"def",
"is_package",
"(",
"self",
",",
"fullname",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"__get_module",
"(",
"fullname",
")",
",",
"\"__path__\"",
")"
] | [
208,
4
] | [
215,
63
] | python | en | ['en', 'error', 'th'] | False |
_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 |
DataSource.__getitem__ | (self, index) | Allows use of the index [] operator to get a layer at the index. | Allows use of the index [] operator to get a layer at the index. | def __getitem__(self, index):
"Allows use of the index [] operator to get a layer at the index."
if isinstance(index, str):
try:
layer = capi.get_layer_by_name(self.ptr, force_bytes(index))
except GDALException:
raise IndexError('Invalid OGR layer ... | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"try",
":",
"layer",
"=",
"capi",
".",
"get_layer_by_name",
"(",
"self",
".",
"ptr",
",",
"force_bytes",
"(",
"index",
")",
")",
"excep... | [
86,
4
] | [
100,
33
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__len__ | (self) | Return the number of layers within the data source. | Return the number of layers within the data source. | def __len__(self):
"Return the number of layers within the data source."
return self.layer_count | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"layer_count"
] | [
102,
4
] | [
104,
31
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__str__ | (self) | Return OGR GetName and Driver for the Data Source. | Return OGR GetName and Driver for the Data Source. | def __str__(self):
"Return OGR GetName and Driver for the Data Source."
return '%s (%s)' % (self.name, self.driver) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"'%s (%s)'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"driver",
")"
] | [
106,
4
] | [
108,
51
] | python | en | ['en', 'en', 'en'] | True |
DataSource.layer_count | (self) | Return the number of layers in the data source. | Return the number of layers in the data source. | def layer_count(self):
"Return the number of layers in the data source."
return capi.get_layer_count(self._ptr) | [
"def",
"layer_count",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_layer_count",
"(",
"self",
".",
"_ptr",
")"
] | [
111,
4
] | [
113,
46
] | python | en | ['en', 'en', 'en'] | True |
DataSource.name | (self) | Return the name of the data source. | Return the name of the data source. | def name(self):
"Return the name of the data source."
name = capi.get_ds_name(self._ptr)
return force_str(name, self.encoding, strings_only=True) | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"capi",
".",
"get_ds_name",
"(",
"self",
".",
"_ptr",
")",
"return",
"force_str",
"(",
"name",
",",
"self",
".",
"encoding",
",",
"strings_only",
"=",
"True",
")"
] | [
116,
4
] | [
119,
64
] | python | en | ['en', 'en', 'en'] | True |
url_to_file_path | (url, filecache) | Return the file cache path based on the URL.
This does not ensure the file exists!
| Return the file cache path based on the URL. | def url_to_file_path(url, filecache):
"""Return the file cache path based on the URL.
This does not ensure the file exists!
"""
key = CacheController.cache_url(url)
return filecache._fn(key) | [
"def",
"url_to_file_path",
"(",
"url",
",",
"filecache",
")",
":",
"key",
"=",
"CacheController",
".",
"cache_url",
"(",
"url",
")",
"return",
"filecache",
".",
"_fn",
"(",
"key",
")"
] | [
139,
0
] | [
145,
29
] | python | en | ['en', 'en', 'en'] | True |
forbid_multi_line_headers | (name, val, encoding) | Forbid multi-line headers to prevent header injection. | Forbid multi-line headers to prevent header injection. | def forbid_multi_line_headers(name, val, encoding):
"""Forbid multi-line headers to prevent header injection."""
encoding = encoding or settings.DEFAULT_CHARSET
val = str(val) # val may be lazy
if '\n' in val or '\r' in val:
raise BadHeaderError("Header values can't contain newlines (got %r for... | [
"def",
"forbid_multi_line_headers",
"(",
"name",
",",
"val",
",",
"encoding",
")",
":",
"encoding",
"=",
"encoding",
"or",
"settings",
".",
"DEFAULT_CHARSET",
"val",
"=",
"str",
"(",
"val",
")",
"# val may be lazy",
"if",
"'\\n'",
"in",
"val",
"or",
"'\\r'",... | [
54,
0
] | [
70,
20
] | python | en | ['en', 'en', 'en'] | True |
sanitize_address | (addr, encoding) |
Format a pair of (name, address) or an email address string.
|
Format a pair of (name, address) or an email address string.
| def sanitize_address(addr, encoding):
"""
Format a pair of (name, address) or an email address string.
"""
address = None
if not isinstance(addr, tuple):
addr = force_str(addr)
try:
token, rest = parser.get_mailbox(addr)
except (HeaderParseError, ValueError, Index... | [
"def",
"sanitize_address",
"(",
"addr",
",",
"encoding",
")",
":",
"address",
"=",
"None",
"if",
"not",
"isinstance",
"(",
"addr",
",",
"tuple",
")",
":",
"addr",
"=",
"force_str",
"(",
"addr",
")",
"try",
":",
"token",
",",
"rest",
"=",
"parser",
".... | [
73,
0
] | [
107,
30
] | python | en | ['en', 'error', 'th'] | False |
MIMEMixin.as_string | (self, unixfrom=False, linesep='\n') | Return the entire formatted message as a string.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This overrides the default as_string() implementation to not mangle
lines that begin with 'From '. See bug #13433 for details.
| Return the entire formatted message as a string.
Optional `unixfrom' when True, means include the Unix From_ envelope
header. | def as_string(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as a string.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This overrides the default as_string() implementation to not mangle
lines that begin with 'From '. ... | [
"def",
"as_string",
"(",
"self",
",",
"unixfrom",
"=",
"False",
",",
"linesep",
"=",
"'\\n'",
")",
":",
"fp",
"=",
"StringIO",
"(",
")",
"g",
"=",
"generator",
".",
"Generator",
"(",
"fp",
",",
"mangle_from_",
"=",
"False",
")",
"g",
".",
"flatten",
... | [
111,
4
] | [
122,
28
] | python | en | ['en', 'en', 'en'] | True |
MIMEMixin.as_bytes | (self, unixfrom=False, linesep='\n') | Return the entire formatted message as bytes.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This overrides the default as_bytes() implementation to not mangle
lines that begin with 'From '. See bug #13433 for details.
| Return the entire formatted message as bytes.
Optional `unixfrom' when True, means include the Unix From_ envelope
header. | def as_bytes(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as bytes.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This overrides the default as_bytes() implementation to not mangle
lines that begin with 'From '. See b... | [
"def",
"as_bytes",
"(",
"self",
",",
"unixfrom",
"=",
"False",
",",
"linesep",
"=",
"'\\n'",
")",
":",
"fp",
"=",
"BytesIO",
"(",
")",
"g",
"=",
"generator",
".",
"BytesGenerator",
"(",
"fp",
",",
"mangle_from_",
"=",
"False",
")",
"g",
".",
"flatten... | [
124,
4
] | [
135,
28
] | python | en | ['en', 'en', 'en'] | True |
EmailMessage.__init__ | (self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, cc=None,
reply_to=None) |
Initialize a single email message (which can be sent to multiple
recipients).
|
Initialize a single email message (which can be sent to multiple
recipients).
| def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, cc=None,
reply_to=None):
"""
Initialize a single email message (which can be sent to multiple
recipients).
"""
if to:
... | [
"def",
"__init__",
"(",
"self",
",",
"subject",
"=",
"''",
",",
"body",
"=",
"''",
",",
"from_email",
"=",
"None",
",",
"to",
"=",
"None",
",",
"bcc",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"attachments",
"=",
"None",
",",
"headers",
"="... | [
185,
4
] | [
227,
36
] | python | en | ['en', 'error', 'th'] | False |
EmailMessage.recipients | (self) |
Return a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).
|
Return a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).
| def recipients(self):
"""
Return a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).
"""
return [email for email in (self.to + self.cc + self.bcc) if email] | [
"def",
"recipients",
"(",
"self",
")",
":",
"return",
"[",
"email",
"for",
"email",
"in",
"(",
"self",
".",
"to",
"+",
"self",
".",
"cc",
"+",
"self",
".",
"bcc",
")",
"if",
"email",
"]"
] | [
262,
4
] | [
267,
75
] | python | en | ['en', 'error', 'th'] | False |
EmailMessage.send | (self, fail_silently=False) | Send the email message. | Send the email message. | def send(self, fail_silently=False):
"""Send the email message."""
if not self.recipients():
# Don't bother creating the network connection if there's nobody to
# send to.
return 0
return self.get_connection(fail_silently).send_messages([self]) | [
"def",
"send",
"(",
"self",
",",
"fail_silently",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"recipients",
"(",
")",
":",
"# Don't bother creating the network connection if there's nobody to",
"# send to.",
"return",
"0",
"return",
"self",
".",
"get_connectio... | [
269,
4
] | [
275,
71
] | python | en | ['en', 'en', 'en'] | True |
EmailMessage.attach | (self, filename=None, content=None, mimetype=None) |
Attach a file with the given filename and content. The filename can
be omitted and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass, insert it directly
into the resulting message attachments.
For a text/* mimetype (guessed or specified), ... |
Attach a file with the given filename and content. The filename can
be omitted and the mimetype is guessed, if not provided. | def attach(self, filename=None, content=None, mimetype=None):
"""
Attach a file with the given filename and content. The filename can
be omitted and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass, insert it directly
into the resulting mes... | [
"def",
"attach",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"content",
"=",
"None",
",",
"mimetype",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"MIMEBase",
")",
":",
"assert",
"content",
"is",
"None",
"assert",
"mimetype",
"i... | [
277,
4
] | [
307,
66
] | python | en | ['en', 'error', 'th'] | False |
EmailMessage.attach_file | (self, path, mimetype=None) |
Attach a file from the filesystem.
Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified
and cannot be guessed.
For a text/* mimetype (guessed or specified), decode the file's content
as UTF-8. If that fails, set the mimetype to
DEFAULT_ATTACHMENT_MIME... |
Attach a file from the filesystem. | def attach_file(self, path, mimetype=None):
"""
Attach a file from the filesystem.
Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified
and cannot be guessed.
For a text/* mimetype (guessed or specified), decode the file's content
as UTF-8. If that fai... | [
"def",
"attach_file",
"(",
"self",
",",
"path",
",",
"mimetype",
"=",
"None",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"with",
"path",
".",
"open",
"(",
"'rb'",
")",
"as",
"file",
":",
"content",
"=",
"file",
".",
"read",
"(",
")",
"self"... | [
309,
4
] | [
323,
53
] | python | en | ['en', 'error', 'th'] | False |
EmailMessage._create_mime_attachment | (self, content, mimetype) |
Convert the content, mimetype pair into a MIME attachment object.
If the mimetype is message/rfc822, content may be an
email.Message or EmailMessage object, as well as a str.
|
Convert the content, mimetype pair into a MIME attachment object. | def _create_mime_attachment(self, content, mimetype):
"""
Convert the content, mimetype pair into a MIME attachment object.
If the mimetype is message/rfc822, content may be an
email.Message or EmailMessage object, as well as a str.
"""
basetype, subtype = mimetype.split... | [
"def",
"_create_mime_attachment",
"(",
"self",
",",
"content",
",",
"mimetype",
")",
":",
"basetype",
",",
"subtype",
"=",
"mimetype",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"if",
"basetype",
"==",
"'text'",
":",
"encoding",
"=",
"self",
".",
"encoding... | [
342,
4
] | [
370,
25
] | python | en | ['en', 'error', 'th'] | False |
EmailMessage._create_attachment | (self, filename, content, mimetype=None) |
Convert the filename, content, mimetype triple into a MIME attachment
object.
|
Convert the filename, content, mimetype triple into a MIME attachment
object.
| def _create_attachment(self, filename, content, mimetype=None):
"""
Convert the filename, content, mimetype triple into a MIME attachment
object.
"""
attachment = self._create_mime_attachment(content, mimetype)
if filename:
try:
filename.encode... | [
"def",
"_create_attachment",
"(",
"self",
",",
"filename",
",",
"content",
",",
"mimetype",
"=",
"None",
")",
":",
"attachment",
"=",
"self",
".",
"_create_mime_attachment",
"(",
"content",
",",
"mimetype",
")",
"if",
"filename",
":",
"try",
":",
"filename",... | [
372,
4
] | [
384,
25
] | python | en | ['en', 'error', 'th'] | False |
EmailMessage._set_list_header_if_not_empty | (self, msg, header, values) |
Set msg's header, either from self.extra_headers, if present, or from
the values argument.
|
Set msg's header, either from self.extra_headers, if present, or from
the values argument.
| def _set_list_header_if_not_empty(self, msg, header, values):
"""
Set msg's header, either from self.extra_headers, if present, or from
the values argument.
"""
if values:
try:
value = self.extra_headers[header]
except KeyError:
... | [
"def",
"_set_list_header_if_not_empty",
"(",
"self",
",",
"msg",
",",
"header",
",",
"values",
")",
":",
"if",
"values",
":",
"try",
":",
"value",
"=",
"self",
".",
"extra_headers",
"[",
"header",
"]",
"except",
"KeyError",
":",
"value",
"=",
"', '",
"."... | [
386,
4
] | [
396,
31
] | python | en | ['en', 'error', 'th'] | False |
EmailMultiAlternatives.__init__ | (self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, alternatives=None,
cc=None, reply_to=None) |
Initialize a single email message (which can be sent to multiple
recipients).
|
Initialize a single email message (which can be sent to multiple
recipients).
| def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, alternatives=None,
cc=None, reply_to=None):
"""
Initialize a single email message (which can be sent to multiple
recipients).
"""... | [
"def",
"__init__",
"(",
"self",
",",
"subject",
"=",
"''",
",",
"body",
"=",
"''",
",",
"from_email",
"=",
"None",
",",
"to",
"=",
"None",
",",
"bcc",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"attachments",
"=",
"None",
",",
"headers",
"="... | [
407,
4
] | [
418,
46
] | python | en | ['en', 'error', 'th'] | False |
EmailMultiAlternatives.attach_alternative | (self, content, mimetype) | Attach an alternative content representation. | Attach an alternative content representation. | def attach_alternative(self, content, mimetype):
"""Attach an alternative content representation."""
assert content is not None
assert mimetype is not None
self.alternatives.append((content, mimetype)) | [
"def",
"attach_alternative",
"(",
"self",
",",
"content",
",",
"mimetype",
")",
":",
"assert",
"content",
"is",
"not",
"None",
"assert",
"mimetype",
"is",
"not",
"None",
"self",
".",
"alternatives",
".",
"append",
"(",
"(",
"content",
",",
"mimetype",
")",... | [
420,
4
] | [
424,
53
] | python | en | ['en', 'lb', 'en'] | True |
HTTPResponse.get_redirect_location | (self) |
Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.
|
Should we redirect and where to? | def get_redirect_location(self):
"""
Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.
"""
... | [
"def",
"get_redirect_location",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"in",
"self",
".",
"REDIRECT_STATUSES",
":",
"return",
"self",
".",
"headers",
".",
"get",
"(",
"\"location\"",
")",
"return",
"False"
] | [
259,
4
] | [
270,
20
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.tell | (self) |
Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``HTTPResponse.read`` if bytes
are encoded on the wire (e.g, compressed).
|
Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``HTTPResponse.read`` if bytes
are encoded on the wire (e.g, compressed).
| def tell(self):
"""
Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``HTTPResponse.read`` if bytes
are encoded on the wire (e.g, compressed).
"""
return self._fp_bytes_read | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"self",
".",
"_fp_bytes_read"
] | [
295,
4
] | [
301,
34
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._init_length | (self, request_method) |
Set initial length value for Response content if available.
|
Set initial length value for Response content if available.
| def _init_length(self, request_method):
"""
Set initial length value for Response content if available.
"""
length = self.headers.get("content-length")
if length is not None:
if self.chunked:
# This Response will fail with an IncompleteRead if it can'... | [
"def",
"_init_length",
"(",
"self",
",",
"request_method",
")",
":",
"length",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"content-length\"",
")",
"if",
"length",
"is",
"not",
"None",
":",
"if",
"self",
".",
"chunked",
":",
"# This Response will fail wi... | [
303,
4
] | [
353,
21
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._init_decoder | (self) |
Set-up the _decoder attribute if necessary.
|
Set-up the _decoder attribute if necessary.
| def _init_decoder(self):
"""
Set-up the _decoder attribute if necessary.
"""
# Note: content-encoding value should be case-insensitive, per RFC 7230
# Section 3.2
content_encoding = self.headers.get("content-encoding", "").lower()
if self._decoder is None:
... | [
"def",
"_init_decoder",
"(",
"self",
")",
":",
"# Note: content-encoding value should be case-insensitive, per RFC 7230",
"# Section 3.2",
"content_encoding",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"content-encoding\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",... | [
355,
4
] | [
372,
66
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._decode | (self, data, decode_content, flush_decoder) |
Decode the data passed in and potentially flush the decoder.
|
Decode the data passed in and potentially flush the decoder.
| def _decode(self, data, decode_content, flush_decoder):
"""
Decode the data passed in and potentially flush the decoder.
"""
if not decode_content:
return data
try:
if self._decoder:
data = self._decoder.decompress(data)
except sel... | [
"def",
"_decode",
"(",
"self",
",",
"data",
",",
"decode_content",
",",
"flush_decoder",
")",
":",
"if",
"not",
"decode_content",
":",
"return",
"data",
"try",
":",
"if",
"self",
".",
"_decoder",
":",
"data",
"=",
"self",
".",
"_decoder",
".",
"decompres... | [
378,
4
] | [
398,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._flush_decoder | (self) |
Flushes the decoder. Should only be called if the decoder is actually
being used.
|
Flushes the decoder. Should only be called if the decoder is actually
being used.
| def _flush_decoder(self):
"""
Flushes the decoder. Should only be called if the decoder is actually
being used.
"""
if self._decoder:
buf = self._decoder.decompress(b"")
return buf + self._decoder.flush()
return b"" | [
"def",
"_flush_decoder",
"(",
"self",
")",
":",
"if",
"self",
".",
"_decoder",
":",
"buf",
"=",
"self",
".",
"_decoder",
".",
"decompress",
"(",
"b\"\"",
")",
"return",
"buf",
"+",
"self",
".",
"_decoder",
".",
"flush",
"(",
")",
"return",
"b\"\""
] | [
400,
4
] | [
409,
18
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._error_catcher | (self) |
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
|
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api. | def _error_catcher(self):
"""
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
"""
clean_exit = False
try:
... | [
"def",
"_error_catcher",
"(",
"self",
")",
":",
"clean_exit",
"=",
"False",
"try",
":",
"try",
":",
"yield",
"except",
"SocketTimeout",
":",
"# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but",
"# there is yet no clean way to get at it from this context.",... | [
412,
4
] | [
466,
35
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.read | (self, amt=None, decode_content=None, cache_content=False) |
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
... |
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``. | def read(self, amt=None, decode_content=None, cache_content=False):
"""
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
... | [
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
",",
"cache_content",
"=",
"False",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"if",
"decode_content",
"is",
"None",
":",
"decode_content",
"=",
"self",
".",
... | [
468,
4
] | [
540,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.stream | (self, amt=2 ** 16, decode_content=None) |
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may r... |
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed. | def stream(self, amt=2 ** 16, decode_content=None):
"""
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator w... | [
"def",
"stream",
"(",
"self",
",",
"amt",
"=",
"2",
"**",
"16",
",",
"decode_content",
"=",
"None",
")",
":",
"if",
"self",
".",
"chunked",
"and",
"self",
".",
"supports_chunked_reads",
"(",
")",
":",
"for",
"line",
"in",
"self",
".",
"read_chunked",
... | [
542,
4
] | [
566,
30
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.from_httplib | (ResponseCls, r, **response_kw) |
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
|
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object. | def from_httplib(ResponseCls, r, **response_kw):
"""
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
... | [
"def",
"from_httplib",
"(",
"ResponseCls",
",",
"r",
",",
"*",
"*",
"response_kw",
")",
":",
"headers",
"=",
"r",
".",
"msg",
"if",
"not",
"isinstance",
"(",
"headers",
",",
"HTTPHeaderDict",
")",
":",
"if",
"PY3",
":",
"headers",
"=",
"HTTPHeaderDict",
... | [
569,
4
] | [
598,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.supports_chunked_reads | (self) |
Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
|
Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
| def supports_chunked_reads(self):
"""
Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
"""
return hasatt... | [
"def",
"supports_chunked_reads",
"(",
"self",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"_fp",
",",
"\"fp\"",
")"
] | [
667,
4
] | [
674,
38
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.read_chunked | (self, amt=None, decode_content=None) |
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:p... |
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``. | def read_chunked(self, amt=None, decode_content=None):
"""
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to c... | [
"def",
"read_chunked",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"# FIXME: Rewrite this method and make it a class with a better structured logic.",
"if",
"not",
"self",
".",
"chunked",
... | [
712,
4
] | [
780,
47
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.geturl | (self) |
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
|
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
| def geturl(self):
"""
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
"""
if self.retries is not None and len(self.retries.history):
return self.... | [
"def",
"geturl",
"(",
"self",
")",
":",
"if",
"self",
".",
"retries",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"retries",
".",
"history",
")",
":",
"return",
"self",
".",
"retries",
".",
"history",
"[",
"-",
"1",
"]",
".",
"redirect_loc... | [
782,
4
] | [
791,
36
] | python | en | ['en', 'error', 'th'] | False |
prepopulated_fields_js | (context) |
Create a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the admin form and inlines.
|
Create a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the admin form and inlines.
| def prepopulated_fields_js(context):
"""
Create a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the admin form and inlines.
"""
prepopulated_fields = []
if 'adminform' in context:
prepopulated_fields.extend(context['adminform'].prepopulate... | [
"def",
"prepopulated_fields_js",
"(",
"context",
")",
":",
"prepopulated_fields",
"=",
"[",
"]",
"if",
"'adminform'",
"in",
"context",
":",
"prepopulated_fields",
".",
"extend",
"(",
"context",
"[",
"'adminform'",
"]",
".",
"prepopulated_fields",
")",
"if",
"'in... | [
10,
0
] | [
39,
18
] | python | en | ['en', 'error', 'th'] | False |
submit_row | (context) |
Display the row of buttons for delete and save.
|
Display the row of buttons for delete and save.
| def submit_row(context):
"""
Display the row of buttons for delete and save.
"""
add = context['add']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
show_save = context.get('show_save', True)
show_save_and_continue = context.get('show_save_and_... | [
"def",
"submit_row",
"(",
"context",
")",
":",
"add",
"=",
"context",
"[",
"'add'",
"]",
"change",
"=",
"context",
"[",
"'change'",
"]",
"is_popup",
"=",
"context",
"[",
"'is_popup'",
"]",
"save_as",
"=",
"context",
"[",
"'save_as'",
"]",
"show_save",
"=... | [
47,
0
] | [
80,
14
] | python | en | ['en', 'error', 'th'] | False |
change_form_object_tools_tag | (parser, token) | Display the row of change form object tools. | Display the row of change form object tools. | def change_form_object_tools_tag(parser, token):
"""Display the row of change form object tools."""
return InclusionAdminNode(
parser, token,
func=lambda context: context,
template_name='change_form_object_tools.html',
) | [
"def",
"change_form_object_tools_tag",
"(",
"parser",
",",
"token",
")",
":",
"return",
"InclusionAdminNode",
"(",
"parser",
",",
"token",
",",
"func",
"=",
"lambda",
"context",
":",
"context",
",",
"template_name",
"=",
"'change_form_object_tools.html'",
",",
")"... | [
89,
0
] | [
95,
5
] | python | en | ['en', 'en', 'en'] | True |
cell_count | (inline_admin_form) | Return the number of cells used in a tabular inline. | Return the number of cells used in a tabular inline. | def cell_count(inline_admin_form):
"""Return the number of cells used in a tabular inline."""
count = 1 # Hidden cell with hidden 'id' field
for fieldset in inline_admin_form:
# Loop through all the fields (one per cell)
for line in fieldset:
for field in line:
c... | [
"def",
"cell_count",
"(",
"inline_admin_form",
")",
":",
"count",
"=",
"1",
"# Hidden cell with hidden 'id' field",
"for",
"fieldset",
"in",
"inline_admin_form",
":",
"# Loop through all the fields (one per cell)",
"for",
"line",
"in",
"fieldset",
":",
"for",
"field",
"... | [
99,
0
] | [
110,
16
] | python | en | ['en', 'en', 'en'] | True |
TestUtilsTF.test_clip_eta_norm_0 | (self) | test_clip_eta_norm_0: Test that `clip_eta` still works when the
norm of `eta` is zero. This used to cause a divide by zero for ord
1 and ord 2. | test_clip_eta_norm_0: Test that `clip_eta` still works when the
norm of `eta` is zero. This used to cause a divide by zero for ord
1 and ord 2. | def test_clip_eta_norm_0(self):
"""test_clip_eta_norm_0: Test that `clip_eta` still works when the
norm of `eta` is zero. This used to cause a divide by zero for ord
1 and ord 2."""
eta = tf.zeros((5, 3))
self.assertTrue(eta.dtype == tf.float32, eta.dtype)
eps = 0.25
... | [
"def",
"test_clip_eta_norm_0",
"(",
"self",
")",
":",
"eta",
"=",
"tf",
".",
"zeros",
"(",
"(",
"5",
",",
"3",
")",
")",
"self",
".",
"assertTrue",
"(",
"eta",
".",
"dtype",
"==",
"tf",
".",
"float32",
",",
"eta",
".",
"dtype",
")",
"eps",
"=",
... | [
58,
4
] | [
73,
78
] | python | en | ['en', 'gd', 'en'] | True |
TestUtilsTF.test_clip_eta_goldilocks | (self) | test_clip_eta_goldilocks: Test that the clipping handles perturbations
that are too small, just right, and too big correctly | test_clip_eta_goldilocks: Test that the clipping handles perturbations
that are too small, just right, and too big correctly | def test_clip_eta_goldilocks(self):
"""test_clip_eta_goldilocks: Test that the clipping handles perturbations
that are too small, just right, and too big correctly"""
eta = tf.constant([[2.0], [3.0], [4.0]])
self.assertTrue(eta.dtype == tf.float32, eta.dtype)
eps = 3.0
fo... | [
"def",
"test_clip_eta_goldilocks",
"(",
"self",
")",
":",
"eta",
"=",
"tf",
".",
"constant",
"(",
"[",
"[",
"2.0",
"]",
",",
"[",
"3.0",
"]",
",",
"[",
"4.0",
"]",
"]",
")",
"self",
".",
"assertTrue",
"(",
"eta",
".",
"dtype",
"==",
"tf",
".",
... | [
75,
4
] | [
99,
50
] | python | en | ['en', 'la', 'en'] | True |
TestUtilsTF.test_zero_out_clipped_grads | (self) |
test_zero_out_clipped_grads: Test that gradient gets zeroed out at positions
where no progress can be made due to clipping.
|
test_zero_out_clipped_grads: Test that gradient gets zeroed out at positions
where no progress can be made due to clipping.
| def test_zero_out_clipped_grads(self):
"""
test_zero_out_clipped_grads: Test that gradient gets zeroed out at positions
where no progress can be made due to clipping.
"""
clip_min = -1
clip_max = 1
eta = tf.constant([[0.0], [-1.0], [1], [0.5], [-1], [1], [-0.9], ... | [
"def",
"test_zero_out_clipped_grads",
"(",
"self",
")",
":",
"clip_min",
"=",
"-",
"1",
"clip_max",
"=",
"1",
"eta",
"=",
"tf",
".",
"constant",
"(",
"[",
"[",
"0.0",
"]",
",",
"[",
"-",
"1.0",
"]",
",",
"[",
"1",
"]",
",",
"[",
"0.5",
"]",
","... | [
101,
4
] | [
119,
41
] | python | en | ['en', 'error', 'th'] | False |
TestUtilsTF.test_random_lp_vector_linf | (self) |
test_random_lp_sample_linf: Test that `random_lp_vector` returns
random samples in the l-inf ball.
|
test_random_lp_sample_linf: Test that `random_lp_vector` returns
random samples in the l-inf ball.
| def test_random_lp_vector_linf(self):
"""
test_random_lp_sample_linf: Test that `random_lp_vector` returns
random samples in the l-inf ball.
"""
eps = 0.5
d = 10
r = self.sess.run(utils_tf.random_lp_vector((1000, d), np.infty, eps))
# test that some val... | [
"def",
"test_random_lp_vector_linf",
"(",
"self",
")",
":",
"eps",
"=",
"0.5",
"d",
"=",
"10",
"r",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"utils_tf",
".",
"random_lp_vector",
"(",
"(",
"1000",
",",
"d",
")",
",",
"np",
".",
"infty",
",",
"eps"... | [
121,
4
] | [
140,
55
] | python | en | ['en', 'error', 'th'] | False |
TestUtilsTF.test_random_lp_srandom_lp_vector_l1_l2 | (self) |
test_random_lp_vector_l1_l2: Test that `random_lp_vector` returns
random samples in an l1 or l2 ball.
|
test_random_lp_vector_l1_l2: Test that `random_lp_vector` returns
random samples in an l1 or l2 ball.
| def test_random_lp_srandom_lp_vector_l1_l2(self):
"""
test_random_lp_vector_l1_l2: Test that `random_lp_vector` returns
random samples in an l1 or l2 ball.
"""
eps = 0.5
d = 10
for ord in [1, 2]:
r = self.sess.run(utils_tf.random_lp_vector((1000, d),... | [
"def",
"test_random_lp_srandom_lp_vector_l1_l2",
"(",
"self",
")",
":",
"eps",
"=",
"0.5",
"d",
"=",
"10",
"for",
"ord",
"in",
"[",
"1",
",",
"2",
"]",
":",
"r",
"=",
"self",
".",
"sess",
".",
"run",
"(",
"utils_tf",
".",
"random_lp_vector",
"(",
"("... | [
142,
4
] | [
164,
75
] | python | en | ['en', 'error', 'th'] | False |
load_handler | (path, *args, **kwargs) |
Given a path to a handler, return an instance of that handler.
E.g.::
>>> from django.http import HttpRequest
>>> request = HttpRequest()
>>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request)
<TemporaryFileUploadHandler object at 0x...>
|
Given a path to a handler, return an instance of that handler. | def load_handler(path, *args, **kwargs):
"""
Given a path to a handler, return an instance of that handler.
E.g.::
>>> from django.http import HttpRequest
>>> request = HttpRequest()
>>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request)
<Tem... | [
"def",
"load_handler",
"(",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"import_string",
"(",
"path",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
194,
0
] | [
204,
47
] | python | en | ['en', 'error', 'th'] | False |
StopUpload.__init__ | (self, connection_reset=False) |
If ``connection_reset`` is ``True``, Django knows will halt the upload
without consuming the rest of the upload. This will cause the browser to
show a "connection reset" error.
|
If ``connection_reset`` is ``True``, Django knows will halt the upload
without consuming the rest of the upload. This will cause the browser to
show a "connection reset" error.
| def __init__(self, connection_reset=False):
"""
If ``connection_reset`` is ``True``, Django knows will halt the upload
without consuming the rest of the upload. This will cause the browser to
show a "connection reset" error.
"""
self.connection_reset = connection_reset | [
"def",
"__init__",
"(",
"self",
",",
"connection_reset",
"=",
"False",
")",
":",
"self",
".",
"connection_reset",
"=",
"connection_reset"
] | [
30,
4
] | [
36,
48
] | python | en | ['en', 'error', 'th'] | False |
FileUploadHandler.handle_raw_input | (self, input_data, META, content_length, boundary, encoding=None) |
Handle the raw input from the client.
Parameters:
:input_data:
An object that supports reading via .read().
:META:
``request.META``.
:content_length:
The (integer) value of the Content-Length header from the
... |
Handle the raw input from the client. | def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
"""
Handle the raw input from the client.
Parameters:
:input_data:
An object that supports reading via .read().
:META:
``request.META``.
:c... | [
"def",
"handle_raw_input",
"(",
"self",
",",
"input_data",
",",
"META",
",",
"content_length",
",",
"boundary",
",",
"encoding",
"=",
"None",
")",
":",
"pass"
] | [
74,
4
] | [
90,
12
] | python | en | ['en', 'error', 'th'] | False |
FileUploadHandler.new_file | (self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None) |
Signal that a new file has been started.
Warning: As with any data from the client, you should not trust
content_length (and sometimes won't even get it).
|
Signal that a new file has been started. | def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None):
"""
Signal that a new file has been started.
Warning: As with any data from the client, you should not trust
content_length (and sometimes won't even get it).
"""
... | [
"def",
"new_file",
"(",
"self",
",",
"field_name",
",",
"file_name",
",",
"content_type",
",",
"content_length",
",",
"charset",
"=",
"None",
",",
"content_type_extra",
"=",
"None",
")",
":",
"self",
".",
"field_name",
"=",
"field_name",
"self",
".",
"file_n... | [
92,
4
] | [
104,
52
] | python | en | ['en', 'error', 'th'] | False |
FileUploadHandler.receive_data_chunk | (self, raw_data, start) |
Receive data from the streamed upload parser. ``start`` is the position
in the file of the chunk.
|
Receive data from the streamed upload parser. ``start`` is the position
in the file of the chunk.
| def receive_data_chunk(self, raw_data, start):
"""
Receive data from the streamed upload parser. ``start`` is the position
in the file of the chunk.
"""
raise NotImplementedError('subclasses of FileUploadHandler must provide a receive_data_chunk() method') | [
"def",
"receive_data_chunk",
"(",
"self",
",",
"raw_data",
",",
"start",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of FileUploadHandler must provide a receive_data_chunk() method'",
")"
] | [
106,
4
] | [
111,
111
] | python | en | ['en', 'error', 'th'] | False |
FileUploadHandler.file_complete | (self, file_size) |
Signal that a file has completed. File size corresponds to the actual
size accumulated by all the chunks.
Subclasses should return a valid ``UploadedFile`` object.
|
Signal that a file has completed. File size corresponds to the actual
size accumulated by all the chunks. | def file_complete(self, file_size):
"""
Signal that a file has completed. File size corresponds to the actual
size accumulated by all the chunks.
Subclasses should return a valid ``UploadedFile`` object.
"""
raise NotImplementedError('subclasses of FileUploadHandler must... | [
"def",
"file_complete",
"(",
"self",
",",
"file_size",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of FileUploadHandler must provide a file_complete() method'",
")"
] | [
113,
4
] | [
120,
106
] | python | en | ['en', 'error', 'th'] | False |
FileUploadHandler.upload_complete | (self) |
Signal that the upload is complete. Subclasses should perform cleanup
that is necessary for this handler.
|
Signal that the upload is complete. Subclasses should perform cleanup
that is necessary for this handler.
| def upload_complete(self):
"""
Signal that the upload is complete. Subclasses should perform cleanup
that is necessary for this handler.
"""
pass | [
"def",
"upload_complete",
"(",
"self",
")",
":",
"pass"
] | [
122,
4
] | [
127,
12
] | python | en | ['en', 'error', 'th'] | False |
TemporaryFileUploadHandler.new_file | (self, *args, **kwargs) |
Create the file object to append to as data is coming in.
|
Create the file object to append to as data is coming in.
| def new_file(self, *args, **kwargs):
"""
Create the file object to append to as data is coming in.
"""
super().new_file(*args, **kwargs)
self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset, self.content_type_extra) | [
"def",
"new_file",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"new_file",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"file",
"=",
"TemporaryUploadedFile",
"(",
"self",
".",
"file_name... | [
134,
4
] | [
139,
118
] | python | en | ['en', 'error', 'th'] | False |
MemoryFileUploadHandler.handle_raw_input | (self, input_data, META, content_length, boundary, encoding=None) |
Use the content_length to signal whether or not this handler should be
used.
|
Use the content_length to signal whether or not this handler should be
used.
| def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
"""
Use the content_length to signal whether or not this handler should be
used.
"""
# Check the content-length header to see if we should
# If the post is too large, we cannot use the ... | [
"def",
"handle_raw_input",
"(",
"self",
",",
"input_data",
",",
"META",
",",
"content_length",
",",
"boundary",
",",
"encoding",
"=",
"None",
")",
":",
"# Check the content-length header to see if we should",
"# If the post is too large, we cannot use the Memory handler.",
"s... | [
155,
4
] | [
162,
79
] | python | en | ['en', 'error', 'th'] | False |
MemoryFileUploadHandler.receive_data_chunk | (self, raw_data, start) | Add the data to the BytesIO file. | Add the data to the BytesIO file. | def receive_data_chunk(self, raw_data, start):
"""Add the data to the BytesIO file."""
if self.activated:
self.file.write(raw_data)
else:
return raw_data | [
"def",
"receive_data_chunk",
"(",
"self",
",",
"raw_data",
",",
"start",
")",
":",
"if",
"self",
".",
"activated",
":",
"self",
".",
"file",
".",
"write",
"(",
"raw_data",
")",
"else",
":",
"return",
"raw_data"
] | [
170,
4
] | [
175,
27
] | python | en | ['en', 'en', 'en'] | True |
MemoryFileUploadHandler.file_complete | (self, file_size) | Return a file object if this handler is activated. | Return a file object if this handler is activated. | def file_complete(self, file_size):
"""Return a file object if this handler is activated."""
if not self.activated:
return
self.file.seek(0)
return InMemoryUploadedFile(
file=self.file,
field_name=self.field_name,
name=self.file_name,
... | [
"def",
"file_complete",
"(",
"self",
",",
"file_size",
")",
":",
"if",
"not",
"self",
".",
"activated",
":",
"return",
"self",
".",
"file",
".",
"seek",
"(",
"0",
")",
"return",
"InMemoryUploadedFile",
"(",
"file",
"=",
"self",
".",
"file",
",",
"field... | [
177,
4
] | [
191,
9
] | python | en | ['en', 'en', 'en'] | True |
install_lib.get_outputs | (self) | Return the list of files that would be installed if this command
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet.
| Return the list of files that would be installed if this command
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet.
| def get_outputs(self):
"""Return the list of files that would be installed if this command
were actually run. Not affected by the "dry-run" flag or whether
modules have actually been built yet.
"""
pure_outputs = \
self._mutate_outputs(self.distribution.has_pure_modu... | [
"def",
"get_outputs",
"(",
"self",
")",
":",
"pure_outputs",
"=",
"self",
".",
"_mutate_outputs",
"(",
"self",
".",
"distribution",
".",
"has_pure_modules",
"(",
")",
",",
"'build_py'",
",",
"'build_lib'",
",",
"self",
".",
"install_dir",
")",
"if",
"self",
... | [
179,
4
] | [
198,
60
] | python | en | ['en', 'en', 'en'] | True |
install_lib.get_inputs | (self) | Get the list of files that are input to this command, ie. the
files that get installed as they are named in the build tree.
The files in this list correspond one-to-one to the output
filenames returned by 'get_outputs()'.
| Get the list of files that are input to this command, ie. the
files that get installed as they are named in the build tree.
The files in this list correspond one-to-one to the output
filenames returned by 'get_outputs()'.
| def get_inputs(self):
"""Get the list of files that are input to this command, ie. the
files that get installed as they are named in the build tree.
The files in this list correspond one-to-one to the output
filenames returned by 'get_outputs()'.
"""
inputs = []
... | [
"def",
"get_inputs",
"(",
"self",
")",
":",
"inputs",
"=",
"[",
"]",
"if",
"self",
".",
"distribution",
".",
"has_pure_modules",
"(",
")",
":",
"build_py",
"=",
"self",
".",
"get_finalized_command",
"(",
"'build_py'",
")",
"inputs",
".",
"extend",
"(",
"... | [
200,
4
] | [
216,
21
] | python | en | ['en', 'en', 'en'] | True |
DatabaseFeatures._mysql_storage_engine | (self) | Internal method used in Django tests. Don't rely on this from your code | Internal method used in Django tests. Don't rely on this from your code | def _mysql_storage_engine(self):
"Internal method used in Django tests. Don't rely on this from your code"
with self.connection.cursor() as cursor:
cursor.execute("SELECT ENGINE FROM INFORMATION_SCHEMA.ENGINES WHERE SUPPORT = 'DEFAULT'")
result = cursor.fetchone()
return ... | [
"def",
"_mysql_storage_engine",
"(",
"self",
")",
":",
"with",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT ENGINE FROM INFORMATION_SCHEMA.ENGINES WHERE SUPPORT = 'DEFAULT'\"",
")",
"result",
"=",
... | [
57,
4
] | [
62,
24
] | python | en | ['en', 'en', 'en'] | True |
DatabaseFeatures.can_introspect_foreign_keys | (self) | Confirm support for introspected foreign keys | Confirm support for introspected foreign keys | def can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
return self._mysql_storage_engine != 'MyISAM' | [
"def",
"can_introspect_foreign_keys",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mysql_storage_engine",
"!=",
"'MyISAM'"
] | [
65,
4
] | [
67,
53
] | python | en | ['en', 'en', 'en'] | True |
DatabaseFeatures.supports_transactions | (self) |
All storage engines except MyISAM support transactions.
|
All storage engines except MyISAM support transactions.
| def supports_transactions(self):
"""
All storage engines except MyISAM support transactions.
"""
return self._mysql_storage_engine != 'MyISAM' | [
"def",
"supports_transactions",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mysql_storage_engine",
"!=",
"'MyISAM'"
] | [
121,
4
] | [
125,
53
] | python | en | ['en', 'error', 'th'] | False |
GDALBand._flush | (self) |
Call the flush method on the Band's parent raster and force a refresh
of the statistics attribute when requested the next time.
|
Call the flush method on the Band's parent raster and force a refresh
of the statistics attribute when requested the next time.
| def _flush(self):
"""
Call the flush method on the Band's parent raster and force a refresh
of the statistics attribute when requested the next time.
"""
self.source._flush()
self._stats_refresh = True | [
"def",
"_flush",
"(",
"self",
")",
":",
"self",
".",
"source",
".",
"_flush",
"(",
")",
"self",
".",
"_stats_refresh",
"=",
"True"
] | [
21,
4
] | [
27,
34
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.description | (self) |
Return the description string of the band.
|
Return the description string of the band.
| def description(self):
"""
Return the description string of the band.
"""
return force_str(capi.get_band_description(self._ptr)) | [
"def",
"description",
"(",
"self",
")",
":",
"return",
"force_str",
"(",
"capi",
".",
"get_band_description",
"(",
"self",
".",
"_ptr",
")",
")"
] | [
30,
4
] | [
34,
62
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.width | (self) |
Width (X axis) in pixels of the band.
|
Width (X axis) in pixels of the band.
| def width(self):
"""
Width (X axis) in pixels of the band.
"""
return capi.get_band_xsize(self._ptr) | [
"def",
"width",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_band_xsize",
"(",
"self",
".",
"_ptr",
")"
] | [
37,
4
] | [
41,
45
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.height | (self) |
Height (Y axis) in pixels of the band.
|
Height (Y axis) in pixels of the band.
| def height(self):
"""
Height (Y axis) in pixels of the band.
"""
return capi.get_band_ysize(self._ptr) | [
"def",
"height",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_band_ysize",
"(",
"self",
".",
"_ptr",
")"
] | [
44,
4
] | [
48,
45
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.pixel_count | (self) |
Return the total number of pixels in this band.
|
Return the total number of pixels in this band.
| def pixel_count(self):
"""
Return the total number of pixels in this band.
"""
return self.width * self.height | [
"def",
"pixel_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"width",
"*",
"self",
".",
"height"
] | [
51,
4
] | [
55,
39
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.statistics | (self, refresh=False, approximate=False) |
Compute statistics on the pixel values of this band.
The return value is a tuple with the following structure:
(minimum, maximum, mean, standard deviation).
If approximate=True, the statistics may be computed based on overviews
or a subset of image tiles.
If refresh=T... |
Compute statistics on the pixel values of this band. | def statistics(self, refresh=False, approximate=False):
"""
Compute statistics on the pixel values of this band.
The return value is a tuple with the following structure:
(minimum, maximum, mean, standard deviation).
If approximate=True, the statistics may be computed based on ... | [
"def",
"statistics",
"(",
"self",
",",
"refresh",
"=",
"False",
",",
"approximate",
"=",
"False",
")",
":",
"# Prepare array with arguments for capi function",
"smin",
",",
"smax",
",",
"smean",
",",
"sstd",
"=",
"c_double",
"(",
")",
",",
"c_double",
"(",
"... | [
59,
4
] | [
103,
21
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.min | (self) |
Return the minimum pixel value for this band.
|
Return the minimum pixel value for this band.
| def min(self):
"""
Return the minimum pixel value for this band.
"""
return self.statistics()[0] | [
"def",
"min",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"0",
"]"
] | [
106,
4
] | [
110,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.max | (self) |
Return the maximum pixel value for this band.
|
Return the maximum pixel value for this band.
| def max(self):
"""
Return the maximum pixel value for this band.
"""
return self.statistics()[1] | [
"def",
"max",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"1",
"]"
] | [
113,
4
] | [
117,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.mean | (self) |
Return the mean of all pixel values of this band.
|
Return the mean of all pixel values of this band.
| def mean(self):
"""
Return the mean of all pixel values of this band.
"""
return self.statistics()[2] | [
"def",
"mean",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"2",
"]"
] | [
120,
4
] | [
124,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.std | (self) |
Return the standard deviation of all pixel values of this band.
|
Return the standard deviation of all pixel values of this band.
| def std(self):
"""
Return the standard deviation of all pixel values of this band.
"""
return self.statistics()[3] | [
"def",
"std",
"(",
"self",
")",
":",
"return",
"self",
".",
"statistics",
"(",
")",
"[",
"3",
"]"
] | [
127,
4
] | [
131,
35
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.nodata_value | (self) |
Return the nodata value for this band, or None if it isn't set.
|
Return the nodata value for this band, or None if it isn't set.
| def nodata_value(self):
"""
Return the nodata value for this band, or None if it isn't set.
"""
# Get value and nodata exists flag
nodata_exists = c_int()
value = capi.get_band_nodata_value(self._ptr, nodata_exists)
if not nodata_exists:
value = None
... | [
"def",
"nodata_value",
"(",
"self",
")",
":",
"# Get value and nodata exists flag",
"nodata_exists",
"=",
"c_int",
"(",
")",
"value",
"=",
"capi",
".",
"get_band_nodata_value",
"(",
"self",
".",
"_ptr",
",",
"nodata_exists",
")",
"if",
"not",
"nodata_exists",
":... | [
134,
4
] | [
146,
20
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.nodata_value | (self, value) |
Set the nodata value for this band.
|
Set the nodata value for this band.
| def nodata_value(self, value):
"""
Set the nodata value for this band.
"""
if value is None:
if not capi.delete_band_nodata_value:
raise ValueError('GDAL >= 2.1 required to delete nodata values.')
capi.delete_band_nodata_value(self._ptr)
el... | [
"def",
"nodata_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"not",
"capi",
".",
"delete_band_nodata_value",
":",
"raise",
"ValueError",
"(",
"'GDAL >= 2.1 required to delete nodata values.'",
")",
"capi",
".",
"delete_band_n... | [
149,
4
] | [
161,
21
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.datatype | (self, as_string=False) |
Return the GDAL Pixel Datatype for this band.
|
Return the GDAL Pixel Datatype for this band.
| def datatype(self, as_string=False):
"""
Return the GDAL Pixel Datatype for this band.
"""
dtype = capi.get_band_datatype(self._ptr)
if as_string:
dtype = GDAL_PIXEL_TYPES[dtype]
return dtype | [
"def",
"datatype",
"(",
"self",
",",
"as_string",
"=",
"False",
")",
":",
"dtype",
"=",
"capi",
".",
"get_band_datatype",
"(",
"self",
".",
"_ptr",
")",
"if",
"as_string",
":",
"dtype",
"=",
"GDAL_PIXEL_TYPES",
"[",
"dtype",
"]",
"return",
"dtype"
] | [
163,
4
] | [
170,
20
] | python | en | ['en', 'error', 'th'] | False |
GDALBand.color_interp | (self, as_string=False) | Return the GDAL color interpretation for this band. | Return the GDAL color interpretation for this band. | def color_interp(self, as_string=False):
"""Return the GDAL color interpretation for this band."""
color = capi.get_band_color_interp(self._ptr)
if as_string:
color = GDAL_COLOR_TYPES[color]
return color | [
"def",
"color_interp",
"(",
"self",
",",
"as_string",
"=",
"False",
")",
":",
"color",
"=",
"capi",
".",
"get_band_color_interp",
"(",
"self",
".",
"_ptr",
")",
"if",
"as_string",
":",
"color",
"=",
"GDAL_COLOR_TYPES",
"[",
"color",
"]",
"return",
"color"
... | [
172,
4
] | [
177,
20
] | python | en | ['en', 'en', 'en'] | True |
GDALBand.data | (self, data=None, offset=None, size=None, shape=None, as_memoryview=False) |
Read or writes pixel values for this band. Blocks of data can
be accessed by specifying the width, height and offset of the
desired block. The same specification can be used to update
parts of a raster by providing an array of values.
Allowed input data types are bytes, memoryv... |
Read or writes pixel values for this band. Blocks of data can
be accessed by specifying the width, height and offset of the
desired block. The same specification can be used to update
parts of a raster by providing an array of values. | def data(self, data=None, offset=None, size=None, shape=None, as_memoryview=False):
"""
Read or writes pixel values for this band. Blocks of data can
be accessed by specifying the width, height and offset of the
desired block. The same specification can be used to update
parts of... | [
"def",
"data",
"(",
"self",
",",
"data",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"size",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"as_memoryview",
"=",
"False",
")",
":",
"offset",
"=",
"offset",
"or",
"(",
"0",
",",
"0",
")",
"size",
... | [
179,
4
] | [
232,
25
] | python | en | ['en', 'error', 'th'] | False |
to_genshi | (walker) | Convert a tree to a genshi tree
:arg walker: the treewalker to use to walk the tree to convert it
:returns: generator of genshi nodes
| Convert a tree to a genshi tree | def to_genshi(walker):
"""Convert a tree to a genshi tree
:arg walker: the treewalker to use to walk the tree to convert it
:returns: generator of genshi nodes
"""
text = []
for token in walker:
type = token["type"]
if type in ("Characters", "SpaceCharacters"):
tex... | [
"def",
"to_genshi",
"(",
"walker",
")",
":",
"text",
"=",
"[",
"]",
"for",
"token",
"in",
"walker",
":",
"type",
"=",
"token",
"[",
"\"type\"",
"]",
"if",
"type",
"in",
"(",
"\"Characters\"",
",",
"\"SpaceCharacters\"",
")",
":",
"text",
".",
"append",... | [
6,
0
] | [
53,
49
] | python | en | ['en', 'mk', 'en'] | True |
render_to_response | (*args, **kwargs) |
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
|
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
| def render_to_response(*args, **kwargs):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)}
return HttpResponse(loader.ren... | [
"def",
"render_to_response",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"httpresponse_kwargs",
"=",
"{",
"'content_type'",
":",
"kwargs",
".",
"pop",
"(",
"'content_type'",
",",
"None",
")",
"}",
"return",
"HttpResponse",
"(",
"loader",
".",
"ren... | [
15,
0
] | [
22,
88
] | python | en | ['en', 'error', 'th'] | False |
render | (request, *args, **kwargs) |
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
Uses a RequestContext by default.
|
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
Uses a RequestContext by default.
| def render(request, *args, **kwargs):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
Uses a RequestContext by default.
"""
httpresponse_kwargs = {
'content_type': kwargs.pop('content_type'... | [
"def",
"render",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"httpresponse_kwargs",
"=",
"{",
"'content_type'",
":",
"kwargs",
".",
"pop",
"(",
"'content_type'",
",",
"None",
")",
",",
"'status'",
":",
"kwargs",
".",
"pop",
"("... | [
25,
0
] | [
48,
46
] | python | en | ['en', 'error', 'th'] | False |
redirect | (to, *args, **kwargs) |
Returns an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the nam... |
Returns an HttpResponseRedirect to the appropriate URL for the arguments
passed. | def redirect(to, *args, **kwargs):
"""
Returns an HttpResponseRedirect to the appropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
... | [
"def",
"redirect",
"(",
"to",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"pop",
"(",
"'permanent'",
",",
"False",
")",
":",
"redirect_class",
"=",
"HttpResponsePermanentRedirect",
"else",
":",
"redirect_class",
"=",
"HttpResp... | [
51,
0
] | [
73,
59
] | python | en | ['en', 'error', 'th'] | False |
_get_queryset | (klass) |
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY.
Raises a ValueError if klass is not a Model, Manager, or QuerySet.
|
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY. | def _get_queryset(klass):
"""
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY.
Raises a ValueError if klass is not a Model, Manager, or QuerySet.
"""
if isinstance(klass, QuerySet):
return klass
elif isinstance(kl... | [
"def",
"_get_queryset",
"(",
"klass",
")",
":",
"if",
"isinstance",
"(",
"klass",
",",
"QuerySet",
")",
":",
"return",
"klass",
"elif",
"isinstance",
"(",
"klass",
",",
"Manager",
")",
":",
"manager",
"=",
"klass",
"elif",
"isinstance",
"(",
"klass",
","... | [
76,
0
] | [
96,
24
] | python | en | ['en', 'error', 'th'] | False |
get_object_or_404 | (klass, *args, **kwargs) |
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more tha... |
Uses get() to return an object, or raises a Http404 exception if the object
does not exist. | def get_object_or_404(klass, *args, **kwargs):
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(),... | [
"def",
"get_object_or_404",
"(",
"klass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"_get_queryset",
"(",
"klass",
")",
"try",
":",
"return",
"queryset",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except"... | [
99,
0
] | [
114,
90
] | python | en | ['en', 'error', 'th'] | False |
get_list_or_404 | (klass, *args, **kwargs) |
Uses filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
|
Uses filter() to return a list of objects, or raise a Http404 exception if
the list is empty. | def get_list_or_404(klass, *args, **kwargs):
"""
Uses filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _... | [
"def",
"get_list_or_404",
"(",
"klass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"_get_queryset",
"(",
"klass",
")",
"obj_list",
"=",
"list",
"(",
"queryset",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",... | [
117,
0
] | [
129,
19
] | python | en | ['en', 'error', 'th'] | False |
resolve_url | (to, *args, **kwargs) |
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the name.
* A URL, which will be... |
Return a URL appropriate for the arguments passed. | def resolve_url(to, *args, **kwargs):
"""
Return a URL appropriate for the arguments passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-reso... | [
"def",
"resolve_url",
"(",
"to",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# If it's a model, use get_absolute_url()",
"if",
"hasattr",
"(",
"to",
",",
"'get_absolute_url'",
")",
":",
"return",
"to",
".",
"get_absolute_url",
"(",
")",
"if",
"isin... | [
132,
0
] | [
167,
13
] | python | en | ['en', 'error', 'th'] | False |
staticfiles_urlpatterns | (prefix=None) |
Helper function to return a URL pattern for serving static files.
|
Helper function to return a URL pattern for serving static files.
| def staticfiles_urlpatterns(prefix=None):
"""
Helper function to return a URL pattern for serving static files.
"""
if prefix is None:
prefix = settings.STATIC_URL
return static(prefix, view=serve) | [
"def",
"staticfiles_urlpatterns",
"(",
"prefix",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"settings",
".",
"STATIC_URL",
"return",
"static",
"(",
"prefix",
",",
"view",
"=",
"serve",
")"
] | [
7,
0
] | [
13,
37
] | python | en | ['en', 'error', 'th'] | False |
carlini_wagner_l2 | (
model_fn,
x,
n_classes,
y=None,
targeted=False,
lr=5e-3,
confidence=0,
clip_min=0,
clip_max=1,
initial_const=1e-2,
binary_search_steps=5,
max_iterations=1000,
) |
This attack was originally proposed by Carlini and Wagner. It is an
iterative attack that finds adversarial examples on many defenses that
are robust to other attacks.
Paper link: https://arxiv.org/abs/1608.04644
At a high level, this attack is an iterative attack using Adam and
a specially-ch... |
This attack was originally proposed by Carlini and Wagner. It is an
iterative attack that finds adversarial examples on many defenses that
are robust to other attacks.
Paper link: https://arxiv.org/abs/1608.04644 | def carlini_wagner_l2(
model_fn,
x,
n_classes,
y=None,
targeted=False,
lr=5e-3,
confidence=0,
clip_min=0,
clip_max=1,
initial_const=1e-2,
binary_search_steps=5,
max_iterations=1000,
):
"""
This attack was originally proposed by Carlini and Wagner. It is an
ite... | [
"def",
"carlini_wagner_l2",
"(",
"model_fn",
",",
"x",
",",
"n_classes",
",",
"y",
"=",
"None",
",",
"targeted",
"=",
"False",
",",
"lr",
"=",
"5e-3",
",",
"confidence",
"=",
"0",
",",
"clip_min",
"=",
"0",
",",
"clip_max",
"=",
"1",
",",
"initial_co... | [
7,
0
] | [
197,
32
] | python | en | ['en', 'error', 'th'] | False |
TestTicket14567.test_empty_queryset_return | (self) | If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned. | If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned. | def test_empty_queryset_return(self):
"If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned."
option = ChoiceOptionModel.objects.create(name='default')
form = OptionalMultiChoiceModelForm({'multi_choice_optional': '', 'multi_choice': [option.pk]})
... | [
"def",
"test_empty_queryset_return",
"(",
"self",
")",
":",
"option",
"=",
"ChoiceOptionModel",
".",
"objects",
".",
"create",
"(",
"name",
"=",
"'default'",
")",
"form",
"=",
"OptionalMultiChoiceModelForm",
"(",
"{",
"'multi_choice_optional'",
":",
"''",
",",
"... | [
74,
4
] | [
82,
87
] | python | en | ['en', 'en', 'en'] | True |
ModelFormCallableModelDefault.test_no_empty_option | (self) | If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792). | If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792). | def test_no_empty_option(self):
"If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)."
option = ChoiceOptionModel.objects.create(name='default')
choices = list(ChoiceFieldForm().fields['choice'].choices)
self.assertEqual(len(choices), 1)
... | [
"def",
"test_no_empty_option",
"(",
"self",
")",
":",
"option",
"=",
"ChoiceOptionModel",
".",
"objects",
".",
"create",
"(",
"name",
"=",
"'default'",
")",
"choices",
"=",
"list",
"(",
"ChoiceFieldForm",
"(",
")",
".",
"fields",
"[",
"'choice'",
"]",
".",... | [
86,
4
] | [
92,
72
] | python | en | ['en', 'en', 'en'] | True |
ModelFormCallableModelDefault.test_callable_initial_value | (self) | The initial value for a callable default returning a queryset is the pk (refs #13769) | The initial value for a callable default returning a queryset is the pk (refs #13769) | def test_callable_initial_value(self):
"The initial value for a callable default returning a queryset is the pk (refs #13769)"
ChoiceOptionModel.objects.create(id=1, name='default')
ChoiceOptionModel.objects.create(id=2, name='option 2')
ChoiceOptionModel.objects.create(id=3, name='optio... | [
"def",
"test_callable_initial_value",
"(",
"self",
")",
":",
"ChoiceOptionModel",
".",
"objects",
".",
"create",
"(",
"id",
"=",
"1",
",",
"name",
"=",
"'default'",
")",
"ChoiceOptionModel",
".",
"objects",
".",
"create",
"(",
"id",
"=",
"2",
",",
"name",
... | [
94,
4
] | [
118,
117
] | python | en | ['en', 'en', 'en'] | True |
ModelFormCallableModelDefault.test_initial_instance_value | (self) | Initial instances for model fields may also be instances (refs #7287) | Initial instances for model fields may also be instances (refs #7287) | def test_initial_instance_value(self):
"Initial instances for model fields may also be instances (refs #7287)"
ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option ... | [
"def",
"test_initial_instance_value",
"(",
"self",
")",
":",
"ChoiceOptionModel",
".",
"objects",
".",
"create",
"(",
"id",
"=",
"1",
",",
"name",
"=",
"'default'",
")",
"obj2",
"=",
"ChoiceOptionModel",
".",
"objects",
".",
"create",
"(",
"id",
"=",
"2",
... | [
120,
4
] | [
151,
108
] | python | en | ['en', 'en', 'en'] | True |
RelatedModelFormTests.test_invalid_loading_order | (self) |
Test for issue 10405
|
Test for issue 10405
| def test_invalid_loading_order(self):
"""
Test for issue 10405
"""
class A(models.Model):
ref = models.ForeignKey("B")
class Meta:
model = A
fields = '__all__'
self.assertRaises(ValueError, ModelFormMetaclass, str('Form'), (ModelForm,... | [
"def",
"test_invalid_loading_order",
"(",
"self",
")",
":",
"class",
"A",
"(",
"models",
".",
"Model",
")",
":",
"ref",
"=",
"models",
".",
"ForeignKey",
"(",
"\"B\"",
")",
"class",
"Meta",
":",
"model",
"=",
"A",
"fields",
"=",
"'__all__'",
"self",
".... | [
221,
4
] | [
235,
16
] | python | en | ['en', 'error', 'th'] | False |
RelatedModelFormTests.test_valid_loading_order | (self) |
Test for issue 10405
|
Test for issue 10405
| def test_valid_loading_order(self):
"""
Test for issue 10405
"""
class C(models.Model):
ref = models.ForeignKey("D")
class D(models.Model):
pass
class Meta:
model = C
fields = '__all__'
self.assertTrue(issubclass(... | [
"def",
"test_valid_loading_order",
"(",
"self",
")",
":",
"class",
"C",
"(",
"models",
".",
"Model",
")",
":",
"ref",
"=",
"models",
".",
"ForeignKey",
"(",
"\"D\"",
")",
"class",
"D",
"(",
"models",
".",
"Model",
")",
":",
"pass",
"class",
"Meta",
"... | [
237,
4
] | [
251,
109
] | python | en | ['en', 'error', 'th'] | False |
get_callable | (lookup_view, can_fail=False) |
Return a callable corresponding to lookup_view. This function is used
by both resolve() and reverse(), so can_fail allows the caller to choose
between returning the input as is and raising an exception when the input
string can't be interpreted as an import path.
If lookup_view is already a callab... |
Return a callable corresponding to lookup_view. This function is used
by both resolve() and reverse(), so can_fail allows the caller to choose
between returning the input as is and raising an exception when the input
string can't be interpreted as an import path. | def get_callable(lookup_view, can_fail=False):
"""
Return a callable corresponding to lookup_view. This function is used
by both resolve() and reverse(), so can_fail allows the caller to choose
between returning the input as is and raising an exception when the input
string can't be interpreted as a... | [
"def",
"get_callable",
"(",
"lookup_view",
",",
"can_fail",
"=",
"False",
")",
":",
"if",
"callable",
"(",
"lookup_view",
")",
":",
"return",
"lookup_view",
"mod_name",
",",
"func_name",
"=",
"get_mod_func",
"(",
"lookup_view",
")",
"if",
"not",
"func_name",
... | [
79,
0
] | [
135,
28
] | python | en | ['en', 'error', 'th'] | False |
set_script_prefix | (prefix) |
Sets the script prefix for the current thread.
|
Sets the script prefix for the current thread.
| def set_script_prefix(prefix):
"""
Sets the script prefix for the current thread.
"""
if not prefix.endswith('/'):
prefix += '/'
_prefixes.value = prefix | [
"def",
"set_script_prefix",
"(",
"prefix",
")",
":",
"if",
"not",
"prefix",
".",
"endswith",
"(",
"'/'",
")",
":",
"prefix",
"+=",
"'/'",
"_prefixes",
".",
"value",
"=",
"prefix"
] | [
590,
0
] | [
596,
28
] | python | en | ['en', 'error', 'th'] | False |
get_script_prefix | () |
Returns the currently active script prefix. Useful for client code that
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
|
Returns the currently active script prefix. Useful for client code that
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
| def get_script_prefix():
"""
Returns the currently active script prefix. Useful for client code that
wishes to construct their own URLs manually (although accessing the request
instance is normally going to be a lot cleaner).
"""
return getattr(_prefixes, "value", '/') | [
"def",
"get_script_prefix",
"(",
")",
":",
"return",
"getattr",
"(",
"_prefixes",
",",
"\"value\"",
",",
"'/'",
")"
] | [
599,
0
] | [
605,
43
] | python | en | ['en', 'error', 'th'] | False |
clear_script_prefix | () |
Unsets the script prefix for the current thread.
|
Unsets the script prefix for the current thread.
| def clear_script_prefix():
"""
Unsets the script prefix for the current thread.
"""
try:
del _prefixes.value
except AttributeError:
pass | [
"def",
"clear_script_prefix",
"(",
")",
":",
"try",
":",
"del",
"_prefixes",
".",
"value",
"except",
"AttributeError",
":",
"pass"
] | [
608,
0
] | [
615,
12
] | 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.