Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Storage.path | (self, name) |
Return a local filesystem path where the file can be retrieved using
Python's built-in open() function. Storage systems that can't be
accessed using open() should *not* implement this method.
|
Return a local filesystem path where the file can be retrieved using
Python's built-in open() function. Storage systems that can't be
accessed using open() should *not* implement this method.
| def path(self, name):
"""
Return a local filesystem path where the file can be retrieved using
Python's built-in open() function. Storage systems that can't be
accessed using open() should *not* implement this method.
"""
raise NotImplementedError("This backend doesn't support absolute paths.") | [
"def",
"path",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"This backend doesn't support absolute paths.\"",
")"
] | [
116,
4
] | [
122,
81
] | python | en | ['en', 'error', 'th'] | False |
Storage.delete | (self, name) |
Delete the specified file from the storage system.
|
Delete the specified file from the storage system.
| def delete(self, name):
"""
Delete the specified file from the storage system.
"""
raise NotImplementedError('subclasses of Storage must provide a delete() method') | [
"def",
"delete",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide a delete() method'",
")"
] | [
127,
4
] | [
131,
89
] | python | en | ['en', 'error', 'th'] | False |
Storage.exists | (self, name) |
Return True if a file referenced by the given name already exists in the
storage system, or False if the name is available for a new file.
|
Return True if a file referenced by the given name already exists in the
storage system, or False if the name is available for a new file.
| def exists(self, name):
"""
Return True if a file referenced by the given name already exists in the
storage system, or False if the name is available for a new file.
"""
raise NotImplementedError('subclasses of Storage must provide an exists() method') | [
"def",
"exists",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide an exists() method'",
")"
] | [
133,
4
] | [
138,
90
] | python | en | ['en', 'error', 'th'] | False |
Storage.listdir | (self, path) |
List the contents of the specified path. Return a 2-tuple of lists:
the first item being directories, the second item being files.
|
List the contents of the specified path. Return a 2-tuple of lists:
the first item being directories, the second item being files.
| def listdir(self, path):
"""
List the contents of the specified path. Return a 2-tuple of lists:
the first item being directories, the second item being files.
"""
raise NotImplementedError('subclasses of Storage must provide a listdir() method') | [
"def",
"listdir",
"(",
"self",
",",
"path",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide a listdir() method'",
")"
] | [
140,
4
] | [
145,
90
] | python | en | ['en', 'error', 'th'] | False |
Storage.size | (self, name) |
Return the total size, in bytes, of the file specified by name.
|
Return the total size, in bytes, of the file specified by name.
| def size(self, name):
"""
Return the total size, in bytes, of the file specified by name.
"""
raise NotImplementedError('subclasses of Storage must provide a size() method') | [
"def",
"size",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide a size() method'",
")"
] | [
147,
4
] | [
151,
87
] | python | en | ['en', 'error', 'th'] | False |
Storage.url | (self, name) |
Return an absolute URL where the file's contents can be accessed
directly by a Web browser.
|
Return an absolute URL where the file's contents can be accessed
directly by a Web browser.
| def url(self, name):
"""
Return an absolute URL where the file's contents can be accessed
directly by a Web browser.
"""
raise NotImplementedError('subclasses of Storage must provide a url() method') | [
"def",
"url",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide a url() method'",
")"
] | [
153,
4
] | [
158,
86
] | python | en | ['en', 'error', 'th'] | False |
Storage.get_accessed_time | (self, name) |
Return the last accessed time (as a datetime) of the file specified by
name. The datetime will be timezone-aware if USE_TZ=True.
|
Return the last accessed time (as a datetime) of the file specified by
name. The datetime will be timezone-aware if USE_TZ=True.
| def get_accessed_time(self, name):
"""
Return the last accessed time (as a datetime) of the file specified by
name. The datetime will be timezone-aware if USE_TZ=True.
"""
raise NotImplementedError('subclasses of Storage must provide a get_accessed_time() method') | [
"def",
"get_accessed_time",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide a get_accessed_time() method'",
")"
] | [
160,
4
] | [
165,
100
] | python | en | ['en', 'error', 'th'] | False |
Storage.get_created_time | (self, name) |
Return the creation time (as a datetime) of the file specified by name.
The datetime will be timezone-aware if USE_TZ=True.
|
Return the creation time (as a datetime) of the file specified by name.
The datetime will be timezone-aware if USE_TZ=True.
| def get_created_time(self, name):
"""
Return the creation time (as a datetime) of the file specified by name.
The datetime will be timezone-aware if USE_TZ=True.
"""
raise NotImplementedError('subclasses of Storage must provide a get_created_time() method') | [
"def",
"get_created_time",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide a get_created_time() method'",
")"
] | [
167,
4
] | [
172,
99
] | python | en | ['en', 'error', 'th'] | False |
Storage.get_modified_time | (self, name) |
Return the last modified time (as a datetime) of the file specified by
name. The datetime will be timezone-aware if USE_TZ=True.
|
Return the last modified time (as a datetime) of the file specified by
name. The datetime will be timezone-aware if USE_TZ=True.
| def get_modified_time(self, name):
"""
Return the last modified time (as a datetime) of the file specified by
name. The datetime will be timezone-aware if USE_TZ=True.
"""
raise NotImplementedError('subclasses of Storage must provide a get_modified_time() method') | [
"def",
"get_modified_time",
"(",
"self",
",",
"name",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Storage must provide a get_modified_time() method'",
")"
] | [
174,
4
] | [
179,
100
] | python | en | ['en', 'error', 'th'] | False |
shell | (name: Optional[str] = None, **attrs: Any) | Creates a new :class:`Shell` with a function as callback. This
works otherwise the same as :func:`command` just that the `cls`
parameter is set to :class:`Shell`.
| Creates a new :class:`Shell` with a function as callback. This
works otherwise the same as :func:`command` just that the `cls`
parameter is set to :class:`Shell`.
| def shell(name: Optional[str] = None, **attrs: Any) -> Callable[[F], Shell]:
"""Creates a new :class:`Shell` with a function as callback. This
works otherwise the same as :func:`command` just that the `cls`
parameter is set to :class:`Shell`.
"""
attrs.setdefault('cls', Shell)
return cast(Shell, click.command(name, **attrs)) | [
"def",
"shell",
"(",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"*",
"*",
"attrs",
":",
"Any",
")",
"->",
"Callable",
"[",
"[",
"F",
"]",
",",
"Shell",
"]",
":",
"attrs",
".",
"setdefault",
"(",
"'cls'",
",",
"Shell",
")",
"return",
"cast",
"(",
"Shell",
",",
"click",
".",
"command",
"(",
"name",
",",
"*",
"*",
"attrs",
")",
")"
] | [
15,
0
] | [
21,
52
] | python | en | ['en', 'en', 'en'] | True |
Command.get_input_data | (self, field, message, default=None) |
Override this method if you want to customize data inputs or
validation exceptions.
|
Override this method if you want to customize data inputs or
validation exceptions.
| def get_input_data(self, field, message, default=None):
"""
Override this method if you want to customize data inputs or
validation exceptions.
"""
raw_value = input(message)
if default and raw_value == '':
raw_value = default
try:
val = field.clean(raw_value, None)
except exceptions.ValidationError as e:
self.stderr.write("Error: %s" % '; '.join(e.messages))
val = None
return val | [
"def",
"get_input_data",
"(",
"self",
",",
"field",
",",
"message",
",",
"default",
"=",
"None",
")",
":",
"raw_value",
"=",
"input",
"(",
"message",
")",
"if",
"default",
"and",
"raw_value",
"==",
"''",
":",
"raw_value",
"=",
"default",
"try",
":",
"val",
"=",
"field",
".",
"clean",
"(",
"raw_value",
",",
"None",
")",
"except",
"exceptions",
".",
"ValidationError",
"as",
"e",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"\"Error: %s\"",
"%",
"'; '",
".",
"join",
"(",
"e",
".",
"messages",
")",
")",
"val",
"=",
"None",
"return",
"val"
] | [
203,
4
] | [
217,
18
] | python | en | ['en', 'error', 'th'] | False |
Command._validate_username | (self, username, verbose_field_name, database) | Validate username. If invalid, return a string error message. | Validate username. If invalid, return a string error message. | def _validate_username(self, username, verbose_field_name, database):
"""Validate username. If invalid, return a string error message."""
if self.username_field.unique:
try:
self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
except self.UserModel.DoesNotExist:
pass
else:
return 'Error: That %s is already taken.' % verbose_field_name
if not username:
return '%s cannot be blank.' % capfirst(verbose_field_name)
try:
self.username_field.clean(username, None)
except exceptions.ValidationError as e:
return '; '.join(e.messages) | [
"def",
"_validate_username",
"(",
"self",
",",
"username",
",",
"verbose_field_name",
",",
"database",
")",
":",
"if",
"self",
".",
"username_field",
".",
"unique",
":",
"try",
":",
"self",
".",
"UserModel",
".",
"_default_manager",
".",
"db_manager",
"(",
"database",
")",
".",
"get_by_natural_key",
"(",
"username",
")",
"except",
"self",
".",
"UserModel",
".",
"DoesNotExist",
":",
"pass",
"else",
":",
"return",
"'Error: That %s is already taken.'",
"%",
"verbose_field_name",
"if",
"not",
"username",
":",
"return",
"'%s cannot be blank.'",
"%",
"capfirst",
"(",
"verbose_field_name",
")",
"try",
":",
"self",
".",
"username_field",
".",
"clean",
"(",
"username",
",",
"None",
")",
"except",
"exceptions",
".",
"ValidationError",
"as",
"e",
":",
"return",
"'; '",
".",
"join",
"(",
"e",
".",
"messages",
")"
] | [
229,
4
] | [
243,
40
] | python | en | ['en', 'en', 'en'] | True |
IFDRational.__init__ | (self, value, denominator=1) |
:param value: either an integer numerator, a
float/rational/other number, or an IFDRational
:param denominator: Optional integer denominator
|
:param value: either an integer numerator, a
float/rational/other number, or an IFDRational
:param denominator: Optional integer denominator
| def __init__(self, value, denominator=1):
"""
:param value: either an integer numerator, a
float/rational/other number, or an IFDRational
:param denominator: Optional integer denominator
"""
if isinstance(value, IFDRational):
self._numerator = value.numerator
self._denominator = value.denominator
self._val = value._val
return
if isinstance(value, Fraction):
self._numerator = value.numerator
self._denominator = value.denominator
else:
self._numerator = value
self._denominator = denominator
if denominator == 0:
self._val = float("nan")
elif denominator == 1:
self._val = Fraction(value)
else:
self._val = Fraction(value, denominator) | [
"def",
"__init__",
"(",
"self",
",",
"value",
",",
"denominator",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"IFDRational",
")",
":",
"self",
".",
"_numerator",
"=",
"value",
".",
"numerator",
"self",
".",
"_denominator",
"=",
"value",
".",
"denominator",
"self",
".",
"_val",
"=",
"value",
".",
"_val",
"return",
"if",
"isinstance",
"(",
"value",
",",
"Fraction",
")",
":",
"self",
".",
"_numerator",
"=",
"value",
".",
"numerator",
"self",
".",
"_denominator",
"=",
"value",
".",
"denominator",
"else",
":",
"self",
".",
"_numerator",
"=",
"value",
"self",
".",
"_denominator",
"=",
"denominator",
"if",
"denominator",
"==",
"0",
":",
"self",
".",
"_val",
"=",
"float",
"(",
"\"nan\"",
")",
"elif",
"denominator",
"==",
"1",
":",
"self",
".",
"_val",
"=",
"Fraction",
"(",
"value",
")",
"else",
":",
"self",
".",
"_val",
"=",
"Fraction",
"(",
"value",
",",
"denominator",
")"
] | [
302,
4
] | [
326,
52
] | python | en | ['en', 'error', 'th'] | False |
IFDRational.limit_rational | (self, max_denominator) |
:param max_denominator: Integer, the maximum denominator value
:returns: Tuple of (numerator, denominator)
| def limit_rational(self, max_denominator):
"""
:param max_denominator: Integer, the maximum denominator value
:returns: Tuple of (numerator, denominator)
"""
if self.denominator == 0:
return (self.numerator, self.denominator)
f = self._val.limit_denominator(max_denominator)
return (f.numerator, f.denominator) | [
"def",
"limit_rational",
"(",
"self",
",",
"max_denominator",
")",
":",
"if",
"self",
".",
"denominator",
"==",
"0",
":",
"return",
"(",
"self",
".",
"numerator",
",",
"self",
".",
"denominator",
")",
"f",
"=",
"self",
".",
"_val",
".",
"limit_denominator",
"(",
"max_denominator",
")",
"return",
"(",
"f",
".",
"numerator",
",",
"f",
".",
"denominator",
")"
] | [
336,
4
] | [
347,
43
] | python | en | ['en', 'error', 'th'] | False |
|
ImageFileDirectory_v2.__init__ | (self, ifh=b"II\052\0\0\0\0\0", prefix=None, group=None) | Initialize an ImageFileDirectory.
To construct an ImageFileDirectory from a real file, pass the 8-byte
magic header to the constructor. To only set the endianness, pass it
as the 'prefix' keyword argument.
:param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
endianness.
:param prefix: Override the endianness of the file.
| Initialize an ImageFileDirectory. | def __init__(self, ifh=b"II\052\0\0\0\0\0", prefix=None, group=None):
"""Initialize an ImageFileDirectory.
To construct an ImageFileDirectory from a real file, pass the 8-byte
magic header to the constructor. To only set the endianness, pass it
as the 'prefix' keyword argument.
:param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
endianness.
:param prefix: Override the endianness of the file.
"""
if ifh[:4] not in PREFIXES:
raise SyntaxError(f"not a TIFF file (header {repr(ifh)} not valid)")
self._prefix = prefix if prefix is not None else ifh[:2]
if self._prefix == MM:
self._endian = ">"
elif self._prefix == II:
self._endian = "<"
else:
raise SyntaxError("not a TIFF IFD")
self.group = group
self.tagtype = {}
""" Dictionary of tag types """
self.reset()
(self.next,) = self._unpack("L", ifh[4:])
self._legacy_api = False | [
"def",
"__init__",
"(",
"self",
",",
"ifh",
"=",
"b\"II\\052\\0\\0\\0\\0\\0\"",
",",
"prefix",
"=",
"None",
",",
"group",
"=",
"None",
")",
":",
"if",
"ifh",
"[",
":",
"4",
"]",
"not",
"in",
"PREFIXES",
":",
"raise",
"SyntaxError",
"(",
"f\"not a TIFF file (header {repr(ifh)} not valid)\"",
")",
"self",
".",
"_prefix",
"=",
"prefix",
"if",
"prefix",
"is",
"not",
"None",
"else",
"ifh",
"[",
":",
"2",
"]",
"if",
"self",
".",
"_prefix",
"==",
"MM",
":",
"self",
".",
"_endian",
"=",
"\">\"",
"elif",
"self",
".",
"_prefix",
"==",
"II",
":",
"self",
".",
"_endian",
"=",
"\"<\"",
"else",
":",
"raise",
"SyntaxError",
"(",
"\"not a TIFF IFD\"",
")",
"self",
".",
"group",
"=",
"group",
"self",
".",
"tagtype",
"=",
"{",
"}",
"\"\"\" Dictionary of tag types \"\"\"",
"self",
".",
"reset",
"(",
")",
"(",
"self",
".",
"next",
",",
")",
"=",
"self",
".",
"_unpack",
"(",
"\"L\"",
",",
"ifh",
"[",
"4",
":",
"]",
")",
"self",
".",
"_legacy_api",
"=",
"False"
] | [
470,
4
] | [
495,
32
] | python | en | ['en', 'en', 'en'] | True |
ImageFileDirectory_v2.named | (self) |
:returns: dict of name|key: value
Returns the complete tag dictionary, with named tags where possible.
|
:returns: dict of name|key: value | def named(self):
"""
:returns: dict of name|key: value
Returns the complete tag dictionary, with named tags where possible.
"""
return {
TiffTags.lookup(code, self.group).name: value
for code, value in self.items()
} | [
"def",
"named",
"(",
"self",
")",
":",
"return",
"{",
"TiffTags",
".",
"lookup",
"(",
"code",
",",
"self",
".",
"group",
")",
".",
"name",
":",
"value",
"for",
"code",
",",
"value",
"in",
"self",
".",
"items",
"(",
")",
"}"
] | [
516,
4
] | [
525,
9
] | python | en | ['en', 'error', 'th'] | False |
ImageFileDirectory_v1.from_v2 | (cls, original) | Returns an
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
instance with the same data as is contained in the original
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
instance.
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
| Returns an
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
instance with the same data as is contained in the original
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
instance. | def from_v2(cls, original):
"""Returns an
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
instance with the same data as is contained in the original
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
instance.
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
"""
ifd = cls(prefix=original.prefix)
ifd._tagdata = original._tagdata
ifd.tagtype = original.tagtype
ifd.next = original.next # an indicator for multipage tiffs
return ifd | [
"def",
"from_v2",
"(",
"cls",
",",
"original",
")",
":",
"ifd",
"=",
"cls",
"(",
"prefix",
"=",
"original",
".",
"prefix",
")",
"ifd",
".",
"_tagdata",
"=",
"original",
".",
"_tagdata",
"ifd",
".",
"tagtype",
"=",
"original",
".",
"tagtype",
"ifd",
".",
"next",
"=",
"original",
".",
"next",
"# an indicator for multipage tiffs",
"return",
"ifd"
] | [
942,
4
] | [
957,
18
] | python | en | ['en', 'lb', 'en'] | False |
ImageFileDirectory_v1.to_v2 | (self) | Returns an
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
instance with the same data as is contained in the original
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
instance.
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
| Returns an
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
instance with the same data as is contained in the original
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
instance. | def to_v2(self):
"""Returns an
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
instance with the same data as is contained in the original
:py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
instance.
:returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
"""
ifd = ImageFileDirectory_v2(prefix=self.prefix)
ifd._tagdata = dict(self._tagdata)
ifd.tagtype = dict(self.tagtype)
ifd._tags_v2 = dict(self._tags_v2)
return ifd | [
"def",
"to_v2",
"(",
"self",
")",
":",
"ifd",
"=",
"ImageFileDirectory_v2",
"(",
"prefix",
"=",
"self",
".",
"prefix",
")",
"ifd",
".",
"_tagdata",
"=",
"dict",
"(",
"self",
".",
"_tagdata",
")",
"ifd",
".",
"tagtype",
"=",
"dict",
"(",
"self",
".",
"tagtype",
")",
"ifd",
".",
"_tags_v2",
"=",
"dict",
"(",
"self",
".",
"_tags_v2",
")",
"return",
"ifd"
] | [
959,
4
] | [
974,
18
] | python | en | ['en', 'lb', 'en'] | False |
TiffImageFile.__init__ | (self, fp=None, filename=None) | Image file directory (tag dictionary) | Image file directory (tag dictionary) | def __init__(self, fp=None, filename=None):
self.tag_v2 = None
""" Image file directory (tag dictionary) """
self.tag = None
""" Legacy tag entries """
super().__init__(fp, filename) | [
"def",
"__init__",
"(",
"self",
",",
"fp",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"self",
".",
"tag_v2",
"=",
"None",
"self",
".",
"tag",
"=",
"None",
"\"\"\" Legacy tag entries \"\"\"",
"super",
"(",
")",
".",
"__init__",
"(",
"fp",
",",
"filename",
")"
] | [
1016,
4
] | [
1023,
38
] | python | it | ['it', 'en', 'it'] | True |
TiffImageFile._open | (self) | Open the first image in a TIFF file | Open the first image in a TIFF file | def _open(self):
"""Open the first image in a TIFF file"""
# Header
ifh = self.fp.read(8)
self.tag_v2 = ImageFileDirectory_v2(ifh)
# legacy IFD entries will be filled in later
self.ifd = None
# setup frame pointers
self.__first = self.__next = self.tag_v2.next
self.__frame = -1
self.__fp = self.fp
self._frame_pos = []
self._n_frames = None
logger.debug("*** TiffImageFile._open ***")
logger.debug(f"- __first: {self.__first}")
logger.debug(f"- ifh: {repr(ifh)}") # Use repr to avoid str(bytes)
# and load the first frame
self._seek(0) | [
"def",
"_open",
"(",
"self",
")",
":",
"# Header",
"ifh",
"=",
"self",
".",
"fp",
".",
"read",
"(",
"8",
")",
"self",
".",
"tag_v2",
"=",
"ImageFileDirectory_v2",
"(",
"ifh",
")",
"# legacy IFD entries will be filled in later",
"self",
".",
"ifd",
"=",
"None",
"# setup frame pointers",
"self",
".",
"__first",
"=",
"self",
".",
"__next",
"=",
"self",
".",
"tag_v2",
".",
"next",
"self",
".",
"__frame",
"=",
"-",
"1",
"self",
".",
"__fp",
"=",
"self",
".",
"fp",
"self",
".",
"_frame_pos",
"=",
"[",
"]",
"self",
".",
"_n_frames",
"=",
"None",
"logger",
".",
"debug",
"(",
"\"*** TiffImageFile._open ***\"",
")",
"logger",
".",
"debug",
"(",
"f\"- __first: {self.__first}\"",
")",
"logger",
".",
"debug",
"(",
"f\"- ifh: {repr(ifh)}\"",
")",
"# Use repr to avoid str(bytes)",
"# and load the first frame",
"self",
".",
"_seek",
"(",
"0",
")"
] | [
1025,
4
] | [
1048,
21
] | python | en | ['en', 'en', 'en'] | True |
TiffImageFile.seek | (self, frame) | Select a given frame as current image | Select a given frame as current image | def seek(self, frame):
"""Select a given frame as current image"""
if not self._seek_check(frame):
return
self._seek(frame)
# Create a new core image object on second and
# subsequent frames in the image. Image may be
# different size/mode.
Image._decompression_bomb_check(self.size)
self.im = Image.core.new(self.mode, self.size) | [
"def",
"seek",
"(",
"self",
",",
"frame",
")",
":",
"if",
"not",
"self",
".",
"_seek_check",
"(",
"frame",
")",
":",
"return",
"self",
".",
"_seek",
"(",
"frame",
")",
"# Create a new core image object on second and",
"# subsequent frames in the image. Image may be",
"# different size/mode.",
"Image",
".",
"_decompression_bomb_check",
"(",
"self",
".",
"size",
")",
"self",
".",
"im",
"=",
"Image",
".",
"core",
".",
"new",
"(",
"self",
".",
"mode",
",",
"self",
".",
"size",
")"
] | [
1060,
4
] | [
1069,
54
] | python | en | ['en', 'en', 'en'] | True |
TiffImageFile.tell | (self) | Return the current frame number | Return the current frame number | def tell(self):
"""Return the current frame number"""
return self.__frame | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"self",
".",
"__frame"
] | [
1107,
4
] | [
1109,
27
] | python | en | ['en', 'da', 'en'] | True |
TiffImageFile.getxmp | (self) |
Returns a dictionary containing the XMP tags.
Requires defusedxml to be installed.
:returns: XMP tags in a dictionary.
|
Returns a dictionary containing the XMP tags.
Requires defusedxml to be installed.
:returns: XMP tags in a dictionary.
| def getxmp(self):
"""
Returns a dictionary containing the XMP tags.
Requires defusedxml to be installed.
:returns: XMP tags in a dictionary.
"""
return self._getxmp(self.tag_v2[700]) if 700 in self.tag_v2 else {} | [
"def",
"getxmp",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getxmp",
"(",
"self",
".",
"tag_v2",
"[",
"700",
"]",
")",
"if",
"700",
"in",
"self",
".",
"tag_v2",
"else",
"{",
"}"
] | [
1111,
4
] | [
1117,
75
] | python | en | ['en', 'error', 'th'] | False |
TiffImageFile._load_libtiff | (self) | Overload method triggered when we detect a compressed tiff
Calls out to libtiff | Overload method triggered when we detect a compressed tiff
Calls out to libtiff | def _load_libtiff(self):
"""Overload method triggered when we detect a compressed tiff
Calls out to libtiff"""
Image.Image.load(self)
self.load_prepare()
if not len(self.tile) == 1:
raise OSError("Not exactly one tile")
# (self._compression, (extents tuple),
# 0, (rawmode, self._compression, fp))
extents = self.tile[0][1]
args = list(self.tile[0][3])
# To be nice on memory footprint, if there's a
# file descriptor, use that instead of reading
# into a string in python.
# libtiff closes the file descriptor, so pass in a dup.
try:
fp = hasattr(self.fp, "fileno") and os.dup(self.fp.fileno())
# flush the file descriptor, prevents error on pypy 2.4+
# should also eliminate the need for fp.tell
# in _seek
if hasattr(self.fp, "flush"):
self.fp.flush()
except OSError:
# io.BytesIO have a fileno, but returns an OSError if
# it doesn't use a file descriptor.
fp = False
if fp:
args[2] = fp
decoder = Image._getdecoder(
self.mode, "libtiff", tuple(args), self.decoderconfig
)
try:
decoder.setimage(self.im, extents)
except ValueError as e:
raise OSError("Couldn't set the image") from e
close_self_fp = self._exclusive_fp and not self.is_animated
if hasattr(self.fp, "getvalue"):
# We've got a stringio like thing passed in. Yay for all in memory.
# The decoder needs the entire file in one shot, so there's not
# a lot we can do here other than give it the entire file.
# unless we could do something like get the address of the
# underlying string for stringio.
#
# Rearranging for supporting byteio items, since they have a fileno
# that returns an OSError if there's no underlying fp. Easier to
# deal with here by reordering.
logger.debug("have getvalue. just sending in a string from getvalue")
n, err = decoder.decode(self.fp.getvalue())
elif fp:
# we've got a actual file on disk, pass in the fp.
logger.debug("have fileno, calling fileno version of the decoder.")
if not close_self_fp:
self.fp.seek(0)
# 4 bytes, otherwise the trace might error out
n, err = decoder.decode(b"fpfp")
else:
# we have something else.
logger.debug("don't have fileno or getvalue. just reading")
self.fp.seek(0)
# UNDONE -- so much for that buffer size thing.
n, err = decoder.decode(self.fp.read())
self.tile = []
self.readonly = 0
self.load_end()
# libtiff closed the fp in a, we need to close self.fp, if possible
if close_self_fp:
self.fp.close()
self.fp = None # might be shared
if err < 0:
raise OSError(err)
return Image.Image.load(self) | [
"def",
"_load_libtiff",
"(",
"self",
")",
":",
"Image",
".",
"Image",
".",
"load",
"(",
"self",
")",
"self",
".",
"load_prepare",
"(",
")",
"if",
"not",
"len",
"(",
"self",
".",
"tile",
")",
"==",
"1",
":",
"raise",
"OSError",
"(",
"\"Not exactly one tile\"",
")",
"# (self._compression, (extents tuple),",
"# 0, (rawmode, self._compression, fp))",
"extents",
"=",
"self",
".",
"tile",
"[",
"0",
"]",
"[",
"1",
"]",
"args",
"=",
"list",
"(",
"self",
".",
"tile",
"[",
"0",
"]",
"[",
"3",
"]",
")",
"# To be nice on memory footprint, if there's a",
"# file descriptor, use that instead of reading",
"# into a string in python.",
"# libtiff closes the file descriptor, so pass in a dup.",
"try",
":",
"fp",
"=",
"hasattr",
"(",
"self",
".",
"fp",
",",
"\"fileno\"",
")",
"and",
"os",
".",
"dup",
"(",
"self",
".",
"fp",
".",
"fileno",
"(",
")",
")",
"# flush the file descriptor, prevents error on pypy 2.4+",
"# should also eliminate the need for fp.tell",
"# in _seek",
"if",
"hasattr",
"(",
"self",
".",
"fp",
",",
"\"flush\"",
")",
":",
"self",
".",
"fp",
".",
"flush",
"(",
")",
"except",
"OSError",
":",
"# io.BytesIO have a fileno, but returns an OSError if",
"# it doesn't use a file descriptor.",
"fp",
"=",
"False",
"if",
"fp",
":",
"args",
"[",
"2",
"]",
"=",
"fp",
"decoder",
"=",
"Image",
".",
"_getdecoder",
"(",
"self",
".",
"mode",
",",
"\"libtiff\"",
",",
"tuple",
"(",
"args",
")",
",",
"self",
".",
"decoderconfig",
")",
"try",
":",
"decoder",
".",
"setimage",
"(",
"self",
".",
"im",
",",
"extents",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"OSError",
"(",
"\"Couldn't set the image\"",
")",
"from",
"e",
"close_self_fp",
"=",
"self",
".",
"_exclusive_fp",
"and",
"not",
"self",
".",
"is_animated",
"if",
"hasattr",
"(",
"self",
".",
"fp",
",",
"\"getvalue\"",
")",
":",
"# We've got a stringio like thing passed in. Yay for all in memory.",
"# The decoder needs the entire file in one shot, so there's not",
"# a lot we can do here other than give it the entire file.",
"# unless we could do something like get the address of the",
"# underlying string for stringio.",
"#",
"# Rearranging for supporting byteio items, since they have a fileno",
"# that returns an OSError if there's no underlying fp. Easier to",
"# deal with here by reordering.",
"logger",
".",
"debug",
"(",
"\"have getvalue. just sending in a string from getvalue\"",
")",
"n",
",",
"err",
"=",
"decoder",
".",
"decode",
"(",
"self",
".",
"fp",
".",
"getvalue",
"(",
")",
")",
"elif",
"fp",
":",
"# we've got a actual file on disk, pass in the fp.",
"logger",
".",
"debug",
"(",
"\"have fileno, calling fileno version of the decoder.\"",
")",
"if",
"not",
"close_self_fp",
":",
"self",
".",
"fp",
".",
"seek",
"(",
"0",
")",
"# 4 bytes, otherwise the trace might error out",
"n",
",",
"err",
"=",
"decoder",
".",
"decode",
"(",
"b\"fpfp\"",
")",
"else",
":",
"# we have something else.",
"logger",
".",
"debug",
"(",
"\"don't have fileno or getvalue. just reading\"",
")",
"self",
".",
"fp",
".",
"seek",
"(",
"0",
")",
"# UNDONE -- so much for that buffer size thing.",
"n",
",",
"err",
"=",
"decoder",
".",
"decode",
"(",
"self",
".",
"fp",
".",
"read",
"(",
")",
")",
"self",
".",
"tile",
"=",
"[",
"]",
"self",
".",
"readonly",
"=",
"0",
"self",
".",
"load_end",
"(",
")",
"# libtiff closed the fp in a, we need to close self.fp, if possible",
"if",
"close_self_fp",
":",
"self",
".",
"fp",
".",
"close",
"(",
")",
"self",
".",
"fp",
"=",
"None",
"# might be shared",
"if",
"err",
"<",
"0",
":",
"raise",
"OSError",
"(",
"err",
")",
"return",
"Image",
".",
"Image",
".",
"load",
"(",
"self",
")"
] | [
1144,
4
] | [
1227,
37
] | python | en | ['en', 'en', 'en'] | True |
TiffImageFile._setup | (self) | Setup this image object based on current tags | Setup this image object based on current tags | def _setup(self):
"""Setup this image object based on current tags"""
if 0xBC01 in self.tag_v2:
raise OSError("Windows Media Photo files not yet supported")
# extract relevant tags
self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
# photometric is a required tag, but not everyone is reading
# the specification
photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)
# old style jpeg compression images most certainly are YCbCr
if self._compression == "tiff_jpeg":
photo = 6
fillorder = self.tag_v2.get(FILLORDER, 1)
logger.debug("*** Summary ***")
logger.debug(f"- compression: {self._compression}")
logger.debug(f"- photometric_interpretation: {photo}")
logger.debug(f"- planar_configuration: {self._planar_configuration}")
logger.debug(f"- fill_order: {fillorder}")
logger.debug(f"- YCbCr subsampling: {self.tag.get(530)}")
# size
xsize = int(self.tag_v2.get(IMAGEWIDTH))
ysize = int(self.tag_v2.get(IMAGELENGTH))
self._size = xsize, ysize
logger.debug(f"- size: {self.size}")
sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))
if len(sampleFormat) > 1 and max(sampleFormat) == min(sampleFormat) == 1:
# SAMPLEFORMAT is properly per band, so an RGB image will
# be (1,1,1). But, we don't support per band pixel types,
# and anything more than one band is a uint8. So, just
# take the first element. Revisit this if adding support
# for more exotic images.
sampleFormat = (1,)
bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))
extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())
if photo in (2, 6, 8): # RGB, YCbCr, LAB
bps_count = 3
elif photo == 5: # CMYK
bps_count = 4
else:
bps_count = 1
bps_count += len(extra_tuple)
# Some files have only one value in bps_tuple,
# while should have more. Fix it
if bps_count > len(bps_tuple) and len(bps_tuple) == 1:
bps_tuple = bps_tuple * bps_count
samplesPerPixel = self.tag_v2.get(
SAMPLESPERPIXEL,
3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1,
)
if len(bps_tuple) != samplesPerPixel:
raise SyntaxError("unknown data organization")
# mode: check photometric interpretation and bits per pixel
key = (
self.tag_v2.prefix,
photo,
sampleFormat,
fillorder,
bps_tuple,
extra_tuple,
)
logger.debug(f"format key: {key}")
try:
self.mode, rawmode = OPEN_INFO[key]
except KeyError as e:
logger.debug("- unsupported format")
raise SyntaxError("unknown pixel mode") from e
logger.debug(f"- raw mode: {rawmode}")
logger.debug(f"- pil mode: {self.mode}")
self.info["compression"] = self._compression
xres = self.tag_v2.get(X_RESOLUTION, 1)
yres = self.tag_v2.get(Y_RESOLUTION, 1)
if xres and yres:
resunit = self.tag_v2.get(RESOLUTION_UNIT)
if resunit == 2: # dots per inch
self.info["dpi"] = (xres, yres)
elif resunit == 3: # dots per centimeter. convert to dpi
self.info["dpi"] = (xres * 2.54, yres * 2.54)
elif resunit is None: # used to default to 1, but now 2)
self.info["dpi"] = (xres, yres)
# For backward compatibility,
# we also preserve the old behavior
self.info["resolution"] = xres, yres
else: # No absolute unit of measurement
self.info["resolution"] = xres, yres
# build tile descriptors
x = y = layer = 0
self.tile = []
self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"
if self.use_load_libtiff:
# Decoder expects entire file as one tile.
# There's a buffer size limit in load (64k)
# so large g4 images will fail if we use that
# function.
#
# Setup the one tile for the whole image, then
# use the _load_libtiff function.
# libtiff handles the fillmode for us, so 1;IR should
# actually be 1;I. Including the R double reverses the
# bits, so stripes of the image are reversed. See
# https://github.com/python-pillow/Pillow/issues/279
if fillorder == 2:
# Replace fillorder with fillorder=1
key = key[:3] + (1,) + key[4:]
logger.debug(f"format key: {key}")
# this should always work, since all the
# fillorder==2 modes have a corresponding
# fillorder=1 mode
self.mode, rawmode = OPEN_INFO[key]
# libtiff always returns the bytes in native order.
# we're expecting image byte order. So, if the rawmode
# contains I;16, we need to convert from native to image
# byte order.
if rawmode == "I;16":
rawmode = "I;16N"
if ";16B" in rawmode:
rawmode = rawmode.replace(";16B", ";16N")
if ";16L" in rawmode:
rawmode = rawmode.replace(";16L", ";16N")
# YCbCr images with new jpeg compression with pixels in one plane
# unpacked straight into RGB values
if (
photo == 6
and self._compression == "jpeg"
and self._planar_configuration == 1
):
rawmode = "RGB"
# Offset in the tile tuple is 0, we go from 0,0 to
# w,h, and we only do this once -- eds
a = (rawmode, self._compression, False, self.tag_v2.offset)
self.tile.append(("libtiff", (0, 0, xsize, ysize), 0, a))
elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
# striped image
if STRIPOFFSETS in self.tag_v2:
offsets = self.tag_v2[STRIPOFFSETS]
h = self.tag_v2.get(ROWSPERSTRIP, ysize)
w = self.size[0]
else:
# tiled image
offsets = self.tag_v2[TILEOFFSETS]
w = self.tag_v2.get(322)
h = self.tag_v2.get(323)
for offset in offsets:
if x + w > xsize:
stride = w * sum(bps_tuple) / 8 # bytes per line
else:
stride = 0
tile_rawmode = rawmode
if self._planar_configuration == 2:
# each band on it's own layer
tile_rawmode = rawmode[layer]
# adjust stride width accordingly
stride /= bps_count
a = (tile_rawmode, int(stride), 1)
self.tile.append(
(
self._compression,
(x, y, min(x + w, xsize), min(y + h, ysize)),
offset,
a,
)
)
x = x + w
if x >= self.size[0]:
x, y = 0, y + h
if y >= self.size[1]:
x = y = 0
layer += 1
else:
logger.debug("- unsupported data organization")
raise SyntaxError("unknown data organization")
# Fix up info.
if ICCPROFILE in self.tag_v2:
self.info["icc_profile"] = self.tag_v2[ICCPROFILE]
# fixup palette descriptor
if self.mode in ["P", "PA"]:
palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
self._tile_orientation = self.tag_v2.get(0x0112) | [
"def",
"_setup",
"(",
"self",
")",
":",
"if",
"0xBC01",
"in",
"self",
".",
"tag_v2",
":",
"raise",
"OSError",
"(",
"\"Windows Media Photo files not yet supported\"",
")",
"# extract relevant tags",
"self",
".",
"_compression",
"=",
"COMPRESSION_INFO",
"[",
"self",
".",
"tag_v2",
".",
"get",
"(",
"COMPRESSION",
",",
"1",
")",
"]",
"self",
".",
"_planar_configuration",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"PLANAR_CONFIGURATION",
",",
"1",
")",
"# photometric is a required tag, but not everyone is reading",
"# the specification",
"photo",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"PHOTOMETRIC_INTERPRETATION",
",",
"0",
")",
"# old style jpeg compression images most certainly are YCbCr",
"if",
"self",
".",
"_compression",
"==",
"\"tiff_jpeg\"",
":",
"photo",
"=",
"6",
"fillorder",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"FILLORDER",
",",
"1",
")",
"logger",
".",
"debug",
"(",
"\"*** Summary ***\"",
")",
"logger",
".",
"debug",
"(",
"f\"- compression: {self._compression}\"",
")",
"logger",
".",
"debug",
"(",
"f\"- photometric_interpretation: {photo}\"",
")",
"logger",
".",
"debug",
"(",
"f\"- planar_configuration: {self._planar_configuration}\"",
")",
"logger",
".",
"debug",
"(",
"f\"- fill_order: {fillorder}\"",
")",
"logger",
".",
"debug",
"(",
"f\"- YCbCr subsampling: {self.tag.get(530)}\"",
")",
"# size",
"xsize",
"=",
"int",
"(",
"self",
".",
"tag_v2",
".",
"get",
"(",
"IMAGEWIDTH",
")",
")",
"ysize",
"=",
"int",
"(",
"self",
".",
"tag_v2",
".",
"get",
"(",
"IMAGELENGTH",
")",
")",
"self",
".",
"_size",
"=",
"xsize",
",",
"ysize",
"logger",
".",
"debug",
"(",
"f\"- size: {self.size}\"",
")",
"sampleFormat",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"SAMPLEFORMAT",
",",
"(",
"1",
",",
")",
")",
"if",
"len",
"(",
"sampleFormat",
")",
">",
"1",
"and",
"max",
"(",
"sampleFormat",
")",
"==",
"min",
"(",
"sampleFormat",
")",
"==",
"1",
":",
"# SAMPLEFORMAT is properly per band, so an RGB image will",
"# be (1,1,1). But, we don't support per band pixel types,",
"# and anything more than one band is a uint8. So, just",
"# take the first element. Revisit this if adding support",
"# for more exotic images.",
"sampleFormat",
"=",
"(",
"1",
",",
")",
"bps_tuple",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"BITSPERSAMPLE",
",",
"(",
"1",
",",
")",
")",
"extra_tuple",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"EXTRASAMPLES",
",",
"(",
")",
")",
"if",
"photo",
"in",
"(",
"2",
",",
"6",
",",
"8",
")",
":",
"# RGB, YCbCr, LAB",
"bps_count",
"=",
"3",
"elif",
"photo",
"==",
"5",
":",
"# CMYK",
"bps_count",
"=",
"4",
"else",
":",
"bps_count",
"=",
"1",
"bps_count",
"+=",
"len",
"(",
"extra_tuple",
")",
"# Some files have only one value in bps_tuple,",
"# while should have more. Fix it",
"if",
"bps_count",
">",
"len",
"(",
"bps_tuple",
")",
"and",
"len",
"(",
"bps_tuple",
")",
"==",
"1",
":",
"bps_tuple",
"=",
"bps_tuple",
"*",
"bps_count",
"samplesPerPixel",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"SAMPLESPERPIXEL",
",",
"3",
"if",
"self",
".",
"_compression",
"==",
"\"tiff_jpeg\"",
"and",
"photo",
"in",
"(",
"2",
",",
"6",
")",
"else",
"1",
",",
")",
"if",
"len",
"(",
"bps_tuple",
")",
"!=",
"samplesPerPixel",
":",
"raise",
"SyntaxError",
"(",
"\"unknown data organization\"",
")",
"# mode: check photometric interpretation and bits per pixel",
"key",
"=",
"(",
"self",
".",
"tag_v2",
".",
"prefix",
",",
"photo",
",",
"sampleFormat",
",",
"fillorder",
",",
"bps_tuple",
",",
"extra_tuple",
",",
")",
"logger",
".",
"debug",
"(",
"f\"format key: {key}\"",
")",
"try",
":",
"self",
".",
"mode",
",",
"rawmode",
"=",
"OPEN_INFO",
"[",
"key",
"]",
"except",
"KeyError",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"\"- unsupported format\"",
")",
"raise",
"SyntaxError",
"(",
"\"unknown pixel mode\"",
")",
"from",
"e",
"logger",
".",
"debug",
"(",
"f\"- raw mode: {rawmode}\"",
")",
"logger",
".",
"debug",
"(",
"f\"- pil mode: {self.mode}\"",
")",
"self",
".",
"info",
"[",
"\"compression\"",
"]",
"=",
"self",
".",
"_compression",
"xres",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"X_RESOLUTION",
",",
"1",
")",
"yres",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"Y_RESOLUTION",
",",
"1",
")",
"if",
"xres",
"and",
"yres",
":",
"resunit",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"RESOLUTION_UNIT",
")",
"if",
"resunit",
"==",
"2",
":",
"# dots per inch",
"self",
".",
"info",
"[",
"\"dpi\"",
"]",
"=",
"(",
"xres",
",",
"yres",
")",
"elif",
"resunit",
"==",
"3",
":",
"# dots per centimeter. convert to dpi",
"self",
".",
"info",
"[",
"\"dpi\"",
"]",
"=",
"(",
"xres",
"*",
"2.54",
",",
"yres",
"*",
"2.54",
")",
"elif",
"resunit",
"is",
"None",
":",
"# used to default to 1, but now 2)",
"self",
".",
"info",
"[",
"\"dpi\"",
"]",
"=",
"(",
"xres",
",",
"yres",
")",
"# For backward compatibility,",
"# we also preserve the old behavior",
"self",
".",
"info",
"[",
"\"resolution\"",
"]",
"=",
"xres",
",",
"yres",
"else",
":",
"# No absolute unit of measurement",
"self",
".",
"info",
"[",
"\"resolution\"",
"]",
"=",
"xres",
",",
"yres",
"# build tile descriptors",
"x",
"=",
"y",
"=",
"layer",
"=",
"0",
"self",
".",
"tile",
"=",
"[",
"]",
"self",
".",
"use_load_libtiff",
"=",
"READ_LIBTIFF",
"or",
"self",
".",
"_compression",
"!=",
"\"raw\"",
"if",
"self",
".",
"use_load_libtiff",
":",
"# Decoder expects entire file as one tile.",
"# There's a buffer size limit in load (64k)",
"# so large g4 images will fail if we use that",
"# function.",
"#",
"# Setup the one tile for the whole image, then",
"# use the _load_libtiff function.",
"# libtiff handles the fillmode for us, so 1;IR should",
"# actually be 1;I. Including the R double reverses the",
"# bits, so stripes of the image are reversed. See",
"# https://github.com/python-pillow/Pillow/issues/279",
"if",
"fillorder",
"==",
"2",
":",
"# Replace fillorder with fillorder=1",
"key",
"=",
"key",
"[",
":",
"3",
"]",
"+",
"(",
"1",
",",
")",
"+",
"key",
"[",
"4",
":",
"]",
"logger",
".",
"debug",
"(",
"f\"format key: {key}\"",
")",
"# this should always work, since all the",
"# fillorder==2 modes have a corresponding",
"# fillorder=1 mode",
"self",
".",
"mode",
",",
"rawmode",
"=",
"OPEN_INFO",
"[",
"key",
"]",
"# libtiff always returns the bytes in native order.",
"# we're expecting image byte order. So, if the rawmode",
"# contains I;16, we need to convert from native to image",
"# byte order.",
"if",
"rawmode",
"==",
"\"I;16\"",
":",
"rawmode",
"=",
"\"I;16N\"",
"if",
"\";16B\"",
"in",
"rawmode",
":",
"rawmode",
"=",
"rawmode",
".",
"replace",
"(",
"\";16B\"",
",",
"\";16N\"",
")",
"if",
"\";16L\"",
"in",
"rawmode",
":",
"rawmode",
"=",
"rawmode",
".",
"replace",
"(",
"\";16L\"",
",",
"\";16N\"",
")",
"# YCbCr images with new jpeg compression with pixels in one plane",
"# unpacked straight into RGB values",
"if",
"(",
"photo",
"==",
"6",
"and",
"self",
".",
"_compression",
"==",
"\"jpeg\"",
"and",
"self",
".",
"_planar_configuration",
"==",
"1",
")",
":",
"rawmode",
"=",
"\"RGB\"",
"# Offset in the tile tuple is 0, we go from 0,0 to",
"# w,h, and we only do this once -- eds",
"a",
"=",
"(",
"rawmode",
",",
"self",
".",
"_compression",
",",
"False",
",",
"self",
".",
"tag_v2",
".",
"offset",
")",
"self",
".",
"tile",
".",
"append",
"(",
"(",
"\"libtiff\"",
",",
"(",
"0",
",",
"0",
",",
"xsize",
",",
"ysize",
")",
",",
"0",
",",
"a",
")",
")",
"elif",
"STRIPOFFSETS",
"in",
"self",
".",
"tag_v2",
"or",
"TILEOFFSETS",
"in",
"self",
".",
"tag_v2",
":",
"# striped image",
"if",
"STRIPOFFSETS",
"in",
"self",
".",
"tag_v2",
":",
"offsets",
"=",
"self",
".",
"tag_v2",
"[",
"STRIPOFFSETS",
"]",
"h",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"ROWSPERSTRIP",
",",
"ysize",
")",
"w",
"=",
"self",
".",
"size",
"[",
"0",
"]",
"else",
":",
"# tiled image",
"offsets",
"=",
"self",
".",
"tag_v2",
"[",
"TILEOFFSETS",
"]",
"w",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"322",
")",
"h",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"323",
")",
"for",
"offset",
"in",
"offsets",
":",
"if",
"x",
"+",
"w",
">",
"xsize",
":",
"stride",
"=",
"w",
"*",
"sum",
"(",
"bps_tuple",
")",
"/",
"8",
"# bytes per line",
"else",
":",
"stride",
"=",
"0",
"tile_rawmode",
"=",
"rawmode",
"if",
"self",
".",
"_planar_configuration",
"==",
"2",
":",
"# each band on it's own layer",
"tile_rawmode",
"=",
"rawmode",
"[",
"layer",
"]",
"# adjust stride width accordingly",
"stride",
"/=",
"bps_count",
"a",
"=",
"(",
"tile_rawmode",
",",
"int",
"(",
"stride",
")",
",",
"1",
")",
"self",
".",
"tile",
".",
"append",
"(",
"(",
"self",
".",
"_compression",
",",
"(",
"x",
",",
"y",
",",
"min",
"(",
"x",
"+",
"w",
",",
"xsize",
")",
",",
"min",
"(",
"y",
"+",
"h",
",",
"ysize",
")",
")",
",",
"offset",
",",
"a",
",",
")",
")",
"x",
"=",
"x",
"+",
"w",
"if",
"x",
">=",
"self",
".",
"size",
"[",
"0",
"]",
":",
"x",
",",
"y",
"=",
"0",
",",
"y",
"+",
"h",
"if",
"y",
">=",
"self",
".",
"size",
"[",
"1",
"]",
":",
"x",
"=",
"y",
"=",
"0",
"layer",
"+=",
"1",
"else",
":",
"logger",
".",
"debug",
"(",
"\"- unsupported data organization\"",
")",
"raise",
"SyntaxError",
"(",
"\"unknown data organization\"",
")",
"# Fix up info.",
"if",
"ICCPROFILE",
"in",
"self",
".",
"tag_v2",
":",
"self",
".",
"info",
"[",
"\"icc_profile\"",
"]",
"=",
"self",
".",
"tag_v2",
"[",
"ICCPROFILE",
"]",
"# fixup palette descriptor",
"if",
"self",
".",
"mode",
"in",
"[",
"\"P\"",
",",
"\"PA\"",
"]",
":",
"palette",
"=",
"[",
"o8",
"(",
"b",
"//",
"256",
")",
"for",
"b",
"in",
"self",
".",
"tag_v2",
"[",
"COLORMAP",
"]",
"]",
"self",
".",
"palette",
"=",
"ImagePalette",
".",
"raw",
"(",
"\"RGB;L\"",
",",
"b\"\"",
".",
"join",
"(",
"palette",
")",
")",
"self",
".",
"_tile_orientation",
"=",
"self",
".",
"tag_v2",
".",
"get",
"(",
"0x0112",
")"
] | [
1229,
4
] | [
1435,
56
] | python | en | ['en', 'en', 'en'] | True |
get_path_uid | (path: str) |
Return path's uid.
Does not follow symlinks:
https://github.com/pypa/pip/pull/935#discussion_r5307003
Placed this function in compat due to differences on AIX and
Jython, that should eventually go away.
:raises OSError: When path is a symlink or can't be read.
|
Return path's uid. | def get_path_uid(path: str) -> int:
"""
Return path's uid.
Does not follow symlinks:
https://github.com/pypa/pip/pull/935#discussion_r5307003
Placed this function in compat due to differences on AIX and
Jython, that should eventually go away.
:raises OSError: When path is a symlink or can't be read.
"""
if hasattr(os, "O_NOFOLLOW"):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
file_uid = os.fstat(fd).st_uid
os.close(fd)
else: # AIX and Jython
# WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW
if not os.path.islink(path):
# older versions of Jython don't have `os.fstat`
file_uid = os.stat(path).st_uid
else:
# raise OSError for parity with os.O_NOFOLLOW above
raise OSError(f"{path} is a symlink; Will not return uid for symlinks")
return file_uid | [
"def",
"get_path_uid",
"(",
"path",
":",
"str",
")",
"->",
"int",
":",
"if",
"hasattr",
"(",
"os",
",",
"\"O_NOFOLLOW\"",
")",
":",
"fd",
"=",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_RDONLY",
"|",
"os",
".",
"O_NOFOLLOW",
")",
"file_uid",
"=",
"os",
".",
"fstat",
"(",
"fd",
")",
".",
"st_uid",
"os",
".",
"close",
"(",
"fd",
")",
"else",
":",
"# AIX and Jython",
"# WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW",
"if",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
":",
"# older versions of Jython don't have `os.fstat`",
"file_uid",
"=",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_uid",
"else",
":",
"# raise OSError for parity with os.O_NOFOLLOW above",
"raise",
"OSError",
"(",
"f\"{path} is a symlink; Will not return uid for symlinks\"",
")",
"return",
"file_uid"
] | [
26,
0
] | [
50,
19
] | python | en | ['en', 'error', 'th'] | False |
_proxy_stream | () | Finds the most appropriate error stream for the application. If a
WSGI request is in flight we log to wsgi.errors, otherwise this resolves
to sys.stderr.
| Finds the most appropriate error stream for the application. If a
WSGI request is in flight we log to wsgi.errors, otherwise this resolves
to sys.stderr.
| def _proxy_stream():
"""Finds the most appropriate error stream for the application. If a
WSGI request is in flight we log to wsgi.errors, otherwise this resolves
to sys.stderr.
"""
ctx = _request_ctx_stack.top
if ctx is not None:
return ctx.request.environ['wsgi.errors']
return sys.stderr | [
"def",
"_proxy_stream",
"(",
")",
":",
"ctx",
"=",
"_request_ctx_stack",
".",
"top",
"if",
"ctx",
"is",
"not",
"None",
":",
"return",
"ctx",
".",
"request",
".",
"environ",
"[",
"'wsgi.errors'",
"]",
"return",
"sys",
".",
"stderr"
] | [
31,
0
] | [
39,
21
] | python | en | ['en', 'en', 'en'] | True |
create_logger | (app) | Creates a logger for the given application. This logger works
similar to a regular Python logger but changes the effective logging
level based on the application's debug flag. Furthermore this
function also removes all attached handlers in case there was a
logger with the log name before.
| Creates a logger for the given application. This logger works
similar to a regular Python logger but changes the effective logging
level based on the application's debug flag. Furthermore this
function also removes all attached handlers in case there was a
logger with the log name before.
| def create_logger(app):
"""Creates a logger for the given application. This logger works
similar to a regular Python logger but changes the effective logging
level based on the application's debug flag. Furthermore this
function also removes all attached handlers in case there was a
logger with the log name before.
"""
Logger = getLoggerClass()
class DebugLogger(Logger):
def getEffectiveLevel(self):
if self.level == 0 and app.debug:
return DEBUG
return Logger.getEffectiveLevel(self)
class DebugHandler(StreamHandler):
def emit(self, record):
if app.debug and _should_log_for(app, 'debug'):
StreamHandler.emit(self, record)
class ProductionHandler(StreamHandler):
def emit(self, record):
if not app.debug and _should_log_for(app, 'production'):
StreamHandler.emit(self, record)
debug_handler = DebugHandler()
debug_handler.setLevel(DEBUG)
debug_handler.setFormatter(Formatter(DEBUG_LOG_FORMAT))
prod_handler = ProductionHandler(_proxy_stream)
prod_handler.setLevel(ERROR)
prod_handler.setFormatter(Formatter(PROD_LOG_FORMAT))
logger = getLogger(app.logger_name)
# just in case that was not a new logger, get rid of all the handlers
# already attached to it.
del logger.handlers[:]
logger.__class__ = DebugLogger
logger.addHandler(debug_handler)
logger.addHandler(prod_handler)
# Disable propagation by default
logger.propagate = False
return logger | [
"def",
"create_logger",
"(",
"app",
")",
":",
"Logger",
"=",
"getLoggerClass",
"(",
")",
"class",
"DebugLogger",
"(",
"Logger",
")",
":",
"def",
"getEffectiveLevel",
"(",
"self",
")",
":",
"if",
"self",
".",
"level",
"==",
"0",
"and",
"app",
".",
"debug",
":",
"return",
"DEBUG",
"return",
"Logger",
".",
"getEffectiveLevel",
"(",
"self",
")",
"class",
"DebugHandler",
"(",
"StreamHandler",
")",
":",
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"if",
"app",
".",
"debug",
"and",
"_should_log_for",
"(",
"app",
",",
"'debug'",
")",
":",
"StreamHandler",
".",
"emit",
"(",
"self",
",",
"record",
")",
"class",
"ProductionHandler",
"(",
"StreamHandler",
")",
":",
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"if",
"not",
"app",
".",
"debug",
"and",
"_should_log_for",
"(",
"app",
",",
"'production'",
")",
":",
"StreamHandler",
".",
"emit",
"(",
"self",
",",
"record",
")",
"debug_handler",
"=",
"DebugHandler",
"(",
")",
"debug_handler",
".",
"setLevel",
"(",
"DEBUG",
")",
"debug_handler",
".",
"setFormatter",
"(",
"Formatter",
"(",
"DEBUG_LOG_FORMAT",
")",
")",
"prod_handler",
"=",
"ProductionHandler",
"(",
"_proxy_stream",
")",
"prod_handler",
".",
"setLevel",
"(",
"ERROR",
")",
"prod_handler",
".",
"setFormatter",
"(",
"Formatter",
"(",
"PROD_LOG_FORMAT",
")",
")",
"logger",
"=",
"getLogger",
"(",
"app",
".",
"logger_name",
")",
"# just in case that was not a new logger, get rid of all the handlers",
"# already attached to it.",
"del",
"logger",
".",
"handlers",
"[",
":",
"]",
"logger",
".",
"__class__",
"=",
"DebugLogger",
"logger",
".",
"addHandler",
"(",
"debug_handler",
")",
"logger",
".",
"addHandler",
"(",
"prod_handler",
")",
"# Disable propagation by default",
"logger",
".",
"propagate",
"=",
"False",
"return",
"logger"
] | [
49,
0
] | [
93,
17
] | python | en | ['en', 'en', 'en'] | True |
OracleSpatialAdapter.__init__ | (self, geom) |
Oracle requires that polygon rings are in proper orientation. This
affects spatial operations and an invalid orientation may cause
failures. Correct orientations are:
* Outer ring - counter clockwise
* Inner ring(s) - clockwise
|
Oracle requires that polygon rings are in proper orientation. This
affects spatial operations and an invalid orientation may cause
failures. Correct orientations are:
* Outer ring - counter clockwise
* Inner ring(s) - clockwise
| def __init__(self, geom):
"""
Oracle requires that polygon rings are in proper orientation. This
affects spatial operations and an invalid orientation may cause
failures. Correct orientations are:
* Outer ring - counter clockwise
* Inner ring(s) - clockwise
"""
if isinstance(geom, Polygon):
if self._polygon_must_be_fixed(geom):
geom = self._fix_polygon(geom)
elif isinstance(geom, GeometryCollection):
if any(isinstance(g, Polygon) and self._polygon_must_be_fixed(g) for g in geom):
geom = self._fix_geometry_collection(geom)
self.wkt = geom.wkt
self.srid = geom.srid | [
"def",
"__init__",
"(",
"self",
",",
"geom",
")",
":",
"if",
"isinstance",
"(",
"geom",
",",
"Polygon",
")",
":",
"if",
"self",
".",
"_polygon_must_be_fixed",
"(",
"geom",
")",
":",
"geom",
"=",
"self",
".",
"_fix_polygon",
"(",
"geom",
")",
"elif",
"isinstance",
"(",
"geom",
",",
"GeometryCollection",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"g",
",",
"Polygon",
")",
"and",
"self",
".",
"_polygon_must_be_fixed",
"(",
"g",
")",
"for",
"g",
"in",
"geom",
")",
":",
"geom",
"=",
"self",
".",
"_fix_geometry_collection",
"(",
"geom",
")",
"self",
".",
"wkt",
"=",
"geom",
".",
"wkt",
"self",
".",
"srid",
"=",
"geom",
".",
"srid"
] | [
9,
4
] | [
25,
29
] | python | en | ['en', 'error', 'th'] | False |
OracleSpatialAdapter._fix_polygon | (cls, poly, clone=True) | Fix single polygon orientation as described in __init__(). | Fix single polygon orientation as described in __init__(). | def _fix_polygon(cls, poly, clone=True):
"""Fix single polygon orientation as described in __init__()."""
if clone:
poly = poly.clone()
if not poly.exterior_ring.is_counterclockwise:
poly.exterior_ring = list(reversed(poly.exterior_ring))
for i in range(1, len(poly)):
if poly[i].is_counterclockwise:
poly[i] = list(reversed(poly[i]))
return poly | [
"def",
"_fix_polygon",
"(",
"cls",
",",
"poly",
",",
"clone",
"=",
"True",
")",
":",
"if",
"clone",
":",
"poly",
"=",
"poly",
".",
"clone",
"(",
")",
"if",
"not",
"poly",
".",
"exterior_ring",
".",
"is_counterclockwise",
":",
"poly",
".",
"exterior_ring",
"=",
"list",
"(",
"reversed",
"(",
"poly",
".",
"exterior_ring",
")",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"poly",
")",
")",
":",
"if",
"poly",
"[",
"i",
"]",
".",
"is_counterclockwise",
":",
"poly",
"[",
"i",
"]",
"=",
"list",
"(",
"reversed",
"(",
"poly",
"[",
"i",
"]",
")",
")",
"return",
"poly"
] | [
38,
4
] | [
50,
19
] | python | en | ['en', 'es', 'en'] | True |
OracleSpatialAdapter._fix_geometry_collection | (cls, coll) |
Fix polygon orientations in geometry collections as described in
__init__().
|
Fix polygon orientations in geometry collections as described in
__init__().
| def _fix_geometry_collection(cls, coll):
"""
Fix polygon orientations in geometry collections as described in
__init__().
"""
coll = coll.clone()
for i, geom in enumerate(coll):
if isinstance(geom, Polygon):
coll[i] = cls._fix_polygon(geom, clone=False)
return coll | [
"def",
"_fix_geometry_collection",
"(",
"cls",
",",
"coll",
")",
":",
"coll",
"=",
"coll",
".",
"clone",
"(",
")",
"for",
"i",
",",
"geom",
"in",
"enumerate",
"(",
"coll",
")",
":",
"if",
"isinstance",
"(",
"geom",
",",
"Polygon",
")",
":",
"coll",
"[",
"i",
"]",
"=",
"cls",
".",
"_fix_polygon",
"(",
"geom",
",",
"clone",
"=",
"False",
")",
"return",
"coll"
] | [
53,
4
] | [
62,
19
] | python | en | ['en', 'error', 'th'] | False |
_get | (
d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None
) | Get value from dictionary and verify expected type. | Get value from dictionary and verify expected type. | def _get(
d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None
) -> Optional[T]:
"""Get value from dictionary and verify expected type."""
if key not in d:
return default
value = d[key]
if not isinstance(value, expected_type):
raise DirectUrlValidationError(
"{!r} has unexpected type for {} (expected {})".format(
value, key, expected_type
)
)
return value | [
"def",
"_get",
"(",
"d",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"expected_type",
":",
"Type",
"[",
"T",
"]",
",",
"key",
":",
"str",
",",
"default",
":",
"Optional",
"[",
"T",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"T",
"]",
":",
"if",
"key",
"not",
"in",
"d",
":",
"return",
"default",
"value",
"=",
"d",
"[",
"key",
"]",
"if",
"not",
"isinstance",
"(",
"value",
",",
"expected_type",
")",
":",
"raise",
"DirectUrlValidationError",
"(",
"\"{!r} has unexpected type for {} (expected {})\"",
".",
"format",
"(",
"value",
",",
"key",
",",
"expected_type",
")",
")",
"return",
"value"
] | [
24,
0
] | [
37,
16
] | python | en | ['en', 'en', 'en'] | True |
_filter_none | (**kwargs: Any) | Make dict excluding None values. | Make dict excluding None values. | def _filter_none(**kwargs: Any) -> Dict[str, Any]:
"""Make dict excluding None values."""
return {k: v for k, v in kwargs.items() if v is not None} | [
"def",
"_filter_none",
"(",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}"
] | [
63,
0
] | [
65,
61
] | python | en | ['en', 'en', 'en'] | True |
DirectUrl.redacted_url | (self) | url with user:password part removed unless it is formed with
environment variables as specified in PEP 610, or it is ``git``
in the case of a git URL.
| url with user:password part removed unless it is formed with
environment variables as specified in PEP 610, or it is ``git``
in the case of a git URL.
| def redacted_url(self) -> str:
"""url with user:password part removed unless it is formed with
environment variables as specified in PEP 610, or it is ``git``
in the case of a git URL.
"""
purl = urllib.parse.urlsplit(self.url)
netloc = self._remove_auth_from_netloc(purl.netloc)
surl = urllib.parse.urlunsplit(
(purl.scheme, netloc, purl.path, purl.query, purl.fragment)
)
return surl | [
"def",
"redacted_url",
"(",
"self",
")",
"->",
"str",
":",
"purl",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"self",
".",
"url",
")",
"netloc",
"=",
"self",
".",
"_remove_auth_from_netloc",
"(",
"purl",
".",
"netloc",
")",
"surl",
"=",
"urllib",
".",
"parse",
".",
"urlunsplit",
"(",
"(",
"purl",
".",
"scheme",
",",
"netloc",
",",
"purl",
".",
"path",
",",
"purl",
".",
"query",
",",
"purl",
".",
"fragment",
")",
")",
"return",
"surl"
] | [
177,
4
] | [
187,
19
] | python | en | ['en', 'en', 'en'] | True |
check_requires_python | (requires_python, version_info) |
Check if the given Python version matches a "Requires-Python" specifier.
:param version_info: A 3-tuple of ints representing a Python
major-minor-micro version to check (e.g. `sys.version_info[:3]`).
:return: `True` if the given Python version satisfies the requirement.
Otherwise, return `False`.
:raises InvalidSpecifier: If `requires_python` has an invalid format.
|
Check if the given Python version matches a "Requires-Python" specifier. | def check_requires_python(requires_python, version_info):
# type: (Optional[str], Tuple[int, ...]) -> bool
"""
Check if the given Python version matches a "Requires-Python" specifier.
:param version_info: A 3-tuple of ints representing a Python
major-minor-micro version to check (e.g. `sys.version_info[:3]`).
:return: `True` if the given Python version satisfies the requirement.
Otherwise, return `False`.
:raises InvalidSpecifier: If `requires_python` has an invalid format.
"""
if requires_python is None:
# The package provides no information
return True
requires_python_specifier = specifiers.SpecifierSet(requires_python)
python_version = version.parse(".".join(map(str, version_info)))
return python_version in requires_python_specifier | [
"def",
"check_requires_python",
"(",
"requires_python",
",",
"version_info",
")",
":",
"# type: (Optional[str], Tuple[int, ...]) -> bool",
"if",
"requires_python",
"is",
"None",
":",
"# The package provides no information",
"return",
"True",
"requires_python_specifier",
"=",
"specifiers",
".",
"SpecifierSet",
"(",
"requires_python",
")",
"python_version",
"=",
"version",
".",
"parse",
"(",
"\".\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"version_info",
")",
")",
")",
"return",
"python_version",
"in",
"requires_python_specifier"
] | [
15,
0
] | [
34,
54
] | python | en | ['en', 'error', 'th'] | False |
get_metadata | (dist) |
:raises NoneMetadataError: if the distribution reports `has_metadata()`
True but `get_metadata()` returns None.
|
:raises NoneMetadataError: if the distribution reports `has_metadata()`
True but `get_metadata()` returns None.
| def get_metadata(dist):
# type: (Distribution) -> Message
"""
:raises NoneMetadataError: if the distribution reports `has_metadata()`
True but `get_metadata()` returns None.
"""
metadata_name = "METADATA"
if isinstance(dist, pkg_resources.DistInfoDistribution) and dist.has_metadata(
metadata_name
):
metadata = dist.get_metadata(metadata_name)
elif dist.has_metadata("PKG-INFO"):
metadata_name = "PKG-INFO"
metadata = dist.get_metadata(metadata_name)
else:
logger.warning("No metadata found in %s", display_path(dist.location))
metadata = ""
if metadata is None:
raise NoneMetadataError(dist, metadata_name)
feed_parser = FeedParser()
# The following line errors out if with a "NoneType" TypeError if
# passed metadata=None.
feed_parser.feed(metadata)
return feed_parser.close() | [
"def",
"get_metadata",
"(",
"dist",
")",
":",
"# type: (Distribution) -> Message",
"metadata_name",
"=",
"\"METADATA\"",
"if",
"isinstance",
"(",
"dist",
",",
"pkg_resources",
".",
"DistInfoDistribution",
")",
"and",
"dist",
".",
"has_metadata",
"(",
"metadata_name",
")",
":",
"metadata",
"=",
"dist",
".",
"get_metadata",
"(",
"metadata_name",
")",
"elif",
"dist",
".",
"has_metadata",
"(",
"\"PKG-INFO\"",
")",
":",
"metadata_name",
"=",
"\"PKG-INFO\"",
"metadata",
"=",
"dist",
".",
"get_metadata",
"(",
"metadata_name",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"\"No metadata found in %s\"",
",",
"display_path",
"(",
"dist",
".",
"location",
")",
")",
"metadata",
"=",
"\"\"",
"if",
"metadata",
"is",
"None",
":",
"raise",
"NoneMetadataError",
"(",
"dist",
",",
"metadata_name",
")",
"feed_parser",
"=",
"FeedParser",
"(",
")",
"# The following line errors out if with a \"NoneType\" TypeError if",
"# passed metadata=None.",
"feed_parser",
".",
"feed",
"(",
"metadata",
")",
"return",
"feed_parser",
".",
"close",
"(",
")"
] | [
37,
0
] | [
62,
30
] | python | en | ['en', 'error', 'th'] | False |
get_requires_python | (dist) |
Return the "Requires-Python" metadata for a distribution, or None
if not present.
|
Return the "Requires-Python" metadata for a distribution, or None
if not present.
| def get_requires_python(dist):
# type: (pkg_resources.Distribution) -> Optional[str]
"""
Return the "Requires-Python" metadata for a distribution, or None
if not present.
"""
pkg_info_dict = get_metadata(dist)
requires_python = pkg_info_dict.get("Requires-Python")
if requires_python is not None:
# Convert to a str to satisfy the type checker, since requires_python
# can be a Header object.
requires_python = str(requires_python)
return requires_python | [
"def",
"get_requires_python",
"(",
"dist",
")",
":",
"# type: (pkg_resources.Distribution) -> Optional[str]",
"pkg_info_dict",
"=",
"get_metadata",
"(",
"dist",
")",
"requires_python",
"=",
"pkg_info_dict",
".",
"get",
"(",
"\"Requires-Python\"",
")",
"if",
"requires_python",
"is",
"not",
"None",
":",
"# Convert to a str to satisfy the type checker, since requires_python",
"# can be a Header object.",
"requires_python",
"=",
"str",
"(",
"requires_python",
")",
"return",
"requires_python"
] | [
65,
0
] | [
79,
26
] | python | en | ['en', 'error', 'th'] | False |
build_instance | (Model, data, db) |
Build a model instance.
If the model instance doesn't have a primary key and the model supports
natural keys, try to retrieve it from the database.
|
Build a model instance. | def build_instance(Model, data, db):
"""
Build a model instance.
If the model instance doesn't have a primary key and the model supports
natural keys, try to retrieve it from the database.
"""
default_manager = Model._meta.default_manager
pk = data.get(Model._meta.pk.attname)
if (pk is None and hasattr(default_manager, 'get_by_natural_key') and
hasattr(Model, 'natural_key')):
natural_key = Model(**data).natural_key()
try:
data[Model._meta.pk.attname] = Model._meta.pk.to_python(
default_manager.db_manager(db).get_by_natural_key(*natural_key).pk
)
except Model.DoesNotExist:
pass
return Model(**data) | [
"def",
"build_instance",
"(",
"Model",
",",
"data",
",",
"db",
")",
":",
"default_manager",
"=",
"Model",
".",
"_meta",
".",
"default_manager",
"pk",
"=",
"data",
".",
"get",
"(",
"Model",
".",
"_meta",
".",
"pk",
".",
"attname",
")",
"if",
"(",
"pk",
"is",
"None",
"and",
"hasattr",
"(",
"default_manager",
",",
"'get_by_natural_key'",
")",
"and",
"hasattr",
"(",
"Model",
",",
"'natural_key'",
")",
")",
":",
"natural_key",
"=",
"Model",
"(",
"*",
"*",
"data",
")",
".",
"natural_key",
"(",
")",
"try",
":",
"data",
"[",
"Model",
".",
"_meta",
".",
"pk",
".",
"attname",
"]",
"=",
"Model",
".",
"_meta",
".",
"pk",
".",
"to_python",
"(",
"default_manager",
".",
"db_manager",
"(",
"db",
")",
".",
"get_by_natural_key",
"(",
"*",
"natural_key",
")",
".",
"pk",
")",
"except",
"Model",
".",
"DoesNotExist",
":",
"pass",
"return",
"Model",
"(",
"*",
"*",
"data",
")"
] | [
251,
0
] | [
269,
24
] | python | en | ['en', 'error', 'th'] | False |
DeserializationError.WithData | (cls, original_exc, model, fk, field_value) |
Factory method for creating a deserialization error which has a more
explanatory message.
|
Factory method for creating a deserialization error which has a more
explanatory message.
| def WithData(cls, original_exc, model, fk, field_value):
"""
Factory method for creating a deserialization error which has a more
explanatory message.
"""
return cls("%s: (%s:pk=%s) field_value was '%s'" % (original_exc, model, fk, field_value)) | [
"def",
"WithData",
"(",
"cls",
",",
"original_exc",
",",
"model",
",",
"fk",
",",
"field_value",
")",
":",
"return",
"cls",
"(",
"\"%s: (%s:pk=%s) field_value was '%s'\"",
"%",
"(",
"original_exc",
",",
"model",
",",
"fk",
",",
"field_value",
")",
")"
] | [
25,
4
] | [
30,
98
] | python | en | ['en', 'error', 'th'] | False |
Serializer.serialize | (self, queryset, *, stream=None, fields=None, use_natural_foreign_keys=False,
use_natural_primary_keys=False, progress_output=None, object_count=0, **options) |
Serialize a queryset.
|
Serialize a queryset.
| def serialize(self, queryset, *, stream=None, fields=None, use_natural_foreign_keys=False,
use_natural_primary_keys=False, progress_output=None, object_count=0, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = stream if stream is not None else self.stream_class()
self.selected_fields = fields
self.use_natural_foreign_keys = use_natural_foreign_keys
self.use_natural_primary_keys = use_natural_primary_keys
progress_bar = self.progress_class(progress_output, object_count)
self.start_serialization()
self.first = True
for count, obj in enumerate(queryset, start=1):
self.start_object(obj)
# Use the concrete parent class' _meta instead of the object's _meta
# This is to avoid local_fields problems for proxy models. Refs #17717.
concrete_model = obj._meta.concrete_model
# When using natural primary keys, retrieve the pk field of the
# parent for multi-table inheritance child models. That field must
# be serialized, otherwise deserialization isn't possible.
if self.use_natural_primary_keys:
pk = concrete_model._meta.pk
pk_parent = pk if pk.remote_field and pk.remote_field.parent_link else None
else:
pk_parent = None
for field in concrete_model._meta.local_fields:
if field.serialize or field is pk_parent:
if field.remote_field is None:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_field(obj, field)
else:
if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
self.handle_fk_field(obj, field)
for field in concrete_model._meta.local_many_to_many:
if field.serialize:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_m2m_field(obj, field)
self.end_object(obj)
progress_bar.update(count)
self.first = self.first and False
self.end_serialization()
return self.getvalue() | [
"def",
"serialize",
"(",
"self",
",",
"queryset",
",",
"*",
",",
"stream",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"use_natural_foreign_keys",
"=",
"False",
",",
"use_natural_primary_keys",
"=",
"False",
",",
"progress_output",
"=",
"None",
",",
"object_count",
"=",
"0",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"options",
"=",
"options",
"self",
".",
"stream",
"=",
"stream",
"if",
"stream",
"is",
"not",
"None",
"else",
"self",
".",
"stream_class",
"(",
")",
"self",
".",
"selected_fields",
"=",
"fields",
"self",
".",
"use_natural_foreign_keys",
"=",
"use_natural_foreign_keys",
"self",
".",
"use_natural_primary_keys",
"=",
"use_natural_primary_keys",
"progress_bar",
"=",
"self",
".",
"progress_class",
"(",
"progress_output",
",",
"object_count",
")",
"self",
".",
"start_serialization",
"(",
")",
"self",
".",
"first",
"=",
"True",
"for",
"count",
",",
"obj",
"in",
"enumerate",
"(",
"queryset",
",",
"start",
"=",
"1",
")",
":",
"self",
".",
"start_object",
"(",
"obj",
")",
"# Use the concrete parent class' _meta instead of the object's _meta",
"# This is to avoid local_fields problems for proxy models. Refs #17717.",
"concrete_model",
"=",
"obj",
".",
"_meta",
".",
"concrete_model",
"# When using natural primary keys, retrieve the pk field of the",
"# parent for multi-table inheritance child models. That field must",
"# be serialized, otherwise deserialization isn't possible.",
"if",
"self",
".",
"use_natural_primary_keys",
":",
"pk",
"=",
"concrete_model",
".",
"_meta",
".",
"pk",
"pk_parent",
"=",
"pk",
"if",
"pk",
".",
"remote_field",
"and",
"pk",
".",
"remote_field",
".",
"parent_link",
"else",
"None",
"else",
":",
"pk_parent",
"=",
"None",
"for",
"field",
"in",
"concrete_model",
".",
"_meta",
".",
"local_fields",
":",
"if",
"field",
".",
"serialize",
"or",
"field",
"is",
"pk_parent",
":",
"if",
"field",
".",
"remote_field",
"is",
"None",
":",
"if",
"self",
".",
"selected_fields",
"is",
"None",
"or",
"field",
".",
"attname",
"in",
"self",
".",
"selected_fields",
":",
"self",
".",
"handle_field",
"(",
"obj",
",",
"field",
")",
"else",
":",
"if",
"self",
".",
"selected_fields",
"is",
"None",
"or",
"field",
".",
"attname",
"[",
":",
"-",
"3",
"]",
"in",
"self",
".",
"selected_fields",
":",
"self",
".",
"handle_fk_field",
"(",
"obj",
",",
"field",
")",
"for",
"field",
"in",
"concrete_model",
".",
"_meta",
".",
"local_many_to_many",
":",
"if",
"field",
".",
"serialize",
":",
"if",
"self",
".",
"selected_fields",
"is",
"None",
"or",
"field",
".",
"attname",
"in",
"self",
".",
"selected_fields",
":",
"self",
".",
"handle_m2m_field",
"(",
"obj",
",",
"field",
")",
"self",
".",
"end_object",
"(",
"obj",
")",
"progress_bar",
".",
"update",
"(",
"count",
")",
"self",
".",
"first",
"=",
"self",
".",
"first",
"and",
"False",
"self",
".",
"end_serialization",
"(",
")",
"return",
"self",
".",
"getvalue",
"(",
")"
] | [
74,
4
] | [
118,
30
] | python | en | ['en', 'error', 'th'] | False |
Serializer.start_serialization | (self) |
Called when serializing of the queryset starts.
|
Called when serializing of the queryset starts.
| def start_serialization(self):
"""
Called when serializing of the queryset starts.
"""
raise NotImplementedError('subclasses of Serializer must provide a start_serialization() method') | [
"def",
"start_serialization",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Serializer must provide a start_serialization() method'",
")"
] | [
120,
4
] | [
124,
105
] | python | en | ['en', 'error', 'th'] | False |
Serializer.end_serialization | (self) |
Called when serializing of the queryset ends.
|
Called when serializing of the queryset ends.
| def end_serialization(self):
"""
Called when serializing of the queryset ends.
"""
pass | [
"def",
"end_serialization",
"(",
"self",
")",
":",
"pass"
] | [
126,
4
] | [
130,
12
] | python | en | ['en', 'error', 'th'] | False |
Serializer.start_object | (self, obj) |
Called when serializing of an object starts.
|
Called when serializing of an object starts.
| def start_object(self, obj):
"""
Called when serializing of an object starts.
"""
raise NotImplementedError('subclasses of Serializer must provide a start_object() method') | [
"def",
"start_object",
"(",
"self",
",",
"obj",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Serializer must provide a start_object() method'",
")"
] | [
132,
4
] | [
136,
98
] | python | en | ['en', 'error', 'th'] | False |
Serializer.end_object | (self, obj) |
Called when serializing of an object ends.
|
Called when serializing of an object ends.
| def end_object(self, obj):
"""
Called when serializing of an object ends.
"""
pass | [
"def",
"end_object",
"(",
"self",
",",
"obj",
")",
":",
"pass"
] | [
138,
4
] | [
142,
12
] | python | en | ['en', 'error', 'th'] | False |
Serializer.handle_field | (self, obj, field) |
Called to handle each individual (non-relational) field on an object.
|
Called to handle each individual (non-relational) field on an object.
| def handle_field(self, obj, field):
"""
Called to handle each individual (non-relational) field on an object.
"""
raise NotImplementedError('subclasses of Serializer must provide a handle_field() method') | [
"def",
"handle_field",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Serializer must provide a handle_field() method'",
")"
] | [
144,
4
] | [
148,
98
] | python | en | ['en', 'error', 'th'] | False |
Serializer.handle_fk_field | (self, obj, field) |
Called to handle a ForeignKey field.
|
Called to handle a ForeignKey field.
| def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey field.
"""
raise NotImplementedError('subclasses of Serializer must provide a handle_fk_field() method') | [
"def",
"handle_fk_field",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Serializer must provide a handle_fk_field() method'",
")"
] | [
150,
4
] | [
154,
101
] | python | en | ['en', 'error', 'th'] | False |
Serializer.handle_m2m_field | (self, obj, field) |
Called to handle a ManyToManyField.
|
Called to handle a ManyToManyField.
| def handle_m2m_field(self, obj, field):
"""
Called to handle a ManyToManyField.
"""
raise NotImplementedError('subclasses of Serializer must provide a handle_m2m_field() method') | [
"def",
"handle_m2m_field",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Serializer must provide a handle_m2m_field() method'",
")"
] | [
156,
4
] | [
160,
102
] | python | en | ['en', 'error', 'th'] | False |
Serializer.getvalue | (self) |
Return the fully serialized queryset (or None if the output stream is
not seekable).
|
Return the fully serialized queryset (or None if the output stream is
not seekable).
| def getvalue(self):
"""
Return the fully serialized queryset (or None if the output stream is
not seekable).
"""
if callable(getattr(self.stream, 'getvalue', None)):
return self.stream.getvalue() | [
"def",
"getvalue",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"getattr",
"(",
"self",
".",
"stream",
",",
"'getvalue'",
",",
"None",
")",
")",
":",
"return",
"self",
".",
"stream",
".",
"getvalue",
"(",
")"
] | [
162,
4
] | [
168,
41
] | python | en | ['en', 'error', 'th'] | False |
Deserializer.__init__ | (self, stream_or_string, **options) |
Init this serializer given a stream or a string
|
Init this serializer given a stream or a string
| def __init__(self, stream_or_string, **options):
"""
Init this serializer given a stream or a string
"""
self.options = options
if isinstance(stream_or_string, str):
self.stream = StringIO(stream_or_string)
else:
self.stream = stream_or_string | [
"def",
"__init__",
"(",
"self",
",",
"stream_or_string",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"options",
"=",
"options",
"if",
"isinstance",
"(",
"stream_or_string",
",",
"str",
")",
":",
"self",
".",
"stream",
"=",
"StringIO",
"(",
"stream_or_string",
")",
"else",
":",
"self",
".",
"stream",
"=",
"stream_or_string"
] | [
176,
4
] | [
184,
42
] | python | en | ['en', 'error', 'th'] | False |
Deserializer.__next__ | (self) | Iteration interface -- return the next item in the stream | Iteration interface -- return the next item in the stream | def __next__(self):
"""Iteration interface -- return the next item in the stream"""
raise NotImplementedError('subclasses of Deserializer must provide a __next__() method') | [
"def",
"__next__",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Deserializer must provide a __next__() method'",
")"
] | [
189,
4
] | [
191,
96
] | python | en | ['en', 'en', 'en'] | True |
normalize_together | (option_together) |
option_together can be either a tuple of tuples, or a single
tuple of two strings. Normalize it to a tuple of tuples, so that
calling code can uniformly expect that.
|
option_together can be either a tuple of tuples, or a single
tuple of two strings. Normalize it to a tuple of tuples, so that
calling code can uniformly expect that.
| def normalize_together(option_together):
"""
option_together can be either a tuple of tuples, or a single
tuple of two strings. Normalize it to a tuple of tuples, so that
calling code can uniformly expect that.
"""
try:
if not option_together:
return ()
if not isinstance(option_together, (tuple, list)):
raise TypeError
first_element = option_together[0]
if not isinstance(first_element, (tuple, list)):
option_together = (option_together,)
# Normalize everything to tuples
return tuple(tuple(ot) for ot in option_together)
except TypeError:
# If the value of option_together isn't valid, return it
# verbatim; this will be picked up by the check framework later.
return option_together | [
"def",
"normalize_together",
"(",
"option_together",
")",
":",
"try",
":",
"if",
"not",
"option_together",
":",
"return",
"(",
")",
"if",
"not",
"isinstance",
"(",
"option_together",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"raise",
"TypeError",
"first_element",
"=",
"option_together",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"first_element",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"option_together",
"=",
"(",
"option_together",
",",
")",
"# Normalize everything to tuples",
"return",
"tuple",
"(",
"tuple",
"(",
"ot",
")",
"for",
"ot",
"in",
"option_together",
")",
"except",
"TypeError",
":",
"# If the value of option_together isn't valid, return it",
"# verbatim; this will be picked up by the check framework later.",
"return",
"option_together"
] | [
37,
0
] | [
56,
30
] | python | en | ['en', 'error', 'th'] | False |
Options._format_names_with_class | (self, cls, objs) | App label/class name interpolation for object names. | App label/class name interpolation for object names. | def _format_names_with_class(self, cls, objs):
"""App label/class name interpolation for object names."""
new_objs = []
for obj in objs:
obj = obj.clone()
obj.name = obj.name % {
'app_label': cls._meta.app_label.lower(),
'class': cls.__name__.lower(),
}
new_objs.append(obj)
return new_objs | [
"def",
"_format_names_with_class",
"(",
"self",
",",
"cls",
",",
"objs",
")",
":",
"new_objs",
"=",
"[",
"]",
"for",
"obj",
"in",
"objs",
":",
"obj",
"=",
"obj",
".",
"clone",
"(",
")",
"obj",
".",
"name",
"=",
"obj",
".",
"name",
"%",
"{",
"'app_label'",
":",
"cls",
".",
"_meta",
".",
"app_label",
".",
"lower",
"(",
")",
",",
"'class'",
":",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"}",
"new_objs",
".",
"append",
"(",
"obj",
")",
"return",
"new_objs"
] | [
208,
4
] | [
218,
23
] | python | en | ['nb', 'en', 'en'] | True |
Options.setup_proxy | (self, target) |
Do the internal setup so that the current model is a proxy for
"target".
|
Do the internal setup so that the current model is a proxy for
"target".
| def setup_proxy(self, target):
"""
Do the internal setup so that the current model is a proxy for
"target".
"""
self.pk = target._meta.pk
self.proxy_for_model = target
self.db_table = target._meta.db_table | [
"def",
"setup_proxy",
"(",
"self",
",",
"target",
")",
":",
"self",
".",
"pk",
"=",
"target",
".",
"_meta",
".",
"pk",
"self",
".",
"proxy_for_model",
"=",
"target",
"self",
".",
"db_table",
"=",
"target",
".",
"_meta",
".",
"db_table"
] | [
327,
4
] | [
334,
45
] | python | en | ['en', 'error', 'th'] | False |
Options.can_migrate | (self, connection) |
Return True if the model can/should be migrated on the `connection`.
`connection` can be either a real connection or a connection alias.
|
Return True if the model can/should be migrated on the `connection`.
`connection` can be either a real connection or a connection alias.
| def can_migrate(self, connection):
"""
Return True if the model can/should be migrated on the `connection`.
`connection` can be either a real connection or a connection alias.
"""
if self.proxy or self.swapped or not self.managed:
return False
if isinstance(connection, str):
connection = connections[connection]
if self.required_db_vendor:
return self.required_db_vendor == connection.vendor
if self.required_db_features:
return all(getattr(connection.features, feat, False)
for feat in self.required_db_features)
return True | [
"def",
"can_migrate",
"(",
"self",
",",
"connection",
")",
":",
"if",
"self",
".",
"proxy",
"or",
"self",
".",
"swapped",
"or",
"not",
"self",
".",
"managed",
":",
"return",
"False",
"if",
"isinstance",
"(",
"connection",
",",
"str",
")",
":",
"connection",
"=",
"connections",
"[",
"connection",
"]",
"if",
"self",
".",
"required_db_vendor",
":",
"return",
"self",
".",
"required_db_vendor",
"==",
"connection",
".",
"vendor",
"if",
"self",
".",
"required_db_features",
":",
"return",
"all",
"(",
"getattr",
"(",
"connection",
".",
"features",
",",
"feat",
",",
"False",
")",
"for",
"feat",
"in",
"self",
".",
"required_db_features",
")",
"return",
"True"
] | [
342,
4
] | [
356,
19
] | python | en | ['en', 'error', 'th'] | False |
Options.verbose_name_raw | (self) | Return the untranslated verbose name. | Return the untranslated verbose name. | def verbose_name_raw(self):
"""Return the untranslated verbose name."""
with override(None):
return str(self.verbose_name) | [
"def",
"verbose_name_raw",
"(",
"self",
")",
":",
"with",
"override",
"(",
"None",
")",
":",
"return",
"str",
"(",
"self",
".",
"verbose_name",
")"
] | [
359,
4
] | [
362,
41
] | python | en | ['en', 'da', 'en'] | True |
Options.swapped | (self) |
Has this model been swapped out for another? If so, return the model
name of the replacement; otherwise, return None.
For historical reasons, model name lookups using get_model() are
case insensitive, so we make sure we are case insensitive here.
|
Has this model been swapped out for another? If so, return the model
name of the replacement; otherwise, return None. | def swapped(self):
"""
Has this model been swapped out for another? If so, return the model
name of the replacement; otherwise, return None.
For historical reasons, model name lookups using get_model() are
case insensitive, so we make sure we are case insensitive here.
"""
if self.swappable:
swapped_for = getattr(settings, self.swappable, None)
if swapped_for:
try:
swapped_label, swapped_object = swapped_for.split('.')
except ValueError:
# setting not in the format app_label.model_name
# raising ImproperlyConfigured here causes problems with
# test cleanup code - instead it is raised in get_user_model
# or as part of validation.
return swapped_for
if '%s.%s' % (swapped_label, swapped_object.lower()) != self.label_lower:
return swapped_for
return None | [
"def",
"swapped",
"(",
"self",
")",
":",
"if",
"self",
".",
"swappable",
":",
"swapped_for",
"=",
"getattr",
"(",
"settings",
",",
"self",
".",
"swappable",
",",
"None",
")",
"if",
"swapped_for",
":",
"try",
":",
"swapped_label",
",",
"swapped_object",
"=",
"swapped_for",
".",
"split",
"(",
"'.'",
")",
"except",
"ValueError",
":",
"# setting not in the format app_label.model_name",
"# raising ImproperlyConfigured here causes problems with",
"# test cleanup code - instead it is raised in get_user_model",
"# or as part of validation.",
"return",
"swapped_for",
"if",
"'%s.%s'",
"%",
"(",
"swapped_label",
",",
"swapped_object",
".",
"lower",
"(",
")",
")",
"!=",
"self",
".",
"label_lower",
":",
"return",
"swapped_for",
"return",
"None"
] | [
365,
4
] | [
387,
19
] | python | en | ['en', 'error', 'th'] | False |
Options.fields | (self) |
Return a list of all forward fields on the model and its parents,
excluding ManyToManyFields.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
|
Return a list of all forward fields on the model and its parents,
excluding ManyToManyFields. | def fields(self):
"""
Return a list of all forward fields on the model and its parents,
excluding ManyToManyFields.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
# For legacy reasons, the fields property should only contain forward
# fields that are not private or with a m2m cardinality. Therefore we
# pass these three filters as filters to the generator.
# The third lambda is a longwinded way of checking f.related_model - we don't
# use that property directly because related_model is a cached property,
# and all the models may not have been loaded yet; we don't want to cache
# the string reference to the related_model.
def is_not_an_m2m_field(f):
return not (f.is_relation and f.many_to_many)
def is_not_a_generic_relation(f):
return not (f.is_relation and f.one_to_many)
def is_not_a_generic_foreign_key(f):
return not (
f.is_relation and f.many_to_one and not (hasattr(f.remote_field, 'model') and f.remote_field.model)
)
return make_immutable_fields_list(
"fields",
(f for f in self._get_fields(reverse=False)
if is_not_an_m2m_field(f) and is_not_a_generic_relation(f) and is_not_a_generic_foreign_key(f))
) | [
"def",
"fields",
"(",
"self",
")",
":",
"# For legacy reasons, the fields property should only contain forward",
"# fields that are not private or with a m2m cardinality. Therefore we",
"# pass these three filters as filters to the generator.",
"# The third lambda is a longwinded way of checking f.related_model - we don't",
"# use that property directly because related_model is a cached property,",
"# and all the models may not have been loaded yet; we don't want to cache",
"# the string reference to the related_model.",
"def",
"is_not_an_m2m_field",
"(",
"f",
")",
":",
"return",
"not",
"(",
"f",
".",
"is_relation",
"and",
"f",
".",
"many_to_many",
")",
"def",
"is_not_a_generic_relation",
"(",
"f",
")",
":",
"return",
"not",
"(",
"f",
".",
"is_relation",
"and",
"f",
".",
"one_to_many",
")",
"def",
"is_not_a_generic_foreign_key",
"(",
"f",
")",
":",
"return",
"not",
"(",
"f",
".",
"is_relation",
"and",
"f",
".",
"many_to_one",
"and",
"not",
"(",
"hasattr",
"(",
"f",
".",
"remote_field",
",",
"'model'",
")",
"and",
"f",
".",
"remote_field",
".",
"model",
")",
")",
"return",
"make_immutable_fields_list",
"(",
"\"fields\"",
",",
"(",
"f",
"for",
"f",
"in",
"self",
".",
"_get_fields",
"(",
"reverse",
"=",
"False",
")",
"if",
"is_not_an_m2m_field",
"(",
"f",
")",
"and",
"is_not_a_generic_relation",
"(",
"f",
")",
"and",
"is_not_a_generic_foreign_key",
"(",
"f",
")",
")",
")"
] | [
466,
4
] | [
497,
9
] | python | en | ['en', 'error', 'th'] | False |
Options.concrete_fields | (self) |
Return a list of all concrete fields on the model and its parents.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
|
Return a list of all concrete fields on the model and its parents. | def concrete_fields(self):
"""
Return a list of all concrete fields on the model and its parents.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
return make_immutable_fields_list(
"concrete_fields", (f for f in self.fields if f.concrete)
) | [
"def",
"concrete_fields",
"(",
"self",
")",
":",
"return",
"make_immutable_fields_list",
"(",
"\"concrete_fields\"",
",",
"(",
"f",
"for",
"f",
"in",
"self",
".",
"fields",
"if",
"f",
".",
"concrete",
")",
")"
] | [
500,
4
] | [
510,
9
] | python | en | ['en', 'error', 'th'] | False |
Options.local_concrete_fields | (self) |
Return a list of all concrete fields on the model.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
|
Return a list of all concrete fields on the model. | def local_concrete_fields(self):
"""
Return a list of all concrete fields on the model.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
return make_immutable_fields_list(
"local_concrete_fields", (f for f in self.local_fields if f.concrete)
) | [
"def",
"local_concrete_fields",
"(",
"self",
")",
":",
"return",
"make_immutable_fields_list",
"(",
"\"local_concrete_fields\"",
",",
"(",
"f",
"for",
"f",
"in",
"self",
".",
"local_fields",
"if",
"f",
".",
"concrete",
")",
")"
] | [
513,
4
] | [
523,
9
] | python | en | ['en', 'error', 'th'] | False |
Options.many_to_many | (self) |
Return a list of all many to many fields on the model and its parents.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this list.
|
Return a list of all many to many fields on the model and its parents. | def many_to_many(self):
"""
Return a list of all many to many fields on the model and its parents.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this list.
"""
return make_immutable_fields_list(
"many_to_many",
(f for f in self._get_fields(reverse=False) if f.is_relation and f.many_to_many)
) | [
"def",
"many_to_many",
"(",
"self",
")",
":",
"return",
"make_immutable_fields_list",
"(",
"\"many_to_many\"",
",",
"(",
"f",
"for",
"f",
"in",
"self",
".",
"_get_fields",
"(",
"reverse",
"=",
"False",
")",
"if",
"f",
".",
"is_relation",
"and",
"f",
".",
"many_to_many",
")",
")"
] | [
526,
4
] | [
537,
9
] | python | en | ['en', 'error', 'th'] | False |
Options.related_objects | (self) |
Return all related objects pointing to the current model. The related
objects can come from a one-to-one, one-to-many, or many-to-many field
relation type.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
|
Return all related objects pointing to the current model. The related
objects can come from a one-to-one, one-to-many, or many-to-many field
relation type. | def related_objects(self):
"""
Return all related objects pointing to the current model. The related
objects can come from a one-to-one, one-to-many, or many-to-many field
relation type.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
all_related_fields = self._get_fields(forward=False, reverse=True, include_hidden=True)
return make_immutable_fields_list(
"related_objects",
(obj for obj in all_related_fields if not obj.hidden or obj.field.many_to_many)
) | [
"def",
"related_objects",
"(",
"self",
")",
":",
"all_related_fields",
"=",
"self",
".",
"_get_fields",
"(",
"forward",
"=",
"False",
",",
"reverse",
"=",
"True",
",",
"include_hidden",
"=",
"True",
")",
"return",
"make_immutable_fields_list",
"(",
"\"related_objects\"",
",",
"(",
"obj",
"for",
"obj",
"in",
"all_related_fields",
"if",
"not",
"obj",
".",
"hidden",
"or",
"obj",
".",
"field",
".",
"many_to_many",
")",
")"
] | [
540,
4
] | [
554,
9
] | python | en | ['en', 'error', 'th'] | False |
Options.get_field | (self, field_name) |
Return a field instance given the name of a forward or reverse field.
|
Return a field instance given the name of a forward or reverse field.
| def get_field(self, field_name):
"""
Return a field instance given the name of a forward or reverse field.
"""
try:
# In order to avoid premature loading of the relation tree
# (expensive) we prefer checking if the field is a forward field.
return self._forward_fields_map[field_name]
except KeyError:
# If the app registry is not ready, reverse fields are
# unavailable, therefore we throw a FieldDoesNotExist exception.
if not self.apps.models_ready:
raise FieldDoesNotExist(
"%s has no field named '%s'. The app cache isn't ready yet, "
"so if this is an auto-created related field, it won't "
"be available yet." % (self.object_name, field_name)
)
try:
# Retrieve field instance by name from cached or just-computed
# field map.
return self.fields_map[field_name]
except KeyError:
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) | [
"def",
"get_field",
"(",
"self",
",",
"field_name",
")",
":",
"try",
":",
"# In order to avoid premature loading of the relation tree",
"# (expensive) we prefer checking if the field is a forward field.",
"return",
"self",
".",
"_forward_fields_map",
"[",
"field_name",
"]",
"except",
"KeyError",
":",
"# If the app registry is not ready, reverse fields are",
"# unavailable, therefore we throw a FieldDoesNotExist exception.",
"if",
"not",
"self",
".",
"apps",
".",
"models_ready",
":",
"raise",
"FieldDoesNotExist",
"(",
"\"%s has no field named '%s'. The app cache isn't ready yet, \"",
"\"so if this is an auto-created related field, it won't \"",
"\"be available yet.\"",
"%",
"(",
"self",
".",
"object_name",
",",
"field_name",
")",
")",
"try",
":",
"# Retrieve field instance by name from cached or just-computed",
"# field map.",
"return",
"self",
".",
"fields_map",
"[",
"field_name",
"]",
"except",
"KeyError",
":",
"raise",
"FieldDoesNotExist",
"(",
"\"%s has no field named '%s'\"",
"%",
"(",
"self",
".",
"object_name",
",",
"field_name",
")",
")"
] | [
586,
4
] | [
609,
98
] | python | en | ['en', 'error', 'th'] | False |
Options.get_base_chain | (self, model) |
Return a list of parent classes leading to `model` (ordered from
closest to most distant ancestor). This has to handle the case where
`model` is a grandparent or even more distant relation.
|
Return a list of parent classes leading to `model` (ordered from
closest to most distant ancestor). This has to handle the case where
`model` is a grandparent or even more distant relation.
| def get_base_chain(self, model):
"""
Return a list of parent classes leading to `model` (ordered from
closest to most distant ancestor). This has to handle the case where
`model` is a grandparent or even more distant relation.
"""
if not self.parents:
return []
if model in self.parents:
return [model]
for parent in self.parents:
res = parent._meta.get_base_chain(model)
if res:
res.insert(0, parent)
return res
return [] | [
"def",
"get_base_chain",
"(",
"self",
",",
"model",
")",
":",
"if",
"not",
"self",
".",
"parents",
":",
"return",
"[",
"]",
"if",
"model",
"in",
"self",
".",
"parents",
":",
"return",
"[",
"model",
"]",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"res",
"=",
"parent",
".",
"_meta",
".",
"get_base_chain",
"(",
"model",
")",
"if",
"res",
":",
"res",
".",
"insert",
"(",
"0",
",",
"parent",
")",
"return",
"res",
"return",
"[",
"]"
] | [
611,
4
] | [
626,
17
] | python | en | ['en', 'error', 'th'] | False |
Options.get_parent_list | (self) |
Return all the ancestors of this model as a list ordered by MRO.
Useful for determining if something is an ancestor, regardless of lineage.
|
Return all the ancestors of this model as a list ordered by MRO.
Useful for determining if something is an ancestor, regardless of lineage.
| def get_parent_list(self):
"""
Return all the ancestors of this model as a list ordered by MRO.
Useful for determining if something is an ancestor, regardless of lineage.
"""
result = OrderedSet(self.parents)
for parent in self.parents:
for ancestor in parent._meta.get_parent_list():
result.add(ancestor)
return list(result) | [
"def",
"get_parent_list",
"(",
"self",
")",
":",
"result",
"=",
"OrderedSet",
"(",
"self",
".",
"parents",
")",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"for",
"ancestor",
"in",
"parent",
".",
"_meta",
".",
"get_parent_list",
"(",
")",
":",
"result",
".",
"add",
"(",
"ancestor",
")",
"return",
"list",
"(",
"result",
")"
] | [
628,
4
] | [
637,
27
] | python | en | ['en', 'error', 'th'] | False |
Options.get_ancestor_link | (self, ancestor) |
Return the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance.
Return None if the model isn't an ancestor of this one.
|
Return the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance. | def get_ancestor_link(self, ancestor):
"""
Return the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance.
Return None if the model isn't an ancestor of this one.
"""
if ancestor in self.parents:
return self.parents[ancestor]
for parent in self.parents:
# Tries to get a link field from the immediate parent
parent_link = parent._meta.get_ancestor_link(ancestor)
if parent_link:
# In case of a proxied model, the first link
# of the chain to the ancestor is that parent
# links
return self.parents[parent] or parent_link | [
"def",
"get_ancestor_link",
"(",
"self",
",",
"ancestor",
")",
":",
"if",
"ancestor",
"in",
"self",
".",
"parents",
":",
"return",
"self",
".",
"parents",
"[",
"ancestor",
"]",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"# Tries to get a link field from the immediate parent",
"parent_link",
"=",
"parent",
".",
"_meta",
".",
"get_ancestor_link",
"(",
"ancestor",
")",
"if",
"parent_link",
":",
"# In case of a proxied model, the first link",
"# of the chain to the ancestor is that parent",
"# links",
"return",
"self",
".",
"parents",
"[",
"parent",
"]",
"or",
"parent_link"
] | [
639,
4
] | [
657,
58
] | python | en | ['en', 'error', 'th'] | False |
Options.get_path_to_parent | (self, parent) |
Return a list of PathInfos containing the path from the current
model to the parent model, or an empty list if parent is not a
parent of the current model.
|
Return a list of PathInfos containing the path from the current
model to the parent model, or an empty list if parent is not a
parent of the current model.
| def get_path_to_parent(self, parent):
"""
Return a list of PathInfos containing the path from the current
model to the parent model, or an empty list if parent is not a
parent of the current model.
"""
if self.model is parent:
return []
# Skip the chain of proxy to the concrete proxied model.
proxied_model = self.concrete_model
path = []
opts = self
for int_model in self.get_base_chain(parent):
if int_model is proxied_model:
opts = int_model._meta
else:
final_field = opts.parents[int_model]
targets = (final_field.remote_field.get_related_field(),)
opts = int_model._meta
path.append(PathInfo(
from_opts=final_field.model._meta,
to_opts=opts,
target_fields=targets,
join_field=final_field,
m2m=False,
direct=True,
filtered_relation=None,
))
return path | [
"def",
"get_path_to_parent",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"model",
"is",
"parent",
":",
"return",
"[",
"]",
"# Skip the chain of proxy to the concrete proxied model.",
"proxied_model",
"=",
"self",
".",
"concrete_model",
"path",
"=",
"[",
"]",
"opts",
"=",
"self",
"for",
"int_model",
"in",
"self",
".",
"get_base_chain",
"(",
"parent",
")",
":",
"if",
"int_model",
"is",
"proxied_model",
":",
"opts",
"=",
"int_model",
".",
"_meta",
"else",
":",
"final_field",
"=",
"opts",
".",
"parents",
"[",
"int_model",
"]",
"targets",
"=",
"(",
"final_field",
".",
"remote_field",
".",
"get_related_field",
"(",
")",
",",
")",
"opts",
"=",
"int_model",
".",
"_meta",
"path",
".",
"append",
"(",
"PathInfo",
"(",
"from_opts",
"=",
"final_field",
".",
"model",
".",
"_meta",
",",
"to_opts",
"=",
"opts",
",",
"target_fields",
"=",
"targets",
",",
"join_field",
"=",
"final_field",
",",
"m2m",
"=",
"False",
",",
"direct",
"=",
"True",
",",
"filtered_relation",
"=",
"None",
",",
")",
")",
"return",
"path"
] | [
659,
4
] | [
687,
19
] | python | en | ['en', 'error', 'th'] | False |
Options.get_path_from_parent | (self, parent) |
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
|
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
| def get_path_from_parent(self, parent):
"""
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if self.model is parent:
return []
model = self.concrete_model
# Get a reversed base chain including both the current and parent
# models.
chain = model._meta.get_base_chain(parent)
chain.reverse()
chain.append(model)
# Construct a list of the PathInfos between models in chain.
path = []
for i, ancestor in enumerate(chain[:-1]):
child = chain[i + 1]
link = child._meta.get_ancestor_link(ancestor)
path.extend(link.get_reverse_path_info())
return path | [
"def",
"get_path_from_parent",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"model",
"is",
"parent",
":",
"return",
"[",
"]",
"model",
"=",
"self",
".",
"concrete_model",
"# Get a reversed base chain including both the current and parent",
"# models.",
"chain",
"=",
"model",
".",
"_meta",
".",
"get_base_chain",
"(",
"parent",
")",
"chain",
".",
"reverse",
"(",
")",
"chain",
".",
"append",
"(",
"model",
")",
"# Construct a list of the PathInfos between models in chain.",
"path",
"=",
"[",
"]",
"for",
"i",
",",
"ancestor",
"in",
"enumerate",
"(",
"chain",
"[",
":",
"-",
"1",
"]",
")",
":",
"child",
"=",
"chain",
"[",
"i",
"+",
"1",
"]",
"link",
"=",
"child",
".",
"_meta",
".",
"get_ancestor_link",
"(",
"ancestor",
")",
"path",
".",
"extend",
"(",
"link",
".",
"get_reverse_path_info",
"(",
")",
")",
"return",
"path"
] | [
689,
4
] | [
709,
19
] | python | en | ['en', 'error', 'th'] | False |
Options._populate_directed_relation_graph | (self) |
This method is used by each model to find its reverse objects. As this
method is very expensive and is accessed frequently (it looks up every
field in a model, in every app), it is computed on first access and then
is set as a property on every model.
|
This method is used by each model to find its reverse objects. As this
method is very expensive and is accessed frequently (it looks up every
field in a model, in every app), it is computed on first access and then
is set as a property on every model.
| def _populate_directed_relation_graph(self):
"""
This method is used by each model to find its reverse objects. As this
method is very expensive and is accessed frequently (it looks up every
field in a model, in every app), it is computed on first access and then
is set as a property on every model.
"""
related_objects_graph = defaultdict(list)
all_models = self.apps.get_models(include_auto_created=True)
for model in all_models:
opts = model._meta
# Abstract model's fields are copied to child models, hence we will
# see the fields from the child models.
if opts.abstract:
continue
fields_with_relations = (
f for f in opts._get_fields(reverse=False, include_parents=False)
if f.is_relation and f.related_model is not None
)
for f in fields_with_relations:
if not isinstance(f.remote_field.model, str):
remote_label = f.remote_field.model._meta.concrete_model._meta.label
related_objects_graph[remote_label].append(f)
for model in all_models:
# Set the relation_tree using the internal __dict__. In this way
# we avoid calling the cached property. In attribute lookup,
# __dict__ takes precedence over a data descriptor (such as
# @cached_property). This means that the _meta._relation_tree is
# only called if related_objects is not in __dict__.
related_objects = related_objects_graph[model._meta.concrete_model._meta.label]
model._meta.__dict__['_relation_tree'] = related_objects
# It seems it is possible that self is not in all_models, so guard
# against that with default for get().
return self.__dict__.get('_relation_tree', EMPTY_RELATION_TREE) | [
"def",
"_populate_directed_relation_graph",
"(",
"self",
")",
":",
"related_objects_graph",
"=",
"defaultdict",
"(",
"list",
")",
"all_models",
"=",
"self",
".",
"apps",
".",
"get_models",
"(",
"include_auto_created",
"=",
"True",
")",
"for",
"model",
"in",
"all_models",
":",
"opts",
"=",
"model",
".",
"_meta",
"# Abstract model's fields are copied to child models, hence we will",
"# see the fields from the child models.",
"if",
"opts",
".",
"abstract",
":",
"continue",
"fields_with_relations",
"=",
"(",
"f",
"for",
"f",
"in",
"opts",
".",
"_get_fields",
"(",
"reverse",
"=",
"False",
",",
"include_parents",
"=",
"False",
")",
"if",
"f",
".",
"is_relation",
"and",
"f",
".",
"related_model",
"is",
"not",
"None",
")",
"for",
"f",
"in",
"fields_with_relations",
":",
"if",
"not",
"isinstance",
"(",
"f",
".",
"remote_field",
".",
"model",
",",
"str",
")",
":",
"remote_label",
"=",
"f",
".",
"remote_field",
".",
"model",
".",
"_meta",
".",
"concrete_model",
".",
"_meta",
".",
"label",
"related_objects_graph",
"[",
"remote_label",
"]",
".",
"append",
"(",
"f",
")",
"for",
"model",
"in",
"all_models",
":",
"# Set the relation_tree using the internal __dict__. In this way",
"# we avoid calling the cached property. In attribute lookup,",
"# __dict__ takes precedence over a data descriptor (such as",
"# @cached_property). This means that the _meta._relation_tree is",
"# only called if related_objects is not in __dict__.",
"related_objects",
"=",
"related_objects_graph",
"[",
"model",
".",
"_meta",
".",
"concrete_model",
".",
"_meta",
".",
"label",
"]",
"model",
".",
"_meta",
".",
"__dict__",
"[",
"'_relation_tree'",
"]",
"=",
"related_objects",
"# It seems it is possible that self is not in all_models, so guard",
"# against that with default for get().",
"return",
"self",
".",
"__dict__",
".",
"get",
"(",
"'_relation_tree'",
",",
"EMPTY_RELATION_TREE",
")"
] | [
711,
4
] | [
746,
71
] | python | en | ['en', 'error', 'th'] | False |
Options.get_fields | (self, include_parents=True, include_hidden=False) |
Return a list of fields associated to the model. By default, include
forward and reverse fields, fields derived from inheritance, but not
hidden fields. The returned fields can be changed using the parameters:
- include_parents: include fields derived from inheritance
- include_hidden: include fields that have a related_name that
starts with a "+"
|
Return a list of fields associated to the model. By default, include
forward and reverse fields, fields derived from inheritance, but not
hidden fields. The returned fields can be changed using the parameters: | def get_fields(self, include_parents=True, include_hidden=False):
"""
Return a list of fields associated to the model. By default, include
forward and reverse fields, fields derived from inheritance, but not
hidden fields. The returned fields can be changed using the parameters:
- include_parents: include fields derived from inheritance
- include_hidden: include fields that have a related_name that
starts with a "+"
"""
if include_parents is False:
include_parents = PROXY_PARENTS
return self._get_fields(include_parents=include_parents, include_hidden=include_hidden) | [
"def",
"get_fields",
"(",
"self",
",",
"include_parents",
"=",
"True",
",",
"include_hidden",
"=",
"False",
")",
":",
"if",
"include_parents",
"is",
"False",
":",
"include_parents",
"=",
"PROXY_PARENTS",
"return",
"self",
".",
"_get_fields",
"(",
"include_parents",
"=",
"include_parents",
",",
"include_hidden",
"=",
"include_hidden",
")"
] | [
765,
4
] | [
777,
95
] | python | en | ['en', 'error', 'th'] | False |
Options._get_fields | (self, forward=True, reverse=True, include_parents=True, include_hidden=False,
seen_models=None) |
Internal helper function to return fields of the model.
* If forward=True, then fields defined on this model are returned.
* If reverse=True, then relations pointing to this model are returned.
* If include_hidden=True, then fields with is_hidden=True are returned.
* The include_parents argument toggles if fields from parent models
should be included. It has three values: True, False, and
PROXY_PARENTS. When set to PROXY_PARENTS, the call will return all
fields defined for the current model or any of its parents in the
parent chain to the model's concrete model.
|
Internal helper function to return fields of the model.
* If forward=True, then fields defined on this model are returned.
* If reverse=True, then relations pointing to this model are returned.
* If include_hidden=True, then fields with is_hidden=True are returned.
* The include_parents argument toggles if fields from parent models
should be included. It has three values: True, False, and
PROXY_PARENTS. When set to PROXY_PARENTS, the call will return all
fields defined for the current model or any of its parents in the
parent chain to the model's concrete model.
| def _get_fields(self, forward=True, reverse=True, include_parents=True, include_hidden=False,
seen_models=None):
"""
Internal helper function to return fields of the model.
* If forward=True, then fields defined on this model are returned.
* If reverse=True, then relations pointing to this model are returned.
* If include_hidden=True, then fields with is_hidden=True are returned.
* The include_parents argument toggles if fields from parent models
should be included. It has three values: True, False, and
PROXY_PARENTS. When set to PROXY_PARENTS, the call will return all
fields defined for the current model or any of its parents in the
parent chain to the model's concrete model.
"""
if include_parents not in (True, False, PROXY_PARENTS):
raise TypeError("Invalid argument for include_parents: %s" % (include_parents,))
# This helper function is used to allow recursion in ``get_fields()``
# implementation and to provide a fast way for Django's internals to
# access specific subsets of fields.
# We must keep track of which models we have already seen. Otherwise we
# could include the same field multiple times from different models.
topmost_call = seen_models is None
if topmost_call:
seen_models = set()
seen_models.add(self.model)
# Creates a cache key composed of all arguments
cache_key = (forward, reverse, include_parents, include_hidden, topmost_call)
try:
# In order to avoid list manipulation. Always return a shallow copy
# of the results.
return self._get_fields_cache[cache_key]
except KeyError:
pass
fields = []
# Recursively call _get_fields() on each parent, with the same
# options provided in this call.
if include_parents is not False:
for parent in self.parents:
# In diamond inheritance it is possible that we see the same
# model from two different routes. In that case, avoid adding
# fields from the same parent again.
if parent in seen_models:
continue
if (parent._meta.concrete_model != self.concrete_model and
include_parents == PROXY_PARENTS):
continue
for obj in parent._meta._get_fields(
forward=forward, reverse=reverse, include_parents=include_parents,
include_hidden=include_hidden, seen_models=seen_models):
if not getattr(obj, 'parent_link', False) or obj.model == self.concrete_model:
fields.append(obj)
if reverse and not self.proxy:
# Tree is computed once and cached until the app cache is expired.
# It is composed of a list of fields pointing to the current model
# from other models.
all_fields = self._relation_tree
for field in all_fields:
# If hidden fields should be included or the relation is not
# intentionally hidden, add to the fields dict.
if include_hidden or not field.remote_field.hidden:
fields.append(field.remote_field)
if forward:
fields += self.local_fields
fields += self.local_many_to_many
# Private fields are recopied to each child model, and they get a
# different model as field.model in each child. Hence we have to
# add the private fields separately from the topmost call. If we
# did this recursively similar to local_fields, we would get field
# instances with field.model != self.model.
if topmost_call:
fields += self.private_fields
# In order to avoid list manipulation. Always
# return a shallow copy of the results
fields = make_immutable_fields_list("get_fields()", fields)
# Store result into cache for later access
self._get_fields_cache[cache_key] = fields
return fields | [
"def",
"_get_fields",
"(",
"self",
",",
"forward",
"=",
"True",
",",
"reverse",
"=",
"True",
",",
"include_parents",
"=",
"True",
",",
"include_hidden",
"=",
"False",
",",
"seen_models",
"=",
"None",
")",
":",
"if",
"include_parents",
"not",
"in",
"(",
"True",
",",
"False",
",",
"PROXY_PARENTS",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid argument for include_parents: %s\"",
"%",
"(",
"include_parents",
",",
")",
")",
"# This helper function is used to allow recursion in ``get_fields()``",
"# implementation and to provide a fast way for Django's internals to",
"# access specific subsets of fields.",
"# We must keep track of which models we have already seen. Otherwise we",
"# could include the same field multiple times from different models.",
"topmost_call",
"=",
"seen_models",
"is",
"None",
"if",
"topmost_call",
":",
"seen_models",
"=",
"set",
"(",
")",
"seen_models",
".",
"add",
"(",
"self",
".",
"model",
")",
"# Creates a cache key composed of all arguments",
"cache_key",
"=",
"(",
"forward",
",",
"reverse",
",",
"include_parents",
",",
"include_hidden",
",",
"topmost_call",
")",
"try",
":",
"# In order to avoid list manipulation. Always return a shallow copy",
"# of the results.",
"return",
"self",
".",
"_get_fields_cache",
"[",
"cache_key",
"]",
"except",
"KeyError",
":",
"pass",
"fields",
"=",
"[",
"]",
"# Recursively call _get_fields() on each parent, with the same",
"# options provided in this call.",
"if",
"include_parents",
"is",
"not",
"False",
":",
"for",
"parent",
"in",
"self",
".",
"parents",
":",
"# In diamond inheritance it is possible that we see the same",
"# model from two different routes. In that case, avoid adding",
"# fields from the same parent again.",
"if",
"parent",
"in",
"seen_models",
":",
"continue",
"if",
"(",
"parent",
".",
"_meta",
".",
"concrete_model",
"!=",
"self",
".",
"concrete_model",
"and",
"include_parents",
"==",
"PROXY_PARENTS",
")",
":",
"continue",
"for",
"obj",
"in",
"parent",
".",
"_meta",
".",
"_get_fields",
"(",
"forward",
"=",
"forward",
",",
"reverse",
"=",
"reverse",
",",
"include_parents",
"=",
"include_parents",
",",
"include_hidden",
"=",
"include_hidden",
",",
"seen_models",
"=",
"seen_models",
")",
":",
"if",
"not",
"getattr",
"(",
"obj",
",",
"'parent_link'",
",",
"False",
")",
"or",
"obj",
".",
"model",
"==",
"self",
".",
"concrete_model",
":",
"fields",
".",
"append",
"(",
"obj",
")",
"if",
"reverse",
"and",
"not",
"self",
".",
"proxy",
":",
"# Tree is computed once and cached until the app cache is expired.",
"# It is composed of a list of fields pointing to the current model",
"# from other models.",
"all_fields",
"=",
"self",
".",
"_relation_tree",
"for",
"field",
"in",
"all_fields",
":",
"# If hidden fields should be included or the relation is not",
"# intentionally hidden, add to the fields dict.",
"if",
"include_hidden",
"or",
"not",
"field",
".",
"remote_field",
".",
"hidden",
":",
"fields",
".",
"append",
"(",
"field",
".",
"remote_field",
")",
"if",
"forward",
":",
"fields",
"+=",
"self",
".",
"local_fields",
"fields",
"+=",
"self",
".",
"local_many_to_many",
"# Private fields are recopied to each child model, and they get a",
"# different model as field.model in each child. Hence we have to",
"# add the private fields separately from the topmost call. If we",
"# did this recursively similar to local_fields, we would get field",
"# instances with field.model != self.model.",
"if",
"topmost_call",
":",
"fields",
"+=",
"self",
".",
"private_fields",
"# In order to avoid list manipulation. Always",
"# return a shallow copy of the results",
"fields",
"=",
"make_immutable_fields_list",
"(",
"\"get_fields()\"",
",",
"fields",
")",
"# Store result into cache for later access",
"self",
".",
"_get_fields_cache",
"[",
"cache_key",
"]",
"=",
"fields",
"return",
"fields"
] | [
779,
4
] | [
861,
21
] | python | en | ['en', 'error', 'th'] | False |
Options.total_unique_constraints | (self) |
Return a list of total unique constraints. Useful for determining set
of fields guaranteed to be unique for all rows.
|
Return a list of total unique constraints. Useful for determining set
of fields guaranteed to be unique for all rows.
| def total_unique_constraints(self):
"""
Return a list of total unique constraints. Useful for determining set
of fields guaranteed to be unique for all rows.
"""
return [
constraint
for constraint in self.constraints
if isinstance(constraint, UniqueConstraint) and constraint.condition is None
] | [
"def",
"total_unique_constraints",
"(",
"self",
")",
":",
"return",
"[",
"constraint",
"for",
"constraint",
"in",
"self",
".",
"constraints",
"if",
"isinstance",
"(",
"constraint",
",",
"UniqueConstraint",
")",
"and",
"constraint",
".",
"condition",
"is",
"None",
"]"
] | [
864,
4
] | [
873,
9
] | python | en | ['en', 'error', 'th'] | False |
Options._property_names | (self) | Return a set of the names of the properties defined on the model. | Return a set of the names of the properties defined on the model. | def _property_names(self):
"""Return a set of the names of the properties defined on the model."""
names = []
for name in dir(self.model):
attr = inspect.getattr_static(self.model, name)
if isinstance(attr, property):
names.append(name)
return frozenset(names) | [
"def",
"_property_names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"for",
"name",
"in",
"dir",
"(",
"self",
".",
"model",
")",
":",
"attr",
"=",
"inspect",
".",
"getattr_static",
"(",
"self",
".",
"model",
",",
"name",
")",
"if",
"isinstance",
"(",
"attr",
",",
"property",
")",
":",
"names",
".",
"append",
"(",
"name",
")",
"return",
"frozenset",
"(",
"names",
")"
] | [
876,
4
] | [
883,
31
] | python | en | ['en', 'en', 'en'] | True |
Options.db_returning_fields | (self) |
Private API intended only to be used by Django itself.
Fields to be returned after a database insert.
|
Private API intended only to be used by Django itself.
Fields to be returned after a database insert.
| def db_returning_fields(self):
"""
Private API intended only to be used by Django itself.
Fields to be returned after a database insert.
"""
return [
field for field in self._get_fields(forward=True, reverse=False, include_parents=PROXY_PARENTS)
if getattr(field, 'db_returning', False)
] | [
"def",
"db_returning_fields",
"(",
"self",
")",
":",
"return",
"[",
"field",
"for",
"field",
"in",
"self",
".",
"_get_fields",
"(",
"forward",
"=",
"True",
",",
"reverse",
"=",
"False",
",",
"include_parents",
"=",
"PROXY_PARENTS",
")",
"if",
"getattr",
"(",
"field",
",",
"'db_returning'",
",",
"False",
")",
"]"
] | [
886,
4
] | [
894,
9
] | python | en | ['en', 'error', 'th'] | False |
_get_project_id | () | Get project ID from default GCP connection. | Get project ID from default GCP connection. | def _get_project_id():
"""Get project ID from default GCP connection."""
extras = BaseHook.get_connection("google_cloud_default").extra_dejson
key = "extra__google_cloud_platform__project"
if key in extras:
project_id = extras[key]
else:
raise ("Must configure project_id in google_cloud_default "
"connection from Airflow Console")
return project_id | [
"def",
"_get_project_id",
"(",
")",
":",
"extras",
"=",
"BaseHook",
".",
"get_connection",
"(",
"\"google_cloud_default\"",
")",
".",
"extra_dejson",
"key",
"=",
"\"extra__google_cloud_platform__project\"",
"if",
"key",
"in",
"extras",
":",
"project_id",
"=",
"extras",
"[",
"key",
"]",
"else",
":",
"raise",
"(",
"\"Must configure project_id in google_cloud_default \"",
"\"connection from Airflow Console\"",
")",
"return",
"project_id"
] | [
32,
0
] | [
42,
19
] | python | en | ['en', 'en', 'en'] | True |
run | (argv=None) | Build and run the pipeline. | Build and run the pipeline. | def run(argv=None):
"""Build and run the pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--project',
help=('Google Cloud Project ID'),
required=True)
parser.add_argument(
'--input_topic',
help=('Google Cloud PubSub topic name '),
required=True)
known_args, pipeline_args = parser.parse_known_args(argv)
pipeline_options = PipelineOptions(
pipeline_args.append('--project={}'.format(known_args.project)))
pipeline_options.view_as(SetupOptions).save_main_session = True
pipeline_options.view_as(StandardOptions).streaming = True
p = beam.Pipeline(options=pipeline_options)
TOPIC = 'projects/{}/topics/{}'.format(known_args.project,known_args.input_topic)
table_spec = '{}:taxifare.traffic_realtime'.format(known_args.project) # table needs to exist
def to_bq_format(count):
"""BigQuery writer requires rows to be stored as python dictionary"""
return {'trips_last_5min':count,'time':datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
pipeline = (p
| 'read_from_pubusub' >> beam.io.ReadFromPubSub(topic=TOPIC).with_output_types(bytes)
| 'window' >> # TODO
| 'count' >> beam.CombineGlobally(CountFn()).without_defaults()
| 'format_for_bq' >> beam.Map(to_bq_format)
| 'write_to_bq' >> beam.io.WriteToBigQuery(
table_spec,
write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND, #WRITE_TRUNCATE not supported for streaming
create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER))
result = p.run() | [
"def",
"run",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--project'",
",",
"help",
"=",
"(",
"'Google Cloud Project ID'",
")",
",",
"required",
"=",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--input_topic'",
",",
"help",
"=",
"(",
"'Google Cloud PubSub topic name '",
")",
",",
"required",
"=",
"True",
")",
"known_args",
",",
"pipeline_args",
"=",
"parser",
".",
"parse_known_args",
"(",
"argv",
")",
"pipeline_options",
"=",
"PipelineOptions",
"(",
"pipeline_args",
".",
"append",
"(",
"'--project={}'",
".",
"format",
"(",
"known_args",
".",
"project",
")",
")",
")",
"pipeline_options",
".",
"view_as",
"(",
"SetupOptions",
")",
".",
"save_main_session",
"=",
"True",
"pipeline_options",
".",
"view_as",
"(",
"StandardOptions",
")",
".",
"streaming",
"=",
"True",
"p",
"=",
"beam",
".",
"Pipeline",
"(",
"options",
"=",
"pipeline_options",
")",
"TOPIC",
"=",
"'projects/{}/topics/{}'",
".",
"format",
"(",
"known_args",
".",
"project",
",",
"known_args",
".",
"input_topic",
")",
"table_spec",
"=",
"'{}:taxifare.traffic_realtime'",
".",
"format",
"(",
"known_args",
".",
"project",
")",
"# table needs to exist",
"def",
"to_bq_format",
"(",
"count",
")",
":",
"\"\"\"BigQuery writer requires rows to be stored as python dictionary\"\"\"",
"return",
"{",
"'trips_last_5min'",
":",
"count",
",",
"'time'",
":",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"}",
"pipeline",
"=",
"(",
"p",
"|",
"'read_from_pubusub'",
">>",
"beam",
".",
"io",
".",
"ReadFromPubSub",
"(",
"topic",
"=",
"TOPIC",
")",
".",
"with_output_types",
"(",
"bytes",
")",
"|",
"'window'",
">>",
"# TODO",
"|",
"'count'",
">>",
"beam",
".",
"CombineGlobally",
"(",
"CountFn",
"(",
")",
")",
".",
"without_defaults",
"(",
")",
"|",
"'format_for_bq'",
">>",
"beam",
".",
"Map",
"(",
"to_bq_format",
")",
"|",
"'write_to_bq'",
">>",
"beam",
".",
"io",
".",
"WriteToBigQuery",
"(",
"table_spec",
",",
"write_disposition",
"=",
"beam",
".",
"io",
".",
"BigQueryDisposition",
".",
"WRITE_APPEND",
",",
"#WRITE_TRUNCATE not supported for streaming",
"create_disposition",
"=",
"beam",
".",
"io",
".",
"BigQueryDisposition",
".",
"CREATE_NEVER",
")",
")",
"result",
"=",
"p",
".",
"run",
"(",
")"
] | [
32,
0
] | [
71,
18
] | python | en | ['en', 'en', 'en'] | True |
arg_byref | (args, offset=-1) | Return the pointer argument's by-reference value. | Return the pointer argument's by-reference value. | def arg_byref(args, offset=-1):
"Return the pointer argument's by-reference value."
return args[offset]._obj.value | [
"def",
"arg_byref",
"(",
"args",
",",
"offset",
"=",
"-",
"1",
")",
":",
"return",
"args",
"[",
"offset",
"]",
".",
"_obj",
".",
"value"
] | [
14,
0
] | [
16,
34
] | python | en | ['en', 'en', 'en'] | True |
ptr_byref | (args, offset=-1) | Return the pointer argument passed in by-reference. | Return the pointer argument passed in by-reference. | def ptr_byref(args, offset=-1):
"Return the pointer argument passed in by-reference."
return args[offset]._obj | [
"def",
"ptr_byref",
"(",
"args",
",",
"offset",
"=",
"-",
"1",
")",
":",
"return",
"args",
"[",
"offset",
"]",
".",
"_obj"
] | [
19,
0
] | [
21,
28
] | python | en | ['en', 'en', 'en'] | True |
check_const_string | (result, func, cargs, offset=None, cpl=False) |
Similar functionality to `check_string`, but does not free the pointer.
|
Similar functionality to `check_string`, but does not free the pointer.
| def check_const_string(result, func, cargs, offset=None, cpl=False):
"""
Similar functionality to `check_string`, but does not free the pointer.
"""
if offset:
check_err(result, cpl=cpl)
ptr = ptr_byref(cargs, offset)
return ptr.value
else:
return result | [
"def",
"check_const_string",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"None",
",",
"cpl",
"=",
"False",
")",
":",
"if",
"offset",
":",
"check_err",
"(",
"result",
",",
"cpl",
"=",
"cpl",
")",
"ptr",
"=",
"ptr_byref",
"(",
"cargs",
",",
"offset",
")",
"return",
"ptr",
".",
"value",
"else",
":",
"return",
"result"
] | [
25,
0
] | [
34,
21
] | python | en | ['en', 'error', 'th'] | False |
check_string | (result, func, cargs, offset=-1, str_result=False) |
Check the string output returned from the given function, and free
the string pointer allocated by OGR. The `str_result` keyword
may be used when the result is the string pointer, otherwise
the OGR error code is assumed. The `offset` keyword may be used
to extract the string pointer passed in by-reference at the given
slice offset in the function arguments.
|
Check the string output returned from the given function, and free
the string pointer allocated by OGR. The `str_result` keyword
may be used when the result is the string pointer, otherwise
the OGR error code is assumed. The `offset` keyword may be used
to extract the string pointer passed in by-reference at the given
slice offset in the function arguments.
| def check_string(result, func, cargs, offset=-1, str_result=False):
"""
Check the string output returned from the given function, and free
the string pointer allocated by OGR. The `str_result` keyword
may be used when the result is the string pointer, otherwise
the OGR error code is assumed. The `offset` keyword may be used
to extract the string pointer passed in by-reference at the given
slice offset in the function arguments.
"""
if str_result:
# For routines that return a string.
ptr = result
if not ptr:
s = None
else:
s = string_at(result)
else:
# Error-code return specified.
check_err(result)
ptr = ptr_byref(cargs, offset)
# Getting the string value
s = ptr.value
# Correctly freeing the allocated memory behind GDAL pointer
# with the VSIFree routine.
if ptr:
lgdal.VSIFree(ptr)
return s | [
"def",
"check_string",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"-",
"1",
",",
"str_result",
"=",
"False",
")",
":",
"if",
"str_result",
":",
"# For routines that return a string.",
"ptr",
"=",
"result",
"if",
"not",
"ptr",
":",
"s",
"=",
"None",
"else",
":",
"s",
"=",
"string_at",
"(",
"result",
")",
"else",
":",
"# Error-code return specified.",
"check_err",
"(",
"result",
")",
"ptr",
"=",
"ptr_byref",
"(",
"cargs",
",",
"offset",
")",
"# Getting the string value",
"s",
"=",
"ptr",
".",
"value",
"# Correctly freeing the allocated memory behind GDAL pointer",
"# with the VSIFree routine.",
"if",
"ptr",
":",
"lgdal",
".",
"VSIFree",
"(",
"ptr",
")",
"return",
"s"
] | [
37,
0
] | [
63,
12
] | python | en | ['en', 'error', 'th'] | False |
check_envelope | (result, func, cargs, offset=-1) | Check a function that returns an OGR Envelope by reference. | Check a function that returns an OGR Envelope by reference. | def check_envelope(result, func, cargs, offset=-1):
"Check a function that returns an OGR Envelope by reference."
return ptr_byref(cargs, offset) | [
"def",
"check_envelope",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"-",
"1",
")",
":",
"return",
"ptr_byref",
"(",
"cargs",
",",
"offset",
")"
] | [
69,
0
] | [
71,
35
] | python | en | ['en', 'en', 'en'] | True |
check_geom | (result, func, cargs) | Check a function that returns a geometry. | Check a function that returns a geometry. | def check_geom(result, func, cargs):
"Check a function that returns a geometry."
# OGR_G_Clone may return an integer, even though the
# restype is set to c_void_p
if isinstance(result, int):
result = c_void_p(result)
if not result:
raise GDALException('Invalid geometry pointer returned from "%s".' % func.__name__)
return result | [
"def",
"check_geom",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"# OGR_G_Clone may return an integer, even though the",
"# restype is set to c_void_p",
"if",
"isinstance",
"(",
"result",
",",
"int",
")",
":",
"result",
"=",
"c_void_p",
"(",
"result",
")",
"if",
"not",
"result",
":",
"raise",
"GDALException",
"(",
"'Invalid geometry pointer returned from \"%s\".'",
"%",
"func",
".",
"__name__",
")",
"return",
"result"
] | [
75,
0
] | [
83,
17
] | python | en | ['en', 'en', 'en'] | True |
check_geom_offset | (result, func, cargs, offset=-1) | Check the geometry at the given offset in the C parameter list. | Check the geometry at the given offset in the C parameter list. | def check_geom_offset(result, func, cargs, offset=-1):
"Check the geometry at the given offset in the C parameter list."
check_err(result)
geom = ptr_byref(cargs, offset=offset)
return check_geom(geom, func, cargs) | [
"def",
"check_geom_offset",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"offset",
"=",
"-",
"1",
")",
":",
"check_err",
"(",
"result",
")",
"geom",
"=",
"ptr_byref",
"(",
"cargs",
",",
"offset",
"=",
"offset",
")",
"return",
"check_geom",
"(",
"geom",
",",
"func",
",",
"cargs",
")"
] | [
86,
0
] | [
90,
40
] | python | en | ['en', 'en', 'en'] | True |
check_arg_errcode | (result, func, cargs, cpl=False) |
The error code is returned in the last argument, by reference.
Check its value with `check_err` before returning the result.
|
The error code is returned in the last argument, by reference.
Check its value with `check_err` before returning the result.
| def check_arg_errcode(result, func, cargs, cpl=False):
"""
The error code is returned in the last argument, by reference.
Check its value with `check_err` before returning the result.
"""
check_err(arg_byref(cargs), cpl=cpl)
return result | [
"def",
"check_arg_errcode",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"cpl",
"=",
"False",
")",
":",
"check_err",
"(",
"arg_byref",
"(",
"cargs",
")",
",",
"cpl",
"=",
"cpl",
")",
"return",
"result"
] | [
103,
0
] | [
109,
17
] | python | en | ['en', 'error', 'th'] | False |
check_errcode | (result, func, cargs, cpl=False) |
Check the error code returned (c_int).
|
Check the error code returned (c_int).
| def check_errcode(result, func, cargs, cpl=False):
"""
Check the error code returned (c_int).
"""
check_err(result, cpl=cpl) | [
"def",
"check_errcode",
"(",
"result",
",",
"func",
",",
"cargs",
",",
"cpl",
"=",
"False",
")",
":",
"check_err",
"(",
"result",
",",
"cpl",
"=",
"cpl",
")"
] | [
112,
0
] | [
116,
30
] | python | en | ['en', 'error', 'th'] | False |
check_pointer | (result, func, cargs) | Make sure the result pointer is valid. | Make sure the result pointer is valid. | def check_pointer(result, func, cargs):
"Make sure the result pointer is valid."
if isinstance(result, int):
result = c_void_p(result)
if result:
return result
else:
raise GDALException('Invalid pointer returned from "%s"' % func.__name__) | [
"def",
"check_pointer",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"int",
")",
":",
"result",
"=",
"c_void_p",
"(",
"result",
")",
"if",
"result",
":",
"return",
"result",
"else",
":",
"raise",
"GDALException",
"(",
"'Invalid pointer returned from \"%s\"'",
"%",
"func",
".",
"__name__",
")"
] | [
119,
0
] | [
126,
81
] | python | en | ['en', 'en', 'en'] | True |
check_str_arg | (result, func, cargs) |
This is for the OSRGet[Angular|Linear]Units functions, which
require that the returned string pointer not be freed. This
returns both the double and string values.
|
This is for the OSRGet[Angular|Linear]Units functions, which
require that the returned string pointer not be freed. This
returns both the double and string values.
| def check_str_arg(result, func, cargs):
"""
This is for the OSRGet[Angular|Linear]Units functions, which
require that the returned string pointer not be freed. This
returns both the double and string values.
"""
dbl = result
ptr = cargs[-1]._obj
return dbl, ptr.value.decode() | [
"def",
"check_str_arg",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"dbl",
"=",
"result",
"ptr",
"=",
"cargs",
"[",
"-",
"1",
"]",
".",
"_obj",
"return",
"dbl",
",",
"ptr",
".",
"value",
".",
"decode",
"(",
")"
] | [
129,
0
] | [
137,
34
] | python | en | ['en', 'error', 'th'] | False |
autoescape | (parser, token) |
Force autoescape behavior for this block.
|
Force autoescape behavior for this block.
| def autoescape(parser, token):
"""
Force autoescape behavior for this block.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
if len(args) != 2:
raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.")
arg = args[1]
if arg not in ('on', 'off'):
raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'")
nodelist = parser.parse(('endautoescape',))
parser.delete_first_token()
return AutoEscapeControlNode((arg == 'on'), nodelist) | [
"def",
"autoescape",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"args",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'autoescape' tag requires exactly one argument.\"",
")",
"arg",
"=",
"args",
"[",
"1",
"]",
"if",
"arg",
"not",
"in",
"(",
"'on'",
",",
"'off'",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'autoescape' argument should be 'on' or 'off'\"",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endautoescape'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"AutoEscapeControlNode",
"(",
"(",
"arg",
"==",
"'on'",
")",
",",
"nodelist",
")"
] | [
519,
0
] | [
532,
57
] | python | en | ['en', 'error', 'th'] | False |
comment | (parser, token) |
Ignore everything between ``{% comment %}`` and ``{% endcomment %}``.
|
Ignore everything between ``{% comment %}`` and ``{% endcomment %}``.
| def comment(parser, token):
"""
Ignore everything between ``{% comment %}`` and ``{% endcomment %}``.
"""
parser.skip_past('endcomment')
return CommentNode() | [
"def",
"comment",
"(",
"parser",
",",
"token",
")",
":",
"parser",
".",
"skip_past",
"(",
"'endcomment'",
")",
"return",
"CommentNode",
"(",
")"
] | [
536,
0
] | [
541,
24
] | python | en | ['en', 'error', 'th'] | False |
cycle | (parser, token) |
Cycle among the given strings each time this tag is encountered.
Within a loop, cycles among the given strings each time through
the loop::
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Outside of a loop, give the values a unique name the first time you call
it, then use that name each successive time through::
<tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr>
<tr class="{% cycle rowcolors %}">...</tr>
<tr class="{% cycle rowcolors %}">...</tr>
You can use any number of values, separated by spaces. Commas can also
be used to separate values; if a comma is used, the cycle values are
interpreted as literal strings.
The optional flag "silent" can be used to prevent the cycle declaration
from returning any value::
{% for o in some_list %}
{% cycle 'row1' 'row2' as rowcolors silent %}
<tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr>
{% endfor %}
|
Cycle among the given strings each time this tag is encountered. | def cycle(parser, token):
"""
Cycle among the given strings each time this tag is encountered.
Within a loop, cycles among the given strings each time through
the loop::
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Outside of a loop, give the values a unique name the first time you call
it, then use that name each successive time through::
<tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr>
<tr class="{% cycle rowcolors %}">...</tr>
<tr class="{% cycle rowcolors %}">...</tr>
You can use any number of values, separated by spaces. Commas can also
be used to separate values; if a comma is used, the cycle values are
interpreted as literal strings.
The optional flag "silent" can be used to prevent the cycle declaration
from returning any value::
{% for o in some_list %}
{% cycle 'row1' 'row2' as rowcolors silent %}
<tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr>
{% endfor %}
"""
# Note: This returns the exact same node on each {% cycle name %} call;
# that is, the node object returned from {% cycle a b c as name %} and the
# one returned from {% cycle name %} are the exact same object. This
# shouldn't cause problems (heh), but if it does, now you know.
#
# Ugly hack warning: This stuffs the named template dict into parser so
# that names are only unique within each template (as opposed to using
# a global variable, which would make cycle names have to be unique across
# *all* templates.
#
# It keeps the last node in the parser to be able to reset it with
# {% resetcycle %}.
args = token.split_contents()
if len(args) < 2:
raise TemplateSyntaxError("'cycle' tag requires at least two arguments")
if len(args) == 2:
# {% cycle foo %} case.
name = args[1]
if not hasattr(parser, '_named_cycle_nodes'):
raise TemplateSyntaxError("No named cycles in template. '%s' is not defined" % name)
if name not in parser._named_cycle_nodes:
raise TemplateSyntaxError("Named cycle '%s' does not exist" % name)
return parser._named_cycle_nodes[name]
as_form = False
if len(args) > 4:
# {% cycle ... as foo [silent] %} case.
if args[-3] == "as":
if args[-1] != "silent":
raise TemplateSyntaxError("Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1])
as_form = True
silent = True
args = args[:-1]
elif args[-2] == "as":
as_form = True
silent = False
if as_form:
name = args[-1]
values = [parser.compile_filter(arg) for arg in args[1:-2]]
node = CycleNode(values, name, silent=silent)
if not hasattr(parser, '_named_cycle_nodes'):
parser._named_cycle_nodes = {}
parser._named_cycle_nodes[name] = node
else:
values = [parser.compile_filter(arg) for arg in args[1:]]
node = CycleNode(values)
parser._last_cycle_node = node
return node | [
"def",
"cycle",
"(",
"parser",
",",
"token",
")",
":",
"# Note: This returns the exact same node on each {% cycle name %} call;",
"# that is, the node object returned from {% cycle a b c as name %} and the",
"# one returned from {% cycle name %} are the exact same object. This",
"# shouldn't cause problems (heh), but if it does, now you know.",
"#",
"# Ugly hack warning: This stuffs the named template dict into parser so",
"# that names are only unique within each template (as opposed to using",
"# a global variable, which would make cycle names have to be unique across",
"# *all* templates.",
"#",
"# It keeps the last node in the parser to be able to reset it with",
"# {% resetcycle %}.",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'cycle' tag requires at least two arguments\"",
")",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"# {% cycle foo %} case.",
"name",
"=",
"args",
"[",
"1",
"]",
"if",
"not",
"hasattr",
"(",
"parser",
",",
"'_named_cycle_nodes'",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"No named cycles in template. '%s' is not defined\"",
"%",
"name",
")",
"if",
"name",
"not",
"in",
"parser",
".",
"_named_cycle_nodes",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"Named cycle '%s' does not exist\"",
"%",
"name",
")",
"return",
"parser",
".",
"_named_cycle_nodes",
"[",
"name",
"]",
"as_form",
"=",
"False",
"if",
"len",
"(",
"args",
")",
">",
"4",
":",
"# {% cycle ... as foo [silent] %} case.",
"if",
"args",
"[",
"-",
"3",
"]",
"==",
"\"as\"",
":",
"if",
"args",
"[",
"-",
"1",
"]",
"!=",
"\"silent\"",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"Only 'silent' flag is allowed after cycle's name, not '%s'.\"",
"%",
"args",
"[",
"-",
"1",
"]",
")",
"as_form",
"=",
"True",
"silent",
"=",
"True",
"args",
"=",
"args",
"[",
":",
"-",
"1",
"]",
"elif",
"args",
"[",
"-",
"2",
"]",
"==",
"\"as\"",
":",
"as_form",
"=",
"True",
"silent",
"=",
"False",
"if",
"as_form",
":",
"name",
"=",
"args",
"[",
"-",
"1",
"]",
"values",
"=",
"[",
"parser",
".",
"compile_filter",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"[",
"1",
":",
"-",
"2",
"]",
"]",
"node",
"=",
"CycleNode",
"(",
"values",
",",
"name",
",",
"silent",
"=",
"silent",
")",
"if",
"not",
"hasattr",
"(",
"parser",
",",
"'_named_cycle_nodes'",
")",
":",
"parser",
".",
"_named_cycle_nodes",
"=",
"{",
"}",
"parser",
".",
"_named_cycle_nodes",
"[",
"name",
"]",
"=",
"node",
"else",
":",
"values",
"=",
"[",
"parser",
".",
"compile_filter",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"[",
"1",
":",
"]",
"]",
"node",
"=",
"CycleNode",
"(",
"values",
")",
"parser",
".",
"_last_cycle_node",
"=",
"node",
"return",
"node"
] | [
545,
0
] | [
629,
15
] | python | en | ['en', 'error', 'th'] | False |
debug | (parser, token) |
Output a whole load of debugging information, including the current
context and imported modules.
Sample usage::
<pre>
{% debug %}
</pre>
|
Output a whole load of debugging information, including the current
context and imported modules. | def debug(parser, token):
"""
Output a whole load of debugging information, including the current
context and imported modules.
Sample usage::
<pre>
{% debug %}
</pre>
"""
return DebugNode() | [
"def",
"debug",
"(",
"parser",
",",
"token",
")",
":",
"return",
"DebugNode",
"(",
")"
] | [
638,
0
] | [
649,
22
] | python | en | ['en', 'error', 'th'] | False |
do_filter | (parser, token) |
Filter the contents of the block through variable filters.
Filters can also be piped through each other, and they can have
arguments -- just like in variable syntax.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in lowercase.
{% endfilter %}
Note that the ``escape`` and ``safe`` filters are not acceptable arguments.
Instead, use the ``autoescape`` tag to manage autoescaping for blocks of
template code.
|
Filter the contents of the block through variable filters. | def do_filter(parser, token):
"""
Filter the contents of the block through variable filters.
Filters can also be piped through each other, and they can have
arguments -- just like in variable syntax.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in lowercase.
{% endfilter %}
Note that the ``escape`` and ``safe`` filters are not acceptable arguments.
Instead, use the ``autoescape`` tag to manage autoescaping for blocks of
template code.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
_, rest = token.contents.split(None, 1)
filter_expr = parser.compile_filter("var|%s" % (rest))
for func, unused in filter_expr.filters:
filter_name = getattr(func, '_filter_name', None)
if filter_name in ('escape', 'safe'):
raise TemplateSyntaxError('"filter %s" is not permitted. Use the "autoescape" tag instead.' % filter_name)
nodelist = parser.parse(('endfilter',))
parser.delete_first_token()
return FilterNode(filter_expr, nodelist) | [
"def",
"do_filter",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"_",
",",
"rest",
"=",
"token",
".",
"contents",
".",
"split",
"(",
"None",
",",
"1",
")",
"filter_expr",
"=",
"parser",
".",
"compile_filter",
"(",
"\"var|%s\"",
"%",
"(",
"rest",
")",
")",
"for",
"func",
",",
"unused",
"in",
"filter_expr",
".",
"filters",
":",
"filter_name",
"=",
"getattr",
"(",
"func",
",",
"'_filter_name'",
",",
"None",
")",
"if",
"filter_name",
"in",
"(",
"'escape'",
",",
"'safe'",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"'\"filter %s\" is not permitted. Use the \"autoescape\" tag instead.'",
"%",
"filter_name",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endfilter'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"FilterNode",
"(",
"filter_expr",
",",
"nodelist",
")"
] | [
653,
0
] | [
679,
44
] | python | en | ['en', 'error', 'th'] | False |
firstof | (parser, token) |
Output the first variable passed that is not False.
Output nothing if all the passed variables are False.
Sample usage::
{% firstof var1 var2 var3 as myvar %}
This is equivalent to::
{% if var1 %}
{{ var1 }}
{% elif var2 %}
{{ var2 }}
{% elif var3 %}
{{ var3 }}
{% endif %}
but much cleaner!
You can also use a literal string as a fallback value in case all
passed variables are False::
{% firstof var1 var2 var3 "fallback value" %}
If you want to disable auto-escaping of variables you can use::
{% autoescape off %}
{% firstof var1 var2 var3 "<strong>fallback value</strong>" %}
{% autoescape %}
Or if only some variables should be escaped, you can use::
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}
|
Output the first variable passed that is not False. | def firstof(parser, token):
"""
Output the first variable passed that is not False.
Output nothing if all the passed variables are False.
Sample usage::
{% firstof var1 var2 var3 as myvar %}
This is equivalent to::
{% if var1 %}
{{ var1 }}
{% elif var2 %}
{{ var2 }}
{% elif var3 %}
{{ var3 }}
{% endif %}
but much cleaner!
You can also use a literal string as a fallback value in case all
passed variables are False::
{% firstof var1 var2 var3 "fallback value" %}
If you want to disable auto-escaping of variables you can use::
{% autoescape off %}
{% firstof var1 var2 var3 "<strong>fallback value</strong>" %}
{% autoescape %}
Or if only some variables should be escaped, you can use::
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}
"""
bits = token.split_contents()[1:]
asvar = None
if not bits:
raise TemplateSyntaxError("'firstof' statement requires at least one argument")
if len(bits) >= 2 and bits[-2] == 'as':
asvar = bits[-1]
bits = bits[:-2]
return FirstOfNode([parser.compile_filter(bit) for bit in bits], asvar) | [
"def",
"firstof",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"asvar",
"=",
"None",
"if",
"not",
"bits",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'firstof' statement requires at least one argument\"",
")",
"if",
"len",
"(",
"bits",
")",
">=",
"2",
"and",
"bits",
"[",
"-",
"2",
"]",
"==",
"'as'",
":",
"asvar",
"=",
"bits",
"[",
"-",
"1",
"]",
"bits",
"=",
"bits",
"[",
":",
"-",
"2",
"]",
"return",
"FirstOfNode",
"(",
"[",
"parser",
".",
"compile_filter",
"(",
"bit",
")",
"for",
"bit",
"in",
"bits",
"]",
",",
"asvar",
")"
] | [
683,
0
] | [
728,
75
] | python | en | ['en', 'error', 'th'] | False |
do_for | (parser, token) |
Loop over each item in an array.
For example, to display a list of athletes given ``athlete_list``::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
You can loop over a list in reverse by using
``{% for obj in list reversed %}``.
You can also unpack multiple values from a two-dimensional array::
{% for key,value in dict.items %}
{{ key }}: {{ value }}
{% endfor %}
The ``for`` tag can take an optional ``{% empty %}`` clause that will
be displayed if the given array is empty or could not be found::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
<ul>
The above is equivalent to -- but shorter, cleaner, and possibly faster
than -- the following::
<ul>
{% if athlete_list %}
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
{% else %}
<li>Sorry, no athletes in this list.</li>
{% endif %}
</ul>
The for loop sets a number of variables available within the loop:
========================== ================================================
Variable Description
========================== ================================================
``forloop.counter`` The current iteration of the loop (1-indexed)
``forloop.counter0`` The current iteration of the loop (0-indexed)
``forloop.revcounter`` The number of iterations from the end of the
loop (1-indexed)
``forloop.revcounter0`` The number of iterations from the end of the
loop (0-indexed)
``forloop.first`` True if this is the first time through the loop
``forloop.last`` True if this is the last time through the loop
``forloop.parentloop`` For nested loops, this is the loop "above" the
current one
========================== ================================================
|
Loop over each item in an array. | def do_for(parser, token):
"""
Loop over each item in an array.
For example, to display a list of athletes given ``athlete_list``::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
You can loop over a list in reverse by using
``{% for obj in list reversed %}``.
You can also unpack multiple values from a two-dimensional array::
{% for key,value in dict.items %}
{{ key }}: {{ value }}
{% endfor %}
The ``for`` tag can take an optional ``{% empty %}`` clause that will
be displayed if the given array is empty or could not be found::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
<ul>
The above is equivalent to -- but shorter, cleaner, and possibly faster
than -- the following::
<ul>
{% if athlete_list %}
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
{% else %}
<li>Sorry, no athletes in this list.</li>
{% endif %}
</ul>
The for loop sets a number of variables available within the loop:
========================== ================================================
Variable Description
========================== ================================================
``forloop.counter`` The current iteration of the loop (1-indexed)
``forloop.counter0`` The current iteration of the loop (0-indexed)
``forloop.revcounter`` The number of iterations from the end of the
loop (1-indexed)
``forloop.revcounter0`` The number of iterations from the end of the
loop (0-indexed)
``forloop.first`` True if this is the first time through the loop
``forloop.last`` True if this is the last time through the loop
``forloop.parentloop`` For nested loops, this is the loop "above" the
current one
========================== ================================================
"""
bits = token.split_contents()
if len(bits) < 4:
raise TemplateSyntaxError("'for' statements should have at least four"
" words: %s" % token.contents)
is_reversed = bits[-1] == 'reversed'
in_index = -3 if is_reversed else -2
if bits[in_index] != 'in':
raise TemplateSyntaxError("'for' statements should use the format"
" 'for x in y': %s" % token.contents)
invalid_chars = frozenset((' ', '"', "'", FILTER_SEPARATOR))
loopvars = re.split(r' *, *', ' '.join(bits[1:in_index]))
for var in loopvars:
if not var or not invalid_chars.isdisjoint(var):
raise TemplateSyntaxError("'for' tag received an invalid argument:"
" %s" % token.contents)
sequence = parser.compile_filter(bits[in_index + 1])
nodelist_loop = parser.parse(('empty', 'endfor',))
token = parser.next_token()
if token.contents == 'empty':
nodelist_empty = parser.parse(('endfor',))
parser.delete_first_token()
else:
nodelist_empty = None
return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty) | [
"def",
"do_for",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"4",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'for' statements should have at least four\"",
"\" words: %s\"",
"%",
"token",
".",
"contents",
")",
"is_reversed",
"=",
"bits",
"[",
"-",
"1",
"]",
"==",
"'reversed'",
"in_index",
"=",
"-",
"3",
"if",
"is_reversed",
"else",
"-",
"2",
"if",
"bits",
"[",
"in_index",
"]",
"!=",
"'in'",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'for' statements should use the format\"",
"\" 'for x in y': %s\"",
"%",
"token",
".",
"contents",
")",
"invalid_chars",
"=",
"frozenset",
"(",
"(",
"' '",
",",
"'\"'",
",",
"\"'\"",
",",
"FILTER_SEPARATOR",
")",
")",
"loopvars",
"=",
"re",
".",
"split",
"(",
"r' *, *'",
",",
"' '",
".",
"join",
"(",
"bits",
"[",
"1",
":",
"in_index",
"]",
")",
")",
"for",
"var",
"in",
"loopvars",
":",
"if",
"not",
"var",
"or",
"not",
"invalid_chars",
".",
"isdisjoint",
"(",
"var",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'for' tag received an invalid argument:\"",
"\" %s\"",
"%",
"token",
".",
"contents",
")",
"sequence",
"=",
"parser",
".",
"compile_filter",
"(",
"bits",
"[",
"in_index",
"+",
"1",
"]",
")",
"nodelist_loop",
"=",
"parser",
".",
"parse",
"(",
"(",
"'empty'",
",",
"'endfor'",
",",
")",
")",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"if",
"token",
".",
"contents",
"==",
"'empty'",
":",
"nodelist_empty",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endfor'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"else",
":",
"nodelist_empty",
"=",
"None",
"return",
"ForNode",
"(",
"loopvars",
",",
"sequence",
",",
"is_reversed",
",",
"nodelist_loop",
",",
"nodelist_empty",
")"
] | [
732,
0
] | [
820,
82
] | python | en | ['en', 'error', 'th'] | False |
ifequal | (parser, token) |
Output the contents of the block if the two arguments equal each other.
Examples::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
{% ifnotequal user.id comment.user_id %}
...
{% else %}
...
{% endifnotequal %}
|
Output the contents of the block if the two arguments equal each other. | def ifequal(parser, token):
"""
Output the contents of the block if the two arguments equal each other.
Examples::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
{% ifnotequal user.id comment.user_id %}
...
{% else %}
...
{% endifnotequal %}
"""
warnings.warn(
'The {% ifequal %} template tag is deprecated in favor of {% if %}.',
RemovedInDjango40Warning,
)
return do_ifequal(parser, token, False) | [
"def",
"ifequal",
"(",
"parser",
",",
"token",
")",
":",
"warnings",
".",
"warn",
"(",
"'The {% ifequal %} template tag is deprecated in favor of {% if %}.'",
",",
"RemovedInDjango40Warning",
",",
")",
"return",
"do_ifequal",
"(",
"parser",
",",
"token",
",",
"False",
")"
] | [
842,
0
] | [
862,
43
] | python | en | ['en', 'error', 'th'] | False |
ifnotequal | (parser, token) |
Output the contents of the block if the two arguments are not equal.
See ifequal.
|
Output the contents of the block if the two arguments are not equal.
See ifequal.
| def ifnotequal(parser, token):
"""
Output the contents of the block if the two arguments are not equal.
See ifequal.
"""
warnings.warn(
'The {% ifnotequal %} template tag is deprecated in favor of '
'{% if %}.',
RemovedInDjango40Warning,
)
return do_ifequal(parser, token, True) | [
"def",
"ifnotequal",
"(",
"parser",
",",
"token",
")",
":",
"warnings",
".",
"warn",
"(",
"'The {% ifnotequal %} template tag is deprecated in favor of '",
"'{% if %}.'",
",",
"RemovedInDjango40Warning",
",",
")",
"return",
"do_ifequal",
"(",
"parser",
",",
"token",
",",
"True",
")"
] | [
866,
0
] | [
876,
42
] | python | en | ['en', 'error', 'th'] | False |
do_if | (parser, token) |
Evaluate a variable, and if that variable is "true" (i.e., exists, is not
empty, and is not a false boolean value), output the contents of the block:
::
{% if athlete_list %}
Number of athletes: {{ athlete_list|count }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
In the above, if ``athlete_list`` is not empty, the number of athletes will
be displayed by the ``{{ athlete_list|count }}`` variable.
The ``if`` tag may take one or several `` {% elif %}`` clauses, as well as
an ``{% else %}`` clause that will be displayed if all previous conditions
fail. These clauses are optional.
``if`` tags may use ``or``, ``and`` or ``not`` to test a number of
variables or to negate a given variable::
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes, or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
Comparison operators are also available, and the use of filters is also
allowed, for example::
{% if articles|length >= 5 %}...{% endif %}
Arguments and operators _must_ have a space between them, so
``{% if 1>2 %}`` is not a valid if tag.
All supported operators are: ``or``, ``and``, ``in``, ``not in``
``==``, ``!=``, ``>``, ``>=``, ``<`` and ``<=``.
Operator precedence follows Python.
|
Evaluate a variable, and if that variable is "true" (i.e., exists, is not
empty, and is not a false boolean value), output the contents of the block: | def do_if(parser, token):
"""
Evaluate a variable, and if that variable is "true" (i.e., exists, is not
empty, and is not a false boolean value), output the contents of the block:
::
{% if athlete_list %}
Number of athletes: {{ athlete_list|count }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
In the above, if ``athlete_list`` is not empty, the number of athletes will
be displayed by the ``{{ athlete_list|count }}`` variable.
The ``if`` tag may take one or several `` {% elif %}`` clauses, as well as
an ``{% else %}`` clause that will be displayed if all previous conditions
fail. These clauses are optional.
``if`` tags may use ``or``, ``and`` or ``not`` to test a number of
variables or to negate a given variable::
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes, or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
Comparison operators are also available, and the use of filters is also
allowed, for example::
{% if articles|length >= 5 %}...{% endif %}
Arguments and operators _must_ have a space between them, so
``{% if 1>2 %}`` is not a valid if tag.
All supported operators are: ``or``, ``and``, ``in``, ``not in``
``==``, ``!=``, ``>``, ``>=``, ``<`` and ``<=``.
Operator precedence follows Python.
"""
# {% if ... %}
bits = token.split_contents()[1:]
condition = TemplateIfParser(parser, bits).parse()
nodelist = parser.parse(('elif', 'else', 'endif'))
conditions_nodelists = [(condition, nodelist)]
token = parser.next_token()
# {% elif ... %} (repeatable)
while token.contents.startswith('elif'):
bits = token.split_contents()[1:]
condition = TemplateIfParser(parser, bits).parse()
nodelist = parser.parse(('elif', 'else', 'endif'))
conditions_nodelists.append((condition, nodelist))
token = parser.next_token()
# {% else %} (optional)
if token.contents == 'else':
nodelist = parser.parse(('endif',))
conditions_nodelists.append((None, nodelist))
token = parser.next_token()
# {% endif %}
if token.contents != 'endif':
raise TemplateSyntaxError('Malformed template tag at line {}: "{}"'.format(token.lineno, token.contents))
return IfNode(conditions_nodelists) | [
"def",
"do_if",
"(",
"parser",
",",
"token",
")",
":",
"# {% if ... %}",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"condition",
"=",
"TemplateIfParser",
"(",
"parser",
",",
"bits",
")",
".",
"parse",
"(",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'elif'",
",",
"'else'",
",",
"'endif'",
")",
")",
"conditions_nodelists",
"=",
"[",
"(",
"condition",
",",
"nodelist",
")",
"]",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"# {% elif ... %} (repeatable)",
"while",
"token",
".",
"contents",
".",
"startswith",
"(",
"'elif'",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"condition",
"=",
"TemplateIfParser",
"(",
"parser",
",",
"bits",
")",
".",
"parse",
"(",
")",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'elif'",
",",
"'else'",
",",
"'endif'",
")",
")",
"conditions_nodelists",
".",
"append",
"(",
"(",
"condition",
",",
"nodelist",
")",
")",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"# {% else %} (optional)",
"if",
"token",
".",
"contents",
"==",
"'else'",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endif'",
",",
")",
")",
"conditions_nodelists",
".",
"append",
"(",
"(",
"None",
",",
"nodelist",
")",
")",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"# {% endif %}",
"if",
"token",
".",
"contents",
"!=",
"'endif'",
":",
"raise",
"TemplateSyntaxError",
"(",
"'Malformed template tag at line {}: \"{}\"'",
".",
"format",
"(",
"token",
".",
"lineno",
",",
"token",
".",
"contents",
")",
")",
"return",
"IfNode",
"(",
"conditions_nodelists",
")"
] | [
903,
0
] | [
986,
39
] | python | en | ['en', 'error', 'th'] | False |
ifchanged | (parser, token) |
Check if a value has changed from the last iteration of a loop.
The ``{% ifchanged %}`` block tag is used within a loop. It has two
possible uses.
1. Check its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a
list of days, only displaying the month if it changes::
<h1>Archive for {{ year }}</h1>
{% for date in days %}
{% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
{% endfor %}
2. If given one or more variables, check whether any variable has changed.
For example, the following shows the date every time it changes, while
showing the hour if either the hour or the date has changed::
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
{% ifchanged date.hour date.date %}
{{ date.hour }}
{% endifchanged %}
{% endfor %}
|
Check if a value has changed from the last iteration of a loop. | def ifchanged(parser, token):
"""
Check if a value has changed from the last iteration of a loop.
The ``{% ifchanged %}`` block tag is used within a loop. It has two
possible uses.
1. Check its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a
list of days, only displaying the month if it changes::
<h1>Archive for {{ year }}</h1>
{% for date in days %}
{% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
{% endfor %}
2. If given one or more variables, check whether any variable has changed.
For example, the following shows the date every time it changes, while
showing the hour if either the hour or the date has changed::
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
{% ifchanged date.hour date.date %}
{{ date.hour }}
{% endifchanged %}
{% endfor %}
"""
bits = token.split_contents()
nodelist_true = parser.parse(('else', 'endifchanged'))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse(('endifchanged',))
parser.delete_first_token()
else:
nodelist_false = NodeList()
values = [parser.compile_filter(bit) for bit in bits[1:]]
return IfChangedNode(nodelist_true, nodelist_false, *values) | [
"def",
"ifchanged",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"nodelist_true",
"=",
"parser",
".",
"parse",
"(",
"(",
"'else'",
",",
"'endifchanged'",
")",
")",
"token",
"=",
"parser",
".",
"next_token",
"(",
")",
"if",
"token",
".",
"contents",
"==",
"'else'",
":",
"nodelist_false",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endifchanged'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"else",
":",
"nodelist_false",
"=",
"NodeList",
"(",
")",
"values",
"=",
"[",
"parser",
".",
"compile_filter",
"(",
"bit",
")",
"for",
"bit",
"in",
"bits",
"[",
"1",
":",
"]",
"]",
"return",
"IfChangedNode",
"(",
"nodelist_true",
",",
"nodelist_false",
",",
"*",
"values",
")"
] | [
990,
0
] | [
1028,
64
] | python | en | ['en', 'error', 'th'] | False |
load_from_library | (library, label, names) |
Return a subset of tags and filters from a library.
|
Return a subset of tags and filters from a library.
| def load_from_library(library, label, names):
"""
Return a subset of tags and filters from a library.
"""
subset = Library()
for name in names:
found = False
if name in library.tags:
found = True
subset.tags[name] = library.tags[name]
if name in library.filters:
found = True
subset.filters[name] = library.filters[name]
if found is False:
raise TemplateSyntaxError(
"'%s' is not a valid tag or filter in tag library '%s'" % (
name, label,
),
)
return subset | [
"def",
"load_from_library",
"(",
"library",
",",
"label",
",",
"names",
")",
":",
"subset",
"=",
"Library",
"(",
")",
"for",
"name",
"in",
"names",
":",
"found",
"=",
"False",
"if",
"name",
"in",
"library",
".",
"tags",
":",
"found",
"=",
"True",
"subset",
".",
"tags",
"[",
"name",
"]",
"=",
"library",
".",
"tags",
"[",
"name",
"]",
"if",
"name",
"in",
"library",
".",
"filters",
":",
"found",
"=",
"True",
"subset",
".",
"filters",
"[",
"name",
"]",
"=",
"library",
".",
"filters",
"[",
"name",
"]",
"if",
"found",
"is",
"False",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' is not a valid tag or filter in tag library '%s'\"",
"%",
"(",
"name",
",",
"label",
",",
")",
",",
")",
"return",
"subset"
] | [
1042,
0
] | [
1061,
17
] | python | en | ['en', 'error', 'th'] | False |
load | (parser, token) |
Load a custom template tag library into the parser.
For example, to load the template tags in
``django/templatetags/news/photos.py``::
{% load news.photos %}
Can also be used to load an individual tag/filter from
a library::
{% load byline from news %}
|
Load a custom template tag library into the parser. | def load(parser, token):
"""
Load a custom template tag library into the parser.
For example, to load the template tags in
``django/templatetags/news/photos.py``::
{% load news.photos %}
Can also be used to load an individual tag/filter from
a library::
{% load byline from news %}
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
bits = token.contents.split()
if len(bits) >= 4 and bits[-2] == "from":
# from syntax is used; load individual tags from the library
name = bits[-1]
lib = find_library(parser, name)
subset = load_from_library(lib, name, bits[1:-2])
parser.add_library(subset)
else:
# one or more libraries are specified; load and add them to the parser
for name in bits[1:]:
lib = find_library(parser, name)
parser.add_library(lib)
return LoadNode() | [
"def",
"load",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">=",
"4",
"and",
"bits",
"[",
"-",
"2",
"]",
"==",
"\"from\"",
":",
"# from syntax is used; load individual tags from the library",
"name",
"=",
"bits",
"[",
"-",
"1",
"]",
"lib",
"=",
"find_library",
"(",
"parser",
",",
"name",
")",
"subset",
"=",
"load_from_library",
"(",
"lib",
",",
"name",
",",
"bits",
"[",
"1",
":",
"-",
"2",
"]",
")",
"parser",
".",
"add_library",
"(",
"subset",
")",
"else",
":",
"# one or more libraries are specified; load and add them to the parser",
"for",
"name",
"in",
"bits",
"[",
"1",
":",
"]",
":",
"lib",
"=",
"find_library",
"(",
"parser",
",",
"name",
")",
"parser",
".",
"add_library",
"(",
"lib",
")",
"return",
"LoadNode",
"(",
")"
] | [
1065,
0
] | [
1092,
21
] | python | en | ['en', 'error', 'th'] | False |
lorem | (parser, token) |
Create random Latin text useful for providing test data in templates.
Usage format::
{% lorem [count] [method] [random] %}
``count`` is a number (or variable) containing the number of paragraphs or
words to generate (default is 1).
``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for
plain-text paragraph blocks (default is ``b``).
``random`` is the word ``random``, which if given, does not use the common
paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
Examples:
* ``{% lorem %}`` outputs the common "lorem ipsum" paragraph
* ``{% lorem 3 p %}`` outputs the common "lorem ipsum" paragraph
and two random paragraphs each wrapped in HTML ``<p>`` tags
* ``{% lorem 2 w random %}`` outputs two random latin words
|
Create random Latin text useful for providing test data in templates. | def lorem(parser, token):
"""
Create random Latin text useful for providing test data in templates.
Usage format::
{% lorem [count] [method] [random] %}
``count`` is a number (or variable) containing the number of paragraphs or
words to generate (default is 1).
``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for
plain-text paragraph blocks (default is ``b``).
``random`` is the word ``random``, which if given, does not use the common
paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
Examples:
* ``{% lorem %}`` outputs the common "lorem ipsum" paragraph
* ``{% lorem 3 p %}`` outputs the common "lorem ipsum" paragraph
and two random paragraphs each wrapped in HTML ``<p>`` tags
* ``{% lorem 2 w random %}`` outputs two random latin words
"""
bits = list(token.split_contents())
tagname = bits[0]
# Random bit
common = bits[-1] != 'random'
if not common:
bits.pop()
# Method bit
if bits[-1] in ('w', 'p', 'b'):
method = bits.pop()
else:
method = 'b'
# Count bit
if len(bits) > 1:
count = bits.pop()
else:
count = '1'
count = parser.compile_filter(count)
if len(bits) != 1:
raise TemplateSyntaxError("Incorrect format for %r tag" % tagname)
return LoremNode(count, method, common) | [
"def",
"lorem",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"list",
"(",
"token",
".",
"split_contents",
"(",
")",
")",
"tagname",
"=",
"bits",
"[",
"0",
"]",
"# Random bit",
"common",
"=",
"bits",
"[",
"-",
"1",
"]",
"!=",
"'random'",
"if",
"not",
"common",
":",
"bits",
".",
"pop",
"(",
")",
"# Method bit",
"if",
"bits",
"[",
"-",
"1",
"]",
"in",
"(",
"'w'",
",",
"'p'",
",",
"'b'",
")",
":",
"method",
"=",
"bits",
".",
"pop",
"(",
")",
"else",
":",
"method",
"=",
"'b'",
"# Count bit",
"if",
"len",
"(",
"bits",
")",
">",
"1",
":",
"count",
"=",
"bits",
".",
"pop",
"(",
")",
"else",
":",
"count",
"=",
"'1'",
"count",
"=",
"parser",
".",
"compile_filter",
"(",
"count",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"1",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"Incorrect format for %r tag\"",
"%",
"tagname",
")",
"return",
"LoremNode",
"(",
"count",
",",
"method",
",",
"common",
")"
] | [
1096,
0
] | [
1139,
43
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.