id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
8,700
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/templatetags/thumbnail.py
|
data_uri
|
def data_uri(thumbnail):
"""
This filter will return the base64 encoded data URI for a given thumbnail object.
Example usage::
{% thumbnail sample_image 25x25 crop as thumb %}
<img src="{{ thumb|data_uri }}">
will for instance be rendered as:
<img src="data:image/png;base64,iVBORw0KGgo...">
"""
try:
thumbnail.open('rb')
data = thumbnail.read()
finally:
thumbnail.close()
mime_type = mimetypes.guess_type(str(thumbnail.file))[0] or 'application/octet-stream'
data = b64encode(data).decode('utf-8')
return 'data:{0};base64,{1}'.format(mime_type, data)
|
python
|
def data_uri(thumbnail):
"""
This filter will return the base64 encoded data URI for a given thumbnail object.
Example usage::
{% thumbnail sample_image 25x25 crop as thumb %}
<img src="{{ thumb|data_uri }}">
will for instance be rendered as:
<img src="data:image/png;base64,iVBORw0KGgo...">
"""
try:
thumbnail.open('rb')
data = thumbnail.read()
finally:
thumbnail.close()
mime_type = mimetypes.guess_type(str(thumbnail.file))[0] or 'application/octet-stream'
data = b64encode(data).decode('utf-8')
return 'data:{0};base64,{1}'.format(mime_type, data)
|
[
"def",
"data_uri",
"(",
"thumbnail",
")",
":",
"try",
":",
"thumbnail",
".",
"open",
"(",
"'rb'",
")",
"data",
"=",
"thumbnail",
".",
"read",
"(",
")",
"finally",
":",
"thumbnail",
".",
"close",
"(",
")",
"mime_type",
"=",
"mimetypes",
".",
"guess_type",
"(",
"str",
"(",
"thumbnail",
".",
"file",
")",
")",
"[",
"0",
"]",
"or",
"'application/octet-stream'",
"data",
"=",
"b64encode",
"(",
"data",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"'data:{0};base64,{1}'",
".",
"format",
"(",
"mime_type",
",",
"data",
")"
] |
This filter will return the base64 encoded data URI for a given thumbnail object.
Example usage::
{% thumbnail sample_image 25x25 crop as thumb %}
<img src="{{ thumb|data_uri }}">
will for instance be rendered as:
<img src="data:image/png;base64,iVBORw0KGgo...">
|
[
"This",
"filter",
"will",
"return",
"the",
"base64",
"encoded",
"data",
"URI",
"for",
"a",
"given",
"thumbnail",
"object",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/templatetags/thumbnail.py#L306-L326
|
8,701
|
SmileyChris/easy-thumbnails
|
setup.py
|
read_files
|
def read_files(*filenames):
"""
Output the contents of one or more files to a single concatenated string.
"""
output = []
for filename in filenames:
f = codecs.open(filename, encoding='utf-8')
try:
output.append(f.read())
finally:
f.close()
return '\n\n'.join(output)
|
python
|
def read_files(*filenames):
"""
Output the contents of one or more files to a single concatenated string.
"""
output = []
for filename in filenames:
f = codecs.open(filename, encoding='utf-8')
try:
output.append(f.read())
finally:
f.close()
return '\n\n'.join(output)
|
[
"def",
"read_files",
"(",
"*",
"filenames",
")",
":",
"output",
"=",
"[",
"]",
"for",
"filename",
"in",
"filenames",
":",
"f",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"try",
":",
"output",
".",
"append",
"(",
"f",
".",
"read",
"(",
")",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"return",
"'\\n\\n'",
".",
"join",
"(",
"output",
")"
] |
Output the contents of one or more files to a single concatenated string.
|
[
"Output",
"the",
"contents",
"of",
"one",
"or",
"more",
"files",
"to",
"a",
"single",
"concatenated",
"string",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/setup.py#L26-L37
|
8,702
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/management/__init__.py
|
all_thumbnails
|
def all_thumbnails(path, recursive=True, prefix=None, subdir=None):
"""
Return a dictionary referencing all files which match the thumbnail format.
Each key is a source image filename, relative to path.
Each value is a list of dictionaries as explained in `thumbnails_for_file`.
"""
if prefix is None:
prefix = settings.THUMBNAIL_PREFIX
if subdir is None:
subdir = settings.THUMBNAIL_SUBDIR
thumbnail_files = {}
if not path.endswith('/'):
path = '%s/' % path
len_path = len(path)
if recursive:
all = os.walk(path)
else:
files = []
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
files.append(file)
all = [(path, [], files)]
for dir_, subdirs, files in all:
rel_dir = dir_[len_path:]
for file in files:
thumb = re_thumbnail_file.match(file)
if not thumb:
continue
d = thumb.groupdict()
source_filename = d.pop('source_filename')
if prefix:
source_path, source_filename = os.path.split(source_filename)
if not source_filename.startswith(prefix):
continue
source_filename = os.path.join(
source_path, source_filename[len(prefix):])
d['options'] = d['options'] and d['options'].split('_') or []
if subdir and rel_dir.endswith(subdir):
rel_dir = rel_dir[:-len(subdir)]
# Corner-case bug: if the filename didn't have an extension but did
# have an underscore, the last underscore will get converted to a
# '.'.
m = re.match(r'(.*)_(.*)', source_filename)
if m:
source_filename = '%s.%s' % m.groups()
filename = os.path.join(rel_dir, source_filename)
thumbnail_file = thumbnail_files.setdefault(filename, [])
d['filename'] = os.path.join(dir_, file)
thumbnail_file.append(d)
return thumbnail_files
|
python
|
def all_thumbnails(path, recursive=True, prefix=None, subdir=None):
"""
Return a dictionary referencing all files which match the thumbnail format.
Each key is a source image filename, relative to path.
Each value is a list of dictionaries as explained in `thumbnails_for_file`.
"""
if prefix is None:
prefix = settings.THUMBNAIL_PREFIX
if subdir is None:
subdir = settings.THUMBNAIL_SUBDIR
thumbnail_files = {}
if not path.endswith('/'):
path = '%s/' % path
len_path = len(path)
if recursive:
all = os.walk(path)
else:
files = []
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
files.append(file)
all = [(path, [], files)]
for dir_, subdirs, files in all:
rel_dir = dir_[len_path:]
for file in files:
thumb = re_thumbnail_file.match(file)
if not thumb:
continue
d = thumb.groupdict()
source_filename = d.pop('source_filename')
if prefix:
source_path, source_filename = os.path.split(source_filename)
if not source_filename.startswith(prefix):
continue
source_filename = os.path.join(
source_path, source_filename[len(prefix):])
d['options'] = d['options'] and d['options'].split('_') or []
if subdir and rel_dir.endswith(subdir):
rel_dir = rel_dir[:-len(subdir)]
# Corner-case bug: if the filename didn't have an extension but did
# have an underscore, the last underscore will get converted to a
# '.'.
m = re.match(r'(.*)_(.*)', source_filename)
if m:
source_filename = '%s.%s' % m.groups()
filename = os.path.join(rel_dir, source_filename)
thumbnail_file = thumbnail_files.setdefault(filename, [])
d['filename'] = os.path.join(dir_, file)
thumbnail_file.append(d)
return thumbnail_files
|
[
"def",
"all_thumbnails",
"(",
"path",
",",
"recursive",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"subdir",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"settings",
".",
"THUMBNAIL_PREFIX",
"if",
"subdir",
"is",
"None",
":",
"subdir",
"=",
"settings",
".",
"THUMBNAIL_SUBDIR",
"thumbnail_files",
"=",
"{",
"}",
"if",
"not",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"path",
"=",
"'%s/'",
"%",
"path",
"len_path",
"=",
"len",
"(",
"path",
")",
"if",
"recursive",
":",
"all",
"=",
"os",
".",
"walk",
"(",
"path",
")",
"else",
":",
"files",
"=",
"[",
"]",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"file",
")",
")",
":",
"files",
".",
"append",
"(",
"file",
")",
"all",
"=",
"[",
"(",
"path",
",",
"[",
"]",
",",
"files",
")",
"]",
"for",
"dir_",
",",
"subdirs",
",",
"files",
"in",
"all",
":",
"rel_dir",
"=",
"dir_",
"[",
"len_path",
":",
"]",
"for",
"file",
"in",
"files",
":",
"thumb",
"=",
"re_thumbnail_file",
".",
"match",
"(",
"file",
")",
"if",
"not",
"thumb",
":",
"continue",
"d",
"=",
"thumb",
".",
"groupdict",
"(",
")",
"source_filename",
"=",
"d",
".",
"pop",
"(",
"'source_filename'",
")",
"if",
"prefix",
":",
"source_path",
",",
"source_filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"source_filename",
")",
"if",
"not",
"source_filename",
".",
"startswith",
"(",
"prefix",
")",
":",
"continue",
"source_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"source_path",
",",
"source_filename",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
")",
"d",
"[",
"'options'",
"]",
"=",
"d",
"[",
"'options'",
"]",
"and",
"d",
"[",
"'options'",
"]",
".",
"split",
"(",
"'_'",
")",
"or",
"[",
"]",
"if",
"subdir",
"and",
"rel_dir",
".",
"endswith",
"(",
"subdir",
")",
":",
"rel_dir",
"=",
"rel_dir",
"[",
":",
"-",
"len",
"(",
"subdir",
")",
"]",
"# Corner-case bug: if the filename didn't have an extension but did",
"# have an underscore, the last underscore will get converted to a",
"# '.'.",
"m",
"=",
"re",
".",
"match",
"(",
"r'(.*)_(.*)'",
",",
"source_filename",
")",
"if",
"m",
":",
"source_filename",
"=",
"'%s.%s'",
"%",
"m",
".",
"groups",
"(",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"rel_dir",
",",
"source_filename",
")",
"thumbnail_file",
"=",
"thumbnail_files",
".",
"setdefault",
"(",
"filename",
",",
"[",
"]",
")",
"d",
"[",
"'filename'",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_",
",",
"file",
")",
"thumbnail_file",
".",
"append",
"(",
"d",
")",
"return",
"thumbnail_files"
] |
Return a dictionary referencing all files which match the thumbnail format.
Each key is a source image filename, relative to path.
Each value is a list of dictionaries as explained in `thumbnails_for_file`.
|
[
"Return",
"a",
"dictionary",
"referencing",
"all",
"files",
"which",
"match",
"the",
"thumbnail",
"format",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L11-L61
|
8,703
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/management/__init__.py
|
thumbnails_for_file
|
def thumbnails_for_file(relative_source_path, root=None, basedir=None,
subdir=None, prefix=None):
"""
Return a list of dictionaries, one for each thumbnail belonging to the
source image.
The following list explains each key of the dictionary:
`filename` -- absolute thumbnail path
`x` and `y` -- the size of the thumbnail
`options` -- list of options for this thumbnail
`quality` -- quality setting for this thumbnail
"""
if root is None:
root = settings.MEDIA_ROOT
if prefix is None:
prefix = settings.THUMBNAIL_PREFIX
if subdir is None:
subdir = settings.THUMBNAIL_SUBDIR
if basedir is None:
basedir = settings.THUMBNAIL_BASEDIR
source_dir, filename = os.path.split(relative_source_path)
thumbs_path = os.path.join(root, basedir, source_dir, subdir)
if not os.path.isdir(thumbs_path):
return []
files = all_thumbnails(thumbs_path, recursive=False, prefix=prefix,
subdir='')
return files.get(filename, [])
|
python
|
def thumbnails_for_file(relative_source_path, root=None, basedir=None,
subdir=None, prefix=None):
"""
Return a list of dictionaries, one for each thumbnail belonging to the
source image.
The following list explains each key of the dictionary:
`filename` -- absolute thumbnail path
`x` and `y` -- the size of the thumbnail
`options` -- list of options for this thumbnail
`quality` -- quality setting for this thumbnail
"""
if root is None:
root = settings.MEDIA_ROOT
if prefix is None:
prefix = settings.THUMBNAIL_PREFIX
if subdir is None:
subdir = settings.THUMBNAIL_SUBDIR
if basedir is None:
basedir = settings.THUMBNAIL_BASEDIR
source_dir, filename = os.path.split(relative_source_path)
thumbs_path = os.path.join(root, basedir, source_dir, subdir)
if not os.path.isdir(thumbs_path):
return []
files = all_thumbnails(thumbs_path, recursive=False, prefix=prefix,
subdir='')
return files.get(filename, [])
|
[
"def",
"thumbnails_for_file",
"(",
"relative_source_path",
",",
"root",
"=",
"None",
",",
"basedir",
"=",
"None",
",",
"subdir",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"settings",
".",
"MEDIA_ROOT",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"settings",
".",
"THUMBNAIL_PREFIX",
"if",
"subdir",
"is",
"None",
":",
"subdir",
"=",
"settings",
".",
"THUMBNAIL_SUBDIR",
"if",
"basedir",
"is",
"None",
":",
"basedir",
"=",
"settings",
".",
"THUMBNAIL_BASEDIR",
"source_dir",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"relative_source_path",
")",
"thumbs_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"basedir",
",",
"source_dir",
",",
"subdir",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"thumbs_path",
")",
":",
"return",
"[",
"]",
"files",
"=",
"all_thumbnails",
"(",
"thumbs_path",
",",
"recursive",
"=",
"False",
",",
"prefix",
"=",
"prefix",
",",
"subdir",
"=",
"''",
")",
"return",
"files",
".",
"get",
"(",
"filename",
",",
"[",
"]",
")"
] |
Return a list of dictionaries, one for each thumbnail belonging to the
source image.
The following list explains each key of the dictionary:
`filename` -- absolute thumbnail path
`x` and `y` -- the size of the thumbnail
`options` -- list of options for this thumbnail
`quality` -- quality setting for this thumbnail
|
[
"Return",
"a",
"list",
"of",
"dictionaries",
"one",
"for",
"each",
"thumbnail",
"belonging",
"to",
"the",
"source",
"image",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L64-L91
|
8,704
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/management/__init__.py
|
delete_thumbnails
|
def delete_thumbnails(relative_source_path, root=None, basedir=None,
subdir=None, prefix=None):
"""
Delete all thumbnails for a source image.
"""
thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir,
prefix)
return _delete_using_thumbs_list(thumbs)
|
python
|
def delete_thumbnails(relative_source_path, root=None, basedir=None,
subdir=None, prefix=None):
"""
Delete all thumbnails for a source image.
"""
thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir,
prefix)
return _delete_using_thumbs_list(thumbs)
|
[
"def",
"delete_thumbnails",
"(",
"relative_source_path",
",",
"root",
"=",
"None",
",",
"basedir",
"=",
"None",
",",
"subdir",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"thumbs",
"=",
"thumbnails_for_file",
"(",
"relative_source_path",
",",
"root",
",",
"basedir",
",",
"subdir",
",",
"prefix",
")",
"return",
"_delete_using_thumbs_list",
"(",
"thumbs",
")"
] |
Delete all thumbnails for a source image.
|
[
"Delete",
"all",
"thumbnails",
"for",
"a",
"source",
"image",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L94-L101
|
8,705
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/management/__init__.py
|
delete_all_thumbnails
|
def delete_all_thumbnails(path, recursive=True):
"""
Delete all files within a path which match the thumbnails pattern.
By default, matching files from all sub-directories are also removed. To
only remove from the path directory, set recursive=False.
"""
total = 0
for thumbs in all_thumbnails(path, recursive=recursive).values():
total += _delete_using_thumbs_list(thumbs)
return total
|
python
|
def delete_all_thumbnails(path, recursive=True):
"""
Delete all files within a path which match the thumbnails pattern.
By default, matching files from all sub-directories are also removed. To
only remove from the path directory, set recursive=False.
"""
total = 0
for thumbs in all_thumbnails(path, recursive=recursive).values():
total += _delete_using_thumbs_list(thumbs)
return total
|
[
"def",
"delete_all_thumbnails",
"(",
"path",
",",
"recursive",
"=",
"True",
")",
":",
"total",
"=",
"0",
"for",
"thumbs",
"in",
"all_thumbnails",
"(",
"path",
",",
"recursive",
"=",
"recursive",
")",
".",
"values",
"(",
")",
":",
"total",
"+=",
"_delete_using_thumbs_list",
"(",
"thumbs",
")",
"return",
"total"
] |
Delete all files within a path which match the thumbnails pattern.
By default, matching files from all sub-directories are also removed. To
only remove from the path directory, set recursive=False.
|
[
"Delete",
"all",
"files",
"within",
"a",
"path",
"which",
"match",
"the",
"thumbnails",
"pattern",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/__init__.py#L117-L127
|
8,706
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/signal_handlers.py
|
signal_committed_filefields
|
def signal_committed_filefields(sender, instance, **kwargs):
"""
A post_save signal handler which sends a signal for each ``FileField`` that
was committed this save.
"""
for field_name in getattr(instance, '_uncommitted_filefields', ()):
fieldfile = getattr(instance, field_name)
# Don't send the signal for deleted files.
if fieldfile:
signals.saved_file.send_robust(sender=sender, fieldfile=fieldfile)
|
python
|
def signal_committed_filefields(sender, instance, **kwargs):
"""
A post_save signal handler which sends a signal for each ``FileField`` that
was committed this save.
"""
for field_name in getattr(instance, '_uncommitted_filefields', ()):
fieldfile = getattr(instance, field_name)
# Don't send the signal for deleted files.
if fieldfile:
signals.saved_file.send_robust(sender=sender, fieldfile=fieldfile)
|
[
"def",
"signal_committed_filefields",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"field_name",
"in",
"getattr",
"(",
"instance",
",",
"'_uncommitted_filefields'",
",",
"(",
")",
")",
":",
"fieldfile",
"=",
"getattr",
"(",
"instance",
",",
"field_name",
")",
"# Don't send the signal for deleted files.",
"if",
"fieldfile",
":",
"signals",
".",
"saved_file",
".",
"send_robust",
"(",
"sender",
"=",
"sender",
",",
"fieldfile",
"=",
"fieldfile",
")"
] |
A post_save signal handler which sends a signal for each ``FileField`` that
was committed this save.
|
[
"A",
"post_save",
"signal",
"handler",
"which",
"sends",
"a",
"signal",
"for",
"each",
"FileField",
"that",
"was",
"committed",
"this",
"save",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/signal_handlers.py#L25-L34
|
8,707
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/signal_handlers.py
|
generate_aliases
|
def generate_aliases(fieldfile, **kwargs):
"""
A saved_file signal handler which generates thumbnails for all field,
model, and app specific aliases matching the saved file's field.
"""
# Avoids circular import.
from easy_thumbnails.files import generate_all_aliases
generate_all_aliases(fieldfile, include_global=False)
|
python
|
def generate_aliases(fieldfile, **kwargs):
"""
A saved_file signal handler which generates thumbnails for all field,
model, and app specific aliases matching the saved file's field.
"""
# Avoids circular import.
from easy_thumbnails.files import generate_all_aliases
generate_all_aliases(fieldfile, include_global=False)
|
[
"def",
"generate_aliases",
"(",
"fieldfile",
",",
"*",
"*",
"kwargs",
")",
":",
"# Avoids circular import.",
"from",
"easy_thumbnails",
".",
"files",
"import",
"generate_all_aliases",
"generate_all_aliases",
"(",
"fieldfile",
",",
"include_global",
"=",
"False",
")"
] |
A saved_file signal handler which generates thumbnails for all field,
model, and app specific aliases matching the saved file's field.
|
[
"A",
"saved_file",
"signal",
"handler",
"which",
"generates",
"thumbnails",
"for",
"all",
"field",
"model",
"and",
"app",
"specific",
"aliases",
"matching",
"the",
"saved",
"file",
"s",
"field",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/signal_handlers.py#L37-L44
|
8,708
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/signal_handlers.py
|
generate_aliases_global
|
def generate_aliases_global(fieldfile, **kwargs):
"""
A saved_file signal handler which generates thumbnails for all field,
model, and app specific aliases matching the saved file's field, also
generating thumbnails for each project-wide alias.
"""
# Avoids circular import.
from easy_thumbnails.files import generate_all_aliases
generate_all_aliases(fieldfile, include_global=True)
|
python
|
def generate_aliases_global(fieldfile, **kwargs):
"""
A saved_file signal handler which generates thumbnails for all field,
model, and app specific aliases matching the saved file's field, also
generating thumbnails for each project-wide alias.
"""
# Avoids circular import.
from easy_thumbnails.files import generate_all_aliases
generate_all_aliases(fieldfile, include_global=True)
|
[
"def",
"generate_aliases_global",
"(",
"fieldfile",
",",
"*",
"*",
"kwargs",
")",
":",
"# Avoids circular import.",
"from",
"easy_thumbnails",
".",
"files",
"import",
"generate_all_aliases",
"generate_all_aliases",
"(",
"fieldfile",
",",
"include_global",
"=",
"True",
")"
] |
A saved_file signal handler which generates thumbnails for all field,
model, and app specific aliases matching the saved file's field, also
generating thumbnails for each project-wide alias.
|
[
"A",
"saved_file",
"signal",
"handler",
"which",
"generates",
"thumbnails",
"for",
"all",
"field",
"model",
"and",
"app",
"specific",
"aliases",
"matching",
"the",
"saved",
"file",
"s",
"field",
"also",
"generating",
"thumbnails",
"for",
"each",
"project",
"-",
"wide",
"alias",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/signal_handlers.py#L47-L55
|
8,709
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/processors.py
|
colorspace
|
def colorspace(im, bw=False, replace_alpha=False, **kwargs):
"""
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_and_crop` so palette is
changed before the image is resized.
bw
Make the thumbnail grayscale (not really just black & white).
replace_alpha
Replace any transparency layer with a solid color. For example,
``replace_alpha='#fff'`` would replace the transparency layer with
white.
"""
if im.mode == 'I':
# PIL (and pillow) have can't convert 16 bit grayscale images to lower
# modes, so manually convert them to an 8 bit grayscale.
im = im.point(list(_points_table()), 'L')
is_transparent = utils.is_transparent(im)
is_grayscale = im.mode in ('L', 'LA')
new_mode = im.mode
if is_grayscale or bw:
new_mode = 'L'
else:
new_mode = 'RGB'
if is_transparent:
if replace_alpha:
if im.mode != 'RGBA':
im = im.convert('RGBA')
base = Image.new('RGBA', im.size, replace_alpha)
base.paste(im, mask=im)
im = base
else:
new_mode = new_mode + 'A'
if im.mode != new_mode:
im = im.convert(new_mode)
return im
|
python
|
def colorspace(im, bw=False, replace_alpha=False, **kwargs):
"""
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_and_crop` so palette is
changed before the image is resized.
bw
Make the thumbnail grayscale (not really just black & white).
replace_alpha
Replace any transparency layer with a solid color. For example,
``replace_alpha='#fff'`` would replace the transparency layer with
white.
"""
if im.mode == 'I':
# PIL (and pillow) have can't convert 16 bit grayscale images to lower
# modes, so manually convert them to an 8 bit grayscale.
im = im.point(list(_points_table()), 'L')
is_transparent = utils.is_transparent(im)
is_grayscale = im.mode in ('L', 'LA')
new_mode = im.mode
if is_grayscale or bw:
new_mode = 'L'
else:
new_mode = 'RGB'
if is_transparent:
if replace_alpha:
if im.mode != 'RGBA':
im = im.convert('RGBA')
base = Image.new('RGBA', im.size, replace_alpha)
base.paste(im, mask=im)
im = base
else:
new_mode = new_mode + 'A'
if im.mode != new_mode:
im = im.convert(new_mode)
return im
|
[
"def",
"colorspace",
"(",
"im",
",",
"bw",
"=",
"False",
",",
"replace_alpha",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"im",
".",
"mode",
"==",
"'I'",
":",
"# PIL (and pillow) have can't convert 16 bit grayscale images to lower",
"# modes, so manually convert them to an 8 bit grayscale.",
"im",
"=",
"im",
".",
"point",
"(",
"list",
"(",
"_points_table",
"(",
")",
")",
",",
"'L'",
")",
"is_transparent",
"=",
"utils",
".",
"is_transparent",
"(",
"im",
")",
"is_grayscale",
"=",
"im",
".",
"mode",
"in",
"(",
"'L'",
",",
"'LA'",
")",
"new_mode",
"=",
"im",
".",
"mode",
"if",
"is_grayscale",
"or",
"bw",
":",
"new_mode",
"=",
"'L'",
"else",
":",
"new_mode",
"=",
"'RGB'",
"if",
"is_transparent",
":",
"if",
"replace_alpha",
":",
"if",
"im",
".",
"mode",
"!=",
"'RGBA'",
":",
"im",
"=",
"im",
".",
"convert",
"(",
"'RGBA'",
")",
"base",
"=",
"Image",
".",
"new",
"(",
"'RGBA'",
",",
"im",
".",
"size",
",",
"replace_alpha",
")",
"base",
".",
"paste",
"(",
"im",
",",
"mask",
"=",
"im",
")",
"im",
"=",
"base",
"else",
":",
"new_mode",
"=",
"new_mode",
"+",
"'A'",
"if",
"im",
".",
"mode",
"!=",
"new_mode",
":",
"im",
"=",
"im",
".",
"convert",
"(",
"new_mode",
")",
"return",
"im"
] |
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_and_crop` so palette is
changed before the image is resized.
bw
Make the thumbnail grayscale (not really just black & white).
replace_alpha
Replace any transparency layer with a solid color. For example,
``replace_alpha='#fff'`` would replace the transparency layer with
white.
|
[
"Convert",
"images",
"to",
"the",
"correct",
"color",
"space",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L45-L90
|
8,710
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/processors.py
|
autocrop
|
def autocrop(im, autocrop=False, **kwargs):
"""
Remove any unnecessary whitespace from the edges of the source image.
This processor should be listed before :func:`scale_and_crop` so the
whitespace is removed from the source image before it is resized.
autocrop
Activates the autocrop method for this image.
"""
if autocrop:
# If transparent, flatten.
if utils.is_transparent(im):
no_alpha = Image.new('L', im.size, (255))
no_alpha.paste(im, mask=im.split()[-1])
else:
no_alpha = im.convert('L')
# Convert to black and white image.
bw = no_alpha.convert('L')
# bw = bw.filter(ImageFilter.MedianFilter)
# White background.
bg = Image.new('L', im.size, 255)
bbox = ImageChops.difference(bw, bg).getbbox()
if bbox:
im = im.crop(bbox)
return im
|
python
|
def autocrop(im, autocrop=False, **kwargs):
"""
Remove any unnecessary whitespace from the edges of the source image.
This processor should be listed before :func:`scale_and_crop` so the
whitespace is removed from the source image before it is resized.
autocrop
Activates the autocrop method for this image.
"""
if autocrop:
# If transparent, flatten.
if utils.is_transparent(im):
no_alpha = Image.new('L', im.size, (255))
no_alpha.paste(im, mask=im.split()[-1])
else:
no_alpha = im.convert('L')
# Convert to black and white image.
bw = no_alpha.convert('L')
# bw = bw.filter(ImageFilter.MedianFilter)
# White background.
bg = Image.new('L', im.size, 255)
bbox = ImageChops.difference(bw, bg).getbbox()
if bbox:
im = im.crop(bbox)
return im
|
[
"def",
"autocrop",
"(",
"im",
",",
"autocrop",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"autocrop",
":",
"# If transparent, flatten.",
"if",
"utils",
".",
"is_transparent",
"(",
"im",
")",
":",
"no_alpha",
"=",
"Image",
".",
"new",
"(",
"'L'",
",",
"im",
".",
"size",
",",
"(",
"255",
")",
")",
"no_alpha",
".",
"paste",
"(",
"im",
",",
"mask",
"=",
"im",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
")",
"else",
":",
"no_alpha",
"=",
"im",
".",
"convert",
"(",
"'L'",
")",
"# Convert to black and white image.",
"bw",
"=",
"no_alpha",
".",
"convert",
"(",
"'L'",
")",
"# bw = bw.filter(ImageFilter.MedianFilter)",
"# White background.",
"bg",
"=",
"Image",
".",
"new",
"(",
"'L'",
",",
"im",
".",
"size",
",",
"255",
")",
"bbox",
"=",
"ImageChops",
".",
"difference",
"(",
"bw",
",",
"bg",
")",
".",
"getbbox",
"(",
")",
"if",
"bbox",
":",
"im",
"=",
"im",
".",
"crop",
"(",
"bbox",
")",
"return",
"im"
] |
Remove any unnecessary whitespace from the edges of the source image.
This processor should be listed before :func:`scale_and_crop` so the
whitespace is removed from the source image before it is resized.
autocrop
Activates the autocrop method for this image.
|
[
"Remove",
"any",
"unnecessary",
"whitespace",
"from",
"the",
"edges",
"of",
"the",
"source",
"image",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L93-L119
|
8,711
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/processors.py
|
filters
|
def filters(im, detail=False, sharpen=False, **kwargs):
"""
Pass the source image through post-processing filters.
sharpen
Sharpen the thumbnail image (using the PIL sharpen filter)
detail
Add detail to the image, like a mild *sharpen* (using the PIL
``detail`` filter).
"""
if detail:
im = im.filter(ImageFilter.DETAIL)
if sharpen:
im = im.filter(ImageFilter.SHARPEN)
return im
|
python
|
def filters(im, detail=False, sharpen=False, **kwargs):
"""
Pass the source image through post-processing filters.
sharpen
Sharpen the thumbnail image (using the PIL sharpen filter)
detail
Add detail to the image, like a mild *sharpen* (using the PIL
``detail`` filter).
"""
if detail:
im = im.filter(ImageFilter.DETAIL)
if sharpen:
im = im.filter(ImageFilter.SHARPEN)
return im
|
[
"def",
"filters",
"(",
"im",
",",
"detail",
"=",
"False",
",",
"sharpen",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"detail",
":",
"im",
"=",
"im",
".",
"filter",
"(",
"ImageFilter",
".",
"DETAIL",
")",
"if",
"sharpen",
":",
"im",
"=",
"im",
".",
"filter",
"(",
"ImageFilter",
".",
"SHARPEN",
")",
"return",
"im"
] |
Pass the source image through post-processing filters.
sharpen
Sharpen the thumbnail image (using the PIL sharpen filter)
detail
Add detail to the image, like a mild *sharpen* (using the PIL
``detail`` filter).
|
[
"Pass",
"the",
"source",
"image",
"through",
"post",
"-",
"processing",
"filters",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L280-L296
|
8,712
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/processors.py
|
background
|
def background(im, size, background=None, **kwargs):
"""
Add borders of a certain color to make the resized image fit exactly within
the dimensions given.
background
Background color to use
"""
if not background:
# Primary option not given, nothing to do.
return im
if not size[0] or not size[1]:
# One of the dimensions aren't specified, can't do anything.
return im
x, y = im.size
if x >= size[0] and y >= size[1]:
# The image is already equal to (or larger than) the expected size, so
# there's nothing to do.
return im
im = colorspace(im, replace_alpha=background, **kwargs)
new_im = Image.new('RGB', size, background)
if new_im.mode != im.mode:
new_im = new_im.convert(im.mode)
offset = (size[0]-x)//2, (size[1]-y)//2
new_im.paste(im, offset)
return new_im
|
python
|
def background(im, size, background=None, **kwargs):
"""
Add borders of a certain color to make the resized image fit exactly within
the dimensions given.
background
Background color to use
"""
if not background:
# Primary option not given, nothing to do.
return im
if not size[0] or not size[1]:
# One of the dimensions aren't specified, can't do anything.
return im
x, y = im.size
if x >= size[0] and y >= size[1]:
# The image is already equal to (or larger than) the expected size, so
# there's nothing to do.
return im
im = colorspace(im, replace_alpha=background, **kwargs)
new_im = Image.new('RGB', size, background)
if new_im.mode != im.mode:
new_im = new_im.convert(im.mode)
offset = (size[0]-x)//2, (size[1]-y)//2
new_im.paste(im, offset)
return new_im
|
[
"def",
"background",
"(",
"im",
",",
"size",
",",
"background",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"background",
":",
"# Primary option not given, nothing to do.",
"return",
"im",
"if",
"not",
"size",
"[",
"0",
"]",
"or",
"not",
"size",
"[",
"1",
"]",
":",
"# One of the dimensions aren't specified, can't do anything.",
"return",
"im",
"x",
",",
"y",
"=",
"im",
".",
"size",
"if",
"x",
">=",
"size",
"[",
"0",
"]",
"and",
"y",
">=",
"size",
"[",
"1",
"]",
":",
"# The image is already equal to (or larger than) the expected size, so",
"# there's nothing to do.",
"return",
"im",
"im",
"=",
"colorspace",
"(",
"im",
",",
"replace_alpha",
"=",
"background",
",",
"*",
"*",
"kwargs",
")",
"new_im",
"=",
"Image",
".",
"new",
"(",
"'RGB'",
",",
"size",
",",
"background",
")",
"if",
"new_im",
".",
"mode",
"!=",
"im",
".",
"mode",
":",
"new_im",
"=",
"new_im",
".",
"convert",
"(",
"im",
".",
"mode",
")",
"offset",
"=",
"(",
"size",
"[",
"0",
"]",
"-",
"x",
")",
"//",
"2",
",",
"(",
"size",
"[",
"1",
"]",
"-",
"y",
")",
"//",
"2",
"new_im",
".",
"paste",
"(",
"im",
",",
"offset",
")",
"return",
"new_im"
] |
Add borders of a certain color to make the resized image fit exactly within
the dimensions given.
background
Background color to use
|
[
"Add",
"borders",
"of",
"a",
"certain",
"color",
"to",
"make",
"the",
"resized",
"image",
"fit",
"exactly",
"within",
"the",
"dimensions",
"given",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/processors.py#L299-L324
|
8,713
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
generate_all_aliases
|
def generate_all_aliases(fieldfile, include_global):
"""
Generate all of a file's aliases.
:param fieldfile: A ``FieldFile`` instance.
:param include_global: A boolean which determines whether to generate
thumbnails for project-wide aliases in addition to field, model, and
app specific aliases.
"""
all_options = aliases.all(fieldfile, include_global=include_global)
if all_options:
thumbnailer = get_thumbnailer(fieldfile)
for key, options in six.iteritems(all_options):
options['ALIAS'] = key
thumbnailer.get_thumbnail(options)
|
python
|
def generate_all_aliases(fieldfile, include_global):
"""
Generate all of a file's aliases.
:param fieldfile: A ``FieldFile`` instance.
:param include_global: A boolean which determines whether to generate
thumbnails for project-wide aliases in addition to field, model, and
app specific aliases.
"""
all_options = aliases.all(fieldfile, include_global=include_global)
if all_options:
thumbnailer = get_thumbnailer(fieldfile)
for key, options in six.iteritems(all_options):
options['ALIAS'] = key
thumbnailer.get_thumbnail(options)
|
[
"def",
"generate_all_aliases",
"(",
"fieldfile",
",",
"include_global",
")",
":",
"all_options",
"=",
"aliases",
".",
"all",
"(",
"fieldfile",
",",
"include_global",
"=",
"include_global",
")",
"if",
"all_options",
":",
"thumbnailer",
"=",
"get_thumbnailer",
"(",
"fieldfile",
")",
"for",
"key",
",",
"options",
"in",
"six",
".",
"iteritems",
"(",
"all_options",
")",
":",
"options",
"[",
"'ALIAS'",
"]",
"=",
"key",
"thumbnailer",
".",
"get_thumbnail",
"(",
"options",
")"
] |
Generate all of a file's aliases.
:param fieldfile: A ``FieldFile`` instance.
:param include_global: A boolean which determines whether to generate
thumbnails for project-wide aliases in addition to field, model, and
app specific aliases.
|
[
"Generate",
"all",
"of",
"a",
"file",
"s",
"aliases",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L79-L93
|
8,714
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailFile._get_image
|
def _get_image(self):
"""
Get a PIL Image instance of this file.
The image is cached to avoid the file needing to be read again if the
function is called again.
"""
if not hasattr(self, '_image_cache'):
from easy_thumbnails.source_generators import pil_image
self.image = pil_image(self)
return self._image_cache
|
python
|
def _get_image(self):
"""
Get a PIL Image instance of this file.
The image is cached to avoid the file needing to be read again if the
function is called again.
"""
if not hasattr(self, '_image_cache'):
from easy_thumbnails.source_generators import pil_image
self.image = pil_image(self)
return self._image_cache
|
[
"def",
"_get_image",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_image_cache'",
")",
":",
"from",
"easy_thumbnails",
".",
"source_generators",
"import",
"pil_image",
"self",
".",
"image",
"=",
"pil_image",
"(",
"self",
")",
"return",
"self",
".",
"_image_cache"
] |
Get a PIL Image instance of this file.
The image is cached to avoid the file needing to be read again if the
function is called again.
|
[
"Get",
"a",
"PIL",
"Image",
"instance",
"of",
"this",
"file",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L183-L193
|
8,715
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailFile._set_image
|
def _set_image(self, image):
"""
Set the image for this file.
This also caches the dimensions of the image.
"""
if image:
self._image_cache = image
self._dimensions_cache = image.size
else:
if hasattr(self, '_image_cache'):
del self._cached_image
if hasattr(self, '_dimensions_cache'):
del self._dimensions_cache
|
python
|
def _set_image(self, image):
"""
Set the image for this file.
This also caches the dimensions of the image.
"""
if image:
self._image_cache = image
self._dimensions_cache = image.size
else:
if hasattr(self, '_image_cache'):
del self._cached_image
if hasattr(self, '_dimensions_cache'):
del self._dimensions_cache
|
[
"def",
"_set_image",
"(",
"self",
",",
"image",
")",
":",
"if",
"image",
":",
"self",
".",
"_image_cache",
"=",
"image",
"self",
".",
"_dimensions_cache",
"=",
"image",
".",
"size",
"else",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_image_cache'",
")",
":",
"del",
"self",
".",
"_cached_image",
"if",
"hasattr",
"(",
"self",
",",
"'_dimensions_cache'",
")",
":",
"del",
"self",
".",
"_dimensions_cache"
] |
Set the image for this file.
This also caches the dimensions of the image.
|
[
"Set",
"the",
"image",
"for",
"this",
"file",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L195-L208
|
8,716
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailFile.set_image_dimensions
|
def set_image_dimensions(self, thumbnail):
"""
Set image dimensions from the cached dimensions of a ``Thumbnail``
model instance.
"""
try:
dimensions = getattr(thumbnail, 'dimensions', None)
except models.ThumbnailDimensions.DoesNotExist:
dimensions = None
if not dimensions:
return False
self._dimensions_cache = dimensions.size
return self._dimensions_cache
|
python
|
def set_image_dimensions(self, thumbnail):
"""
Set image dimensions from the cached dimensions of a ``Thumbnail``
model instance.
"""
try:
dimensions = getattr(thumbnail, 'dimensions', None)
except models.ThumbnailDimensions.DoesNotExist:
dimensions = None
if not dimensions:
return False
self._dimensions_cache = dimensions.size
return self._dimensions_cache
|
[
"def",
"set_image_dimensions",
"(",
"self",
",",
"thumbnail",
")",
":",
"try",
":",
"dimensions",
"=",
"getattr",
"(",
"thumbnail",
",",
"'dimensions'",
",",
"None",
")",
"except",
"models",
".",
"ThumbnailDimensions",
".",
"DoesNotExist",
":",
"dimensions",
"=",
"None",
"if",
"not",
"dimensions",
":",
"return",
"False",
"self",
".",
"_dimensions_cache",
"=",
"dimensions",
".",
"size",
"return",
"self",
".",
"_dimensions_cache"
] |
Set image dimensions from the cached dimensions of a ``Thumbnail``
model instance.
|
[
"Set",
"image",
"dimensions",
"from",
"the",
"cached",
"dimensions",
"of",
"a",
"Thumbnail",
"model",
"instance",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L274-L286
|
8,717
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
Thumbnailer.generate_thumbnail
|
def generate_thumbnail(self, thumbnail_options, high_resolution=False,
silent_template_exception=False):
"""
Return an unsaved ``ThumbnailFile`` containing a thumbnail image.
The thumbnail image is generated using the ``thumbnail_options``
dictionary.
"""
thumbnail_options = self.get_options(thumbnail_options)
orig_size = thumbnail_options['size'] # remember original size
# Size sanity check.
min_dim, max_dim = 0, 0
for dim in orig_size:
try:
dim = int(dim)
except (TypeError, ValueError):
continue
min_dim, max_dim = min(min_dim, dim), max(max_dim, dim)
if max_dim == 0 or min_dim < 0:
raise exceptions.EasyThumbnailsError(
"The source image is an invalid size (%sx%s)" % orig_size)
if high_resolution:
thumbnail_options['size'] = (orig_size[0] * 2, orig_size[1] * 2)
image = engine.generate_source_image(
self, thumbnail_options, self.source_generators,
fail_silently=silent_template_exception)
if image is None:
raise exceptions.InvalidImageFormatError(
"The source file does not appear to be an image")
thumbnail_image = engine.process_image(image, thumbnail_options,
self.thumbnail_processors)
if high_resolution:
thumbnail_options['size'] = orig_size # restore original size
filename = self.get_thumbnail_name(
thumbnail_options,
transparent=utils.is_transparent(thumbnail_image),
high_resolution=high_resolution)
quality = thumbnail_options['quality']
subsampling = thumbnail_options['subsampling']
img = engine.save_image(
thumbnail_image, filename=filename, quality=quality,
subsampling=subsampling)
data = img.read()
thumbnail = ThumbnailFile(
filename, file=ContentFile(data), storage=self.thumbnail_storage,
thumbnail_options=thumbnail_options)
thumbnail.image = thumbnail_image
thumbnail._committed = False
return thumbnail
|
python
|
def generate_thumbnail(self, thumbnail_options, high_resolution=False,
silent_template_exception=False):
"""
Return an unsaved ``ThumbnailFile`` containing a thumbnail image.
The thumbnail image is generated using the ``thumbnail_options``
dictionary.
"""
thumbnail_options = self.get_options(thumbnail_options)
orig_size = thumbnail_options['size'] # remember original size
# Size sanity check.
min_dim, max_dim = 0, 0
for dim in orig_size:
try:
dim = int(dim)
except (TypeError, ValueError):
continue
min_dim, max_dim = min(min_dim, dim), max(max_dim, dim)
if max_dim == 0 or min_dim < 0:
raise exceptions.EasyThumbnailsError(
"The source image is an invalid size (%sx%s)" % orig_size)
if high_resolution:
thumbnail_options['size'] = (orig_size[0] * 2, orig_size[1] * 2)
image = engine.generate_source_image(
self, thumbnail_options, self.source_generators,
fail_silently=silent_template_exception)
if image is None:
raise exceptions.InvalidImageFormatError(
"The source file does not appear to be an image")
thumbnail_image = engine.process_image(image, thumbnail_options,
self.thumbnail_processors)
if high_resolution:
thumbnail_options['size'] = orig_size # restore original size
filename = self.get_thumbnail_name(
thumbnail_options,
transparent=utils.is_transparent(thumbnail_image),
high_resolution=high_resolution)
quality = thumbnail_options['quality']
subsampling = thumbnail_options['subsampling']
img = engine.save_image(
thumbnail_image, filename=filename, quality=quality,
subsampling=subsampling)
data = img.read()
thumbnail = ThumbnailFile(
filename, file=ContentFile(data), storage=self.thumbnail_storage,
thumbnail_options=thumbnail_options)
thumbnail.image = thumbnail_image
thumbnail._committed = False
return thumbnail
|
[
"def",
"generate_thumbnail",
"(",
"self",
",",
"thumbnail_options",
",",
"high_resolution",
"=",
"False",
",",
"silent_template_exception",
"=",
"False",
")",
":",
"thumbnail_options",
"=",
"self",
".",
"get_options",
"(",
"thumbnail_options",
")",
"orig_size",
"=",
"thumbnail_options",
"[",
"'size'",
"]",
"# remember original size",
"# Size sanity check.",
"min_dim",
",",
"max_dim",
"=",
"0",
",",
"0",
"for",
"dim",
"in",
"orig_size",
":",
"try",
":",
"dim",
"=",
"int",
"(",
"dim",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"continue",
"min_dim",
",",
"max_dim",
"=",
"min",
"(",
"min_dim",
",",
"dim",
")",
",",
"max",
"(",
"max_dim",
",",
"dim",
")",
"if",
"max_dim",
"==",
"0",
"or",
"min_dim",
"<",
"0",
":",
"raise",
"exceptions",
".",
"EasyThumbnailsError",
"(",
"\"The source image is an invalid size (%sx%s)\"",
"%",
"orig_size",
")",
"if",
"high_resolution",
":",
"thumbnail_options",
"[",
"'size'",
"]",
"=",
"(",
"orig_size",
"[",
"0",
"]",
"*",
"2",
",",
"orig_size",
"[",
"1",
"]",
"*",
"2",
")",
"image",
"=",
"engine",
".",
"generate_source_image",
"(",
"self",
",",
"thumbnail_options",
",",
"self",
".",
"source_generators",
",",
"fail_silently",
"=",
"silent_template_exception",
")",
"if",
"image",
"is",
"None",
":",
"raise",
"exceptions",
".",
"InvalidImageFormatError",
"(",
"\"The source file does not appear to be an image\"",
")",
"thumbnail_image",
"=",
"engine",
".",
"process_image",
"(",
"image",
",",
"thumbnail_options",
",",
"self",
".",
"thumbnail_processors",
")",
"if",
"high_resolution",
":",
"thumbnail_options",
"[",
"'size'",
"]",
"=",
"orig_size",
"# restore original size",
"filename",
"=",
"self",
".",
"get_thumbnail_name",
"(",
"thumbnail_options",
",",
"transparent",
"=",
"utils",
".",
"is_transparent",
"(",
"thumbnail_image",
")",
",",
"high_resolution",
"=",
"high_resolution",
")",
"quality",
"=",
"thumbnail_options",
"[",
"'quality'",
"]",
"subsampling",
"=",
"thumbnail_options",
"[",
"'subsampling'",
"]",
"img",
"=",
"engine",
".",
"save_image",
"(",
"thumbnail_image",
",",
"filename",
"=",
"filename",
",",
"quality",
"=",
"quality",
",",
"subsampling",
"=",
"subsampling",
")",
"data",
"=",
"img",
".",
"read",
"(",
")",
"thumbnail",
"=",
"ThumbnailFile",
"(",
"filename",
",",
"file",
"=",
"ContentFile",
"(",
"data",
")",
",",
"storage",
"=",
"self",
".",
"thumbnail_storage",
",",
"thumbnail_options",
"=",
"thumbnail_options",
")",
"thumbnail",
".",
"image",
"=",
"thumbnail_image",
"thumbnail",
".",
"_committed",
"=",
"False",
"return",
"thumbnail"
] |
Return an unsaved ``ThumbnailFile`` containing a thumbnail image.
The thumbnail image is generated using the ``thumbnail_options``
dictionary.
|
[
"Return",
"an",
"unsaved",
"ThumbnailFile",
"containing",
"a",
"thumbnail",
"image",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L359-L413
|
8,718
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
Thumbnailer.get_existing_thumbnail
|
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False):
"""
Return a ``ThumbnailFile`` containing an existing thumbnail for a set
of thumbnail options, or ``None`` if not found.
"""
thumbnail_options = self.get_options(thumbnail_options)
names = [
self.get_thumbnail_name(
thumbnail_options, transparent=False,
high_resolution=high_resolution)]
transparent_name = self.get_thumbnail_name(
thumbnail_options, transparent=True,
high_resolution=high_resolution)
if transparent_name not in names:
names.append(transparent_name)
for filename in names:
exists = self.thumbnail_exists(filename)
if exists:
thumbnail_file = ThumbnailFile(
name=filename, storage=self.thumbnail_storage,
thumbnail_options=thumbnail_options)
if settings.THUMBNAIL_CACHE_DIMENSIONS:
# If this wasn't local storage, exists will be a thumbnail
# instance so we can store the image dimensions now to save
# a future potential query.
thumbnail_file.set_image_dimensions(exists)
return thumbnail_file
|
python
|
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False):
"""
Return a ``ThumbnailFile`` containing an existing thumbnail for a set
of thumbnail options, or ``None`` if not found.
"""
thumbnail_options = self.get_options(thumbnail_options)
names = [
self.get_thumbnail_name(
thumbnail_options, transparent=False,
high_resolution=high_resolution)]
transparent_name = self.get_thumbnail_name(
thumbnail_options, transparent=True,
high_resolution=high_resolution)
if transparent_name not in names:
names.append(transparent_name)
for filename in names:
exists = self.thumbnail_exists(filename)
if exists:
thumbnail_file = ThumbnailFile(
name=filename, storage=self.thumbnail_storage,
thumbnail_options=thumbnail_options)
if settings.THUMBNAIL_CACHE_DIMENSIONS:
# If this wasn't local storage, exists will be a thumbnail
# instance so we can store the image dimensions now to save
# a future potential query.
thumbnail_file.set_image_dimensions(exists)
return thumbnail_file
|
[
"def",
"get_existing_thumbnail",
"(",
"self",
",",
"thumbnail_options",
",",
"high_resolution",
"=",
"False",
")",
":",
"thumbnail_options",
"=",
"self",
".",
"get_options",
"(",
"thumbnail_options",
")",
"names",
"=",
"[",
"self",
".",
"get_thumbnail_name",
"(",
"thumbnail_options",
",",
"transparent",
"=",
"False",
",",
"high_resolution",
"=",
"high_resolution",
")",
"]",
"transparent_name",
"=",
"self",
".",
"get_thumbnail_name",
"(",
"thumbnail_options",
",",
"transparent",
"=",
"True",
",",
"high_resolution",
"=",
"high_resolution",
")",
"if",
"transparent_name",
"not",
"in",
"names",
":",
"names",
".",
"append",
"(",
"transparent_name",
")",
"for",
"filename",
"in",
"names",
":",
"exists",
"=",
"self",
".",
"thumbnail_exists",
"(",
"filename",
")",
"if",
"exists",
":",
"thumbnail_file",
"=",
"ThumbnailFile",
"(",
"name",
"=",
"filename",
",",
"storage",
"=",
"self",
".",
"thumbnail_storage",
",",
"thumbnail_options",
"=",
"thumbnail_options",
")",
"if",
"settings",
".",
"THUMBNAIL_CACHE_DIMENSIONS",
":",
"# If this wasn't local storage, exists will be a thumbnail",
"# instance so we can store the image dimensions now to save",
"# a future potential query.",
"thumbnail_file",
".",
"set_image_dimensions",
"(",
"exists",
")",
"return",
"thumbnail_file"
] |
Return a ``ThumbnailFile`` containing an existing thumbnail for a set
of thumbnail options, or ``None`` if not found.
|
[
"Return",
"a",
"ThumbnailFile",
"containing",
"an",
"existing",
"thumbnail",
"for",
"a",
"set",
"of",
"thumbnail",
"options",
"or",
"None",
"if",
"not",
"found",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L461-L488
|
8,719
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
Thumbnailer.get_thumbnail
|
def get_thumbnail(self, thumbnail_options, save=True, generate=None,
silent_template_exception=False):
"""
Return a ``ThumbnailFile`` containing a thumbnail.
If a matching thumbnail already exists, it will simply be returned.
By default (unless the ``Thumbnailer`` was instanciated with
``generate=False``), thumbnails that don't exist are generated.
Otherwise ``None`` is returned.
Force the generation behaviour by setting the ``generate`` param to
either ``True`` or ``False`` as required.
The new thumbnail image is generated using the ``thumbnail_options``
dictionary. If the ``save`` argument is ``True`` (default), the
generated thumbnail will be saved too.
"""
thumbnail_options = self.get_options(thumbnail_options)
if generate is None:
generate = self.generate
thumbnail = self.get_existing_thumbnail(thumbnail_options)
if not thumbnail:
if generate:
thumbnail = self.generate_thumbnail(
thumbnail_options,
silent_template_exception=silent_template_exception)
if save:
self.save_thumbnail(thumbnail)
else:
signals.thumbnail_missed.send(
sender=self, options=thumbnail_options,
high_resolution=False)
if 'HIGH_RESOLUTION' in thumbnail_options:
generate_high_resolution = thumbnail_options.get('HIGH_RESOLUTION')
else:
generate_high_resolution = self.thumbnail_high_resolution
if generate_high_resolution:
thumbnail.high_resolution = self.get_existing_thumbnail(
thumbnail_options, high_resolution=True)
if not thumbnail.high_resolution:
if generate:
thumbnail.high_resolution = self.generate_thumbnail(
thumbnail_options, high_resolution=True,
silent_template_exception=silent_template_exception)
if save:
self.save_thumbnail(thumbnail.high_resolution)
else:
signals.thumbnail_missed.send(
sender=self, options=thumbnail_options,
high_resolution=False)
return thumbnail
|
python
|
def get_thumbnail(self, thumbnail_options, save=True, generate=None,
silent_template_exception=False):
"""
Return a ``ThumbnailFile`` containing a thumbnail.
If a matching thumbnail already exists, it will simply be returned.
By default (unless the ``Thumbnailer`` was instanciated with
``generate=False``), thumbnails that don't exist are generated.
Otherwise ``None`` is returned.
Force the generation behaviour by setting the ``generate`` param to
either ``True`` or ``False`` as required.
The new thumbnail image is generated using the ``thumbnail_options``
dictionary. If the ``save`` argument is ``True`` (default), the
generated thumbnail will be saved too.
"""
thumbnail_options = self.get_options(thumbnail_options)
if generate is None:
generate = self.generate
thumbnail = self.get_existing_thumbnail(thumbnail_options)
if not thumbnail:
if generate:
thumbnail = self.generate_thumbnail(
thumbnail_options,
silent_template_exception=silent_template_exception)
if save:
self.save_thumbnail(thumbnail)
else:
signals.thumbnail_missed.send(
sender=self, options=thumbnail_options,
high_resolution=False)
if 'HIGH_RESOLUTION' in thumbnail_options:
generate_high_resolution = thumbnail_options.get('HIGH_RESOLUTION')
else:
generate_high_resolution = self.thumbnail_high_resolution
if generate_high_resolution:
thumbnail.high_resolution = self.get_existing_thumbnail(
thumbnail_options, high_resolution=True)
if not thumbnail.high_resolution:
if generate:
thumbnail.high_resolution = self.generate_thumbnail(
thumbnail_options, high_resolution=True,
silent_template_exception=silent_template_exception)
if save:
self.save_thumbnail(thumbnail.high_resolution)
else:
signals.thumbnail_missed.send(
sender=self, options=thumbnail_options,
high_resolution=False)
return thumbnail
|
[
"def",
"get_thumbnail",
"(",
"self",
",",
"thumbnail_options",
",",
"save",
"=",
"True",
",",
"generate",
"=",
"None",
",",
"silent_template_exception",
"=",
"False",
")",
":",
"thumbnail_options",
"=",
"self",
".",
"get_options",
"(",
"thumbnail_options",
")",
"if",
"generate",
"is",
"None",
":",
"generate",
"=",
"self",
".",
"generate",
"thumbnail",
"=",
"self",
".",
"get_existing_thumbnail",
"(",
"thumbnail_options",
")",
"if",
"not",
"thumbnail",
":",
"if",
"generate",
":",
"thumbnail",
"=",
"self",
".",
"generate_thumbnail",
"(",
"thumbnail_options",
",",
"silent_template_exception",
"=",
"silent_template_exception",
")",
"if",
"save",
":",
"self",
".",
"save_thumbnail",
"(",
"thumbnail",
")",
"else",
":",
"signals",
".",
"thumbnail_missed",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"options",
"=",
"thumbnail_options",
",",
"high_resolution",
"=",
"False",
")",
"if",
"'HIGH_RESOLUTION'",
"in",
"thumbnail_options",
":",
"generate_high_resolution",
"=",
"thumbnail_options",
".",
"get",
"(",
"'HIGH_RESOLUTION'",
")",
"else",
":",
"generate_high_resolution",
"=",
"self",
".",
"thumbnail_high_resolution",
"if",
"generate_high_resolution",
":",
"thumbnail",
".",
"high_resolution",
"=",
"self",
".",
"get_existing_thumbnail",
"(",
"thumbnail_options",
",",
"high_resolution",
"=",
"True",
")",
"if",
"not",
"thumbnail",
".",
"high_resolution",
":",
"if",
"generate",
":",
"thumbnail",
".",
"high_resolution",
"=",
"self",
".",
"generate_thumbnail",
"(",
"thumbnail_options",
",",
"high_resolution",
"=",
"True",
",",
"silent_template_exception",
"=",
"silent_template_exception",
")",
"if",
"save",
":",
"self",
".",
"save_thumbnail",
"(",
"thumbnail",
".",
"high_resolution",
")",
"else",
":",
"signals",
".",
"thumbnail_missed",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"options",
"=",
"thumbnail_options",
",",
"high_resolution",
"=",
"False",
")",
"return",
"thumbnail"
] |
Return a ``ThumbnailFile`` containing a thumbnail.
If a matching thumbnail already exists, it will simply be returned.
By default (unless the ``Thumbnailer`` was instanciated with
``generate=False``), thumbnails that don't exist are generated.
Otherwise ``None`` is returned.
Force the generation behaviour by setting the ``generate`` param to
either ``True`` or ``False`` as required.
The new thumbnail image is generated using the ``thumbnail_options``
dictionary. If the ``save`` argument is ``True`` (default), the
generated thumbnail will be saved too.
|
[
"Return",
"a",
"ThumbnailFile",
"containing",
"a",
"thumbnail",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L490-L544
|
8,720
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
Thumbnailer.save_thumbnail
|
def save_thumbnail(self, thumbnail):
"""
Save a thumbnail to the thumbnail_storage.
Also triggers the ``thumbnail_created`` signal and caches the
thumbnail values and dimensions for future lookups.
"""
filename = thumbnail.name
try:
self.thumbnail_storage.delete(filename)
except Exception:
pass
self.thumbnail_storage.save(filename, thumbnail)
thumb_cache = self.get_thumbnail_cache(
thumbnail.name, create=True, update=True)
# Cache thumbnail dimensions.
if settings.THUMBNAIL_CACHE_DIMENSIONS:
dimensions_cache, created = (
models.ThumbnailDimensions.objects.get_or_create(
thumbnail=thumb_cache,
defaults={'width': thumbnail.width,
'height': thumbnail.height}))
if not created:
dimensions_cache.width = thumbnail.width
dimensions_cache.height = thumbnail.height
dimensions_cache.save()
signals.thumbnail_created.send(sender=thumbnail)
|
python
|
def save_thumbnail(self, thumbnail):
"""
Save a thumbnail to the thumbnail_storage.
Also triggers the ``thumbnail_created`` signal and caches the
thumbnail values and dimensions for future lookups.
"""
filename = thumbnail.name
try:
self.thumbnail_storage.delete(filename)
except Exception:
pass
self.thumbnail_storage.save(filename, thumbnail)
thumb_cache = self.get_thumbnail_cache(
thumbnail.name, create=True, update=True)
# Cache thumbnail dimensions.
if settings.THUMBNAIL_CACHE_DIMENSIONS:
dimensions_cache, created = (
models.ThumbnailDimensions.objects.get_or_create(
thumbnail=thumb_cache,
defaults={'width': thumbnail.width,
'height': thumbnail.height}))
if not created:
dimensions_cache.width = thumbnail.width
dimensions_cache.height = thumbnail.height
dimensions_cache.save()
signals.thumbnail_created.send(sender=thumbnail)
|
[
"def",
"save_thumbnail",
"(",
"self",
",",
"thumbnail",
")",
":",
"filename",
"=",
"thumbnail",
".",
"name",
"try",
":",
"self",
".",
"thumbnail_storage",
".",
"delete",
"(",
"filename",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"thumbnail_storage",
".",
"save",
"(",
"filename",
",",
"thumbnail",
")",
"thumb_cache",
"=",
"self",
".",
"get_thumbnail_cache",
"(",
"thumbnail",
".",
"name",
",",
"create",
"=",
"True",
",",
"update",
"=",
"True",
")",
"# Cache thumbnail dimensions.",
"if",
"settings",
".",
"THUMBNAIL_CACHE_DIMENSIONS",
":",
"dimensions_cache",
",",
"created",
"=",
"(",
"models",
".",
"ThumbnailDimensions",
".",
"objects",
".",
"get_or_create",
"(",
"thumbnail",
"=",
"thumb_cache",
",",
"defaults",
"=",
"{",
"'width'",
":",
"thumbnail",
".",
"width",
",",
"'height'",
":",
"thumbnail",
".",
"height",
"}",
")",
")",
"if",
"not",
"created",
":",
"dimensions_cache",
".",
"width",
"=",
"thumbnail",
".",
"width",
"dimensions_cache",
".",
"height",
"=",
"thumbnail",
".",
"height",
"dimensions_cache",
".",
"save",
"(",
")",
"signals",
".",
"thumbnail_created",
".",
"send",
"(",
"sender",
"=",
"thumbnail",
")"
] |
Save a thumbnail to the thumbnail_storage.
Also triggers the ``thumbnail_created`` signal and caches the
thumbnail values and dimensions for future lookups.
|
[
"Save",
"a",
"thumbnail",
"to",
"the",
"thumbnail_storage",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L546-L575
|
8,721
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
Thumbnailer.thumbnail_exists
|
def thumbnail_exists(self, thumbnail_name):
"""
Calculate whether the thumbnail already exists and that the source is
not newer than the thumbnail.
If the source and thumbnail file storages are local, their file
modification times are used. Otherwise the database cached modification
times are used.
"""
if self.remote_source:
return False
if utils.is_storage_local(self.source_storage):
source_modtime = utils.get_modified_time(
self.source_storage, self.name)
else:
source = self.get_source_cache()
if not source:
return False
source_modtime = source.modified
if not source_modtime:
return False
local_thumbnails = utils.is_storage_local(self.thumbnail_storage)
if local_thumbnails:
thumbnail_modtime = utils.get_modified_time(
self.thumbnail_storage, thumbnail_name)
if not thumbnail_modtime:
return False
return source_modtime <= thumbnail_modtime
thumbnail = self.get_thumbnail_cache(thumbnail_name)
if not thumbnail:
return False
thumbnail_modtime = thumbnail.modified
if thumbnail.modified and source_modtime <= thumbnail.modified:
return thumbnail
return False
|
python
|
def thumbnail_exists(self, thumbnail_name):
"""
Calculate whether the thumbnail already exists and that the source is
not newer than the thumbnail.
If the source and thumbnail file storages are local, their file
modification times are used. Otherwise the database cached modification
times are used.
"""
if self.remote_source:
return False
if utils.is_storage_local(self.source_storage):
source_modtime = utils.get_modified_time(
self.source_storage, self.name)
else:
source = self.get_source_cache()
if not source:
return False
source_modtime = source.modified
if not source_modtime:
return False
local_thumbnails = utils.is_storage_local(self.thumbnail_storage)
if local_thumbnails:
thumbnail_modtime = utils.get_modified_time(
self.thumbnail_storage, thumbnail_name)
if not thumbnail_modtime:
return False
return source_modtime <= thumbnail_modtime
thumbnail = self.get_thumbnail_cache(thumbnail_name)
if not thumbnail:
return False
thumbnail_modtime = thumbnail.modified
if thumbnail.modified and source_modtime <= thumbnail.modified:
return thumbnail
return False
|
[
"def",
"thumbnail_exists",
"(",
"self",
",",
"thumbnail_name",
")",
":",
"if",
"self",
".",
"remote_source",
":",
"return",
"False",
"if",
"utils",
".",
"is_storage_local",
"(",
"self",
".",
"source_storage",
")",
":",
"source_modtime",
"=",
"utils",
".",
"get_modified_time",
"(",
"self",
".",
"source_storage",
",",
"self",
".",
"name",
")",
"else",
":",
"source",
"=",
"self",
".",
"get_source_cache",
"(",
")",
"if",
"not",
"source",
":",
"return",
"False",
"source_modtime",
"=",
"source",
".",
"modified",
"if",
"not",
"source_modtime",
":",
"return",
"False",
"local_thumbnails",
"=",
"utils",
".",
"is_storage_local",
"(",
"self",
".",
"thumbnail_storage",
")",
"if",
"local_thumbnails",
":",
"thumbnail_modtime",
"=",
"utils",
".",
"get_modified_time",
"(",
"self",
".",
"thumbnail_storage",
",",
"thumbnail_name",
")",
"if",
"not",
"thumbnail_modtime",
":",
"return",
"False",
"return",
"source_modtime",
"<=",
"thumbnail_modtime",
"thumbnail",
"=",
"self",
".",
"get_thumbnail_cache",
"(",
"thumbnail_name",
")",
"if",
"not",
"thumbnail",
":",
"return",
"False",
"thumbnail_modtime",
"=",
"thumbnail",
".",
"modified",
"if",
"thumbnail",
".",
"modified",
"and",
"source_modtime",
"<=",
"thumbnail",
".",
"modified",
":",
"return",
"thumbnail",
"return",
"False"
] |
Calculate whether the thumbnail already exists and that the source is
not newer than the thumbnail.
If the source and thumbnail file storages are local, their file
modification times are used. Otherwise the database cached modification
times are used.
|
[
"Calculate",
"whether",
"the",
"thumbnail",
"already",
"exists",
"and",
"that",
"the",
"source",
"is",
"not",
"newer",
"than",
"the",
"thumbnail",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L577-L616
|
8,722
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailerFieldFile.save
|
def save(self, name, content, *args, **kwargs):
"""
Save the file, also saving a reference to the thumbnail cache Source
model.
"""
super(ThumbnailerFieldFile, self).save(name, content, *args, **kwargs)
self.get_source_cache(create=True, update=True)
|
python
|
def save(self, name, content, *args, **kwargs):
"""
Save the file, also saving a reference to the thumbnail cache Source
model.
"""
super(ThumbnailerFieldFile, self).save(name, content, *args, **kwargs)
self.get_source_cache(create=True, update=True)
|
[
"def",
"save",
"(",
"self",
",",
"name",
",",
"content",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"ThumbnailerFieldFile",
",",
"self",
")",
".",
"save",
"(",
"name",
",",
"content",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"get_source_cache",
"(",
"create",
"=",
"True",
",",
"update",
"=",
"True",
")"
] |
Save the file, also saving a reference to the thumbnail cache Source
model.
|
[
"Save",
"the",
"file",
"also",
"saving",
"a",
"reference",
"to",
"the",
"thumbnail",
"cache",
"Source",
"model",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L665-L671
|
8,723
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailerFieldFile.delete
|
def delete(self, *args, **kwargs):
"""
Delete the image, along with any generated thumbnails.
"""
source_cache = self.get_source_cache()
# First, delete any related thumbnails.
self.delete_thumbnails(source_cache)
# Next, delete the source image.
super(ThumbnailerFieldFile, self).delete(*args, **kwargs)
# Finally, delete the source cache entry.
if source_cache and source_cache.pk is not None:
source_cache.delete()
|
python
|
def delete(self, *args, **kwargs):
"""
Delete the image, along with any generated thumbnails.
"""
source_cache = self.get_source_cache()
# First, delete any related thumbnails.
self.delete_thumbnails(source_cache)
# Next, delete the source image.
super(ThumbnailerFieldFile, self).delete(*args, **kwargs)
# Finally, delete the source cache entry.
if source_cache and source_cache.pk is not None:
source_cache.delete()
|
[
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"source_cache",
"=",
"self",
".",
"get_source_cache",
"(",
")",
"# First, delete any related thumbnails.",
"self",
".",
"delete_thumbnails",
"(",
"source_cache",
")",
"# Next, delete the source image.",
"super",
"(",
"ThumbnailerFieldFile",
",",
"self",
")",
".",
"delete",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Finally, delete the source cache entry.",
"if",
"source_cache",
"and",
"source_cache",
".",
"pk",
"is",
"not",
"None",
":",
"source_cache",
".",
"delete",
"(",
")"
] |
Delete the image, along with any generated thumbnails.
|
[
"Delete",
"the",
"image",
"along",
"with",
"any",
"generated",
"thumbnails",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L673-L684
|
8,724
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailerFieldFile.delete_thumbnails
|
def delete_thumbnails(self, source_cache=None):
"""
Delete any thumbnails generated from the source image.
:arg source_cache: An optional argument only used for optimisation
where the source cache instance is already known.
:returns: The number of files deleted.
"""
source_cache = self.get_source_cache()
deleted = 0
if source_cache:
thumbnail_storage_hash = utils.get_storage_hash(
self.thumbnail_storage)
for thumbnail_cache in source_cache.thumbnails.all():
# Only attempt to delete the file if it was stored using the
# same storage as is currently used.
if thumbnail_cache.storage_hash == thumbnail_storage_hash:
self.thumbnail_storage.delete(thumbnail_cache.name)
# Delete the cache thumbnail instance too.
thumbnail_cache.delete()
deleted += 1
return deleted
|
python
|
def delete_thumbnails(self, source_cache=None):
"""
Delete any thumbnails generated from the source image.
:arg source_cache: An optional argument only used for optimisation
where the source cache instance is already known.
:returns: The number of files deleted.
"""
source_cache = self.get_source_cache()
deleted = 0
if source_cache:
thumbnail_storage_hash = utils.get_storage_hash(
self.thumbnail_storage)
for thumbnail_cache in source_cache.thumbnails.all():
# Only attempt to delete the file if it was stored using the
# same storage as is currently used.
if thumbnail_cache.storage_hash == thumbnail_storage_hash:
self.thumbnail_storage.delete(thumbnail_cache.name)
# Delete the cache thumbnail instance too.
thumbnail_cache.delete()
deleted += 1
return deleted
|
[
"def",
"delete_thumbnails",
"(",
"self",
",",
"source_cache",
"=",
"None",
")",
":",
"source_cache",
"=",
"self",
".",
"get_source_cache",
"(",
")",
"deleted",
"=",
"0",
"if",
"source_cache",
":",
"thumbnail_storage_hash",
"=",
"utils",
".",
"get_storage_hash",
"(",
"self",
".",
"thumbnail_storage",
")",
"for",
"thumbnail_cache",
"in",
"source_cache",
".",
"thumbnails",
".",
"all",
"(",
")",
":",
"# Only attempt to delete the file if it was stored using the",
"# same storage as is currently used.",
"if",
"thumbnail_cache",
".",
"storage_hash",
"==",
"thumbnail_storage_hash",
":",
"self",
".",
"thumbnail_storage",
".",
"delete",
"(",
"thumbnail_cache",
".",
"name",
")",
"# Delete the cache thumbnail instance too.",
"thumbnail_cache",
".",
"delete",
"(",
")",
"deleted",
"+=",
"1",
"return",
"deleted"
] |
Delete any thumbnails generated from the source image.
:arg source_cache: An optional argument only used for optimisation
where the source cache instance is already known.
:returns: The number of files deleted.
|
[
"Delete",
"any",
"thumbnails",
"generated",
"from",
"the",
"source",
"image",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L688-L709
|
8,725
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailerFieldFile.get_thumbnails
|
def get_thumbnails(self, *args, **kwargs):
"""
Return an iterator which returns ThumbnailFile instances.
"""
# First, delete any related thumbnails.
source_cache = self.get_source_cache()
if source_cache:
thumbnail_storage_hash = utils.get_storage_hash(
self.thumbnail_storage)
for thumbnail_cache in source_cache.thumbnails.all():
# Only iterate files which are stored using the current
# thumbnail storage.
if thumbnail_cache.storage_hash == thumbnail_storage_hash:
yield ThumbnailFile(name=thumbnail_cache.name,
storage=self.thumbnail_storage)
|
python
|
def get_thumbnails(self, *args, **kwargs):
"""
Return an iterator which returns ThumbnailFile instances.
"""
# First, delete any related thumbnails.
source_cache = self.get_source_cache()
if source_cache:
thumbnail_storage_hash = utils.get_storage_hash(
self.thumbnail_storage)
for thumbnail_cache in source_cache.thumbnails.all():
# Only iterate files which are stored using the current
# thumbnail storage.
if thumbnail_cache.storage_hash == thumbnail_storage_hash:
yield ThumbnailFile(name=thumbnail_cache.name,
storage=self.thumbnail_storage)
|
[
"def",
"get_thumbnails",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# First, delete any related thumbnails.",
"source_cache",
"=",
"self",
".",
"get_source_cache",
"(",
")",
"if",
"source_cache",
":",
"thumbnail_storage_hash",
"=",
"utils",
".",
"get_storage_hash",
"(",
"self",
".",
"thumbnail_storage",
")",
"for",
"thumbnail_cache",
"in",
"source_cache",
".",
"thumbnails",
".",
"all",
"(",
")",
":",
"# Only iterate files which are stored using the current",
"# thumbnail storage.",
"if",
"thumbnail_cache",
".",
"storage_hash",
"==",
"thumbnail_storage_hash",
":",
"yield",
"ThumbnailFile",
"(",
"name",
"=",
"thumbnail_cache",
".",
"name",
",",
"storage",
"=",
"self",
".",
"thumbnail_storage",
")"
] |
Return an iterator which returns ThumbnailFile instances.
|
[
"Return",
"an",
"iterator",
"which",
"returns",
"ThumbnailFile",
"instances",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L713-L727
|
8,726
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/files.py
|
ThumbnailerImageFieldFile.save
|
def save(self, name, content, *args, **kwargs):
"""
Save the image.
The image will be resized down using a ``ThumbnailField`` if
``resize_source`` (a dictionary of thumbnail options) is provided by
the field.
"""
options = getattr(self.field, 'resize_source', None)
if options:
if 'quality' not in options:
options['quality'] = self.thumbnail_quality
content = Thumbnailer(content, name).generate_thumbnail(options)
# If the generated extension differs from the original, use it
# instead.
orig_name, ext = os.path.splitext(name)
generated_ext = os.path.splitext(content.name)[1]
if generated_ext.lower() != ext.lower():
name = orig_name + generated_ext
super(ThumbnailerImageFieldFile, self).save(name, content, *args,
**kwargs)
|
python
|
def save(self, name, content, *args, **kwargs):
"""
Save the image.
The image will be resized down using a ``ThumbnailField`` if
``resize_source`` (a dictionary of thumbnail options) is provided by
the field.
"""
options = getattr(self.field, 'resize_source', None)
if options:
if 'quality' not in options:
options['quality'] = self.thumbnail_quality
content = Thumbnailer(content, name).generate_thumbnail(options)
# If the generated extension differs from the original, use it
# instead.
orig_name, ext = os.path.splitext(name)
generated_ext = os.path.splitext(content.name)[1]
if generated_ext.lower() != ext.lower():
name = orig_name + generated_ext
super(ThumbnailerImageFieldFile, self).save(name, content, *args,
**kwargs)
|
[
"def",
"save",
"(",
"self",
",",
"name",
",",
"content",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"getattr",
"(",
"self",
".",
"field",
",",
"'resize_source'",
",",
"None",
")",
"if",
"options",
":",
"if",
"'quality'",
"not",
"in",
"options",
":",
"options",
"[",
"'quality'",
"]",
"=",
"self",
".",
"thumbnail_quality",
"content",
"=",
"Thumbnailer",
"(",
"content",
",",
"name",
")",
".",
"generate_thumbnail",
"(",
"options",
")",
"# If the generated extension differs from the original, use it",
"# instead.",
"orig_name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"generated_ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"content",
".",
"name",
")",
"[",
"1",
"]",
"if",
"generated_ext",
".",
"lower",
"(",
")",
"!=",
"ext",
".",
"lower",
"(",
")",
":",
"name",
"=",
"orig_name",
"+",
"generated_ext",
"super",
"(",
"ThumbnailerImageFieldFile",
",",
"self",
")",
".",
"save",
"(",
"name",
",",
"content",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Save the image.
The image will be resized down using a ``ThumbnailField`` if
``resize_source`` (a dictionary of thumbnail options) is provided by
the field.
|
[
"Save",
"the",
"image",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/files.py#L749-L769
|
8,727
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/management/commands/thumbnail_cleanup.py
|
queryset_iterator
|
def queryset_iterator(queryset, chunksize=1000):
"""
The queryset iterator helps to keep the memory consumption down.
And also making it easier to process for weaker computers.
"""
if queryset.exists():
primary_key = 0
last_pk = queryset.order_by('-pk')[0].pk
queryset = queryset.order_by('pk')
while primary_key < last_pk:
for row in queryset.filter(pk__gt=primary_key)[:chunksize]:
primary_key = row.pk
yield row
gc.collect()
|
python
|
def queryset_iterator(queryset, chunksize=1000):
"""
The queryset iterator helps to keep the memory consumption down.
And also making it easier to process for weaker computers.
"""
if queryset.exists():
primary_key = 0
last_pk = queryset.order_by('-pk')[0].pk
queryset = queryset.order_by('pk')
while primary_key < last_pk:
for row in queryset.filter(pk__gt=primary_key)[:chunksize]:
primary_key = row.pk
yield row
gc.collect()
|
[
"def",
"queryset_iterator",
"(",
"queryset",
",",
"chunksize",
"=",
"1000",
")",
":",
"if",
"queryset",
".",
"exists",
"(",
")",
":",
"primary_key",
"=",
"0",
"last_pk",
"=",
"queryset",
".",
"order_by",
"(",
"'-pk'",
")",
"[",
"0",
"]",
".",
"pk",
"queryset",
"=",
"queryset",
".",
"order_by",
"(",
"'pk'",
")",
"while",
"primary_key",
"<",
"last_pk",
":",
"for",
"row",
"in",
"queryset",
".",
"filter",
"(",
"pk__gt",
"=",
"primary_key",
")",
"[",
":",
"chunksize",
"]",
":",
"primary_key",
"=",
"row",
".",
"pk",
"yield",
"row",
"gc",
".",
"collect",
"(",
")"
] |
The queryset iterator helps to keep the memory consumption down.
And also making it easier to process for weaker computers.
|
[
"The",
"queryset",
"iterator",
"helps",
"to",
"keep",
"the",
"memory",
"consumption",
"down",
".",
"And",
"also",
"making",
"it",
"easier",
"to",
"process",
"for",
"weaker",
"computers",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/commands/thumbnail_cleanup.py#L105-L118
|
8,728
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/management/commands/thumbnail_cleanup.py
|
ThumbnailCollectionCleaner.print_stats
|
def print_stats(self):
"""
Print statistics about the cleanup performed.
"""
print(
"{0:-<48}".format(str(datetime.now().strftime('%Y-%m-%d %H:%M '))))
print("{0:<40} {1:>7}".format("Sources checked:", self.sources))
print("{0:<40} {1:>7}".format(
"Source references deleted from DB:", self.source_refs_deleted))
print("{0:<40} {1:>7}".format("Thumbnails deleted from disk:",
self.thumbnails_deleted))
print("(Completed in %s seconds)\n" % self.execution_time)
|
python
|
def print_stats(self):
"""
Print statistics about the cleanup performed.
"""
print(
"{0:-<48}".format(str(datetime.now().strftime('%Y-%m-%d %H:%M '))))
print("{0:<40} {1:>7}".format("Sources checked:", self.sources))
print("{0:<40} {1:>7}".format(
"Source references deleted from DB:", self.source_refs_deleted))
print("{0:<40} {1:>7}".format("Thumbnails deleted from disk:",
self.thumbnails_deleted))
print("(Completed in %s seconds)\n" % self.execution_time)
|
[
"def",
"print_stats",
"(",
"self",
")",
":",
"print",
"(",
"\"{0:-<48}\"",
".",
"format",
"(",
"str",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M '",
")",
")",
")",
")",
"print",
"(",
"\"{0:<40} {1:>7}\"",
".",
"format",
"(",
"\"Sources checked:\"",
",",
"self",
".",
"sources",
")",
")",
"print",
"(",
"\"{0:<40} {1:>7}\"",
".",
"format",
"(",
"\"Source references deleted from DB:\"",
",",
"self",
".",
"source_refs_deleted",
")",
")",
"print",
"(",
"\"{0:<40} {1:>7}\"",
".",
"format",
"(",
"\"Thumbnails deleted from disk:\"",
",",
"self",
".",
"thumbnails_deleted",
")",
")",
"print",
"(",
"\"(Completed in %s seconds)\\n\"",
"%",
"self",
".",
"execution_time",
")"
] |
Print statistics about the cleanup performed.
|
[
"Print",
"statistics",
"about",
"the",
"cleanup",
"performed",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/management/commands/thumbnail_cleanup.py#L91-L102
|
8,729
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/alias.py
|
Aliases.populate_from_settings
|
def populate_from_settings(self):
"""
Populate the aliases from the ``THUMBNAIL_ALIASES`` setting.
"""
settings_aliases = settings.THUMBNAIL_ALIASES
if settings_aliases:
for target, aliases in settings_aliases.items():
target_aliases = self._aliases.setdefault(target, {})
target_aliases.update(aliases)
|
python
|
def populate_from_settings(self):
"""
Populate the aliases from the ``THUMBNAIL_ALIASES`` setting.
"""
settings_aliases = settings.THUMBNAIL_ALIASES
if settings_aliases:
for target, aliases in settings_aliases.items():
target_aliases = self._aliases.setdefault(target, {})
target_aliases.update(aliases)
|
[
"def",
"populate_from_settings",
"(",
"self",
")",
":",
"settings_aliases",
"=",
"settings",
".",
"THUMBNAIL_ALIASES",
"if",
"settings_aliases",
":",
"for",
"target",
",",
"aliases",
"in",
"settings_aliases",
".",
"items",
"(",
")",
":",
"target_aliases",
"=",
"self",
".",
"_aliases",
".",
"setdefault",
"(",
"target",
",",
"{",
"}",
")",
"target_aliases",
".",
"update",
"(",
"aliases",
")"
] |
Populate the aliases from the ``THUMBNAIL_ALIASES`` setting.
|
[
"Populate",
"the",
"aliases",
"from",
"the",
"THUMBNAIL_ALIASES",
"setting",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L23-L31
|
8,730
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/alias.py
|
Aliases.set
|
def set(self, alias, options, target=None):
"""
Add an alias.
:param alias: The name of the alias to add.
:param options: The easy-thumbnails options dictonary for this alias
(should include ``size``).
:param target: A field, model, or app to limit this alias to
(optional).
"""
target = self._coerce_target(target) or ''
target_aliases = self._aliases.setdefault(target, {})
target_aliases[alias] = options
|
python
|
def set(self, alias, options, target=None):
"""
Add an alias.
:param alias: The name of the alias to add.
:param options: The easy-thumbnails options dictonary for this alias
(should include ``size``).
:param target: A field, model, or app to limit this alias to
(optional).
"""
target = self._coerce_target(target) or ''
target_aliases = self._aliases.setdefault(target, {})
target_aliases[alias] = options
|
[
"def",
"set",
"(",
"self",
",",
"alias",
",",
"options",
",",
"target",
"=",
"None",
")",
":",
"target",
"=",
"self",
".",
"_coerce_target",
"(",
"target",
")",
"or",
"''",
"target_aliases",
"=",
"self",
".",
"_aliases",
".",
"setdefault",
"(",
"target",
",",
"{",
"}",
")",
"target_aliases",
"[",
"alias",
"]",
"=",
"options"
] |
Add an alias.
:param alias: The name of the alias to add.
:param options: The easy-thumbnails options dictonary for this alias
(should include ``size``).
:param target: A field, model, or app to limit this alias to
(optional).
|
[
"Add",
"an",
"alias",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L33-L45
|
8,731
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/alias.py
|
Aliases.get
|
def get(self, alias, target=None):
"""
Get a dictionary of aliased options.
:param alias: The name of the aliased options.
:param target: Get alias for this specific target (optional).
If no matching alias is found, returns ``None``.
"""
for target_part in reversed(list(self._get_targets(target))):
options = self._get(target_part, alias)
if options:
return options
|
python
|
def get(self, alias, target=None):
"""
Get a dictionary of aliased options.
:param alias: The name of the aliased options.
:param target: Get alias for this specific target (optional).
If no matching alias is found, returns ``None``.
"""
for target_part in reversed(list(self._get_targets(target))):
options = self._get(target_part, alias)
if options:
return options
|
[
"def",
"get",
"(",
"self",
",",
"alias",
",",
"target",
"=",
"None",
")",
":",
"for",
"target_part",
"in",
"reversed",
"(",
"list",
"(",
"self",
".",
"_get_targets",
"(",
"target",
")",
")",
")",
":",
"options",
"=",
"self",
".",
"_get",
"(",
"target_part",
",",
"alias",
")",
"if",
"options",
":",
"return",
"options"
] |
Get a dictionary of aliased options.
:param alias: The name of the aliased options.
:param target: Get alias for this specific target (optional).
If no matching alias is found, returns ``None``.
|
[
"Get",
"a",
"dictionary",
"of",
"aliased",
"options",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L47-L59
|
8,732
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/alias.py
|
Aliases.all
|
def all(self, target=None, include_global=True):
"""
Get a dictionary of all aliases and their options.
:param target: Include aliases for this specific field, model or app
(optional).
:param include_global: Include all non target-specific aliases
(default ``True``).
For example::
>>> aliases.all(target='my_app.MyModel')
{'small': {'size': (100, 100)}, 'large': {'size': (400, 400)}}
"""
aliases = {}
for target_part in self._get_targets(target, include_global):
aliases.update(self._aliases.get(target_part, {}))
return aliases
|
python
|
def all(self, target=None, include_global=True):
"""
Get a dictionary of all aliases and their options.
:param target: Include aliases for this specific field, model or app
(optional).
:param include_global: Include all non target-specific aliases
(default ``True``).
For example::
>>> aliases.all(target='my_app.MyModel')
{'small': {'size': (100, 100)}, 'large': {'size': (400, 400)}}
"""
aliases = {}
for target_part in self._get_targets(target, include_global):
aliases.update(self._aliases.get(target_part, {}))
return aliases
|
[
"def",
"all",
"(",
"self",
",",
"target",
"=",
"None",
",",
"include_global",
"=",
"True",
")",
":",
"aliases",
"=",
"{",
"}",
"for",
"target_part",
"in",
"self",
".",
"_get_targets",
"(",
"target",
",",
"include_global",
")",
":",
"aliases",
".",
"update",
"(",
"self",
".",
"_aliases",
".",
"get",
"(",
"target_part",
",",
"{",
"}",
")",
")",
"return",
"aliases"
] |
Get a dictionary of all aliases and their options.
:param target: Include aliases for this specific field, model or app
(optional).
:param include_global: Include all non target-specific aliases
(default ``True``).
For example::
>>> aliases.all(target='my_app.MyModel')
{'small': {'size': (100, 100)}, 'large': {'size': (400, 400)}}
|
[
"Get",
"a",
"dictionary",
"of",
"all",
"aliases",
"and",
"their",
"options",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L61-L78
|
8,733
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/alias.py
|
Aliases._get
|
def _get(self, target, alias):
"""
Internal method to get a specific alias.
"""
if target not in self._aliases:
return
return self._aliases[target].get(alias)
|
python
|
def _get(self, target, alias):
"""
Internal method to get a specific alias.
"""
if target not in self._aliases:
return
return self._aliases[target].get(alias)
|
[
"def",
"_get",
"(",
"self",
",",
"target",
",",
"alias",
")",
":",
"if",
"target",
"not",
"in",
"self",
".",
"_aliases",
":",
"return",
"return",
"self",
".",
"_aliases",
"[",
"target",
"]",
".",
"get",
"(",
"alias",
")"
] |
Internal method to get a specific alias.
|
[
"Internal",
"method",
"to",
"get",
"a",
"specific",
"alias",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L80-L86
|
8,734
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/alias.py
|
Aliases._get_targets
|
def _get_targets(self, target, include_global=True):
"""
Internal iterator to split up a complete target into the possible parts
it may match.
For example::
>>> list(aliases._get_targets('my_app.MyModel.somefield'))
['', 'my_app', 'my_app.MyModel', 'my_app.MyModel.somefield']
"""
target = self._coerce_target(target)
if include_global:
yield ''
if not target:
return
target_bits = target.split('.')
for i in range(len(target_bits)):
yield '.'.join(target_bits[:i + 1])
|
python
|
def _get_targets(self, target, include_global=True):
"""
Internal iterator to split up a complete target into the possible parts
it may match.
For example::
>>> list(aliases._get_targets('my_app.MyModel.somefield'))
['', 'my_app', 'my_app.MyModel', 'my_app.MyModel.somefield']
"""
target = self._coerce_target(target)
if include_global:
yield ''
if not target:
return
target_bits = target.split('.')
for i in range(len(target_bits)):
yield '.'.join(target_bits[:i + 1])
|
[
"def",
"_get_targets",
"(",
"self",
",",
"target",
",",
"include_global",
"=",
"True",
")",
":",
"target",
"=",
"self",
".",
"_coerce_target",
"(",
"target",
")",
"if",
"include_global",
":",
"yield",
"''",
"if",
"not",
"target",
":",
"return",
"target_bits",
"=",
"target",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"target_bits",
")",
")",
":",
"yield",
"'.'",
".",
"join",
"(",
"target_bits",
"[",
":",
"i",
"+",
"1",
"]",
")"
] |
Internal iterator to split up a complete target into the possible parts
it may match.
For example::
>>> list(aliases._get_targets('my_app.MyModel.somefield'))
['', 'my_app', 'my_app.MyModel', 'my_app.MyModel.somefield']
|
[
"Internal",
"iterator",
"to",
"split",
"up",
"a",
"complete",
"target",
"into",
"the",
"possible",
"parts",
"it",
"may",
"match",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L88-L105
|
8,735
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/alias.py
|
Aliases._coerce_target
|
def _coerce_target(self, target):
"""
Internal method to coerce a target to a string.
The assumption is that if it is not ``None`` and not a string, it is
a Django ``FieldFile`` object.
"""
if not target or isinstance(target, six.string_types):
return target
if not hasattr(target, 'instance'):
return None
if getattr(target.instance, '_deferred', False):
model = target.instance._meta.proxy_for_model
else:
model = target.instance.__class__
return '%s.%s.%s' % (
model._meta.app_label,
model.__name__,
target.field.name,
)
|
python
|
def _coerce_target(self, target):
"""
Internal method to coerce a target to a string.
The assumption is that if it is not ``None`` and not a string, it is
a Django ``FieldFile`` object.
"""
if not target or isinstance(target, six.string_types):
return target
if not hasattr(target, 'instance'):
return None
if getattr(target.instance, '_deferred', False):
model = target.instance._meta.proxy_for_model
else:
model = target.instance.__class__
return '%s.%s.%s' % (
model._meta.app_label,
model.__name__,
target.field.name,
)
|
[
"def",
"_coerce_target",
"(",
"self",
",",
"target",
")",
":",
"if",
"not",
"target",
"or",
"isinstance",
"(",
"target",
",",
"six",
".",
"string_types",
")",
":",
"return",
"target",
"if",
"not",
"hasattr",
"(",
"target",
",",
"'instance'",
")",
":",
"return",
"None",
"if",
"getattr",
"(",
"target",
".",
"instance",
",",
"'_deferred'",
",",
"False",
")",
":",
"model",
"=",
"target",
".",
"instance",
".",
"_meta",
".",
"proxy_for_model",
"else",
":",
"model",
"=",
"target",
".",
"instance",
".",
"__class__",
"return",
"'%s.%s.%s'",
"%",
"(",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
"__name__",
",",
"target",
".",
"field",
".",
"name",
",",
")"
] |
Internal method to coerce a target to a string.
The assumption is that if it is not ``None`` and not a string, it is
a Django ``FieldFile`` object.
|
[
"Internal",
"method",
"to",
"coerce",
"a",
"target",
"to",
"a",
"string",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/alias.py#L107-L128
|
8,736
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/utils.py
|
image_entropy
|
def image_entropy(im):
"""
Calculate the entropy of an image. Used for "smart cropping".
"""
if not isinstance(im, Image.Image):
# Can only deal with PIL images. Fall back to a constant entropy.
return 0
hist = im.histogram()
hist_size = float(sum(hist))
hist = [h / hist_size for h in hist]
return -sum([p * math.log(p, 2) for p in hist if p != 0])
|
python
|
def image_entropy(im):
"""
Calculate the entropy of an image. Used for "smart cropping".
"""
if not isinstance(im, Image.Image):
# Can only deal with PIL images. Fall back to a constant entropy.
return 0
hist = im.histogram()
hist_size = float(sum(hist))
hist = [h / hist_size for h in hist]
return -sum([p * math.log(p, 2) for p in hist if p != 0])
|
[
"def",
"image_entropy",
"(",
"im",
")",
":",
"if",
"not",
"isinstance",
"(",
"im",
",",
"Image",
".",
"Image",
")",
":",
"# Can only deal with PIL images. Fall back to a constant entropy.",
"return",
"0",
"hist",
"=",
"im",
".",
"histogram",
"(",
")",
"hist_size",
"=",
"float",
"(",
"sum",
"(",
"hist",
")",
")",
"hist",
"=",
"[",
"h",
"/",
"hist_size",
"for",
"h",
"in",
"hist",
"]",
"return",
"-",
"sum",
"(",
"[",
"p",
"*",
"math",
".",
"log",
"(",
"p",
",",
"2",
")",
"for",
"p",
"in",
"hist",
"if",
"p",
"!=",
"0",
"]",
")"
] |
Calculate the entropy of an image. Used for "smart cropping".
|
[
"Calculate",
"the",
"entropy",
"of",
"an",
"image",
".",
"Used",
"for",
"smart",
"cropping",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L18-L28
|
8,737
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/utils.py
|
dynamic_import
|
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:lastdot], import_string[lastdot + 1:]
parent_module = __import__(module_name, {}, {}, [attr])
return getattr(parent_module, attr)
|
python
|
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:lastdot], import_string[lastdot + 1:]
parent_module = __import__(module_name, {}, {}, [attr])
return getattr(parent_module, attr)
|
[
"def",
"dynamic_import",
"(",
"import_string",
")",
":",
"# Use rfind rather than rsplit for Python 2.3 compatibility.",
"lastdot",
"=",
"import_string",
".",
"rfind",
"(",
"'.'",
")",
"if",
"lastdot",
"==",
"-",
"1",
":",
"return",
"__import__",
"(",
"import_string",
",",
"{",
"}",
",",
"{",
"}",
",",
"[",
"]",
")",
"module_name",
",",
"attr",
"=",
"import_string",
"[",
":",
"lastdot",
"]",
",",
"import_string",
"[",
"lastdot",
"+",
"1",
":",
"]",
"parent_module",
"=",
"__import__",
"(",
"module_name",
",",
"{",
"}",
",",
"{",
"}",
",",
"[",
"attr",
"]",
")",
"return",
"getattr",
"(",
"parent_module",
",",
"attr",
")"
] |
Dynamically import a module or object.
|
[
"Dynamically",
"import",
"a",
"module",
"or",
"object",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L31-L41
|
8,738
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/utils.py
|
is_transparent
|
def is_transparent(image):
"""
Check to see if an image is transparent.
"""
if not isinstance(image, Image.Image):
# Can only deal with PIL images, fall back to the assumption that that
# it's not transparent.
return False
return (image.mode in ('RGBA', 'LA') or
(image.mode == 'P' and 'transparency' in image.info))
|
python
|
def is_transparent(image):
"""
Check to see if an image is transparent.
"""
if not isinstance(image, Image.Image):
# Can only deal with PIL images, fall back to the assumption that that
# it's not transparent.
return False
return (image.mode in ('RGBA', 'LA') or
(image.mode == 'P' and 'transparency' in image.info))
|
[
"def",
"is_transparent",
"(",
"image",
")",
":",
"if",
"not",
"isinstance",
"(",
"image",
",",
"Image",
".",
"Image",
")",
":",
"# Can only deal with PIL images, fall back to the assumption that that",
"# it's not transparent.",
"return",
"False",
"return",
"(",
"image",
".",
"mode",
"in",
"(",
"'RGBA'",
",",
"'LA'",
")",
"or",
"(",
"image",
".",
"mode",
"==",
"'P'",
"and",
"'transparency'",
"in",
"image",
".",
"info",
")",
")"
] |
Check to see if an image is transparent.
|
[
"Check",
"to",
"see",
"if",
"an",
"image",
"is",
"transparent",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L89-L98
|
8,739
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/utils.py
|
is_progressive
|
def is_progressive(image):
"""
Check to see if an image is progressive.
"""
if not isinstance(image, Image.Image):
# Can only check PIL images for progressive encoding.
return False
return ('progressive' in image.info) or ('progression' in image.info)
|
python
|
def is_progressive(image):
"""
Check to see if an image is progressive.
"""
if not isinstance(image, Image.Image):
# Can only check PIL images for progressive encoding.
return False
return ('progressive' in image.info) or ('progression' in image.info)
|
[
"def",
"is_progressive",
"(",
"image",
")",
":",
"if",
"not",
"isinstance",
"(",
"image",
",",
"Image",
".",
"Image",
")",
":",
"# Can only check PIL images for progressive encoding.",
"return",
"False",
"return",
"(",
"'progressive'",
"in",
"image",
".",
"info",
")",
"or",
"(",
"'progression'",
"in",
"image",
".",
"info",
")"
] |
Check to see if an image is progressive.
|
[
"Check",
"to",
"see",
"if",
"an",
"image",
"is",
"progressive",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L101-L108
|
8,740
|
SmileyChris/easy-thumbnails
|
easy_thumbnails/utils.py
|
get_modified_time
|
def get_modified_time(storage, name):
"""
Get modified time from storage, ensuring the result is a timezone-aware
datetime.
"""
try:
try:
# Prefer Django 1.10 API and fall back to old one
modified_time = storage.get_modified_time(name)
except AttributeError:
modified_time = storage.modified_time(name)
except OSError:
return 0
except NotImplementedError:
return None
if modified_time and timezone.is_naive(modified_time):
if getattr(settings, 'USE_TZ', False):
default_timezone = timezone.get_default_timezone()
return timezone.make_aware(modified_time, default_timezone)
return modified_time
|
python
|
def get_modified_time(storage, name):
"""
Get modified time from storage, ensuring the result is a timezone-aware
datetime.
"""
try:
try:
# Prefer Django 1.10 API and fall back to old one
modified_time = storage.get_modified_time(name)
except AttributeError:
modified_time = storage.modified_time(name)
except OSError:
return 0
except NotImplementedError:
return None
if modified_time and timezone.is_naive(modified_time):
if getattr(settings, 'USE_TZ', False):
default_timezone = timezone.get_default_timezone()
return timezone.make_aware(modified_time, default_timezone)
return modified_time
|
[
"def",
"get_modified_time",
"(",
"storage",
",",
"name",
")",
":",
"try",
":",
"try",
":",
"# Prefer Django 1.10 API and fall back to old one",
"modified_time",
"=",
"storage",
".",
"get_modified_time",
"(",
"name",
")",
"except",
"AttributeError",
":",
"modified_time",
"=",
"storage",
".",
"modified_time",
"(",
"name",
")",
"except",
"OSError",
":",
"return",
"0",
"except",
"NotImplementedError",
":",
"return",
"None",
"if",
"modified_time",
"and",
"timezone",
".",
"is_naive",
"(",
"modified_time",
")",
":",
"if",
"getattr",
"(",
"settings",
",",
"'USE_TZ'",
",",
"False",
")",
":",
"default_timezone",
"=",
"timezone",
".",
"get_default_timezone",
"(",
")",
"return",
"timezone",
".",
"make_aware",
"(",
"modified_time",
",",
"default_timezone",
")",
"return",
"modified_time"
] |
Get modified time from storage, ensuring the result is a timezone-aware
datetime.
|
[
"Get",
"modified",
"time",
"from",
"storage",
"ensuring",
"the",
"result",
"is",
"a",
"timezone",
"-",
"aware",
"datetime",
"."
] |
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
|
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/utils.py#L140-L159
|
8,741
|
dr-leo/pandaSDMX
|
pandasdmx/utils/anynamedtuple.py
|
namedtuple
|
def namedtuple(typename, field_names, verbose=False, rename=False):
"""Returns a new subclass of tuple with named fields.
This is a patched version of collections.namedtuple from the stdlib.
Unlike the latter, it accepts non-identifier strings as field names.
All values are accessible through dict syntax. Fields whose names are
identifiers are also accessible via attribute syntax as in ordinary namedtuples, alongside traditional
indexing. This feature is needed as SDMX allows field names
to contain '-'.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessable by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = str(typename)
for name in [typename] + field_names:
if type(name) != str:
raise TypeError('Type names and field names must be strings')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
'keyword: %r' % name)
if not _isidentifier(typename):
raise ValueError('Type names must be valid '
'identifiers: %r' % name)
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
'%r' % name)
if name in seen:
raise ValueError('Encountered duplicate field name: %r' % name)
seen.add(name)
arg_names = ['_' + str(i) for i in range(len(field_names))]
# Fill-in the class template
class_definition = _class_template.format(
typename=typename,
field_names=tuple(field_names),
num_fields=len(field_names),
arg_list=repr(tuple(arg_names)).replace("'", "")[1:-1],
repr_fmt=', '.join(_repr_template.format(name=name)
for name in field_names),
field_defs='\n'.join(_field_template.format(index=index, name=name)
for index, name in enumerate(field_names) if _isidentifier(name))
)
# Execute the template string in a temporary namespace and support
# tracing utilities by setting a value for frame.f_globals['__name__']
namespace = dict(__name__='namedtuple_%s' % typename)
exec(class_definition, namespace)
result = namespace[typename]
result._source = class_definition
if verbose:
print(result._source)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython).
try:
result.__module__ = _sys._getframe(
1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return result
|
python
|
def namedtuple(typename, field_names, verbose=False, rename=False):
"""Returns a new subclass of tuple with named fields.
This is a patched version of collections.namedtuple from the stdlib.
Unlike the latter, it accepts non-identifier strings as field names.
All values are accessible through dict syntax. Fields whose names are
identifiers are also accessible via attribute syntax as in ordinary namedtuples, alongside traditional
indexing. This feature is needed as SDMX allows field names
to contain '-'.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessable by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
if isinstance(field_names, str):
field_names = field_names.replace(',', ' ').split()
field_names = list(map(str, field_names))
typename = str(typename)
for name in [typename] + field_names:
if type(name) != str:
raise TypeError('Type names and field names must be strings')
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a '
'keyword: %r' % name)
if not _isidentifier(typename):
raise ValueError('Type names must be valid '
'identifiers: %r' % name)
seen = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: '
'%r' % name)
if name in seen:
raise ValueError('Encountered duplicate field name: %r' % name)
seen.add(name)
arg_names = ['_' + str(i) for i in range(len(field_names))]
# Fill-in the class template
class_definition = _class_template.format(
typename=typename,
field_names=tuple(field_names),
num_fields=len(field_names),
arg_list=repr(tuple(arg_names)).replace("'", "")[1:-1],
repr_fmt=', '.join(_repr_template.format(name=name)
for name in field_names),
field_defs='\n'.join(_field_template.format(index=index, name=name)
for index, name in enumerate(field_names) if _isidentifier(name))
)
# Execute the template string in a temporary namespace and support
# tracing utilities by setting a value for frame.f_globals['__name__']
namespace = dict(__name__='namedtuple_%s' % typename)
exec(class_definition, namespace)
result = namespace[typename]
result._source = class_definition
if verbose:
print(result._source)
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in environments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython).
try:
result.__module__ = _sys._getframe(
1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return result
|
[
"def",
"namedtuple",
"(",
"typename",
",",
"field_names",
",",
"verbose",
"=",
"False",
",",
"rename",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"field_names",
",",
"str",
")",
":",
"field_names",
"=",
"field_names",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"field_names",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"field_names",
")",
")",
"typename",
"=",
"str",
"(",
"typename",
")",
"for",
"name",
"in",
"[",
"typename",
"]",
"+",
"field_names",
":",
"if",
"type",
"(",
"name",
")",
"!=",
"str",
":",
"raise",
"TypeError",
"(",
"'Type names and field names must be strings'",
")",
"if",
"_iskeyword",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"'Type names and field names cannot be a '",
"'keyword: %r'",
"%",
"name",
")",
"if",
"not",
"_isidentifier",
"(",
"typename",
")",
":",
"raise",
"ValueError",
"(",
"'Type names must be valid '",
"'identifiers: %r'",
"%",
"name",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"field_names",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
"and",
"not",
"rename",
":",
"raise",
"ValueError",
"(",
"'Field names cannot start with an underscore: '",
"'%r'",
"%",
"name",
")",
"if",
"name",
"in",
"seen",
":",
"raise",
"ValueError",
"(",
"'Encountered duplicate field name: %r'",
"%",
"name",
")",
"seen",
".",
"add",
"(",
"name",
")",
"arg_names",
"=",
"[",
"'_'",
"+",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"field_names",
")",
")",
"]",
"# Fill-in the class template",
"class_definition",
"=",
"_class_template",
".",
"format",
"(",
"typename",
"=",
"typename",
",",
"field_names",
"=",
"tuple",
"(",
"field_names",
")",
",",
"num_fields",
"=",
"len",
"(",
"field_names",
")",
",",
"arg_list",
"=",
"repr",
"(",
"tuple",
"(",
"arg_names",
")",
")",
".",
"replace",
"(",
"\"'\"",
",",
"\"\"",
")",
"[",
"1",
":",
"-",
"1",
"]",
",",
"repr_fmt",
"=",
"', '",
".",
"join",
"(",
"_repr_template",
".",
"format",
"(",
"name",
"=",
"name",
")",
"for",
"name",
"in",
"field_names",
")",
",",
"field_defs",
"=",
"'\\n'",
".",
"join",
"(",
"_field_template",
".",
"format",
"(",
"index",
"=",
"index",
",",
"name",
"=",
"name",
")",
"for",
"index",
",",
"name",
"in",
"enumerate",
"(",
"field_names",
")",
"if",
"_isidentifier",
"(",
"name",
")",
")",
")",
"# Execute the template string in a temporary namespace and support",
"# tracing utilities by setting a value for frame.f_globals['__name__']",
"namespace",
"=",
"dict",
"(",
"__name__",
"=",
"'namedtuple_%s'",
"%",
"typename",
")",
"exec",
"(",
"class_definition",
",",
"namespace",
")",
"result",
"=",
"namespace",
"[",
"typename",
"]",
"result",
".",
"_source",
"=",
"class_definition",
"if",
"verbose",
":",
"print",
"(",
"result",
".",
"_source",
")",
"# For pickling to work, the __module__ variable needs to be set to the frame",
"# where the named tuple is created. Bypass this step in environments where",
"# sys._getframe is not defined (Jython for example) or sys._getframe is not",
"# defined for arguments greater than 0 (IronPython).",
"try",
":",
"result",
".",
"__module__",
"=",
"_sys",
".",
"_getframe",
"(",
"1",
")",
".",
"f_globals",
".",
"get",
"(",
"'__name__'",
",",
"'__main__'",
")",
"except",
"(",
"AttributeError",
",",
"ValueError",
")",
":",
"pass",
"return",
"result"
] |
Returns a new subclass of tuple with named fields.
This is a patched version of collections.namedtuple from the stdlib.
Unlike the latter, it accepts non-identifier strings as field names.
All values are accessible through dict syntax. Fields whose names are
identifiers are also accessible via attribute syntax as in ordinary namedtuples, alongside traditional
indexing. This feature is needed as SDMX allows field names
to contain '-'.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessable by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
|
[
"Returns",
"a",
"new",
"subclass",
"of",
"tuple",
"with",
"named",
"fields",
".",
"This",
"is",
"a",
"patched",
"version",
"of",
"collections",
".",
"namedtuple",
"from",
"the",
"stdlib",
".",
"Unlike",
"the",
"latter",
"it",
"accepts",
"non",
"-",
"identifier",
"strings",
"as",
"field",
"names",
".",
"All",
"values",
"are",
"accessible",
"through",
"dict",
"syntax",
".",
"Fields",
"whose",
"names",
"are",
"identifiers",
"are",
"also",
"accessible",
"via",
"attribute",
"syntax",
"as",
"in",
"ordinary",
"namedtuples",
"alongside",
"traditional",
"indexing",
".",
"This",
"feature",
"is",
"needed",
"as",
"SDMX",
"allows",
"field",
"names",
"to",
"contain",
"-",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/utils/anynamedtuple.py#L89-L172
|
8,742
|
dr-leo/pandaSDMX
|
pandasdmx/reader/sdmxjson.py
|
Reader.write_source
|
def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True)
|
python
|
def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True)
|
[
"def",
"write_source",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"return",
"json",
".",
"dump",
"(",
"self",
".",
"message",
".",
"_elem",
",",
"fp",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")"
] |
Save source to file by calling `write` on the root element.
|
[
"Save",
"source",
"to",
"file",
"by",
"calling",
"write",
"on",
"the",
"root",
"element",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxjson.py#L86-L91
|
8,743
|
dr-leo/pandaSDMX
|
pandasdmx/reader/sdmxml.py
|
Reader.write_source
|
def write_source(self, filename):
'''
Save XML source to file by calling `write` on the root element.
'''
return self.message._elem.getroottree().write(filename, encoding='utf8')
|
python
|
def write_source(self, filename):
'''
Save XML source to file by calling `write` on the root element.
'''
return self.message._elem.getroottree().write(filename, encoding='utf8')
|
[
"def",
"write_source",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"message",
".",
"_elem",
".",
"getroottree",
"(",
")",
".",
"write",
"(",
"filename",
",",
"encoding",
"=",
"'utf8'",
")"
] |
Save XML source to file by calling `write` on the root element.
|
[
"Save",
"XML",
"source",
"to",
"file",
"by",
"calling",
"write",
"on",
"the",
"root",
"element",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxml.py#L52-L56
|
8,744
|
dr-leo/pandaSDMX
|
pandasdmx/model.py
|
Series.group_attrib
|
def group_attrib(self):
'''
return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member
'''
group_attributes = [g.attrib for g in self.dataset.groups if self in g]
if group_attributes:
return concat_namedtuples(*group_attributes)
|
python
|
def group_attrib(self):
'''
return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member
'''
group_attributes = [g.attrib for g in self.dataset.groups if self in g]
if group_attributes:
return concat_namedtuples(*group_attributes)
|
[
"def",
"group_attrib",
"(",
"self",
")",
":",
"group_attributes",
"=",
"[",
"g",
".",
"attrib",
"for",
"g",
"in",
"self",
".",
"dataset",
".",
"groups",
"if",
"self",
"in",
"g",
"]",
"if",
"group_attributes",
":",
"return",
"concat_namedtuples",
"(",
"*",
"group_attributes",
")"
] |
return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member
|
[
"return",
"a",
"namedtuple",
"containing",
"all",
"attributes",
"attached",
"to",
"groups",
"of",
"which",
"the",
"given",
"series",
"is",
"a",
"member",
"for",
"each",
"group",
"of",
"which",
"the",
"series",
"is",
"a",
"member"
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/model.py#L632-L640
|
8,745
|
dr-leo/pandaSDMX
|
pandasdmx/reader/__init__.py
|
BaseReader.read_instance
|
def read_instance(self, cls, sdmxobj, offset=None, first_only=True):
'''
If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return None.
'''
if offset:
try:
base = self._paths[offset](sdmxobj._elem)[0]
except IndexError:
return None
else:
base = sdmxobj._elem
result = self._paths[cls](base)
if result:
if first_only:
return cls(self, result[0])
else:
return [cls(self, i) for i in result]
|
python
|
def read_instance(self, cls, sdmxobj, offset=None, first_only=True):
'''
If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return None.
'''
if offset:
try:
base = self._paths[offset](sdmxobj._elem)[0]
except IndexError:
return None
else:
base = sdmxobj._elem
result = self._paths[cls](base)
if result:
if first_only:
return cls(self, result[0])
else:
return [cls(self, i) for i in result]
|
[
"def",
"read_instance",
"(",
"self",
",",
"cls",
",",
"sdmxobj",
",",
"offset",
"=",
"None",
",",
"first_only",
"=",
"True",
")",
":",
"if",
"offset",
":",
"try",
":",
"base",
"=",
"self",
".",
"_paths",
"[",
"offset",
"]",
"(",
"sdmxobj",
".",
"_elem",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"return",
"None",
"else",
":",
"base",
"=",
"sdmxobj",
".",
"_elem",
"result",
"=",
"self",
".",
"_paths",
"[",
"cls",
"]",
"(",
"base",
")",
"if",
"result",
":",
"if",
"first_only",
":",
"return",
"cls",
"(",
"self",
",",
"result",
"[",
"0",
"]",
")",
"else",
":",
"return",
"[",
"cls",
"(",
"self",
",",
"i",
")",
"for",
"i",
"in",
"result",
"]"
] |
If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return None.
|
[
"If",
"cls",
"in",
"_paths",
"and",
"matches",
"return",
"an",
"instance",
"of",
"cls",
"with",
"the",
"first",
"XML",
"element",
"or",
"if",
"first_only",
"is",
"False",
"a",
"list",
"of",
"cls",
"instances",
"for",
"all",
"elements",
"found",
"If",
"no",
"matches",
"were",
"found",
"return",
"None",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/__init__.py#L54-L74
|
8,746
|
dr-leo/pandaSDMX
|
pandasdmx/api.py
|
Request.load_agency_profile
|
def load_agency_profile(cls, source):
'''
Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated with the metadata from the
source.
Returns None
'''
if not isinstance(source, str_type):
# so it must be a text file
source = source.read()
new_agencies = json.loads(source)
cls._agencies.update(new_agencies)
|
python
|
def load_agency_profile(cls, source):
'''
Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated with the metadata from the
source.
Returns None
'''
if not isinstance(source, str_type):
# so it must be a text file
source = source.read()
new_agencies = json.loads(source)
cls._agencies.update(new_agencies)
|
[
"def",
"load_agency_profile",
"(",
"cls",
",",
"source",
")",
":",
"if",
"not",
"isinstance",
"(",
"source",
",",
"str_type",
")",
":",
"# so it must be a text file",
"source",
"=",
"source",
".",
"read",
"(",
")",
"new_agencies",
"=",
"json",
".",
"loads",
"(",
"source",
")",
"cls",
".",
"_agencies",
".",
"update",
"(",
"new_agencies",
")"
] |
Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated with the metadata from the
source.
Returns None
|
[
"Classmethod",
"loading",
"metadata",
"on",
"a",
"data",
"provider",
".",
"source",
"must",
"be",
"a",
"json",
"-",
"formated",
"string",
"or",
"file",
"-",
"like",
"object",
"describing",
"one",
"or",
"more",
"data",
"providers",
"(",
"URL",
"of",
"the",
"SDMX",
"web",
"API",
"resource",
"types",
"etc",
".",
"The",
"dict",
"Request",
".",
"_agencies",
"is",
"updated",
"with",
"the",
"metadata",
"from",
"the",
"source",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L63-L77
|
8,747
|
dr-leo/pandaSDMX
|
pandasdmx/api.py
|
Request.series_keys
|
def series_keys(self, flow_id, cache=True):
'''
Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow.
'''
# Check if requested series keys are already cached
cache_id = 'series_keys_' + flow_id
if cache_id in self.cache:
return self.cache[cache_id]
else:
# download an empty dataset with all available series keys
resp = self.data(flow_id, params={'detail': 'serieskeysonly'})
l = list(s.key for s in resp.data.series)
df = PD.DataFrame(l, columns=l[0]._fields, dtype='category')
if cache:
self.cache[cache_id] = df
return df
|
python
|
def series_keys(self, flow_id, cache=True):
'''
Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow.
'''
# Check if requested series keys are already cached
cache_id = 'series_keys_' + flow_id
if cache_id in self.cache:
return self.cache[cache_id]
else:
# download an empty dataset with all available series keys
resp = self.data(flow_id, params={'detail': 'serieskeysonly'})
l = list(s.key for s in resp.data.series)
df = PD.DataFrame(l, columns=l[0]._fields, dtype='category')
if cache:
self.cache[cache_id] = df
return df
|
[
"def",
"series_keys",
"(",
"self",
",",
"flow_id",
",",
"cache",
"=",
"True",
")",
":",
"# Check if requested series keys are already cached",
"cache_id",
"=",
"'series_keys_'",
"+",
"flow_id",
"if",
"cache_id",
"in",
"self",
".",
"cache",
":",
"return",
"self",
".",
"cache",
"[",
"cache_id",
"]",
"else",
":",
"# download an empty dataset with all available series keys",
"resp",
"=",
"self",
".",
"data",
"(",
"flow_id",
",",
"params",
"=",
"{",
"'detail'",
":",
"'serieskeysonly'",
"}",
")",
"l",
"=",
"list",
"(",
"s",
".",
"key",
"for",
"s",
"in",
"resp",
".",
"data",
".",
"series",
")",
"df",
"=",
"PD",
".",
"DataFrame",
"(",
"l",
",",
"columns",
"=",
"l",
"[",
"0",
"]",
".",
"_fields",
",",
"dtype",
"=",
"'category'",
")",
"if",
"cache",
":",
"self",
".",
"cache",
"[",
"cache_id",
"]",
"=",
"df",
"return",
"df"
] |
Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow.
|
[
"Get",
"an",
"empty",
"dataset",
"with",
"all",
"possible",
"series",
"keys",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L150-L170
|
8,748
|
dr-leo/pandaSDMX
|
pandasdmx/api.py
|
Request.preview_data
|
def preview_data(self, flow_id, key=None, count=True, total=True):
'''
Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is,
however, not supported by all data providers.
ECB and UNSD are known to work.
Args:
flow_id(str): dataflow id
key(dict): optional key mapping dimension names to values or lists of values.
Must have been validated before. It is not checked if key values
are actually valid dimension names and values. Default: {}
count(bool): if True (default), return the number of series
of the dataset designated by flow_id and key. If False,
the actual keys are returned as a pandas DataFrame or dict of dataframes, depending on
the value of 'total'.
total(bool): if True (default), return the aggregate number
of series or a single dataframe (depending on the value of 'count'). If False,
return a dict mapping keys to dataframes of series keys.
E.g., if key={'COUNTRY':'IT+CA+AU'}, the dict will
have 3 items describing the series keys for each country
respectively. If 'count' is True, dict values will be int rather than
PD.DataFrame.
'''
all_keys = self.series_keys(flow_id)
# Handle the special case that no key is provided
if not key:
if count:
return all_keys.shape[0]
else:
return all_keys
# So there is a key specifying at least one dimension value.
# Wrap single values in 1-elem list for uniform treatment
key_l = {k: [v] if isinstance(v, str_type) else v
for k, v in key.items()}
# order dim_names that are present in the key
dim_names = [k for k in all_keys if k in key]
# Drop columns that are not in the key
key_df = all_keys.loc[:, dim_names]
if total:
# DataFrame with matching series keys
bool_series = reduce(
and_, (key_df.isin(key_l)[col] for col in dim_names))
if count:
return bool_series.value_counts()[True]
else:
return all_keys[bool_series]
else:
# Dict of value combinations as dict keys
key_product = product(*(key_l[k] for k in dim_names))
# Replace key tuples by namedtuples
PartialKey = namedtuple_factory('PartialKey', dim_names)
matches = {PartialKey(k): reduce(and_, (key_df.isin({k1: [v1]
for k1, v1 in zip(dim_names, k)})[col]
for col in dim_names))
for k in key_product}
if not count:
# dict mapping each key to DataFrame with selected key-set
return {k: all_keys[v] for k, v in matches.items()}
else:
# Number of series per key
return {k: v.value_counts()[True] for k, v in matches.items()}
|
python
|
def preview_data(self, flow_id, key=None, count=True, total=True):
'''
Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is,
however, not supported by all data providers.
ECB and UNSD are known to work.
Args:
flow_id(str): dataflow id
key(dict): optional key mapping dimension names to values or lists of values.
Must have been validated before. It is not checked if key values
are actually valid dimension names and values. Default: {}
count(bool): if True (default), return the number of series
of the dataset designated by flow_id and key. If False,
the actual keys are returned as a pandas DataFrame or dict of dataframes, depending on
the value of 'total'.
total(bool): if True (default), return the aggregate number
of series or a single dataframe (depending on the value of 'count'). If False,
return a dict mapping keys to dataframes of series keys.
E.g., if key={'COUNTRY':'IT+CA+AU'}, the dict will
have 3 items describing the series keys for each country
respectively. If 'count' is True, dict values will be int rather than
PD.DataFrame.
'''
all_keys = self.series_keys(flow_id)
# Handle the special case that no key is provided
if not key:
if count:
return all_keys.shape[0]
else:
return all_keys
# So there is a key specifying at least one dimension value.
# Wrap single values in 1-elem list for uniform treatment
key_l = {k: [v] if isinstance(v, str_type) else v
for k, v in key.items()}
# order dim_names that are present in the key
dim_names = [k for k in all_keys if k in key]
# Drop columns that are not in the key
key_df = all_keys.loc[:, dim_names]
if total:
# DataFrame with matching series keys
bool_series = reduce(
and_, (key_df.isin(key_l)[col] for col in dim_names))
if count:
return bool_series.value_counts()[True]
else:
return all_keys[bool_series]
else:
# Dict of value combinations as dict keys
key_product = product(*(key_l[k] for k in dim_names))
# Replace key tuples by namedtuples
PartialKey = namedtuple_factory('PartialKey', dim_names)
matches = {PartialKey(k): reduce(and_, (key_df.isin({k1: [v1]
for k1, v1 in zip(dim_names, k)})[col]
for col in dim_names))
for k in key_product}
if not count:
# dict mapping each key to DataFrame with selected key-set
return {k: all_keys[v] for k, v in matches.items()}
else:
# Number of series per key
return {k: v.value_counts()[True] for k, v in matches.items()}
|
[
"def",
"preview_data",
"(",
"self",
",",
"flow_id",
",",
"key",
"=",
"None",
",",
"count",
"=",
"True",
",",
"total",
"=",
"True",
")",
":",
"all_keys",
"=",
"self",
".",
"series_keys",
"(",
"flow_id",
")",
"# Handle the special case that no key is provided",
"if",
"not",
"key",
":",
"if",
"count",
":",
"return",
"all_keys",
".",
"shape",
"[",
"0",
"]",
"else",
":",
"return",
"all_keys",
"# So there is a key specifying at least one dimension value.",
"# Wrap single values in 1-elem list for uniform treatment",
"key_l",
"=",
"{",
"k",
":",
"[",
"v",
"]",
"if",
"isinstance",
"(",
"v",
",",
"str_type",
")",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"key",
".",
"items",
"(",
")",
"}",
"# order dim_names that are present in the key",
"dim_names",
"=",
"[",
"k",
"for",
"k",
"in",
"all_keys",
"if",
"k",
"in",
"key",
"]",
"# Drop columns that are not in the key",
"key_df",
"=",
"all_keys",
".",
"loc",
"[",
":",
",",
"dim_names",
"]",
"if",
"total",
":",
"# DataFrame with matching series keys",
"bool_series",
"=",
"reduce",
"(",
"and_",
",",
"(",
"key_df",
".",
"isin",
"(",
"key_l",
")",
"[",
"col",
"]",
"for",
"col",
"in",
"dim_names",
")",
")",
"if",
"count",
":",
"return",
"bool_series",
".",
"value_counts",
"(",
")",
"[",
"True",
"]",
"else",
":",
"return",
"all_keys",
"[",
"bool_series",
"]",
"else",
":",
"# Dict of value combinations as dict keys",
"key_product",
"=",
"product",
"(",
"*",
"(",
"key_l",
"[",
"k",
"]",
"for",
"k",
"in",
"dim_names",
")",
")",
"# Replace key tuples by namedtuples",
"PartialKey",
"=",
"namedtuple_factory",
"(",
"'PartialKey'",
",",
"dim_names",
")",
"matches",
"=",
"{",
"PartialKey",
"(",
"k",
")",
":",
"reduce",
"(",
"and_",
",",
"(",
"key_df",
".",
"isin",
"(",
"{",
"k1",
":",
"[",
"v1",
"]",
"for",
"k1",
",",
"v1",
"in",
"zip",
"(",
"dim_names",
",",
"k",
")",
"}",
")",
"[",
"col",
"]",
"for",
"col",
"in",
"dim_names",
")",
")",
"for",
"k",
"in",
"key_product",
"}",
"if",
"not",
"count",
":",
"# dict mapping each key to DataFrame with selected key-set",
"return",
"{",
"k",
":",
"all_keys",
"[",
"v",
"]",
"for",
"k",
",",
"v",
"in",
"matches",
".",
"items",
"(",
")",
"}",
"else",
":",
"# Number of series per key",
"return",
"{",
"k",
":",
"v",
".",
"value_counts",
"(",
")",
"[",
"True",
"]",
"for",
"k",
",",
"v",
"in",
"matches",
".",
"items",
"(",
")",
"}"
] |
Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is,
however, not supported by all data providers.
ECB and UNSD are known to work.
Args:
flow_id(str): dataflow id
key(dict): optional key mapping dimension names to values or lists of values.
Must have been validated before. It is not checked if key values
are actually valid dimension names and values. Default: {}
count(bool): if True (default), return the number of series
of the dataset designated by flow_id and key. If False,
the actual keys are returned as a pandas DataFrame or dict of dataframes, depending on
the value of 'total'.
total(bool): if True (default), return the aggregate number
of series or a single dataframe (depending on the value of 'count'). If False,
return a dict mapping keys to dataframes of series keys.
E.g., if key={'COUNTRY':'IT+CA+AU'}, the dict will
have 3 items describing the series keys for each country
respectively. If 'count' is True, dict values will be int rather than
PD.DataFrame.
|
[
"Get",
"keys",
"or",
"number",
"of",
"series",
"for",
"a",
"prospective",
"dataset",
"query",
"allowing",
"for",
"keys",
"with",
"multiple",
"values",
"per",
"dimension",
".",
"It",
"downloads",
"the",
"complete",
"list",
"of",
"series",
"keys",
"for",
"a",
"dataflow",
"rather",
"than",
"using",
"constraints",
"and",
"DSD",
".",
"This",
"feature",
"is",
"however",
"not",
"supported",
"by",
"all",
"data",
"providers",
".",
"ECB",
"and",
"UNSD",
"are",
"known",
"to",
"work",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L495-L564
|
8,749
|
dr-leo/pandaSDMX
|
pandasdmx/api.py
|
Response.write
|
def write(self, source=None, **kwargs):
'''Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to write unless specified in the
keyword arguments. If an iterable is given,
the writer should write each item. Keyword arguments may
specify what to do with the output depending on the writer's API. Defaults to self.msg.
Returns:
type: anything the writer returns.
'''
if not source:
source = self.msg
return self._writer.write(source=source, **kwargs)
|
python
|
def write(self, source=None, **kwargs):
'''Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to write unless specified in the
keyword arguments. If an iterable is given,
the writer should write each item. Keyword arguments may
specify what to do with the output depending on the writer's API. Defaults to self.msg.
Returns:
type: anything the writer returns.
'''
if not source:
source = self.msg
return self._writer.write(source=source, **kwargs)
|
[
"def",
"write",
"(",
"self",
",",
"source",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"source",
":",
"source",
"=",
"self",
".",
"msg",
"return",
"self",
".",
"_writer",
".",
"write",
"(",
"source",
"=",
"source",
",",
"*",
"*",
"kwargs",
")"
] |
Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to write unless specified in the
keyword arguments. If an iterable is given,
the writer should write each item. Keyword arguments may
specify what to do with the output depending on the writer's API. Defaults to self.msg.
Returns:
type: anything the writer returns.
|
[
"Wrappe",
"r",
"to",
"call",
"the",
"writer",
"s",
"write",
"method",
"if",
"present",
"."
] |
71dd81ebb0d5169e5adcb8b52d516573d193f2d6
|
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L618-L635
|
8,750
|
dropbox/pyannotate
|
pyannotate_tools/annotations/parse.py
|
parse_json
|
def parse_json(path):
# type: (str) -> List[FunctionInfo]
"""Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
"""
with open(path) as f:
data = json.load(f) # type: List[RawEntry]
result = []
def assert_type(value, typ):
# type: (object, type) -> None
assert isinstance(value, typ), '%s: Unexpected type %r' % (path, type(value).__name__)
def assert_dict_item(dictionary, key, typ):
# type: (Mapping[Any, Any], str, type) -> None
assert key in dictionary, '%s: Missing dictionary key %r' % (path, key)
value = dictionary[key]
assert isinstance(value, typ), '%s: Unexpected type %r for key %r' % (
path, type(value).__name__, key)
assert_type(data, list)
for item in data:
assert_type(item, dict)
assert_dict_item(item, 'path', Text)
assert_dict_item(item, 'line', int)
assert_dict_item(item, 'func_name', Text)
assert_dict_item(item, 'type_comments', list)
for comment in item['type_comments']:
assert_type(comment, Text)
assert_type(item['samples'], int)
info = FunctionInfo(encode(item['path']),
item['line'],
encode(item['func_name']),
[encode(comment) for comment in item['type_comments']],
item['samples'])
result.append(info)
return result
|
python
|
def parse_json(path):
# type: (str) -> List[FunctionInfo]
"""Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
"""
with open(path) as f:
data = json.load(f) # type: List[RawEntry]
result = []
def assert_type(value, typ):
# type: (object, type) -> None
assert isinstance(value, typ), '%s: Unexpected type %r' % (path, type(value).__name__)
def assert_dict_item(dictionary, key, typ):
# type: (Mapping[Any, Any], str, type) -> None
assert key in dictionary, '%s: Missing dictionary key %r' % (path, key)
value = dictionary[key]
assert isinstance(value, typ), '%s: Unexpected type %r for key %r' % (
path, type(value).__name__, key)
assert_type(data, list)
for item in data:
assert_type(item, dict)
assert_dict_item(item, 'path', Text)
assert_dict_item(item, 'line', int)
assert_dict_item(item, 'func_name', Text)
assert_dict_item(item, 'type_comments', list)
for comment in item['type_comments']:
assert_type(comment, Text)
assert_type(item['samples'], int)
info = FunctionInfo(encode(item['path']),
item['line'],
encode(item['func_name']),
[encode(comment) for comment in item['type_comments']],
item['samples'])
result.append(info)
return result
|
[
"def",
"parse_json",
"(",
"path",
")",
":",
"# type: (str) -> List[FunctionInfo]",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"# type: List[RawEntry]",
"result",
"=",
"[",
"]",
"def",
"assert_type",
"(",
"value",
",",
"typ",
")",
":",
"# type: (object, type) -> None",
"assert",
"isinstance",
"(",
"value",
",",
"typ",
")",
",",
"'%s: Unexpected type %r'",
"%",
"(",
"path",
",",
"type",
"(",
"value",
")",
".",
"__name__",
")",
"def",
"assert_dict_item",
"(",
"dictionary",
",",
"key",
",",
"typ",
")",
":",
"# type: (Mapping[Any, Any], str, type) -> None",
"assert",
"key",
"in",
"dictionary",
",",
"'%s: Missing dictionary key %r'",
"%",
"(",
"path",
",",
"key",
")",
"value",
"=",
"dictionary",
"[",
"key",
"]",
"assert",
"isinstance",
"(",
"value",
",",
"typ",
")",
",",
"'%s: Unexpected type %r for key %r'",
"%",
"(",
"path",
",",
"type",
"(",
"value",
")",
".",
"__name__",
",",
"key",
")",
"assert_type",
"(",
"data",
",",
"list",
")",
"for",
"item",
"in",
"data",
":",
"assert_type",
"(",
"item",
",",
"dict",
")",
"assert_dict_item",
"(",
"item",
",",
"'path'",
",",
"Text",
")",
"assert_dict_item",
"(",
"item",
",",
"'line'",
",",
"int",
")",
"assert_dict_item",
"(",
"item",
",",
"'func_name'",
",",
"Text",
")",
"assert_dict_item",
"(",
"item",
",",
"'type_comments'",
",",
"list",
")",
"for",
"comment",
"in",
"item",
"[",
"'type_comments'",
"]",
":",
"assert_type",
"(",
"comment",
",",
"Text",
")",
"assert_type",
"(",
"item",
"[",
"'samples'",
"]",
",",
"int",
")",
"info",
"=",
"FunctionInfo",
"(",
"encode",
"(",
"item",
"[",
"'path'",
"]",
")",
",",
"item",
"[",
"'line'",
"]",
",",
"encode",
"(",
"item",
"[",
"'func_name'",
"]",
")",
",",
"[",
"encode",
"(",
"comment",
")",
"for",
"comment",
"in",
"item",
"[",
"'type_comments'",
"]",
"]",
",",
"item",
"[",
"'samples'",
"]",
")",
"result",
".",
"append",
"(",
"info",
")",
"return",
"result"
] |
Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
|
[
"Deserialize",
"a",
"JSON",
"file",
"containing",
"runtime",
"collected",
"types",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L96-L133
|
8,751
|
dropbox/pyannotate
|
pyannotate_tools/annotations/parse.py
|
tokenize
|
def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0] in '()[],*':
tokens.append(Separator(s[0]))
s = s[1:]
elif s[:2] == '->':
tokens.append(Separator('->'))
s = s[2:]
else:
m = re.match(r'[-\w]+(\s*(\.|:)\s*[-/\w]*)*', s)
if not m:
raise ParseError(original)
fullname = m.group(0)
fullname = fullname.replace(' ', '')
if fullname in TYPE_FIXUPS:
fullname = TYPE_FIXUPS[fullname]
# pytz creates classes with the name of the timezone being used:
# https://github.com/stub42/pytz/blob/f55399cddbef67c56db1b83e0939ecc1e276cf42/src/pytz/tzfile.py#L120-L123
# This causes pyannotates to crash as it's invalid to have a class
# name with a `/` in it (e.g. "pytz.tzfile.America/Los_Angeles")
if fullname.startswith('pytz.tzfile.'):
fullname = 'datetime.tzinfo'
if '-' in fullname or '/' in fullname:
# Not a valid Python name; there are many places that
# generate these, so we just substitute Any rather
# than crashing.
fullname = 'Any'
tokens.append(DottedName(fullname))
s = s[len(m.group(0)):]
|
python
|
def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0] in '()[],*':
tokens.append(Separator(s[0]))
s = s[1:]
elif s[:2] == '->':
tokens.append(Separator('->'))
s = s[2:]
else:
m = re.match(r'[-\w]+(\s*(\.|:)\s*[-/\w]*)*', s)
if not m:
raise ParseError(original)
fullname = m.group(0)
fullname = fullname.replace(' ', '')
if fullname in TYPE_FIXUPS:
fullname = TYPE_FIXUPS[fullname]
# pytz creates classes with the name of the timezone being used:
# https://github.com/stub42/pytz/blob/f55399cddbef67c56db1b83e0939ecc1e276cf42/src/pytz/tzfile.py#L120-L123
# This causes pyannotates to crash as it's invalid to have a class
# name with a `/` in it (e.g. "pytz.tzfile.America/Los_Angeles")
if fullname.startswith('pytz.tzfile.'):
fullname = 'datetime.tzinfo'
if '-' in fullname or '/' in fullname:
# Not a valid Python name; there are many places that
# generate these, so we just substitute Any rather
# than crashing.
fullname = 'Any'
tokens.append(DottedName(fullname))
s = s[len(m.group(0)):]
|
[
"def",
"tokenize",
"(",
"s",
")",
":",
"# type: (str) -> List[Token]",
"original",
"=",
"s",
"tokens",
"=",
"[",
"]",
"# type: List[Token]",
"while",
"True",
":",
"if",
"not",
"s",
":",
"tokens",
".",
"append",
"(",
"End",
"(",
")",
")",
"return",
"tokens",
"elif",
"s",
"[",
"0",
"]",
"==",
"' '",
":",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"elif",
"s",
"[",
"0",
"]",
"in",
"'()[],*'",
":",
"tokens",
".",
"append",
"(",
"Separator",
"(",
"s",
"[",
"0",
"]",
")",
")",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"elif",
"s",
"[",
":",
"2",
"]",
"==",
"'->'",
":",
"tokens",
".",
"append",
"(",
"Separator",
"(",
"'->'",
")",
")",
"s",
"=",
"s",
"[",
"2",
":",
"]",
"else",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'[-\\w]+(\\s*(\\.|:)\\s*[-/\\w]*)*'",
",",
"s",
")",
"if",
"not",
"m",
":",
"raise",
"ParseError",
"(",
"original",
")",
"fullname",
"=",
"m",
".",
"group",
"(",
"0",
")",
"fullname",
"=",
"fullname",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"if",
"fullname",
"in",
"TYPE_FIXUPS",
":",
"fullname",
"=",
"TYPE_FIXUPS",
"[",
"fullname",
"]",
"# pytz creates classes with the name of the timezone being used:",
"# https://github.com/stub42/pytz/blob/f55399cddbef67c56db1b83e0939ecc1e276cf42/src/pytz/tzfile.py#L120-L123",
"# This causes pyannotates to crash as it's invalid to have a class",
"# name with a `/` in it (e.g. \"pytz.tzfile.America/Los_Angeles\")",
"if",
"fullname",
".",
"startswith",
"(",
"'pytz.tzfile.'",
")",
":",
"fullname",
"=",
"'datetime.tzinfo'",
"if",
"'-'",
"in",
"fullname",
"or",
"'/'",
"in",
"fullname",
":",
"# Not a valid Python name; there are many places that",
"# generate these, so we just substitute Any rather",
"# than crashing.",
"fullname",
"=",
"'Any'",
"tokens",
".",
"append",
"(",
"DottedName",
"(",
"fullname",
")",
")",
"s",
"=",
"s",
"[",
"len",
"(",
"m",
".",
"group",
"(",
"0",
")",
")",
":",
"]"
] |
Translate a type comment into a list of tokens.
|
[
"Translate",
"a",
"type",
"comment",
"into",
"a",
"list",
"of",
"tokens",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L173-L210
|
8,752
|
dropbox/pyannotate
|
pyannotate_tools/annotations/main.py
|
generate_annotations_json_string
|
def generate_annotations_json_string(source_path, only_simple=False):
# type: (str, bool) -> List[FunctionData]
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items.
"""
items = parse_json(source_path)
results = []
for item in items:
signature = unify_type_comments(item.type_comments)
if is_signature_simple(signature) or not only_simple:
data = {
'path': item.path,
'line': item.line,
'func_name': item.func_name,
'signature': signature,
'samples': item.samples
} # type: FunctionData
results.append(data)
return results
|
python
|
def generate_annotations_json_string(source_path, only_simple=False):
# type: (str, bool) -> List[FunctionData]
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items.
"""
items = parse_json(source_path)
results = []
for item in items:
signature = unify_type_comments(item.type_comments)
if is_signature_simple(signature) or not only_simple:
data = {
'path': item.path,
'line': item.line,
'func_name': item.func_name,
'signature': signature,
'samples': item.samples
} # type: FunctionData
results.append(data)
return results
|
[
"def",
"generate_annotations_json_string",
"(",
"source_path",
",",
"only_simple",
"=",
"False",
")",
":",
"# type: (str, bool) -> List[FunctionData]",
"items",
"=",
"parse_json",
"(",
"source_path",
")",
"results",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"signature",
"=",
"unify_type_comments",
"(",
"item",
".",
"type_comments",
")",
"if",
"is_signature_simple",
"(",
"signature",
")",
"or",
"not",
"only_simple",
":",
"data",
"=",
"{",
"'path'",
":",
"item",
".",
"path",
",",
"'line'",
":",
"item",
".",
"line",
",",
"'func_name'",
":",
"item",
".",
"func_name",
",",
"'signature'",
":",
"signature",
",",
"'samples'",
":",
"item",
".",
"samples",
"}",
"# type: FunctionData",
"results",
".",
"append",
"(",
"data",
")",
"return",
"results"
] |
Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items.
|
[
"Produce",
"annotation",
"data",
"JSON",
"file",
"from",
"a",
"JSON",
"file",
"with",
"runtime",
"-",
"collected",
"types",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/main.py#L48-L70
|
8,753
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
_my_hash
|
def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res
|
python
|
def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res
|
[
"def",
"_my_hash",
"(",
"arg_list",
")",
":",
"# type: (List[Any]) -> int",
"res",
"=",
"0",
"for",
"arg",
"in",
"arg_list",
":",
"res",
"=",
"res",
"*",
"31",
"+",
"hash",
"(",
"arg",
")",
"return",
"res"
] |
Simple helper hash function
|
[
"Simple",
"helper",
"hash",
"function"
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L69-L75
|
8,754
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
name_from_type
|
def name_from_type(type_):
# type: (InternalType) -> str
"""
Helper function to get PEP-484 compatible string representation of our internal types.
"""
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):
return repr(type_)
else:
if type_.__name__ != 'NoneType':
module = type_.__module__
if module in BUILTIN_MODULES or module == '<unknown>':
# Omit module prefix for known built-ins, for convenience. This
# makes unit tests for this module simpler.
# Also ignore '<uknown>' modules so pyannotate can parse these types
return type_.__name__
else:
name = getattr(type_, '__qualname__', None) or type_.__name__
delim = '.' if '.' not in name else ':'
return '%s%s%s' % (module, delim, name)
else:
return 'None'
|
python
|
def name_from_type(type_):
# type: (InternalType) -> str
"""
Helper function to get PEP-484 compatible string representation of our internal types.
"""
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):
return repr(type_)
else:
if type_.__name__ != 'NoneType':
module = type_.__module__
if module in BUILTIN_MODULES or module == '<unknown>':
# Omit module prefix for known built-ins, for convenience. This
# makes unit tests for this module simpler.
# Also ignore '<uknown>' modules so pyannotate can parse these types
return type_.__name__
else:
name = getattr(type_, '__qualname__', None) or type_.__name__
delim = '.' if '.' not in name else ':'
return '%s%s%s' % (module, delim, name)
else:
return 'None'
|
[
"def",
"name_from_type",
"(",
"type_",
")",
":",
"# type: (InternalType) -> str",
"if",
"isinstance",
"(",
"type_",
",",
"(",
"DictType",
",",
"ListType",
",",
"TupleType",
",",
"SetType",
",",
"IteratorType",
")",
")",
":",
"return",
"repr",
"(",
"type_",
")",
"else",
":",
"if",
"type_",
".",
"__name__",
"!=",
"'NoneType'",
":",
"module",
"=",
"type_",
".",
"__module__",
"if",
"module",
"in",
"BUILTIN_MODULES",
"or",
"module",
"==",
"'<unknown>'",
":",
"# Omit module prefix for known built-ins, for convenience. This",
"# makes unit tests for this module simpler.",
"# Also ignore '<uknown>' modules so pyannotate can parse these types",
"return",
"type_",
".",
"__name__",
"else",
":",
"name",
"=",
"getattr",
"(",
"type_",
",",
"'__qualname__'",
",",
"None",
")",
"or",
"type_",
".",
"__name__",
"delim",
"=",
"'.'",
"if",
"'.'",
"not",
"in",
"name",
"else",
"':'",
"return",
"'%s%s%s'",
"%",
"(",
"module",
",",
"delim",
",",
"name",
")",
"else",
":",
"return",
"'None'"
] |
Helper function to get PEP-484 compatible string representation of our internal types.
|
[
"Helper",
"function",
"to",
"get",
"PEP",
"-",
"484",
"compatible",
"string",
"representation",
"of",
"our",
"internal",
"types",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L417-L437
|
8,755
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
resolve_type
|
def resolve_type(arg):
# type: (object) -> InternalType
"""
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
"""
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list) # this line helps mypy figure out types
sample = arg[:min(4, len(arg))]
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return ListType(tentative_type)
elif arg_type == set:
assert isinstance(arg, set) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return SetType(tentative_type)
elif arg_type == FakeIterator:
assert isinstance(arg, FakeIterator) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return IteratorType(tentative_type)
elif arg_type == tuple:
assert isinstance(arg, tuple) # this line helps mypy figure out types
sample = list(arg[:min(10, len(arg))])
return TupleType([resolve_type(sample_item) for sample_item in sample])
elif arg_type == dict:
assert isinstance(arg, dict) # this line helps mypy figure out types
key_tt = TentativeType()
val_tt = TentativeType()
for i, (k, v) in enumerate(iteritems(arg)):
if i > 4:
break
key_tt.add(resolve_type(k))
val_tt.add(resolve_type(v))
return DictType(key_tt, val_tt)
else:
return type(arg)
|
python
|
def resolve_type(arg):
# type: (object) -> InternalType
"""
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
"""
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list) # this line helps mypy figure out types
sample = arg[:min(4, len(arg))]
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return ListType(tentative_type)
elif arg_type == set:
assert isinstance(arg, set) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return SetType(tentative_type)
elif arg_type == FakeIterator:
assert isinstance(arg, FakeIterator) # this line helps mypy figure out types
sample = []
iterator = iter(arg)
for i in range(0, min(4, len(arg))):
sample.append(next(iterator))
tentative_type = TentativeType()
for sample_item in sample:
tentative_type.add(resolve_type(sample_item))
return IteratorType(tentative_type)
elif arg_type == tuple:
assert isinstance(arg, tuple) # this line helps mypy figure out types
sample = list(arg[:min(10, len(arg))])
return TupleType([resolve_type(sample_item) for sample_item in sample])
elif arg_type == dict:
assert isinstance(arg, dict) # this line helps mypy figure out types
key_tt = TentativeType()
val_tt = TentativeType()
for i, (k, v) in enumerate(iteritems(arg)):
if i > 4:
break
key_tt.add(resolve_type(k))
val_tt.add(resolve_type(v))
return DictType(key_tt, val_tt)
else:
return type(arg)
|
[
"def",
"resolve_type",
"(",
"arg",
")",
":",
"# type: (object) -> InternalType",
"arg_type",
"=",
"type",
"(",
"arg",
")",
"if",
"arg_type",
"==",
"list",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"list",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"arg",
"[",
":",
"min",
"(",
"4",
",",
"len",
"(",
"arg",
")",
")",
"]",
"tentative_type",
"=",
"TentativeType",
"(",
")",
"for",
"sample_item",
"in",
"sample",
":",
"tentative_type",
".",
"add",
"(",
"resolve_type",
"(",
"sample_item",
")",
")",
"return",
"ListType",
"(",
"tentative_type",
")",
"elif",
"arg_type",
"==",
"set",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"set",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"[",
"]",
"iterator",
"=",
"iter",
"(",
"arg",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"4",
",",
"len",
"(",
"arg",
")",
")",
")",
":",
"sample",
".",
"append",
"(",
"next",
"(",
"iterator",
")",
")",
"tentative_type",
"=",
"TentativeType",
"(",
")",
"for",
"sample_item",
"in",
"sample",
":",
"tentative_type",
".",
"add",
"(",
"resolve_type",
"(",
"sample_item",
")",
")",
"return",
"SetType",
"(",
"tentative_type",
")",
"elif",
"arg_type",
"==",
"FakeIterator",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"FakeIterator",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"[",
"]",
"iterator",
"=",
"iter",
"(",
"arg",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"4",
",",
"len",
"(",
"arg",
")",
")",
")",
":",
"sample",
".",
"append",
"(",
"next",
"(",
"iterator",
")",
")",
"tentative_type",
"=",
"TentativeType",
"(",
")",
"for",
"sample_item",
"in",
"sample",
":",
"tentative_type",
".",
"add",
"(",
"resolve_type",
"(",
"sample_item",
")",
")",
"return",
"IteratorType",
"(",
"tentative_type",
")",
"elif",
"arg_type",
"==",
"tuple",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"tuple",
")",
"# this line helps mypy figure out types",
"sample",
"=",
"list",
"(",
"arg",
"[",
":",
"min",
"(",
"10",
",",
"len",
"(",
"arg",
")",
")",
"]",
")",
"return",
"TupleType",
"(",
"[",
"resolve_type",
"(",
"sample_item",
")",
"for",
"sample_item",
"in",
"sample",
"]",
")",
"elif",
"arg_type",
"==",
"dict",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"dict",
")",
"# this line helps mypy figure out types",
"key_tt",
"=",
"TentativeType",
"(",
")",
"val_tt",
"=",
"TentativeType",
"(",
")",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"enumerate",
"(",
"iteritems",
"(",
"arg",
")",
")",
":",
"if",
"i",
">",
"4",
":",
"break",
"key_tt",
".",
"add",
"(",
"resolve_type",
"(",
"k",
")",
")",
"val_tt",
".",
"add",
"(",
"resolve_type",
"(",
"v",
")",
")",
"return",
"DictType",
"(",
"key_tt",
",",
"val_tt",
")",
"else",
":",
"return",
"type",
"(",
"arg",
")"
] |
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
|
[
"Resolve",
"object",
"to",
"one",
"of",
"our",
"internal",
"collection",
"types",
"or",
"generic",
"built",
"-",
"in",
"type",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L498-L549
|
8,756
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
prep_args
|
def prep_args(arg_info):
# type: (ArgInfo) -> ResolvedTypes
"""
Resolve types from ArgInfo
"""
# pull out any varargs declarations
filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]
# we don't care about self/cls first params (perhaps we can test if it's an instance/class method another way?)
if filtered_args and (filtered_args[0] in ('self', 'cls')):
filtered_args = filtered_args[1:]
pos_args = [] # type: List[InternalType]
if filtered_args:
for arg in filtered_args:
if isinstance(arg, str) and arg in arg_info.locals:
# here we know that return type will be of type "type"
resolved_type = resolve_type(arg_info.locals[arg])
pos_args.append(resolved_type)
else:
pos_args.append(type(UnknownType()))
varargs = None # type: Optional[List[InternalType]]
if arg_info.varargs:
varargs_tuple = arg_info.locals[arg_info.varargs]
# It's unclear what all the possible values for 'varargs_tuple' are,
# so perform a defensive type check since we don't want to crash here.
if isinstance(varargs_tuple, tuple):
varargs = [resolve_type(arg) for arg in varargs_tuple[:4]]
return ResolvedTypes(pos_args=pos_args, varargs=varargs)
|
python
|
def prep_args(arg_info):
# type: (ArgInfo) -> ResolvedTypes
"""
Resolve types from ArgInfo
"""
# pull out any varargs declarations
filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]
# we don't care about self/cls first params (perhaps we can test if it's an instance/class method another way?)
if filtered_args and (filtered_args[0] in ('self', 'cls')):
filtered_args = filtered_args[1:]
pos_args = [] # type: List[InternalType]
if filtered_args:
for arg in filtered_args:
if isinstance(arg, str) and arg in arg_info.locals:
# here we know that return type will be of type "type"
resolved_type = resolve_type(arg_info.locals[arg])
pos_args.append(resolved_type)
else:
pos_args.append(type(UnknownType()))
varargs = None # type: Optional[List[InternalType]]
if arg_info.varargs:
varargs_tuple = arg_info.locals[arg_info.varargs]
# It's unclear what all the possible values for 'varargs_tuple' are,
# so perform a defensive type check since we don't want to crash here.
if isinstance(varargs_tuple, tuple):
varargs = [resolve_type(arg) for arg in varargs_tuple[:4]]
return ResolvedTypes(pos_args=pos_args, varargs=varargs)
|
[
"def",
"prep_args",
"(",
"arg_info",
")",
":",
"# type: (ArgInfo) -> ResolvedTypes",
"# pull out any varargs declarations",
"filtered_args",
"=",
"[",
"a",
"for",
"a",
"in",
"arg_info",
".",
"args",
"if",
"getattr",
"(",
"arg_info",
",",
"'varargs'",
",",
"None",
")",
"!=",
"a",
"]",
"# we don't care about self/cls first params (perhaps we can test if it's an instance/class method another way?)",
"if",
"filtered_args",
"and",
"(",
"filtered_args",
"[",
"0",
"]",
"in",
"(",
"'self'",
",",
"'cls'",
")",
")",
":",
"filtered_args",
"=",
"filtered_args",
"[",
"1",
":",
"]",
"pos_args",
"=",
"[",
"]",
"# type: List[InternalType]",
"if",
"filtered_args",
":",
"for",
"arg",
"in",
"filtered_args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
"and",
"arg",
"in",
"arg_info",
".",
"locals",
":",
"# here we know that return type will be of type \"type\"",
"resolved_type",
"=",
"resolve_type",
"(",
"arg_info",
".",
"locals",
"[",
"arg",
"]",
")",
"pos_args",
".",
"append",
"(",
"resolved_type",
")",
"else",
":",
"pos_args",
".",
"append",
"(",
"type",
"(",
"UnknownType",
"(",
")",
")",
")",
"varargs",
"=",
"None",
"# type: Optional[List[InternalType]]",
"if",
"arg_info",
".",
"varargs",
":",
"varargs_tuple",
"=",
"arg_info",
".",
"locals",
"[",
"arg_info",
".",
"varargs",
"]",
"# It's unclear what all the possible values for 'varargs_tuple' are,",
"# so perform a defensive type check since we don't want to crash here.",
"if",
"isinstance",
"(",
"varargs_tuple",
",",
"tuple",
")",
":",
"varargs",
"=",
"[",
"resolve_type",
"(",
"arg",
")",
"for",
"arg",
"in",
"varargs_tuple",
"[",
":",
"4",
"]",
"]",
"return",
"ResolvedTypes",
"(",
"pos_args",
"=",
"pos_args",
",",
"varargs",
"=",
"varargs",
")"
] |
Resolve types from ArgInfo
|
[
"Resolve",
"types",
"from",
"ArgInfo"
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L552-L583
|
8,757
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
_flush_signature
|
def _flush_signature(key, return_type):
# type: (FunctionKey, InternalType) -> None
"""Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'.
"""
signatures = collected_signatures.setdefault(key, set())
args_info = collected_args.pop(key)
if len(signatures) < MAX_ITEMS_PER_FUNCTION:
signatures.add((args_info, return_type))
num_samples[key] = num_samples.get(key, 0) + 1
|
python
|
def _flush_signature(key, return_type):
# type: (FunctionKey, InternalType) -> None
"""Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'.
"""
signatures = collected_signatures.setdefault(key, set())
args_info = collected_args.pop(key)
if len(signatures) < MAX_ITEMS_PER_FUNCTION:
signatures.add((args_info, return_type))
num_samples[key] = num_samples.get(key, 0) + 1
|
[
"def",
"_flush_signature",
"(",
"key",
",",
"return_type",
")",
":",
"# type: (FunctionKey, InternalType) -> None",
"signatures",
"=",
"collected_signatures",
".",
"setdefault",
"(",
"key",
",",
"set",
"(",
")",
")",
"args_info",
"=",
"collected_args",
".",
"pop",
"(",
"key",
")",
"if",
"len",
"(",
"signatures",
")",
"<",
"MAX_ITEMS_PER_FUNCTION",
":",
"signatures",
".",
"add",
"(",
"(",
"args_info",
",",
"return_type",
")",
")",
"num_samples",
"[",
"key",
"]",
"=",
"num_samples",
".",
"get",
"(",
"key",
",",
"0",
")",
"+",
"1"
] |
Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'.
|
[
"Store",
"signature",
"for",
"a",
"function",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L656-L671
|
8,758
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
type_consumer
|
def type_consumer():
# type: () -> None
"""
Infinite loop of the type consumer thread.
It gets types to process from the task query.
"""
# we are not interested in profiling type_consumer itself
# but we start it before any other thread
while True:
item = _task_queue.get()
if isinstance(item, KeyAndTypes):
if item.key in collected_args:
# Previous call didn't get a corresponding return, perhaps because we
# stopped collecting types in the middle of a call or because of
# a recursive function.
_flush_signature(item.key, UnknownType)
collected_args[item.key] = ArgTypes(item.types)
else:
assert isinstance(item, KeyAndReturn)
if item.key in collected_args:
_flush_signature(item.key, item.return_type)
_task_queue.task_done()
|
python
|
def type_consumer():
# type: () -> None
"""
Infinite loop of the type consumer thread.
It gets types to process from the task query.
"""
# we are not interested in profiling type_consumer itself
# but we start it before any other thread
while True:
item = _task_queue.get()
if isinstance(item, KeyAndTypes):
if item.key in collected_args:
# Previous call didn't get a corresponding return, perhaps because we
# stopped collecting types in the middle of a call or because of
# a recursive function.
_flush_signature(item.key, UnknownType)
collected_args[item.key] = ArgTypes(item.types)
else:
assert isinstance(item, KeyAndReturn)
if item.key in collected_args:
_flush_signature(item.key, item.return_type)
_task_queue.task_done()
|
[
"def",
"type_consumer",
"(",
")",
":",
"# type: () -> None",
"# we are not interested in profiling type_consumer itself",
"# but we start it before any other thread",
"while",
"True",
":",
"item",
"=",
"_task_queue",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"item",
",",
"KeyAndTypes",
")",
":",
"if",
"item",
".",
"key",
"in",
"collected_args",
":",
"# Previous call didn't get a corresponding return, perhaps because we",
"# stopped collecting types in the middle of a call or because of",
"# a recursive function.",
"_flush_signature",
"(",
"item",
".",
"key",
",",
"UnknownType",
")",
"collected_args",
"[",
"item",
".",
"key",
"]",
"=",
"ArgTypes",
"(",
"item",
".",
"types",
")",
"else",
":",
"assert",
"isinstance",
"(",
"item",
",",
"KeyAndReturn",
")",
"if",
"item",
".",
"key",
"in",
"collected_args",
":",
"_flush_signature",
"(",
"item",
".",
"key",
",",
"item",
".",
"return_type",
")",
"_task_queue",
".",
"task_done",
"(",
")"
] |
Infinite loop of the type consumer thread.
It gets types to process from the task query.
|
[
"Infinite",
"loop",
"of",
"the",
"type",
"consumer",
"thread",
".",
"It",
"gets",
"types",
"to",
"process",
"from",
"the",
"task",
"query",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L674-L696
|
8,759
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
_make_sampling_sequence
|
def _make_sampling_sequence(n):
# type: (int) -> List[int]
"""
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
"""
seq = list(range(5))
i = 50
while len(seq) < n:
seq.append(i)
i += 50
return seq
|
python
|
def _make_sampling_sequence(n):
# type: (int) -> List[int]
"""
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
"""
seq = list(range(5))
i = 50
while len(seq) < n:
seq.append(i)
i += 50
return seq
|
[
"def",
"_make_sampling_sequence",
"(",
"n",
")",
":",
"# type: (int) -> List[int]",
"seq",
"=",
"list",
"(",
"range",
"(",
"5",
")",
")",
"i",
"=",
"50",
"while",
"len",
"(",
"seq",
")",
"<",
"n",
":",
"seq",
".",
"append",
"(",
"i",
")",
"i",
"+=",
"50",
"return",
"seq"
] |
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
|
[
"Return",
"a",
"list",
"containing",
"the",
"proposed",
"call",
"event",
"sampling",
"sequence",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L711-L727
|
8,760
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
default_filter_filename
|
def default_filter_filename(filename):
# type: (Optional[str]) -> Optional[str]
"""Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection().
"""
if filename is None:
return None
elif filename.startswith(TOP_DIR):
if filename.startswith(TOP_DIR_DOT):
# Skip subdirectories starting with dot (e.g. .vagrant).
return None
else:
# Strip current directory and following slashes.
return filename[TOP_DIR_LEN:].lstrip(os.sep)
elif filename.startswith(os.sep):
# Skip absolute paths not under current directory.
return None
else:
return filename
|
python
|
def default_filter_filename(filename):
# type: (Optional[str]) -> Optional[str]
"""Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection().
"""
if filename is None:
return None
elif filename.startswith(TOP_DIR):
if filename.startswith(TOP_DIR_DOT):
# Skip subdirectories starting with dot (e.g. .vagrant).
return None
else:
# Strip current directory and following slashes.
return filename[TOP_DIR_LEN:].lstrip(os.sep)
elif filename.startswith(os.sep):
# Skip absolute paths not under current directory.
return None
else:
return filename
|
[
"def",
"default_filter_filename",
"(",
"filename",
")",
":",
"# type: (Optional[str]) -> Optional[str]",
"if",
"filename",
"is",
"None",
":",
"return",
"None",
"elif",
"filename",
".",
"startswith",
"(",
"TOP_DIR",
")",
":",
"if",
"filename",
".",
"startswith",
"(",
"TOP_DIR_DOT",
")",
":",
"# Skip subdirectories starting with dot (e.g. .vagrant).",
"return",
"None",
"else",
":",
"# Strip current directory and following slashes.",
"return",
"filename",
"[",
"TOP_DIR_LEN",
":",
"]",
".",
"lstrip",
"(",
"os",
".",
"sep",
")",
"elif",
"filename",
".",
"startswith",
"(",
"os",
".",
"sep",
")",
":",
"# Skip absolute paths not under current directory.",
"return",
"None",
"else",
":",
"return",
"filename"
] |
Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection().
|
[
"Default",
"filter",
"for",
"filenames",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L787-L807
|
8,761
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
_filter_types
|
def _filter_types(types_dict):
# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]
"""Filter type info before dumping it to the file."""
def exclude(k):
# type: (FunctionKey) -> bool
"""Exclude filter"""
return k.path.startswith('<') or k.func_name == '<module>'
return {k: v for k, v in iteritems(types_dict) if not exclude(k)}
|
python
|
def _filter_types(types_dict):
# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]
"""Filter type info before dumping it to the file."""
def exclude(k):
# type: (FunctionKey) -> bool
"""Exclude filter"""
return k.path.startswith('<') or k.func_name == '<module>'
return {k: v for k, v in iteritems(types_dict) if not exclude(k)}
|
[
"def",
"_filter_types",
"(",
"types_dict",
")",
":",
"# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]",
"def",
"exclude",
"(",
"k",
")",
":",
"# type: (FunctionKey) -> bool",
"\"\"\"Exclude filter\"\"\"",
"return",
"k",
".",
"path",
".",
"startswith",
"(",
"'<'",
")",
"or",
"k",
".",
"func_name",
"==",
"'<module>'",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"types_dict",
")",
"if",
"not",
"exclude",
"(",
"k",
")",
"}"
] |
Filter type info before dumping it to the file.
|
[
"Filter",
"type",
"info",
"before",
"dumping",
"it",
"to",
"the",
"file",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L909-L918
|
8,762
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
_dump_impl
|
def _dump_impl():
# type: () -> List[FunctionData]
"""Internal implementation for dump_stats and dumps_stats"""
filtered_signatures = _filter_types(collected_signatures)
sorted_by_file = sorted(iteritems(filtered_signatures),
key=(lambda p: (p[0].path, p[0].line, p[0].func_name)))
res = [] # type: List[FunctionData]
for function_key, signatures in sorted_by_file:
comments = [_make_type_comment(args, ret_type) for args, ret_type in signatures]
res.append(
{
'path': function_key.path,
'line': function_key.line,
'func_name': function_key.func_name,
'type_comments': comments,
'samples': num_samples.get(function_key, 0),
}
)
return res
|
python
|
def _dump_impl():
# type: () -> List[FunctionData]
"""Internal implementation for dump_stats and dumps_stats"""
filtered_signatures = _filter_types(collected_signatures)
sorted_by_file = sorted(iteritems(filtered_signatures),
key=(lambda p: (p[0].path, p[0].line, p[0].func_name)))
res = [] # type: List[FunctionData]
for function_key, signatures in sorted_by_file:
comments = [_make_type_comment(args, ret_type) for args, ret_type in signatures]
res.append(
{
'path': function_key.path,
'line': function_key.line,
'func_name': function_key.func_name,
'type_comments': comments,
'samples': num_samples.get(function_key, 0),
}
)
return res
|
[
"def",
"_dump_impl",
"(",
")",
":",
"# type: () -> List[FunctionData]",
"filtered_signatures",
"=",
"_filter_types",
"(",
"collected_signatures",
")",
"sorted_by_file",
"=",
"sorted",
"(",
"iteritems",
"(",
"filtered_signatures",
")",
",",
"key",
"=",
"(",
"lambda",
"p",
":",
"(",
"p",
"[",
"0",
"]",
".",
"path",
",",
"p",
"[",
"0",
"]",
".",
"line",
",",
"p",
"[",
"0",
"]",
".",
"func_name",
")",
")",
")",
"res",
"=",
"[",
"]",
"# type: List[FunctionData]",
"for",
"function_key",
",",
"signatures",
"in",
"sorted_by_file",
":",
"comments",
"=",
"[",
"_make_type_comment",
"(",
"args",
",",
"ret_type",
")",
"for",
"args",
",",
"ret_type",
"in",
"signatures",
"]",
"res",
".",
"append",
"(",
"{",
"'path'",
":",
"function_key",
".",
"path",
",",
"'line'",
":",
"function_key",
".",
"line",
",",
"'func_name'",
":",
"function_key",
".",
"func_name",
",",
"'type_comments'",
":",
"comments",
",",
"'samples'",
":",
"num_samples",
".",
"get",
"(",
"function_key",
",",
"0",
")",
",",
"}",
")",
"return",
"res"
] |
Internal implementation for dump_stats and dumps_stats
|
[
"Internal",
"implementation",
"for",
"dump_stats",
"and",
"dumps_stats"
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L921-L939
|
8,763
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
dump_stats
|
def dump_stats(filename):
# type: (str) -> None
"""
Write collected information to file.
Args:
filename: absolute filename
"""
res = _dump_impl()
f = open(filename, 'w')
json.dump(res, f, indent=4)
f.close()
|
python
|
def dump_stats(filename):
# type: (str) -> None
"""
Write collected information to file.
Args:
filename: absolute filename
"""
res = _dump_impl()
f = open(filename, 'w')
json.dump(res, f, indent=4)
f.close()
|
[
"def",
"dump_stats",
"(",
"filename",
")",
":",
"# type: (str) -> None",
"res",
"=",
"_dump_impl",
"(",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"json",
".",
"dump",
"(",
"res",
",",
"f",
",",
"indent",
"=",
"4",
")",
"f",
".",
"close",
"(",
")"
] |
Write collected information to file.
Args:
filename: absolute filename
|
[
"Write",
"collected",
"information",
"to",
"file",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L942-L953
|
8,764
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
init_types_collection
|
def init_types_collection(filter_filename=default_filter_filename):
# type: (Callable[[Optional[str]], Optional[str]]) -> None
"""
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename().
"""
global _filter_filename
_filter_filename = filter_filename
sys.setprofile(_trace_dispatch)
threading.setprofile(_trace_dispatch)
|
python
|
def init_types_collection(filter_filename=default_filter_filename):
# type: (Callable[[Optional[str]], Optional[str]]) -> None
"""
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename().
"""
global _filter_filename
_filter_filename = filter_filename
sys.setprofile(_trace_dispatch)
threading.setprofile(_trace_dispatch)
|
[
"def",
"init_types_collection",
"(",
"filter_filename",
"=",
"default_filter_filename",
")",
":",
"# type: (Callable[[Optional[str]], Optional[str]]) -> None",
"global",
"_filter_filename",
"_filter_filename",
"=",
"filter_filename",
"sys",
".",
"setprofile",
"(",
"_trace_dispatch",
")",
"threading",
".",
"setprofile",
"(",
"_trace_dispatch",
")"
] |
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename().
|
[
"Setup",
"profiler",
"hooks",
"to",
"enable",
"type",
"collection",
".",
"Call",
"this",
"one",
"time",
"from",
"the",
"main",
"thread",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L965-L978
|
8,765
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
TentativeType.add
|
def add(self, type):
# type: (InternalType) -> None
"""
Add type to the runtime type samples.
"""
try:
if isinstance(type, SetType):
if EMPTY_SET_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_SET_TYPE)
elif isinstance(type, ListType):
if EMPTY_LIST_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_LIST_TYPE)
elif isinstance(type, IteratorType):
if EMPTY_ITERATOR_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_ITERATOR_TYPE)
elif isinstance(type, DictType):
if EMPTY_DICT_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_DICT_TYPE)
for item in self.types_hashable:
if isinstance(item, DictType):
if item.key_type == type.key_type:
item.val_type.merge(type.val_type)
return
self.types_hashable.add(type)
except (TypeError, AttributeError):
try:
if type not in self.types:
self.types.append(type)
except AttributeError:
if TypeWasIncomparable not in self.types:
self.types.append(TypeWasIncomparable)
|
python
|
def add(self, type):
# type: (InternalType) -> None
"""
Add type to the runtime type samples.
"""
try:
if isinstance(type, SetType):
if EMPTY_SET_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_SET_TYPE)
elif isinstance(type, ListType):
if EMPTY_LIST_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_LIST_TYPE)
elif isinstance(type, IteratorType):
if EMPTY_ITERATOR_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_ITERATOR_TYPE)
elif isinstance(type, DictType):
if EMPTY_DICT_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_DICT_TYPE)
for item in self.types_hashable:
if isinstance(item, DictType):
if item.key_type == type.key_type:
item.val_type.merge(type.val_type)
return
self.types_hashable.add(type)
except (TypeError, AttributeError):
try:
if type not in self.types:
self.types.append(type)
except AttributeError:
if TypeWasIncomparable not in self.types:
self.types.append(TypeWasIncomparable)
|
[
"def",
"add",
"(",
"self",
",",
"type",
")",
":",
"# type: (InternalType) -> None",
"try",
":",
"if",
"isinstance",
"(",
"type",
",",
"SetType",
")",
":",
"if",
"EMPTY_SET_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_SET_TYPE",
")",
"elif",
"isinstance",
"(",
"type",
",",
"ListType",
")",
":",
"if",
"EMPTY_LIST_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_LIST_TYPE",
")",
"elif",
"isinstance",
"(",
"type",
",",
"IteratorType",
")",
":",
"if",
"EMPTY_ITERATOR_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_ITERATOR_TYPE",
")",
"elif",
"isinstance",
"(",
"type",
",",
"DictType",
")",
":",
"if",
"EMPTY_DICT_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
"remove",
"(",
"EMPTY_DICT_TYPE",
")",
"for",
"item",
"in",
"self",
".",
"types_hashable",
":",
"if",
"isinstance",
"(",
"item",
",",
"DictType",
")",
":",
"if",
"item",
".",
"key_type",
"==",
"type",
".",
"key_type",
":",
"item",
".",
"val_type",
".",
"merge",
"(",
"type",
".",
"val_type",
")",
"return",
"self",
".",
"types_hashable",
".",
"add",
"(",
"type",
")",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"try",
":",
"if",
"type",
"not",
"in",
"self",
".",
"types",
":",
"self",
".",
"types",
".",
"append",
"(",
"type",
")",
"except",
"AttributeError",
":",
"if",
"TypeWasIncomparable",
"not",
"in",
"self",
".",
"types",
":",
"self",
".",
"types",
".",
"append",
"(",
"TypeWasIncomparable",
")"
] |
Add type to the runtime type samples.
|
[
"Add",
"type",
"to",
"the",
"runtime",
"type",
"samples",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L336-L367
|
8,766
|
dropbox/pyannotate
|
pyannotate_runtime/collect_types.py
|
TentativeType.merge
|
def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles)
|
python
|
def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles)
|
[
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"# type: (TentativeType) -> None",
"for",
"hashables",
"in",
"other",
".",
"types_hashable",
":",
"self",
".",
"add",
"(",
"hashables",
")",
"for",
"non_hashbles",
"in",
"other",
".",
"types",
":",
"self",
".",
"add",
"(",
"non_hashbles",
")"
] |
Merge two TentativeType instances
|
[
"Merge",
"two",
"TentativeType",
"instances"
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L369-L377
|
8,767
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
infer_annotation
|
def infer_annotation(type_comments):
# type: (List[str]) -> Tuple[List[Argument], AbstractType]
"""Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type).
"""
assert type_comments
args = {} # type: Dict[int, Set[Argument]]
returns = set()
for comment in type_comments:
arg_types, return_type = parse_type_comment(comment)
for i, arg_type in enumerate(arg_types):
args.setdefault(i, set()).add(arg_type)
returns.add(return_type)
combined_args = []
for i in sorted(args):
arg_infos = list(args[i])
kind = argument_kind(arg_infos)
if kind is None:
raise InferError('Ambiguous argument kinds:\n' + '\n'.join(type_comments))
types = [arg.type for arg in arg_infos]
combined = combine_types(types)
if str(combined) == 'None':
# It's very rare for an argument to actually be typed `None`, more likely than
# not we simply don't have any data points for this argument.
combined = UnionType([ClassType('None'), AnyType()])
if kind != ARG_POS and (len(str(combined)) > 120 or isinstance(combined, UnionType)):
# Avoid some noise.
combined = AnyType()
combined_args.append(Argument(combined, kind))
combined_return = combine_types(returns)
return combined_args, combined_return
|
python
|
def infer_annotation(type_comments):
# type: (List[str]) -> Tuple[List[Argument], AbstractType]
"""Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type).
"""
assert type_comments
args = {} # type: Dict[int, Set[Argument]]
returns = set()
for comment in type_comments:
arg_types, return_type = parse_type_comment(comment)
for i, arg_type in enumerate(arg_types):
args.setdefault(i, set()).add(arg_type)
returns.add(return_type)
combined_args = []
for i in sorted(args):
arg_infos = list(args[i])
kind = argument_kind(arg_infos)
if kind is None:
raise InferError('Ambiguous argument kinds:\n' + '\n'.join(type_comments))
types = [arg.type for arg in arg_infos]
combined = combine_types(types)
if str(combined) == 'None':
# It's very rare for an argument to actually be typed `None`, more likely than
# not we simply don't have any data points for this argument.
combined = UnionType([ClassType('None'), AnyType()])
if kind != ARG_POS and (len(str(combined)) > 120 or isinstance(combined, UnionType)):
# Avoid some noise.
combined = AnyType()
combined_args.append(Argument(combined, kind))
combined_return = combine_types(returns)
return combined_args, combined_return
|
[
"def",
"infer_annotation",
"(",
"type_comments",
")",
":",
"# type: (List[str]) -> Tuple[List[Argument], AbstractType]",
"assert",
"type_comments",
"args",
"=",
"{",
"}",
"# type: Dict[int, Set[Argument]]",
"returns",
"=",
"set",
"(",
")",
"for",
"comment",
"in",
"type_comments",
":",
"arg_types",
",",
"return_type",
"=",
"parse_type_comment",
"(",
"comment",
")",
"for",
"i",
",",
"arg_type",
"in",
"enumerate",
"(",
"arg_types",
")",
":",
"args",
".",
"setdefault",
"(",
"i",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"arg_type",
")",
"returns",
".",
"add",
"(",
"return_type",
")",
"combined_args",
"=",
"[",
"]",
"for",
"i",
"in",
"sorted",
"(",
"args",
")",
":",
"arg_infos",
"=",
"list",
"(",
"args",
"[",
"i",
"]",
")",
"kind",
"=",
"argument_kind",
"(",
"arg_infos",
")",
"if",
"kind",
"is",
"None",
":",
"raise",
"InferError",
"(",
"'Ambiguous argument kinds:\\n'",
"+",
"'\\n'",
".",
"join",
"(",
"type_comments",
")",
")",
"types",
"=",
"[",
"arg",
".",
"type",
"for",
"arg",
"in",
"arg_infos",
"]",
"combined",
"=",
"combine_types",
"(",
"types",
")",
"if",
"str",
"(",
"combined",
")",
"==",
"'None'",
":",
"# It's very rare for an argument to actually be typed `None`, more likely than",
"# not we simply don't have any data points for this argument.",
"combined",
"=",
"UnionType",
"(",
"[",
"ClassType",
"(",
"'None'",
")",
",",
"AnyType",
"(",
")",
"]",
")",
"if",
"kind",
"!=",
"ARG_POS",
"and",
"(",
"len",
"(",
"str",
"(",
"combined",
")",
")",
">",
"120",
"or",
"isinstance",
"(",
"combined",
",",
"UnionType",
")",
")",
":",
"# Avoid some noise.",
"combined",
"=",
"AnyType",
"(",
")",
"combined_args",
".",
"append",
"(",
"Argument",
"(",
"combined",
",",
"kind",
")",
")",
"combined_return",
"=",
"combine_types",
"(",
"returns",
")",
"return",
"combined_args",
",",
"combined_return"
] |
Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type).
|
[
"Given",
"some",
"type",
"comments",
"return",
"a",
"single",
"inferred",
"signature",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L32-L66
|
8,768
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
argument_kind
|
def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
return kinds.pop()
|
python
|
def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
return kinds.pop()
|
[
"def",
"argument_kind",
"(",
"args",
")",
":",
"# type: (List[Argument]) -> Optional[str]",
"kinds",
"=",
"set",
"(",
"arg",
".",
"kind",
"for",
"arg",
"in",
"args",
")",
"if",
"len",
"(",
"kinds",
")",
"!=",
"1",
":",
"return",
"None",
"return",
"kinds",
".",
"pop",
"(",
")"
] |
Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
|
[
"Return",
"the",
"kind",
"of",
"an",
"argument",
"based",
"on",
"one",
"or",
"more",
"descriptions",
"of",
"the",
"argument",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L69-L78
|
8,769
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
combine_types
|
def combine_types(types):
# type: (Iterable[AbstractType]) -> AbstractType
"""Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'.
"""
items = simplify_types(types)
if len(items) == 1:
return items[0]
else:
return UnionType(items)
|
python
|
def combine_types(types):
# type: (Iterable[AbstractType]) -> AbstractType
"""Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'.
"""
items = simplify_types(types)
if len(items) == 1:
return items[0]
else:
return UnionType(items)
|
[
"def",
"combine_types",
"(",
"types",
")",
":",
"# type: (Iterable[AbstractType]) -> AbstractType",
"items",
"=",
"simplify_types",
"(",
"types",
")",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"return",
"items",
"[",
"0",
"]",
"else",
":",
"return",
"UnionType",
"(",
"items",
")"
] |
Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'.
|
[
"Given",
"some",
"types",
"return",
"a",
"combined",
"and",
"simplified",
"type",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L81-L92
|
8,770
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
simplify_types
|
def simplify_types(types):
# type: (Iterable[AbstractType]) -> List[AbstractType]
"""Given some types, give simplified types representing the union of types."""
flattened = flatten_types(types)
items = filter_ignored_items(flattened)
items = [simplify_recursive(item) for item in items]
items = merge_items(items)
items = dedupe_types(items)
# We have to remove reundant items after everything has been simplified and
# merged as this simplification may be what makes items redundant.
items = remove_redundant_items(items)
if len(items) > 3:
return [AnyType()]
else:
return items
|
python
|
def simplify_types(types):
# type: (Iterable[AbstractType]) -> List[AbstractType]
"""Given some types, give simplified types representing the union of types."""
flattened = flatten_types(types)
items = filter_ignored_items(flattened)
items = [simplify_recursive(item) for item in items]
items = merge_items(items)
items = dedupe_types(items)
# We have to remove reundant items after everything has been simplified and
# merged as this simplification may be what makes items redundant.
items = remove_redundant_items(items)
if len(items) > 3:
return [AnyType()]
else:
return items
|
[
"def",
"simplify_types",
"(",
"types",
")",
":",
"# type: (Iterable[AbstractType]) -> List[AbstractType]",
"flattened",
"=",
"flatten_types",
"(",
"types",
")",
"items",
"=",
"filter_ignored_items",
"(",
"flattened",
")",
"items",
"=",
"[",
"simplify_recursive",
"(",
"item",
")",
"for",
"item",
"in",
"items",
"]",
"items",
"=",
"merge_items",
"(",
"items",
")",
"items",
"=",
"dedupe_types",
"(",
"items",
")",
"# We have to remove reundant items after everything has been simplified and",
"# merged as this simplification may be what makes items redundant.",
"items",
"=",
"remove_redundant_items",
"(",
"items",
")",
"if",
"len",
"(",
"items",
")",
">",
"3",
":",
"return",
"[",
"AnyType",
"(",
")",
"]",
"else",
":",
"return",
"items"
] |
Given some types, give simplified types representing the union of types.
|
[
"Given",
"some",
"types",
"give",
"simplified",
"types",
"representing",
"the",
"union",
"of",
"types",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L95-L109
|
8,771
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
simplify_recursive
|
def simplify_recursive(typ):
# type: (AbstractType) -> AbstractType
"""Simplify all components of a type."""
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
args = simplified.args
if (simplified.name == 'Dict' and len(args) == 2
and isinstance(args[0], ClassType) and args[0].name in ('str', 'Text')
and isinstance(args[1], UnionType) and not is_optional(args[1])):
# Looks like a potential case for TypedDict, which we don't properly support yet.
return ClassType('Dict', [args[0], AnyType()])
return simplified
elif isinstance(typ, TupleType):
return TupleType([simplify_recursive(item) for item in typ.items])
return typ
|
python
|
def simplify_recursive(typ):
# type: (AbstractType) -> AbstractType
"""Simplify all components of a type."""
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
args = simplified.args
if (simplified.name == 'Dict' and len(args) == 2
and isinstance(args[0], ClassType) and args[0].name in ('str', 'Text')
and isinstance(args[1], UnionType) and not is_optional(args[1])):
# Looks like a potential case for TypedDict, which we don't properly support yet.
return ClassType('Dict', [args[0], AnyType()])
return simplified
elif isinstance(typ, TupleType):
return TupleType([simplify_recursive(item) for item in typ.items])
return typ
|
[
"def",
"simplify_recursive",
"(",
"typ",
")",
":",
"# type: (AbstractType) -> AbstractType",
"if",
"isinstance",
"(",
"typ",
",",
"UnionType",
")",
":",
"return",
"combine_types",
"(",
"typ",
".",
"items",
")",
"elif",
"isinstance",
"(",
"typ",
",",
"ClassType",
")",
":",
"simplified",
"=",
"ClassType",
"(",
"typ",
".",
"name",
",",
"[",
"simplify_recursive",
"(",
"arg",
")",
"for",
"arg",
"in",
"typ",
".",
"args",
"]",
")",
"args",
"=",
"simplified",
".",
"args",
"if",
"(",
"simplified",
".",
"name",
"==",
"'Dict'",
"and",
"len",
"(",
"args",
")",
"==",
"2",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"ClassType",
")",
"and",
"args",
"[",
"0",
"]",
".",
"name",
"in",
"(",
"'str'",
",",
"'Text'",
")",
"and",
"isinstance",
"(",
"args",
"[",
"1",
"]",
",",
"UnionType",
")",
"and",
"not",
"is_optional",
"(",
"args",
"[",
"1",
"]",
")",
")",
":",
"# Looks like a potential case for TypedDict, which we don't properly support yet.",
"return",
"ClassType",
"(",
"'Dict'",
",",
"[",
"args",
"[",
"0",
"]",
",",
"AnyType",
"(",
")",
"]",
")",
"return",
"simplified",
"elif",
"isinstance",
"(",
"typ",
",",
"TupleType",
")",
":",
"return",
"TupleType",
"(",
"[",
"simplify_recursive",
"(",
"item",
")",
"for",
"item",
"in",
"typ",
".",
"items",
"]",
")",
"return",
"typ"
] |
Simplify all components of a type.
|
[
"Simplify",
"all",
"components",
"of",
"a",
"type",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L112-L128
|
8,772
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
remove_redundant_items
|
def remove_redundant_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Filter out redundant union items."""
result = []
for item in items:
for other in items:
if item is not other and is_redundant_union_item(item, other):
break
else:
result.append(item)
return result
|
python
|
def remove_redundant_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Filter out redundant union items."""
result = []
for item in items:
for other in items:
if item is not other and is_redundant_union_item(item, other):
break
else:
result.append(item)
return result
|
[
"def",
"remove_redundant_items",
"(",
"items",
")",
":",
"# type: (List[AbstractType]) -> List[AbstractType]",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"for",
"other",
"in",
"items",
":",
"if",
"item",
"is",
"not",
"other",
"and",
"is_redundant_union_item",
"(",
"item",
",",
"other",
")",
":",
"break",
"else",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
] |
Filter out redundant union items.
|
[
"Filter",
"out",
"redundant",
"union",
"items",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L153-L163
|
8,773
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
is_redundant_union_item
|
def is_redundant_union_item(first, other):
# type: (AbstractType, AbstractType) -> bool
"""If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False.
"""
if isinstance(first, ClassType) and isinstance(other, ClassType):
if first.name == 'str' and other.name == 'Text':
return True
elif first.name == 'bool' and other.name == 'int':
return True
elif first.name == 'int' and other.name == 'float':
return True
elif (first.name in ('List', 'Dict', 'Set') and
other.name == first.name):
if not first.args and other.args:
return True
elif len(first.args) == len(other.args) and first.args:
result = all(first_arg == other_arg or other_arg == AnyType()
for first_arg, other_arg
in zip(first.args, other.args))
return result
return False
|
python
|
def is_redundant_union_item(first, other):
# type: (AbstractType, AbstractType) -> bool
"""If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False.
"""
if isinstance(first, ClassType) and isinstance(other, ClassType):
if first.name == 'str' and other.name == 'Text':
return True
elif first.name == 'bool' and other.name == 'int':
return True
elif first.name == 'int' and other.name == 'float':
return True
elif (first.name in ('List', 'Dict', 'Set') and
other.name == first.name):
if not first.args and other.args:
return True
elif len(first.args) == len(other.args) and first.args:
result = all(first_arg == other_arg or other_arg == AnyType()
for first_arg, other_arg
in zip(first.args, other.args))
return result
return False
|
[
"def",
"is_redundant_union_item",
"(",
"first",
",",
"other",
")",
":",
"# type: (AbstractType, AbstractType) -> bool",
"if",
"isinstance",
"(",
"first",
",",
"ClassType",
")",
"and",
"isinstance",
"(",
"other",
",",
"ClassType",
")",
":",
"if",
"first",
".",
"name",
"==",
"'str'",
"and",
"other",
".",
"name",
"==",
"'Text'",
":",
"return",
"True",
"elif",
"first",
".",
"name",
"==",
"'bool'",
"and",
"other",
".",
"name",
"==",
"'int'",
":",
"return",
"True",
"elif",
"first",
".",
"name",
"==",
"'int'",
"and",
"other",
".",
"name",
"==",
"'float'",
":",
"return",
"True",
"elif",
"(",
"first",
".",
"name",
"in",
"(",
"'List'",
",",
"'Dict'",
",",
"'Set'",
")",
"and",
"other",
".",
"name",
"==",
"first",
".",
"name",
")",
":",
"if",
"not",
"first",
".",
"args",
"and",
"other",
".",
"args",
":",
"return",
"True",
"elif",
"len",
"(",
"first",
".",
"args",
")",
"==",
"len",
"(",
"other",
".",
"args",
")",
"and",
"first",
".",
"args",
":",
"result",
"=",
"all",
"(",
"first_arg",
"==",
"other_arg",
"or",
"other_arg",
"==",
"AnyType",
"(",
")",
"for",
"first_arg",
",",
"other_arg",
"in",
"zip",
"(",
"first",
".",
"args",
",",
"other",
".",
"args",
")",
")",
"return",
"result",
"return",
"False"
] |
If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False.
|
[
"If",
"union",
"has",
"both",
"items",
"is",
"the",
"first",
"one",
"redundant?"
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L166-L191
|
8,774
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
merge_items
|
def merge_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Merge union items that can be merged."""
result = []
while items:
item = items.pop()
merged = None
for i, other in enumerate(items):
merged = merged_type(item, other)
if merged:
break
if merged:
del items[i]
items.append(merged)
else:
result.append(item)
return list(reversed(result))
|
python
|
def merge_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Merge union items that can be merged."""
result = []
while items:
item = items.pop()
merged = None
for i, other in enumerate(items):
merged = merged_type(item, other)
if merged:
break
if merged:
del items[i]
items.append(merged)
else:
result.append(item)
return list(reversed(result))
|
[
"def",
"merge_items",
"(",
"items",
")",
":",
"# type: (List[AbstractType]) -> List[AbstractType]",
"result",
"=",
"[",
"]",
"while",
"items",
":",
"item",
"=",
"items",
".",
"pop",
"(",
")",
"merged",
"=",
"None",
"for",
"i",
",",
"other",
"in",
"enumerate",
"(",
"items",
")",
":",
"merged",
"=",
"merged_type",
"(",
"item",
",",
"other",
")",
"if",
"merged",
":",
"break",
"if",
"merged",
":",
"del",
"items",
"[",
"i",
"]",
"items",
".",
"append",
"(",
"merged",
")",
"else",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"list",
"(",
"reversed",
"(",
"result",
")",
")"
] |
Merge union items that can be merged.
|
[
"Merge",
"union",
"items",
"that",
"can",
"be",
"merged",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L194-L210
|
8,775
|
dropbox/pyannotate
|
pyannotate_tools/annotations/infer.py
|
merged_type
|
def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
"""Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
"""
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) == len(s.items):
return TupleType([combine_types([ti, si]) for ti, si in zip(t.items, s.items)])
all_items = t.items + s.items
if all_items and all(item == all_items[0] for item in all_items[1:]):
# Merge multiple compatible fixed-length tuples into a variable-length tuple type.
return ClassType('Tuple', [all_items[0]])
elif (isinstance(t, TupleType) and isinstance(s, ClassType) and s.name == 'Tuple'
and len(s.args) == 1):
if all(item == s.args[0] for item in t.items):
# Merge fixed-length tuple and variable-length tuple.
return s
elif isinstance(s, TupleType) and isinstance(t, ClassType) and t.name == 'Tuple':
return merged_type(s, t)
elif isinstance(s, NoReturnType):
return t
elif isinstance(t, NoReturnType):
return s
elif isinstance(s, AnyType):
# This seems to be usually desirable, since Anys tend to come from unknown types.
return t
elif isinstance(t, AnyType):
# Similar to above.
return s
return None
|
python
|
def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
"""Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
"""
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) == len(s.items):
return TupleType([combine_types([ti, si]) for ti, si in zip(t.items, s.items)])
all_items = t.items + s.items
if all_items and all(item == all_items[0] for item in all_items[1:]):
# Merge multiple compatible fixed-length tuples into a variable-length tuple type.
return ClassType('Tuple', [all_items[0]])
elif (isinstance(t, TupleType) and isinstance(s, ClassType) and s.name == 'Tuple'
and len(s.args) == 1):
if all(item == s.args[0] for item in t.items):
# Merge fixed-length tuple and variable-length tuple.
return s
elif isinstance(s, TupleType) and isinstance(t, ClassType) and t.name == 'Tuple':
return merged_type(s, t)
elif isinstance(s, NoReturnType):
return t
elif isinstance(t, NoReturnType):
return s
elif isinstance(s, AnyType):
# This seems to be usually desirable, since Anys tend to come from unknown types.
return t
elif isinstance(t, AnyType):
# Similar to above.
return s
return None
|
[
"def",
"merged_type",
"(",
"t",
",",
"s",
")",
":",
"# type: (AbstractType, AbstractType) -> Optional[AbstractType]",
"if",
"isinstance",
"(",
"t",
",",
"TupleType",
")",
"and",
"isinstance",
"(",
"s",
",",
"TupleType",
")",
":",
"if",
"len",
"(",
"t",
".",
"items",
")",
"==",
"len",
"(",
"s",
".",
"items",
")",
":",
"return",
"TupleType",
"(",
"[",
"combine_types",
"(",
"[",
"ti",
",",
"si",
"]",
")",
"for",
"ti",
",",
"si",
"in",
"zip",
"(",
"t",
".",
"items",
",",
"s",
".",
"items",
")",
"]",
")",
"all_items",
"=",
"t",
".",
"items",
"+",
"s",
".",
"items",
"if",
"all_items",
"and",
"all",
"(",
"item",
"==",
"all_items",
"[",
"0",
"]",
"for",
"item",
"in",
"all_items",
"[",
"1",
":",
"]",
")",
":",
"# Merge multiple compatible fixed-length tuples into a variable-length tuple type.",
"return",
"ClassType",
"(",
"'Tuple'",
",",
"[",
"all_items",
"[",
"0",
"]",
"]",
")",
"elif",
"(",
"isinstance",
"(",
"t",
",",
"TupleType",
")",
"and",
"isinstance",
"(",
"s",
",",
"ClassType",
")",
"and",
"s",
".",
"name",
"==",
"'Tuple'",
"and",
"len",
"(",
"s",
".",
"args",
")",
"==",
"1",
")",
":",
"if",
"all",
"(",
"item",
"==",
"s",
".",
"args",
"[",
"0",
"]",
"for",
"item",
"in",
"t",
".",
"items",
")",
":",
"# Merge fixed-length tuple and variable-length tuple.",
"return",
"s",
"elif",
"isinstance",
"(",
"s",
",",
"TupleType",
")",
"and",
"isinstance",
"(",
"t",
",",
"ClassType",
")",
"and",
"t",
".",
"name",
"==",
"'Tuple'",
":",
"return",
"merged_type",
"(",
"s",
",",
"t",
")",
"elif",
"isinstance",
"(",
"s",
",",
"NoReturnType",
")",
":",
"return",
"t",
"elif",
"isinstance",
"(",
"t",
",",
"NoReturnType",
")",
":",
"return",
"s",
"elif",
"isinstance",
"(",
"s",
",",
"AnyType",
")",
":",
"# This seems to be usually desirable, since Anys tend to come from unknown types.",
"return",
"t",
"elif",
"isinstance",
"(",
"t",
",",
"AnyType",
")",
":",
"# Similar to above.",
"return",
"s",
"return",
"None"
] |
Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
|
[
"Return",
"merged",
"type",
"if",
"two",
"items",
"can",
"be",
"merged",
"in",
"to",
"a",
"different",
"more",
"general",
"type",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L213-L243
|
8,776
|
dropbox/pyannotate
|
pyannotate_tools/annotations/__main__.py
|
dump_annotations
|
def dump_annotations(type_info, files):
"""Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path.
"""
with open(type_info) as f:
data = json.load(f)
for item in data:
path, line, func_name = item['path'], item['line'], item['func_name']
if files and path not in files:
for f in files:
if path.startswith(os.path.join(f, '')):
break
else:
continue # Outer loop
print("%s:%d: in %s:" % (path, line, func_name))
type_comments = item['type_comments']
signature = unify_type_comments(type_comments)
arg_types = signature['arg_types']
return_type = signature['return_type']
print(" # type: (%s) -> %s" % (", ".join(arg_types), return_type))
|
python
|
def dump_annotations(type_info, files):
"""Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path.
"""
with open(type_info) as f:
data = json.load(f)
for item in data:
path, line, func_name = item['path'], item['line'], item['func_name']
if files and path not in files:
for f in files:
if path.startswith(os.path.join(f, '')):
break
else:
continue # Outer loop
print("%s:%d: in %s:" % (path, line, func_name))
type_comments = item['type_comments']
signature = unify_type_comments(type_comments)
arg_types = signature['arg_types']
return_type = signature['return_type']
print(" # type: (%s) -> %s" % (", ".join(arg_types), return_type))
|
[
"def",
"dump_annotations",
"(",
"type_info",
",",
"files",
")",
":",
"with",
"open",
"(",
"type_info",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"for",
"item",
"in",
"data",
":",
"path",
",",
"line",
",",
"func_name",
"=",
"item",
"[",
"'path'",
"]",
",",
"item",
"[",
"'line'",
"]",
",",
"item",
"[",
"'func_name'",
"]",
"if",
"files",
"and",
"path",
"not",
"in",
"files",
":",
"for",
"f",
"in",
"files",
":",
"if",
"path",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"join",
"(",
"f",
",",
"''",
")",
")",
":",
"break",
"else",
":",
"continue",
"# Outer loop",
"print",
"(",
"\"%s:%d: in %s:\"",
"%",
"(",
"path",
",",
"line",
",",
"func_name",
")",
")",
"type_comments",
"=",
"item",
"[",
"'type_comments'",
"]",
"signature",
"=",
"unify_type_comments",
"(",
"type_comments",
")",
"arg_types",
"=",
"signature",
"[",
"'arg_types'",
"]",
"return_type",
"=",
"signature",
"[",
"'return_type'",
"]",
"print",
"(",
"\" # type: (%s) -> %s\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"arg_types",
")",
",",
"return_type",
")",
")"
] |
Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path.
|
[
"Dump",
"annotations",
"out",
"of",
"type_info",
"filtered",
"by",
"files",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/__main__.py#L60-L82
|
8,777
|
dropbox/pyannotate
|
pyannotate_tools/fixes/fix_annotate_json.py
|
strip_py
|
def strip_py(arg):
# type: (str) -> Optional[str]
"""Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found.
"""
for ext in PY_EXTENSIONS:
if arg.endswith(ext):
return arg[:-len(ext)]
return None
|
python
|
def strip_py(arg):
# type: (str) -> Optional[str]
"""Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found.
"""
for ext in PY_EXTENSIONS:
if arg.endswith(ext):
return arg[:-len(ext)]
return None
|
[
"def",
"strip_py",
"(",
"arg",
")",
":",
"# type: (str) -> Optional[str]",
"for",
"ext",
"in",
"PY_EXTENSIONS",
":",
"if",
"arg",
".",
"endswith",
"(",
"ext",
")",
":",
"return",
"arg",
"[",
":",
"-",
"len",
"(",
"ext",
")",
"]",
"return",
"None"
] |
Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found.
|
[
"Strip",
"a",
"trailing",
".",
"py",
"or",
".",
"pyi",
"suffix",
".",
"Return",
"None",
"if",
"no",
"such",
"suffix",
"is",
"found",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate_json.py#L61-L69
|
8,778
|
dropbox/pyannotate
|
pyannotate_tools/fixes/fix_annotate.py
|
FixAnnotate.get_decorators
|
def get_decorators(self, node):
"""Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return [].
"""
if node.parent is None:
return []
results = {}
if not self.decorated.match(node.parent, results):
return []
decorators = results.get('dd') or [results['d']]
decs = []
for d in decorators:
for child in d.children:
if isinstance(child, Leaf) and child.type == token.NAME:
decs.append(child.value)
return decs
|
python
|
def get_decorators(self, node):
"""Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return [].
"""
if node.parent is None:
return []
results = {}
if not self.decorated.match(node.parent, results):
return []
decorators = results.get('dd') or [results['d']]
decs = []
for d in decorators:
for child in d.children:
if isinstance(child, Leaf) and child.type == token.NAME:
decs.append(child.value)
return decs
|
[
"def",
"get_decorators",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"parent",
"is",
"None",
":",
"return",
"[",
"]",
"results",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"decorated",
".",
"match",
"(",
"node",
".",
"parent",
",",
"results",
")",
":",
"return",
"[",
"]",
"decorators",
"=",
"results",
".",
"get",
"(",
"'dd'",
")",
"or",
"[",
"results",
"[",
"'d'",
"]",
"]",
"decs",
"=",
"[",
"]",
"for",
"d",
"in",
"decorators",
":",
"for",
"child",
"in",
"d",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"Leaf",
")",
"and",
"child",
".",
"type",
"==",
"token",
".",
"NAME",
":",
"decs",
".",
"append",
"(",
"child",
".",
"value",
")",
"return",
"decs"
] |
Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return [].
|
[
"Return",
"a",
"list",
"of",
"decorators",
"found",
"on",
"a",
"function",
"definition",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L418-L438
|
8,779
|
dropbox/pyannotate
|
pyannotate_tools/fixes/fix_annotate.py
|
FixAnnotate.has_return_exprs
|
def has_return_exprs(self, node):
"""Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.)
"""
results = {}
if self.return_expr.match(node, results):
return True
for child in node.children:
if child.type not in (syms.funcdef, syms.classdef):
if self.has_return_exprs(child):
return True
return False
|
python
|
def has_return_exprs(self, node):
"""Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.)
"""
results = {}
if self.return_expr.match(node, results):
return True
for child in node.children:
if child.type not in (syms.funcdef, syms.classdef):
if self.has_return_exprs(child):
return True
return False
|
[
"def",
"has_return_exprs",
"(",
"self",
",",
"node",
")",
":",
"results",
"=",
"{",
"}",
"if",
"self",
".",
"return_expr",
".",
"match",
"(",
"node",
",",
"results",
")",
":",
"return",
"True",
"for",
"child",
"in",
"node",
".",
"children",
":",
"if",
"child",
".",
"type",
"not",
"in",
"(",
"syms",
".",
"funcdef",
",",
"syms",
".",
"classdef",
")",
":",
"if",
"self",
".",
"has_return_exprs",
"(",
"child",
")",
":",
"return",
"True",
"return",
"False"
] |
Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.)
|
[
"Traverse",
"the",
"tree",
"below",
"node",
"looking",
"for",
"return",
"expr",
"."
] |
d128c76b8a86f208e5c78716f2a917003650cebc
|
https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L454-L467
|
8,780
|
srsudar/eg
|
eg/config.py
|
inform_if_paths_invalid
|
def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True):
"""
If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line.
"""
if (not debug):
return
if (egrc_path):
_inform_if_path_does_not_exist(egrc_path)
if (examples_dir):
_inform_if_path_does_not_exist(examples_dir)
if (custom_dir):
_inform_if_path_does_not_exist(custom_dir)
|
python
|
def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True):
"""
If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line.
"""
if (not debug):
return
if (egrc_path):
_inform_if_path_does_not_exist(egrc_path)
if (examples_dir):
_inform_if_path_does_not_exist(examples_dir)
if (custom_dir):
_inform_if_path_does_not_exist(custom_dir)
|
[
"def",
"inform_if_paths_invalid",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
",",
"debug",
"=",
"True",
")",
":",
"if",
"(",
"not",
"debug",
")",
":",
"return",
"if",
"(",
"egrc_path",
")",
":",
"_inform_if_path_does_not_exist",
"(",
"egrc_path",
")",
"if",
"(",
"examples_dir",
")",
":",
"_inform_if_path_does_not_exist",
"(",
"examples_dir",
")",
"if",
"(",
"custom_dir",
")",
":",
"_inform_if_path_does_not_exist",
"(",
"custom_dir",
")"
] |
If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line.
|
[
"If",
"egrc_path",
"examples_dir",
"or",
"custom_dir",
"is",
"truthy",
"and",
"debug",
"is",
"True",
"informs",
"the",
"user",
"that",
"a",
"path",
"is",
"not",
"set",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L131-L148
|
8,781
|
srsudar/eg
|
eg/config.py
|
get_egrc_config
|
def get_egrc_config(cli_egrc_path):
"""
Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the command line via
--config-file
"""
resolved_path = get_priority(cli_egrc_path, DEFAULT_EGRC_PATH, None)
expanded_path = get_expanded_path(resolved_path)
# Start as if nothing was defined in the egrc.
egrc_config = get_empty_config()
if os.path.isfile(expanded_path):
egrc_config = get_config_tuple_from_egrc(expanded_path)
return egrc_config
|
python
|
def get_egrc_config(cli_egrc_path):
"""
Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the command line via
--config-file
"""
resolved_path = get_priority(cli_egrc_path, DEFAULT_EGRC_PATH, None)
expanded_path = get_expanded_path(resolved_path)
# Start as if nothing was defined in the egrc.
egrc_config = get_empty_config()
if os.path.isfile(expanded_path):
egrc_config = get_config_tuple_from_egrc(expanded_path)
return egrc_config
|
[
"def",
"get_egrc_config",
"(",
"cli_egrc_path",
")",
":",
"resolved_path",
"=",
"get_priority",
"(",
"cli_egrc_path",
",",
"DEFAULT_EGRC_PATH",
",",
"None",
")",
"expanded_path",
"=",
"get_expanded_path",
"(",
"resolved_path",
")",
"# Start as if nothing was defined in the egrc.",
"egrc_config",
"=",
"get_empty_config",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"expanded_path",
")",
":",
"egrc_config",
"=",
"get_config_tuple_from_egrc",
"(",
"expanded_path",
")",
"return",
"egrc_config"
] |
Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the command line via
--config-file
|
[
"Return",
"a",
"Config",
"namedtuple",
"based",
"on",
"the",
"contents",
"of",
"the",
"egrc",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L151-L171
|
8,782
|
srsudar/eg
|
eg/config.py
|
get_resolved_config
|
def get_resolved_config(
egrc_path,
examples_dir,
custom_dir,
use_color,
pager_cmd,
squeeze,
debug=True,
):
"""
Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in arguments. In general, it prefers first command line options,
then values from the egrc, and finally defaults.
examples_dir and custom_dir when returned from this function are fully
expanded.
"""
# Call this with the passed in values, NOT the resolved values. We are
# informing the caller only if values passed in at the command line are
# invalid. If you pass a path to a nonexistent egrc, for example, it's
# helpful to know. If you don't have an egrc, and thus one isn't found
# later at the default location, we don't want to notify them.
inform_if_paths_invalid(egrc_path, examples_dir, custom_dir)
# Expand the paths so we can use them with impunity later.
examples_dir = get_expanded_path(examples_dir)
custom_dir = get_expanded_path(custom_dir)
# The general rule is: caller-defined, egrc-defined, defaults. We'll try
# and get all three then use get_priority to choose the right one.
egrc_config = get_egrc_config(egrc_path)
resolved_examples_dir = get_priority(
examples_dir,
egrc_config.examples_dir,
DEFAULT_EXAMPLES_DIR
)
resolved_examples_dir = get_expanded_path(resolved_examples_dir)
resolved_custom_dir = get_priority(
custom_dir,
egrc_config.custom_dir,
DEFAULT_CUSTOM_DIR
)
resolved_custom_dir = get_expanded_path(resolved_custom_dir)
resolved_use_color = get_priority(
use_color,
egrc_config.use_color,
DEFAULT_USE_COLOR
)
resolved_pager_cmd = get_priority(
pager_cmd,
egrc_config.pager_cmd,
DEFAULT_PAGER_CMD
)
# There is no command line option for this, so in this case we will use the
# priority: egrc, environment, DEFAULT.
environment_editor_cmd = get_editor_cmd_from_environment()
resolved_editor_cmd = get_priority(
egrc_config.editor_cmd,
environment_editor_cmd,
DEFAULT_EDITOR_CMD
)
color_config = None
if resolved_use_color:
default_color_config = get_default_color_config()
color_config = merge_color_configs(
egrc_config.color_config,
default_color_config
)
resolved_squeeze = get_priority(
squeeze,
egrc_config.squeeze,
DEFAULT_SQUEEZE
)
# Pass in None, as subs can't be specified at the command line.
resolved_subs = get_priority(
None,
egrc_config.subs,
get_default_subs()
)
result = Config(
examples_dir=resolved_examples_dir,
custom_dir=resolved_custom_dir,
color_config=color_config,
use_color=resolved_use_color,
pager_cmd=resolved_pager_cmd,
editor_cmd=resolved_editor_cmd,
squeeze=resolved_squeeze,
subs=resolved_subs,
)
return result
|
python
|
def get_resolved_config(
egrc_path,
examples_dir,
custom_dir,
use_color,
pager_cmd,
squeeze,
debug=True,
):
"""
Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in arguments. In general, it prefers first command line options,
then values from the egrc, and finally defaults.
examples_dir and custom_dir when returned from this function are fully
expanded.
"""
# Call this with the passed in values, NOT the resolved values. We are
# informing the caller only if values passed in at the command line are
# invalid. If you pass a path to a nonexistent egrc, for example, it's
# helpful to know. If you don't have an egrc, and thus one isn't found
# later at the default location, we don't want to notify them.
inform_if_paths_invalid(egrc_path, examples_dir, custom_dir)
# Expand the paths so we can use them with impunity later.
examples_dir = get_expanded_path(examples_dir)
custom_dir = get_expanded_path(custom_dir)
# The general rule is: caller-defined, egrc-defined, defaults. We'll try
# and get all three then use get_priority to choose the right one.
egrc_config = get_egrc_config(egrc_path)
resolved_examples_dir = get_priority(
examples_dir,
egrc_config.examples_dir,
DEFAULT_EXAMPLES_DIR
)
resolved_examples_dir = get_expanded_path(resolved_examples_dir)
resolved_custom_dir = get_priority(
custom_dir,
egrc_config.custom_dir,
DEFAULT_CUSTOM_DIR
)
resolved_custom_dir = get_expanded_path(resolved_custom_dir)
resolved_use_color = get_priority(
use_color,
egrc_config.use_color,
DEFAULT_USE_COLOR
)
resolved_pager_cmd = get_priority(
pager_cmd,
egrc_config.pager_cmd,
DEFAULT_PAGER_CMD
)
# There is no command line option for this, so in this case we will use the
# priority: egrc, environment, DEFAULT.
environment_editor_cmd = get_editor_cmd_from_environment()
resolved_editor_cmd = get_priority(
egrc_config.editor_cmd,
environment_editor_cmd,
DEFAULT_EDITOR_CMD
)
color_config = None
if resolved_use_color:
default_color_config = get_default_color_config()
color_config = merge_color_configs(
egrc_config.color_config,
default_color_config
)
resolved_squeeze = get_priority(
squeeze,
egrc_config.squeeze,
DEFAULT_SQUEEZE
)
# Pass in None, as subs can't be specified at the command line.
resolved_subs = get_priority(
None,
egrc_config.subs,
get_default_subs()
)
result = Config(
examples_dir=resolved_examples_dir,
custom_dir=resolved_custom_dir,
color_config=color_config,
use_color=resolved_use_color,
pager_cmd=resolved_pager_cmd,
editor_cmd=resolved_editor_cmd,
squeeze=resolved_squeeze,
subs=resolved_subs,
)
return result
|
[
"def",
"get_resolved_config",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
",",
"use_color",
",",
"pager_cmd",
",",
"squeeze",
",",
"debug",
"=",
"True",
",",
")",
":",
"# Call this with the passed in values, NOT the resolved values. We are",
"# informing the caller only if values passed in at the command line are",
"# invalid. If you pass a path to a nonexistent egrc, for example, it's",
"# helpful to know. If you don't have an egrc, and thus one isn't found",
"# later at the default location, we don't want to notify them.",
"inform_if_paths_invalid",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
")",
"# Expand the paths so we can use them with impunity later.",
"examples_dir",
"=",
"get_expanded_path",
"(",
"examples_dir",
")",
"custom_dir",
"=",
"get_expanded_path",
"(",
"custom_dir",
")",
"# The general rule is: caller-defined, egrc-defined, defaults. We'll try",
"# and get all three then use get_priority to choose the right one.",
"egrc_config",
"=",
"get_egrc_config",
"(",
"egrc_path",
")",
"resolved_examples_dir",
"=",
"get_priority",
"(",
"examples_dir",
",",
"egrc_config",
".",
"examples_dir",
",",
"DEFAULT_EXAMPLES_DIR",
")",
"resolved_examples_dir",
"=",
"get_expanded_path",
"(",
"resolved_examples_dir",
")",
"resolved_custom_dir",
"=",
"get_priority",
"(",
"custom_dir",
",",
"egrc_config",
".",
"custom_dir",
",",
"DEFAULT_CUSTOM_DIR",
")",
"resolved_custom_dir",
"=",
"get_expanded_path",
"(",
"resolved_custom_dir",
")",
"resolved_use_color",
"=",
"get_priority",
"(",
"use_color",
",",
"egrc_config",
".",
"use_color",
",",
"DEFAULT_USE_COLOR",
")",
"resolved_pager_cmd",
"=",
"get_priority",
"(",
"pager_cmd",
",",
"egrc_config",
".",
"pager_cmd",
",",
"DEFAULT_PAGER_CMD",
")",
"# There is no command line option for this, so in this case we will use the",
"# priority: egrc, environment, DEFAULT.",
"environment_editor_cmd",
"=",
"get_editor_cmd_from_environment",
"(",
")",
"resolved_editor_cmd",
"=",
"get_priority",
"(",
"egrc_config",
".",
"editor_cmd",
",",
"environment_editor_cmd",
",",
"DEFAULT_EDITOR_CMD",
")",
"color_config",
"=",
"None",
"if",
"resolved_use_color",
":",
"default_color_config",
"=",
"get_default_color_config",
"(",
")",
"color_config",
"=",
"merge_color_configs",
"(",
"egrc_config",
".",
"color_config",
",",
"default_color_config",
")",
"resolved_squeeze",
"=",
"get_priority",
"(",
"squeeze",
",",
"egrc_config",
".",
"squeeze",
",",
"DEFAULT_SQUEEZE",
")",
"# Pass in None, as subs can't be specified at the command line.",
"resolved_subs",
"=",
"get_priority",
"(",
"None",
",",
"egrc_config",
".",
"subs",
",",
"get_default_subs",
"(",
")",
")",
"result",
"=",
"Config",
"(",
"examples_dir",
"=",
"resolved_examples_dir",
",",
"custom_dir",
"=",
"resolved_custom_dir",
",",
"color_config",
"=",
"color_config",
",",
"use_color",
"=",
"resolved_use_color",
",",
"pager_cmd",
"=",
"resolved_pager_cmd",
",",
"editor_cmd",
"=",
"resolved_editor_cmd",
",",
"squeeze",
"=",
"resolved_squeeze",
",",
"subs",
"=",
"resolved_subs",
",",
")",
"return",
"result"
] |
Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in arguments. In general, it prefers first command line options,
then values from the egrc, and finally defaults.
examples_dir and custom_dir when returned from this function are fully
expanded.
|
[
"Create",
"a",
"Config",
"namedtuple",
".",
"Passed",
"in",
"values",
"will",
"override",
"defaults",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L174-L276
|
8,783
|
srsudar/eg
|
eg/config.py
|
get_config_tuple_from_egrc
|
def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r') as egrc:
try:
config = ConfigParser.RawConfigParser()
except AttributeError:
config = ConfigParser()
config.readfp(egrc)
# default to None
examples_dir = None
custom_dir = None
use_color = None
pager_cmd = None
squeeze = None
subs = None
editor_cmd = None
if config.has_option(DEFAULT_SECTION, EG_EXAMPLES_DIR):
examples_dir = config.get(DEFAULT_SECTION, EG_EXAMPLES_DIR)
examples_dir = get_expanded_path(examples_dir)
if config.has_option(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR):
custom_dir = config.get(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR)
custom_dir = get_expanded_path(custom_dir)
if config.has_option(DEFAULT_SECTION, USE_COLOR):
use_color_raw = config.get(DEFAULT_SECTION, USE_COLOR)
use_color = _parse_bool_from_raw_egrc_value(use_color_raw)
if config.has_option(DEFAULT_SECTION, PAGER_CMD):
pager_cmd_raw = config.get(DEFAULT_SECTION, PAGER_CMD)
pager_cmd = ast.literal_eval(pager_cmd_raw)
if config.has_option(DEFAULT_SECTION, EDITOR_CMD):
editor_cmd_raw = config.get(DEFAULT_SECTION, EDITOR_CMD)
editor_cmd = ast.literal_eval(editor_cmd_raw)
color_config = get_custom_color_config_from_egrc(config)
if config.has_option(DEFAULT_SECTION, SQUEEZE):
squeeze_raw = config.get(DEFAULT_SECTION, SQUEEZE)
squeeze = _parse_bool_from_raw_egrc_value(squeeze_raw)
if config.has_section(SUBSTITUTION_SECTION):
subs = get_substitutions_from_config(config)
return Config(
examples_dir=examples_dir,
custom_dir=custom_dir,
color_config=color_config,
use_color=use_color,
pager_cmd=pager_cmd,
editor_cmd=editor_cmd,
squeeze=squeeze,
subs=subs,
)
|
python
|
def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r') as egrc:
try:
config = ConfigParser.RawConfigParser()
except AttributeError:
config = ConfigParser()
config.readfp(egrc)
# default to None
examples_dir = None
custom_dir = None
use_color = None
pager_cmd = None
squeeze = None
subs = None
editor_cmd = None
if config.has_option(DEFAULT_SECTION, EG_EXAMPLES_DIR):
examples_dir = config.get(DEFAULT_SECTION, EG_EXAMPLES_DIR)
examples_dir = get_expanded_path(examples_dir)
if config.has_option(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR):
custom_dir = config.get(DEFAULT_SECTION, CUSTOM_EXAMPLES_DIR)
custom_dir = get_expanded_path(custom_dir)
if config.has_option(DEFAULT_SECTION, USE_COLOR):
use_color_raw = config.get(DEFAULT_SECTION, USE_COLOR)
use_color = _parse_bool_from_raw_egrc_value(use_color_raw)
if config.has_option(DEFAULT_SECTION, PAGER_CMD):
pager_cmd_raw = config.get(DEFAULT_SECTION, PAGER_CMD)
pager_cmd = ast.literal_eval(pager_cmd_raw)
if config.has_option(DEFAULT_SECTION, EDITOR_CMD):
editor_cmd_raw = config.get(DEFAULT_SECTION, EDITOR_CMD)
editor_cmd = ast.literal_eval(editor_cmd_raw)
color_config = get_custom_color_config_from_egrc(config)
if config.has_option(DEFAULT_SECTION, SQUEEZE):
squeeze_raw = config.get(DEFAULT_SECTION, SQUEEZE)
squeeze = _parse_bool_from_raw_egrc_value(squeeze_raw)
if config.has_section(SUBSTITUTION_SECTION):
subs = get_substitutions_from_config(config)
return Config(
examples_dir=examples_dir,
custom_dir=custom_dir,
color_config=color_config,
use_color=use_color,
pager_cmd=pager_cmd,
editor_cmd=editor_cmd,
squeeze=squeeze,
subs=subs,
)
|
[
"def",
"get_config_tuple_from_egrc",
"(",
"egrc_path",
")",
":",
"with",
"open",
"(",
"egrc_path",
",",
"'r'",
")",
"as",
"egrc",
":",
"try",
":",
"config",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
")",
"except",
"AttributeError",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"config",
".",
"readfp",
"(",
"egrc",
")",
"# default to None",
"examples_dir",
"=",
"None",
"custom_dir",
"=",
"None",
"use_color",
"=",
"None",
"pager_cmd",
"=",
"None",
"squeeze",
"=",
"None",
"subs",
"=",
"None",
"editor_cmd",
"=",
"None",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"EG_EXAMPLES_DIR",
")",
":",
"examples_dir",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"EG_EXAMPLES_DIR",
")",
"examples_dir",
"=",
"get_expanded_path",
"(",
"examples_dir",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"CUSTOM_EXAMPLES_DIR",
")",
":",
"custom_dir",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"CUSTOM_EXAMPLES_DIR",
")",
"custom_dir",
"=",
"get_expanded_path",
"(",
"custom_dir",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"USE_COLOR",
")",
":",
"use_color_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"USE_COLOR",
")",
"use_color",
"=",
"_parse_bool_from_raw_egrc_value",
"(",
"use_color_raw",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"PAGER_CMD",
")",
":",
"pager_cmd_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"PAGER_CMD",
")",
"pager_cmd",
"=",
"ast",
".",
"literal_eval",
"(",
"pager_cmd_raw",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"EDITOR_CMD",
")",
":",
"editor_cmd_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"EDITOR_CMD",
")",
"editor_cmd",
"=",
"ast",
".",
"literal_eval",
"(",
"editor_cmd_raw",
")",
"color_config",
"=",
"get_custom_color_config_from_egrc",
"(",
"config",
")",
"if",
"config",
".",
"has_option",
"(",
"DEFAULT_SECTION",
",",
"SQUEEZE",
")",
":",
"squeeze_raw",
"=",
"config",
".",
"get",
"(",
"DEFAULT_SECTION",
",",
"SQUEEZE",
")",
"squeeze",
"=",
"_parse_bool_from_raw_egrc_value",
"(",
"squeeze_raw",
")",
"if",
"config",
".",
"has_section",
"(",
"SUBSTITUTION_SECTION",
")",
":",
"subs",
"=",
"get_substitutions_from_config",
"(",
"config",
")",
"return",
"Config",
"(",
"examples_dir",
"=",
"examples_dir",
",",
"custom_dir",
"=",
"custom_dir",
",",
"color_config",
"=",
"color_config",
",",
"use_color",
"=",
"use_color",
",",
"pager_cmd",
"=",
"pager_cmd",
",",
"editor_cmd",
"=",
"editor_cmd",
",",
"squeeze",
"=",
"squeeze",
",",
"subs",
"=",
"subs",
",",
")"
] |
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
|
[
"Create",
"a",
"Config",
"named",
"tuple",
"from",
"the",
"values",
"specified",
"in",
"the",
".",
"egrc",
".",
"Expands",
"any",
"paths",
"as",
"necessary",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L279-L342
|
8,784
|
srsudar/eg
|
eg/config.py
|
get_expanded_path
|
def get_expanded_path(path):
"""Expand ~ and variables in a path. If path is not truthy, return None."""
if path:
result = path
result = os.path.expanduser(result)
result = os.path.expandvars(result)
return result
else:
return None
|
python
|
def get_expanded_path(path):
"""Expand ~ and variables in a path. If path is not truthy, return None."""
if path:
result = path
result = os.path.expanduser(result)
result = os.path.expandvars(result)
return result
else:
return None
|
[
"def",
"get_expanded_path",
"(",
"path",
")",
":",
"if",
"path",
":",
"result",
"=",
"path",
"result",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"result",
")",
"result",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"result",
")",
"return",
"result",
"else",
":",
"return",
"None"
] |
Expand ~ and variables in a path. If path is not truthy, return None.
|
[
"Expand",
"~",
"and",
"variables",
"in",
"a",
"path",
".",
"If",
"path",
"is",
"not",
"truthy",
"return",
"None",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L345-L353
|
8,785
|
srsudar/eg
|
eg/config.py
|
get_editor_cmd_from_environment
|
def get_editor_cmd_from_environment():
"""
Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None.
"""
result = os.getenv(ENV_VISUAL)
if (not result):
result = os.getenv(ENV_EDITOR)
return result
|
python
|
def get_editor_cmd_from_environment():
"""
Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None.
"""
result = os.getenv(ENV_VISUAL)
if (not result):
result = os.getenv(ENV_EDITOR)
return result
|
[
"def",
"get_editor_cmd_from_environment",
"(",
")",
":",
"result",
"=",
"os",
".",
"getenv",
"(",
"ENV_VISUAL",
")",
"if",
"(",
"not",
"result",
")",
":",
"result",
"=",
"os",
".",
"getenv",
"(",
"ENV_EDITOR",
")",
"return",
"result"
] |
Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None.
|
[
"Gets",
"and",
"editor",
"command",
"from",
"environment",
"variables",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L356-L366
|
8,786
|
srsudar/eg
|
eg/config.py
|
_inform_if_path_does_not_exist
|
def _inform_if_path_does_not_exist(path):
"""
If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find.
"""
expanded_path = get_expanded_path(path)
if not os.path.exists(expanded_path):
print('Could not find custom path at: {}'.format(expanded_path))
|
python
|
def _inform_if_path_does_not_exist(path):
"""
If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find.
"""
expanded_path = get_expanded_path(path)
if not os.path.exists(expanded_path):
print('Could not find custom path at: {}'.format(expanded_path))
|
[
"def",
"_inform_if_path_does_not_exist",
"(",
"path",
")",
":",
"expanded_path",
"=",
"get_expanded_path",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"expanded_path",
")",
":",
"print",
"(",
"'Could not find custom path at: {}'",
".",
"format",
"(",
"expanded_path",
")",
")"
] |
If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find.
|
[
"If",
"the",
"path",
"does",
"not",
"exist",
"print",
"a",
"message",
"saying",
"so",
".",
"This",
"is",
"intended",
"to",
"be",
"helpful",
"to",
"users",
"if",
"they",
"specify",
"a",
"custom",
"path",
"that",
"eg",
"cannot",
"find",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L383-L390
|
8,787
|
srsudar/eg
|
eg/config.py
|
get_custom_color_config_from_egrc
|
def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config(config, CONFIG_NAMES.code)
backticks = _get_color_from_config(config, CONFIG_NAMES.backticks)
prompt = _get_color_from_config(config, CONFIG_NAMES.prompt)
pound_reset = _get_color_from_config(config, CONFIG_NAMES.pound_reset)
heading_reset = _get_color_from_config(
config,
CONFIG_NAMES.heading_reset
)
code_reset = _get_color_from_config(config, CONFIG_NAMES.code_reset)
backticks_reset = _get_color_from_config(
config,
CONFIG_NAMES.backticks_reset
)
prompt_reset = _get_color_from_config(config, CONFIG_NAMES.prompt_reset)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result
|
python
|
def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config(config, CONFIG_NAMES.code)
backticks = _get_color_from_config(config, CONFIG_NAMES.backticks)
prompt = _get_color_from_config(config, CONFIG_NAMES.prompt)
pound_reset = _get_color_from_config(config, CONFIG_NAMES.pound_reset)
heading_reset = _get_color_from_config(
config,
CONFIG_NAMES.heading_reset
)
code_reset = _get_color_from_config(config, CONFIG_NAMES.code_reset)
backticks_reset = _get_color_from_config(
config,
CONFIG_NAMES.backticks_reset
)
prompt_reset = _get_color_from_config(config, CONFIG_NAMES.prompt_reset)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result
|
[
"def",
"get_custom_color_config_from_egrc",
"(",
"config",
")",
":",
"pound",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"pound",
")",
"heading",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"heading",
")",
"code",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"code",
")",
"backticks",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"backticks",
")",
"prompt",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"prompt",
")",
"pound_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"pound_reset",
")",
"heading_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"heading_reset",
")",
"code_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"code_reset",
")",
"backticks_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"backticks_reset",
")",
"prompt_reset",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"prompt_reset",
")",
"result",
"=",
"ColorConfig",
"(",
"pound",
"=",
"pound",
",",
"heading",
"=",
"heading",
",",
"code",
"=",
"code",
",",
"backticks",
"=",
"backticks",
",",
"prompt",
"=",
"prompt",
",",
"pound_reset",
"=",
"pound_reset",
",",
"heading_reset",
"=",
"heading_reset",
",",
"code_reset",
"=",
"code_reset",
",",
"backticks_reset",
"=",
"backticks_reset",
",",
"prompt_reset",
"=",
"prompt_reset",
")",
"return",
"result"
] |
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
|
[
"Get",
"the",
"ColorConfig",
"from",
"the",
"egrc",
"config",
"object",
".",
"Any",
"colors",
"not",
"defined",
"will",
"be",
"None",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L393-L428
|
8,788
|
srsudar/eg
|
eg/config.py
|
_get_color_from_config
|
def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not config.has_option(COLOR_SECTION, option):
return None
else:
return ast.literal_eval(config.get(COLOR_SECTION, option))
|
python
|
def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not config.has_option(COLOR_SECTION, option):
return None
else:
return ast.literal_eval(config.get(COLOR_SECTION, option))
|
[
"def",
"_get_color_from_config",
"(",
"config",
",",
"option",
")",
":",
"if",
"not",
"config",
".",
"has_option",
"(",
"COLOR_SECTION",
",",
"option",
")",
":",
"return",
"None",
"else",
":",
"return",
"ast",
".",
"literal_eval",
"(",
"config",
".",
"get",
"(",
"COLOR_SECTION",
",",
"option",
")",
")"
] |
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
|
[
"Helper",
"method",
"to",
"uet",
"an",
"option",
"from",
"the",
"COLOR_SECTION",
"of",
"the",
"config",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L431-L442
|
8,789
|
srsudar/eg
|
eg/config.py
|
parse_substitution_from_list
|
def parse_substitution_from_list(list_rep):
"""
Parse a substitution from the list representation in the config file.
"""
# We are expecting [pattern, replacement [, is_multiline]]
if type(list_rep) is not list:
raise SyntaxError('Substitution must be a list')
if len(list_rep) < 2:
raise SyntaxError('Substitution must be a list of size 2')
pattern = list_rep[0]
replacement = list_rep[1]
# By default, substitutions are not multiline.
is_multiline = False
if (len(list_rep) > 2):
is_multiline = list_rep[2]
if type(is_multiline) is not bool:
raise SyntaxError('is_multiline must be a boolean')
result = substitute.Substitution(pattern, replacement, is_multiline)
return result
|
python
|
def parse_substitution_from_list(list_rep):
"""
Parse a substitution from the list representation in the config file.
"""
# We are expecting [pattern, replacement [, is_multiline]]
if type(list_rep) is not list:
raise SyntaxError('Substitution must be a list')
if len(list_rep) < 2:
raise SyntaxError('Substitution must be a list of size 2')
pattern = list_rep[0]
replacement = list_rep[1]
# By default, substitutions are not multiline.
is_multiline = False
if (len(list_rep) > 2):
is_multiline = list_rep[2]
if type(is_multiline) is not bool:
raise SyntaxError('is_multiline must be a boolean')
result = substitute.Substitution(pattern, replacement, is_multiline)
return result
|
[
"def",
"parse_substitution_from_list",
"(",
"list_rep",
")",
":",
"# We are expecting [pattern, replacement [, is_multiline]]",
"if",
"type",
"(",
"list_rep",
")",
"is",
"not",
"list",
":",
"raise",
"SyntaxError",
"(",
"'Substitution must be a list'",
")",
"if",
"len",
"(",
"list_rep",
")",
"<",
"2",
":",
"raise",
"SyntaxError",
"(",
"'Substitution must be a list of size 2'",
")",
"pattern",
"=",
"list_rep",
"[",
"0",
"]",
"replacement",
"=",
"list_rep",
"[",
"1",
"]",
"# By default, substitutions are not multiline.",
"is_multiline",
"=",
"False",
"if",
"(",
"len",
"(",
"list_rep",
")",
">",
"2",
")",
":",
"is_multiline",
"=",
"list_rep",
"[",
"2",
"]",
"if",
"type",
"(",
"is_multiline",
")",
"is",
"not",
"bool",
":",
"raise",
"SyntaxError",
"(",
"'is_multiline must be a boolean'",
")",
"result",
"=",
"substitute",
".",
"Substitution",
"(",
"pattern",
",",
"replacement",
",",
"is_multiline",
")",
"return",
"result"
] |
Parse a substitution from the list representation in the config file.
|
[
"Parse",
"a",
"substitution",
"from",
"the",
"list",
"representation",
"in",
"the",
"config",
"file",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L445-L466
|
8,790
|
srsudar/eg
|
eg/config.py
|
get_substitutions_from_config
|
def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
"""
result = []
pattern_names = config.options(SUBSTITUTION_SECTION)
pattern_names.sort()
for name in pattern_names:
pattern_val = config.get(SUBSTITUTION_SECTION, name)
list_rep = ast.literal_eval(pattern_val)
substitution = parse_substitution_from_list(list_rep)
result.append(substitution)
return result
|
python
|
def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
"""
result = []
pattern_names = config.options(SUBSTITUTION_SECTION)
pattern_names.sort()
for name in pattern_names:
pattern_val = config.get(SUBSTITUTION_SECTION, name)
list_rep = ast.literal_eval(pattern_val)
substitution = parse_substitution_from_list(list_rep)
result.append(substitution)
return result
|
[
"def",
"get_substitutions_from_config",
"(",
"config",
")",
":",
"result",
"=",
"[",
"]",
"pattern_names",
"=",
"config",
".",
"options",
"(",
"SUBSTITUTION_SECTION",
")",
"pattern_names",
".",
"sort",
"(",
")",
"for",
"name",
"in",
"pattern_names",
":",
"pattern_val",
"=",
"config",
".",
"get",
"(",
"SUBSTITUTION_SECTION",
",",
"name",
")",
"list_rep",
"=",
"ast",
".",
"literal_eval",
"(",
"pattern_val",
")",
"substitution",
"=",
"parse_substitution_from_list",
"(",
"list_rep",
")",
"result",
".",
"append",
"(",
"substitution",
")",
"return",
"result"
] |
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
|
[
"Return",
"a",
"list",
"of",
"Substitution",
"objects",
"from",
"the",
"config",
"sorted",
"alphabetically",
"by",
"pattern",
"name",
".",
"Returns",
"an",
"empty",
"list",
"if",
"no",
"Substitutions",
"are",
"specified",
".",
"If",
"there",
"are",
"problems",
"parsing",
"the",
"values",
"a",
"help",
"message",
"will",
"be",
"printed",
"and",
"an",
"error",
"will",
"be",
"thrown",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L469-L484
|
8,791
|
srsudar/eg
|
eg/config.py
|
get_default_color_config
|
def get_default_color_config():
"""Get a color config object with all the defaults."""
result = ColorConfig(
pound=DEFAULT_COLOR_POUND,
heading=DEFAULT_COLOR_HEADING,
code=DEFAULT_COLOR_CODE,
backticks=DEFAULT_COLOR_BACKTICKS,
prompt=DEFAULT_COLOR_PROMPT,
pound_reset=DEFAULT_COLOR_POUND_RESET,
heading_reset=DEFAULT_COLOR_HEADING_RESET,
code_reset=DEFAULT_COLOR_CODE_RESET,
backticks_reset=DEFAULT_COLOR_BACKTICKS_RESET,
prompt_reset=DEFAULT_COLOR_PROMPT_RESET
)
return result
|
python
|
def get_default_color_config():
"""Get a color config object with all the defaults."""
result = ColorConfig(
pound=DEFAULT_COLOR_POUND,
heading=DEFAULT_COLOR_HEADING,
code=DEFAULT_COLOR_CODE,
backticks=DEFAULT_COLOR_BACKTICKS,
prompt=DEFAULT_COLOR_PROMPT,
pound_reset=DEFAULT_COLOR_POUND_RESET,
heading_reset=DEFAULT_COLOR_HEADING_RESET,
code_reset=DEFAULT_COLOR_CODE_RESET,
backticks_reset=DEFAULT_COLOR_BACKTICKS_RESET,
prompt_reset=DEFAULT_COLOR_PROMPT_RESET
)
return result
|
[
"def",
"get_default_color_config",
"(",
")",
":",
"result",
"=",
"ColorConfig",
"(",
"pound",
"=",
"DEFAULT_COLOR_POUND",
",",
"heading",
"=",
"DEFAULT_COLOR_HEADING",
",",
"code",
"=",
"DEFAULT_COLOR_CODE",
",",
"backticks",
"=",
"DEFAULT_COLOR_BACKTICKS",
",",
"prompt",
"=",
"DEFAULT_COLOR_PROMPT",
",",
"pound_reset",
"=",
"DEFAULT_COLOR_POUND_RESET",
",",
"heading_reset",
"=",
"DEFAULT_COLOR_HEADING_RESET",
",",
"code_reset",
"=",
"DEFAULT_COLOR_CODE_RESET",
",",
"backticks_reset",
"=",
"DEFAULT_COLOR_BACKTICKS_RESET",
",",
"prompt_reset",
"=",
"DEFAULT_COLOR_PROMPT_RESET",
")",
"return",
"result"
] |
Get a color config object with all the defaults.
|
[
"Get",
"a",
"color",
"config",
"object",
"with",
"all",
"the",
"defaults",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L487-L501
|
8,792
|
srsudar/eg
|
eg/config.py
|
get_empty_config
|
def get_empty_config():
"""
Return an empty Config object with no options set.
"""
empty_color_config = get_empty_color_config()
result = Config(
examples_dir=None,
custom_dir=None,
color_config=empty_color_config,
use_color=None,
pager_cmd=None,
editor_cmd=None,
squeeze=None,
subs=None
)
return result
|
python
|
def get_empty_config():
"""
Return an empty Config object with no options set.
"""
empty_color_config = get_empty_color_config()
result = Config(
examples_dir=None,
custom_dir=None,
color_config=empty_color_config,
use_color=None,
pager_cmd=None,
editor_cmd=None,
squeeze=None,
subs=None
)
return result
|
[
"def",
"get_empty_config",
"(",
")",
":",
"empty_color_config",
"=",
"get_empty_color_config",
"(",
")",
"result",
"=",
"Config",
"(",
"examples_dir",
"=",
"None",
",",
"custom_dir",
"=",
"None",
",",
"color_config",
"=",
"empty_color_config",
",",
"use_color",
"=",
"None",
",",
"pager_cmd",
"=",
"None",
",",
"editor_cmd",
"=",
"None",
",",
"squeeze",
"=",
"None",
",",
"subs",
"=",
"None",
")",
"return",
"result"
] |
Return an empty Config object with no options set.
|
[
"Return",
"an",
"empty",
"Config",
"object",
"with",
"no",
"options",
"set",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L504-L519
|
8,793
|
srsudar/eg
|
eg/config.py
|
get_empty_color_config
|
def get_empty_color_config():
"""Return a color_config with all values set to None."""
empty_color_config = ColorConfig(
pound=None,
heading=None,
code=None,
backticks=None,
prompt=None,
pound_reset=None,
heading_reset=None,
code_reset=None,
backticks_reset=None,
prompt_reset=None
)
return empty_color_config
|
python
|
def get_empty_color_config():
"""Return a color_config with all values set to None."""
empty_color_config = ColorConfig(
pound=None,
heading=None,
code=None,
backticks=None,
prompt=None,
pound_reset=None,
heading_reset=None,
code_reset=None,
backticks_reset=None,
prompt_reset=None
)
return empty_color_config
|
[
"def",
"get_empty_color_config",
"(",
")",
":",
"empty_color_config",
"=",
"ColorConfig",
"(",
"pound",
"=",
"None",
",",
"heading",
"=",
"None",
",",
"code",
"=",
"None",
",",
"backticks",
"=",
"None",
",",
"prompt",
"=",
"None",
",",
"pound_reset",
"=",
"None",
",",
"heading_reset",
"=",
"None",
",",
"code_reset",
"=",
"None",
",",
"backticks_reset",
"=",
"None",
",",
"prompt_reset",
"=",
"None",
")",
"return",
"empty_color_config"
] |
Return a color_config with all values set to None.
|
[
"Return",
"a",
"color_config",
"with",
"all",
"values",
"set",
"to",
"None",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L522-L536
|
8,794
|
srsudar/eg
|
eg/config.py
|
merge_color_configs
|
def merge_color_configs(first, second):
"""
Merge the color configs.
Values in the first will overwrite non-None values in the second.
"""
# We have to get the desired values first and simultaneously, as nametuple
# is immutable.
pound = get_priority(first.pound, second.pound, None)
heading = get_priority(first.heading, second.heading, None)
code = get_priority(first.code, second.code, None)
backticks = get_priority(first.backticks, second.backticks, None)
prompt = get_priority(first.prompt, second.prompt, None)
pound_reset = get_priority(
first.pound_reset,
second.pound_reset,
None
)
heading_reset = get_priority(
first.heading_reset,
second.heading_reset,
None
)
code_reset = get_priority(
first.code_reset,
second.code_reset,
None
)
backticks_reset = get_priority(
first.backticks_reset,
second.backticks_reset,
None
)
prompt_reset = get_priority(
first.prompt_reset,
second.prompt_reset,
None
)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result
|
python
|
def merge_color_configs(first, second):
"""
Merge the color configs.
Values in the first will overwrite non-None values in the second.
"""
# We have to get the desired values first and simultaneously, as nametuple
# is immutable.
pound = get_priority(first.pound, second.pound, None)
heading = get_priority(first.heading, second.heading, None)
code = get_priority(first.code, second.code, None)
backticks = get_priority(first.backticks, second.backticks, None)
prompt = get_priority(first.prompt, second.prompt, None)
pound_reset = get_priority(
first.pound_reset,
second.pound_reset,
None
)
heading_reset = get_priority(
first.heading_reset,
second.heading_reset,
None
)
code_reset = get_priority(
first.code_reset,
second.code_reset,
None
)
backticks_reset = get_priority(
first.backticks_reset,
second.backticks_reset,
None
)
prompt_reset = get_priority(
first.prompt_reset,
second.prompt_reset,
None
)
result = ColorConfig(
pound=pound,
heading=heading,
code=code,
backticks=backticks,
prompt=prompt,
pound_reset=pound_reset,
heading_reset=heading_reset,
code_reset=code_reset,
backticks_reset=backticks_reset,
prompt_reset=prompt_reset
)
return result
|
[
"def",
"merge_color_configs",
"(",
"first",
",",
"second",
")",
":",
"# We have to get the desired values first and simultaneously, as nametuple",
"# is immutable.",
"pound",
"=",
"get_priority",
"(",
"first",
".",
"pound",
",",
"second",
".",
"pound",
",",
"None",
")",
"heading",
"=",
"get_priority",
"(",
"first",
".",
"heading",
",",
"second",
".",
"heading",
",",
"None",
")",
"code",
"=",
"get_priority",
"(",
"first",
".",
"code",
",",
"second",
".",
"code",
",",
"None",
")",
"backticks",
"=",
"get_priority",
"(",
"first",
".",
"backticks",
",",
"second",
".",
"backticks",
",",
"None",
")",
"prompt",
"=",
"get_priority",
"(",
"first",
".",
"prompt",
",",
"second",
".",
"prompt",
",",
"None",
")",
"pound_reset",
"=",
"get_priority",
"(",
"first",
".",
"pound_reset",
",",
"second",
".",
"pound_reset",
",",
"None",
")",
"heading_reset",
"=",
"get_priority",
"(",
"first",
".",
"heading_reset",
",",
"second",
".",
"heading_reset",
",",
"None",
")",
"code_reset",
"=",
"get_priority",
"(",
"first",
".",
"code_reset",
",",
"second",
".",
"code_reset",
",",
"None",
")",
"backticks_reset",
"=",
"get_priority",
"(",
"first",
".",
"backticks_reset",
",",
"second",
".",
"backticks_reset",
",",
"None",
")",
"prompt_reset",
"=",
"get_priority",
"(",
"first",
".",
"prompt_reset",
",",
"second",
".",
"prompt_reset",
",",
"None",
")",
"result",
"=",
"ColorConfig",
"(",
"pound",
"=",
"pound",
",",
"heading",
"=",
"heading",
",",
"code",
"=",
"code",
",",
"backticks",
"=",
"backticks",
",",
"prompt",
"=",
"prompt",
",",
"pound_reset",
"=",
"pound_reset",
",",
"heading_reset",
"=",
"heading_reset",
",",
"code_reset",
"=",
"code_reset",
",",
"backticks_reset",
"=",
"backticks_reset",
",",
"prompt_reset",
"=",
"prompt_reset",
")",
"return",
"result"
] |
Merge the color configs.
Values in the first will overwrite non-None values in the second.
|
[
"Merge",
"the",
"color",
"configs",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L539-L591
|
8,795
|
srsudar/eg
|
eg/substitute.py
|
Substitution.apply_and_get_result
|
def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
the result.
"""
if self.is_multiline:
compiled_pattern = re.compile(self.pattern, re.MULTILINE)
else:
compiled_pattern = re.compile(self.pattern)
result = re.sub(compiled_pattern, self.repl, string)
return result
|
python
|
def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
the result.
"""
if self.is_multiline:
compiled_pattern = re.compile(self.pattern, re.MULTILINE)
else:
compiled_pattern = re.compile(self.pattern)
result = re.sub(compiled_pattern, self.repl, string)
return result
|
[
"def",
"apply_and_get_result",
"(",
"self",
",",
"string",
")",
":",
"if",
"self",
".",
"is_multiline",
":",
"compiled_pattern",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"pattern",
",",
"re",
".",
"MULTILINE",
")",
"else",
":",
"compiled_pattern",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"pattern",
")",
"result",
"=",
"re",
".",
"sub",
"(",
"compiled_pattern",
",",
"self",
".",
"repl",
",",
"string",
")",
"return",
"result"
] |
Perform the substitution represented by this object on string and return
the result.
|
[
"Perform",
"the",
"substitution",
"represented",
"by",
"this",
"object",
"on",
"string",
"and",
"return",
"the",
"result",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/substitute.py#L23-L34
|
8,796
|
srsudar/eg
|
eg/color.py
|
EgColorizer.colorize_text
|
def colorize_text(self, text):
"""Colorize the text."""
# As originally implemented, this method acts upon all the contents of
# the file as a single string using the MULTILINE option of the re
# package. I believe this was ostensibly for performance reasons, but
# it has a few side effects that are less than ideal. It's non-trivial
# to avoid some substitutions based on other matches using this
# technique, for example. In the case of block indents, e.g., backticks
# that occur in the example ($ pwd is `pwd`) should not be escaped.
# With the MULTILINE flag that is not simple. colorize_backticks() is
# currently operating on a line by line basis and special casing for
# this scenario. If these special cases proliferate, the line breaking
# should occur here in order to minimize the number of iterations.
result = text
result = self.colorize_heading(result)
result = self.colorize_block_indent(result)
result = self.colorize_backticks(result)
return result
|
python
|
def colorize_text(self, text):
"""Colorize the text."""
# As originally implemented, this method acts upon all the contents of
# the file as a single string using the MULTILINE option of the re
# package. I believe this was ostensibly for performance reasons, but
# it has a few side effects that are less than ideal. It's non-trivial
# to avoid some substitutions based on other matches using this
# technique, for example. In the case of block indents, e.g., backticks
# that occur in the example ($ pwd is `pwd`) should not be escaped.
# With the MULTILINE flag that is not simple. colorize_backticks() is
# currently operating on a line by line basis and special casing for
# this scenario. If these special cases proliferate, the line breaking
# should occur here in order to minimize the number of iterations.
result = text
result = self.colorize_heading(result)
result = self.colorize_block_indent(result)
result = self.colorize_backticks(result)
return result
|
[
"def",
"colorize_text",
"(",
"self",
",",
"text",
")",
":",
"# As originally implemented, this method acts upon all the contents of",
"# the file as a single string using the MULTILINE option of the re",
"# package. I believe this was ostensibly for performance reasons, but",
"# it has a few side effects that are less than ideal. It's non-trivial",
"# to avoid some substitutions based on other matches using this",
"# technique, for example. In the case of block indents, e.g., backticks",
"# that occur in the example ($ pwd is `pwd`) should not be escaped.",
"# With the MULTILINE flag that is not simple. colorize_backticks() is",
"# currently operating on a line by line basis and special casing for",
"# this scenario. If these special cases proliferate, the line breaking",
"# should occur here in order to minimize the number of iterations.",
"result",
"=",
"text",
"result",
"=",
"self",
".",
"colorize_heading",
"(",
"result",
")",
"result",
"=",
"self",
".",
"colorize_block_indent",
"(",
"result",
")",
"result",
"=",
"self",
".",
"colorize_backticks",
"(",
"result",
")",
"return",
"result"
] |
Colorize the text.
|
[
"Colorize",
"the",
"text",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/color.py#L67-L85
|
8,797
|
srsudar/eg
|
eg/util.py
|
_recursive_get_all_file_names
|
def _recursive_get_all_file_names(dir):
"""
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
"""
if not dir:
return []
result = []
for basedir, dirs, files in os.walk(dir):
result.extend(files)
return result
|
python
|
def _recursive_get_all_file_names(dir):
"""
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
"""
if not dir:
return []
result = []
for basedir, dirs, files in os.walk(dir):
result.extend(files)
return result
|
[
"def",
"_recursive_get_all_file_names",
"(",
"dir",
")",
":",
"if",
"not",
"dir",
":",
"return",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"basedir",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"result",
".",
"extend",
"(",
"files",
")",
"return",
"result"
] |
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
|
[
"Get",
"all",
"the",
"file",
"names",
"in",
"the",
"directory",
".",
"Gets",
"all",
"the",
"top",
"level",
"file",
"names",
"only",
"not",
"the",
"full",
"path",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L49-L64
|
8,798
|
srsudar/eg
|
eg/util.py
|
edit_custom_examples
|
def edit_custom_examples(program, config):
"""
Edit custom examples for the given program, creating the file if it does
not exist.
"""
if (not config.custom_dir) or (not os.path.exists(config.custom_dir)):
_inform_cannot_edit_no_custom_dir()
return
# resolve aliases
resolved_program = get_resolved_program(program, config)
custom_file_paths = get_file_paths_for_program(
resolved_program,
config.custom_dir
)
if (len(custom_file_paths) > 0):
path_to_edit = custom_file_paths[0]
else:
# A new file.
path_to_edit = os.path.join(config.custom_dir, resolved_program + '.md')
# Edit the first. Handles the base case.
subprocess.call([config.editor_cmd, path_to_edit])
|
python
|
def edit_custom_examples(program, config):
"""
Edit custom examples for the given program, creating the file if it does
not exist.
"""
if (not config.custom_dir) or (not os.path.exists(config.custom_dir)):
_inform_cannot_edit_no_custom_dir()
return
# resolve aliases
resolved_program = get_resolved_program(program, config)
custom_file_paths = get_file_paths_for_program(
resolved_program,
config.custom_dir
)
if (len(custom_file_paths) > 0):
path_to_edit = custom_file_paths[0]
else:
# A new file.
path_to_edit = os.path.join(config.custom_dir, resolved_program + '.md')
# Edit the first. Handles the base case.
subprocess.call([config.editor_cmd, path_to_edit])
|
[
"def",
"edit_custom_examples",
"(",
"program",
",",
"config",
")",
":",
"if",
"(",
"not",
"config",
".",
"custom_dir",
")",
"or",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
".",
"custom_dir",
")",
")",
":",
"_inform_cannot_edit_no_custom_dir",
"(",
")",
"return",
"# resolve aliases",
"resolved_program",
"=",
"get_resolved_program",
"(",
"program",
",",
"config",
")",
"custom_file_paths",
"=",
"get_file_paths_for_program",
"(",
"resolved_program",
",",
"config",
".",
"custom_dir",
")",
"if",
"(",
"len",
"(",
"custom_file_paths",
")",
">",
"0",
")",
":",
"path_to_edit",
"=",
"custom_file_paths",
"[",
"0",
"]",
"else",
":",
"# A new file.",
"path_to_edit",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"custom_dir",
",",
"resolved_program",
"+",
"'.md'",
")",
"# Edit the first. Handles the base case.",
"subprocess",
".",
"call",
"(",
"[",
"config",
".",
"editor_cmd",
",",
"path_to_edit",
"]",
")"
] |
Edit custom examples for the given program, creating the file if it does
not exist.
|
[
"Edit",
"custom",
"examples",
"for",
"the",
"given",
"program",
"creating",
"the",
"file",
"if",
"it",
"does",
"not",
"exist",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L67-L90
|
8,799
|
srsudar/eg
|
eg/util.py
|
get_file_paths_for_program
|
def get_file_paths_for_program(program, dir_to_search):
"""
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables).
"""
if dir_to_search is None:
return []
else:
wanted_file_name = program + EXAMPLE_FILE_SUFFIX
result = []
for basedir, dirs, file_names in os.walk(dir_to_search):
for file_name in file_names:
if file_name == wanted_file_name:
result.append(os.path.join(basedir, file_name))
return result
|
python
|
def get_file_paths_for_program(program, dir_to_search):
"""
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables).
"""
if dir_to_search is None:
return []
else:
wanted_file_name = program + EXAMPLE_FILE_SUFFIX
result = []
for basedir, dirs, file_names in os.walk(dir_to_search):
for file_name in file_names:
if file_name == wanted_file_name:
result.append(os.path.join(basedir, file_name))
return result
|
[
"def",
"get_file_paths_for_program",
"(",
"program",
",",
"dir_to_search",
")",
":",
"if",
"dir_to_search",
"is",
"None",
":",
"return",
"[",
"]",
"else",
":",
"wanted_file_name",
"=",
"program",
"+",
"EXAMPLE_FILE_SUFFIX",
"result",
"=",
"[",
"]",
"for",
"basedir",
",",
"dirs",
",",
"file_names",
"in",
"os",
".",
"walk",
"(",
"dir_to_search",
")",
":",
"for",
"file_name",
"in",
"file_names",
":",
"if",
"file_name",
"==",
"wanted_file_name",
":",
"result",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"file_name",
")",
")",
"return",
"result"
] |
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables).
|
[
"Return",
"an",
"array",
"of",
"full",
"paths",
"matching",
"the",
"given",
"program",
".",
"If",
"no",
"directory",
"is",
"present",
"returns",
"an",
"empty",
"list",
"."
] |
96142a74f4416b4a7000c85032c070df713b849e
|
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L131-L150
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.