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
partition
stringclasses
1 value
PyCQA/pylint-django
pylint_django/augmentations/__init__.py
is_model_mpttmeta_subclass
def is_model_mpttmeta_subclass(node): """Checks that node is derivative of MPTTMeta class.""" if node.name != 'MPTTMeta' or not isinstance(node.parent, ClassDef): return False parents = ('django.db.models.base.Model', '.Model', # for the transformed version used in this plugin 'django.forms.forms.Form', '.Form', 'django.forms.models.ModelForm', '.ModelForm') return node_is_subclass(node.parent, *parents)
python
def is_model_mpttmeta_subclass(node): """Checks that node is derivative of MPTTMeta class.""" if node.name != 'MPTTMeta' or not isinstance(node.parent, ClassDef): return False parents = ('django.db.models.base.Model', '.Model', # for the transformed version used in this plugin 'django.forms.forms.Form', '.Form', 'django.forms.models.ModelForm', '.ModelForm') return node_is_subclass(node.parent, *parents)
[ "def", "is_model_mpttmeta_subclass", "(", "node", ")", ":", "if", "node", ".", "name", "!=", "'MPTTMeta'", "or", "not", "isinstance", "(", "node", ".", "parent", ",", "ClassDef", ")", ":", "return", "False", "parents", "=", "(", "'django.db.models.base.Model'", ",", "'.Model'", ",", "# for the transformed version used in this plugin", "'django.forms.forms.Form'", ",", "'.Form'", ",", "'django.forms.models.ModelForm'", ",", "'.ModelForm'", ")", "return", "node_is_subclass", "(", "node", ".", "parent", ",", "*", "parents", ")" ]
Checks that node is derivative of MPTTMeta class.
[ "Checks", "that", "node", "is", "derivative", "of", "MPTTMeta", "class", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L469-L480
train
PyCQA/pylint-django
pylint_django/augmentations/__init__.py
_attribute_is_magic
def _attribute_is_magic(node, attrs, parents): """Checks that node is an attribute used inside one of allowed parents""" if node.attrname not in attrs: return False if not node.last_child(): return False try: for cls in node.last_child().inferred(): if isinstance(cls, Super): cls = cls._self_class # pylint: disable=protected-access if node_is_subclass(cls, *parents) or cls.qname() in parents: return True except InferenceError: pass return False
python
def _attribute_is_magic(node, attrs, parents): """Checks that node is an attribute used inside one of allowed parents""" if node.attrname not in attrs: return False if not node.last_child(): return False try: for cls in node.last_child().inferred(): if isinstance(cls, Super): cls = cls._self_class # pylint: disable=protected-access if node_is_subclass(cls, *parents) or cls.qname() in parents: return True except InferenceError: pass return False
[ "def", "_attribute_is_magic", "(", "node", ",", "attrs", ",", "parents", ")", ":", "if", "node", ".", "attrname", "not", "in", "attrs", ":", "return", "False", "if", "not", "node", ".", "last_child", "(", ")", ":", "return", "False", "try", ":", "for", "cls", "in", "node", ".", "last_child", "(", ")", ".", "inferred", "(", ")", ":", "if", "isinstance", "(", "cls", ",", "Super", ")", ":", "cls", "=", "cls", ".", "_self_class", "# pylint: disable=protected-access", "if", "node_is_subclass", "(", "cls", ",", "*", "parents", ")", "or", "cls", ".", "qname", "(", ")", "in", "parents", ":", "return", "True", "except", "InferenceError", ":", "pass", "return", "False" ]
Checks that node is an attribute used inside one of allowed parents
[ "Checks", "that", "node", "is", "an", "attribute", "used", "inside", "one", "of", "allowed", "parents" ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L483-L498
train
PyCQA/pylint-django
pylint_django/augmentations/__init__.py
generic_is_view_attribute
def generic_is_view_attribute(parents, attrs): """Generates is_X_attribute function for given parents and attrs.""" def is_attribute(node): return _attribute_is_magic(node, attrs, parents) return is_attribute
python
def generic_is_view_attribute(parents, attrs): """Generates is_X_attribute function for given parents and attrs.""" def is_attribute(node): return _attribute_is_magic(node, attrs, parents) return is_attribute
[ "def", "generic_is_view_attribute", "(", "parents", ",", "attrs", ")", ":", "def", "is_attribute", "(", "node", ")", ":", "return", "_attribute_is_magic", "(", "node", ",", "attrs", ",", "parents", ")", "return", "is_attribute" ]
Generates is_X_attribute function for given parents and attrs.
[ "Generates", "is_X_attribute", "function", "for", "given", "parents", "and", "attrs", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L621-L625
train
PyCQA/pylint-django
pylint_django/augmentations/__init__.py
is_model_view_subclass_method_shouldnt_be_function
def is_model_view_subclass_method_shouldnt_be_function(node): """Checks that node is get or post method of the View class.""" if node.name not in ('get', 'post'): return False parent = node.parent while parent and not isinstance(parent, ScopedClass): parent = parent.parent subclass = ('django.views.View', 'django.views.generic.View', 'django.views.generic.base.View',) return parent is not None and node_is_subclass(parent, *subclass)
python
def is_model_view_subclass_method_shouldnt_be_function(node): """Checks that node is get or post method of the View class.""" if node.name not in ('get', 'post'): return False parent = node.parent while parent and not isinstance(parent, ScopedClass): parent = parent.parent subclass = ('django.views.View', 'django.views.generic.View', 'django.views.generic.base.View',) return parent is not None and node_is_subclass(parent, *subclass)
[ "def", "is_model_view_subclass_method_shouldnt_be_function", "(", "node", ")", ":", "if", "node", ".", "name", "not", "in", "(", "'get'", ",", "'post'", ")", ":", "return", "False", "parent", "=", "node", ".", "parent", "while", "parent", "and", "not", "isinstance", "(", "parent", ",", "ScopedClass", ")", ":", "parent", "=", "parent", ".", "parent", "subclass", "=", "(", "'django.views.View'", ",", "'django.views.generic.View'", ",", "'django.views.generic.base.View'", ",", ")", "return", "parent", "is", "not", "None", "and", "node_is_subclass", "(", "parent", ",", "*", "subclass", ")" ]
Checks that node is get or post method of the View class.
[ "Checks", "that", "node", "is", "get", "or", "post", "method", "of", "the", "View", "class", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L628-L641
train
PyCQA/pylint-django
pylint_django/augmentations/__init__.py
is_model_media_valid_attributes
def is_model_media_valid_attributes(node): """Suppress warnings for valid attributes of Media class.""" if node.name not in ('js', ): return False parent = node.parent while parent and not isinstance(parent, ScopedClass): parent = parent.parent if parent is None or parent.name != "Media": return False return True
python
def is_model_media_valid_attributes(node): """Suppress warnings for valid attributes of Media class.""" if node.name not in ('js', ): return False parent = node.parent while parent and not isinstance(parent, ScopedClass): parent = parent.parent if parent is None or parent.name != "Media": return False return True
[ "def", "is_model_media_valid_attributes", "(", "node", ")", ":", "if", "node", ".", "name", "not", "in", "(", "'js'", ",", ")", ":", "return", "False", "parent", "=", "node", ".", "parent", "while", "parent", "and", "not", "isinstance", "(", "parent", ",", "ScopedClass", ")", ":", "parent", "=", "parent", ".", "parent", "if", "parent", "is", "None", "or", "parent", ".", "name", "!=", "\"Media\"", ":", "return", "False", "return", "True" ]
Suppress warnings for valid attributes of Media class.
[ "Suppress", "warnings", "for", "valid", "attributes", "of", "Media", "class", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L682-L694
train
PyCQA/pylint-django
pylint_django/augmentations/__init__.py
is_templatetags_module_valid_constant
def is_templatetags_module_valid_constant(node): """Suppress warnings for valid constants in templatetags module.""" if node.name not in ('register', ): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if "templatetags." not in parent.name: return False return True
python
def is_templatetags_module_valid_constant(node): """Suppress warnings for valid constants in templatetags module.""" if node.name not in ('register', ): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if "templatetags." not in parent.name: return False return True
[ "def", "is_templatetags_module_valid_constant", "(", "node", ")", ":", "if", "node", ".", "name", "not", "in", "(", "'register'", ",", ")", ":", "return", "False", "parent", "=", "node", ".", "parent", "while", "not", "isinstance", "(", "parent", ",", "Module", ")", ":", "parent", "=", "parent", ".", "parent", "if", "\"templatetags.\"", "not", "in", "parent", ".", "name", ":", "return", "False", "return", "True" ]
Suppress warnings for valid constants in templatetags module.
[ "Suppress", "warnings", "for", "valid", "constants", "in", "templatetags", "module", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L697-L709
train
PyCQA/pylint-django
pylint_django/augmentations/__init__.py
is_urls_module_valid_constant
def is_urls_module_valid_constant(node): """Suppress warnings for valid constants in urls module.""" if node.name not in ('urlpatterns', 'app_name'): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if not parent.name.endswith('urls'): return False return True
python
def is_urls_module_valid_constant(node): """Suppress warnings for valid constants in urls module.""" if node.name not in ('urlpatterns', 'app_name'): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if not parent.name.endswith('urls'): return False return True
[ "def", "is_urls_module_valid_constant", "(", "node", ")", ":", "if", "node", ".", "name", "not", "in", "(", "'urlpatterns'", ",", "'app_name'", ")", ":", "return", "False", "parent", "=", "node", ".", "parent", "while", "not", "isinstance", "(", "parent", ",", "Module", ")", ":", "parent", "=", "parent", ".", "parent", "if", "not", "parent", ".", "name", ".", "endswith", "(", "'urls'", ")", ":", "return", "False", "return", "True" ]
Suppress warnings for valid constants in urls module.
[ "Suppress", "warnings", "for", "valid", "constants", "in", "urls", "module", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/augmentations/__init__.py#L712-L724
train
PyCQA/pylint-django
pylint_django/plugin.py
load_configuration
def load_configuration(linter): """ Amend existing checker config. """ name_checker = get_checker(linter, NameChecker) name_checker.config.good_names += ('qs', 'urlpatterns', 'register', 'app_name', 'handler500') # we don't care about South migrations linter.config.black_list += ('migrations', 'south_migrations')
python
def load_configuration(linter): """ Amend existing checker config. """ name_checker = get_checker(linter, NameChecker) name_checker.config.good_names += ('qs', 'urlpatterns', 'register', 'app_name', 'handler500') # we don't care about South migrations linter.config.black_list += ('migrations', 'south_migrations')
[ "def", "load_configuration", "(", "linter", ")", ":", "name_checker", "=", "get_checker", "(", "linter", ",", "NameChecker", ")", "name_checker", ".", "config", ".", "good_names", "+=", "(", "'qs'", ",", "'urlpatterns'", ",", "'register'", ",", "'app_name'", ",", "'handler500'", ")", "# we don't care about South migrations", "linter", ".", "config", ".", "black_list", "+=", "(", "'migrations'", ",", "'south_migrations'", ")" ]
Amend existing checker config.
[ "Amend", "existing", "checker", "config", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/plugin.py#L13-L21
train
PyCQA/pylint-django
pylint_django/plugin.py
register
def register(linter): """ Registering additional checkers. """ # add all of the checkers register_checkers(linter) # register any checking fiddlers try: from pylint_django.augmentations import apply_augmentations apply_augmentations(linter) except ImportError: # probably trying to execute pylint_django when Django isn't installed # in this case the django-not-installed checker will kick-in pass if not compat.LOAD_CONFIGURATION_SUPPORTED: load_configuration(linter)
python
def register(linter): """ Registering additional checkers. """ # add all of the checkers register_checkers(linter) # register any checking fiddlers try: from pylint_django.augmentations import apply_augmentations apply_augmentations(linter) except ImportError: # probably trying to execute pylint_django when Django isn't installed # in this case the django-not-installed checker will kick-in pass if not compat.LOAD_CONFIGURATION_SUPPORTED: load_configuration(linter)
[ "def", "register", "(", "linter", ")", ":", "# add all of the checkers", "register_checkers", "(", "linter", ")", "# register any checking fiddlers", "try", ":", "from", "pylint_django", ".", "augmentations", "import", "apply_augmentations", "apply_augmentations", "(", "linter", ")", "except", "ImportError", ":", "# probably trying to execute pylint_django when Django isn't installed", "# in this case the django-not-installed checker will kick-in", "pass", "if", "not", "compat", ".", "LOAD_CONFIGURATION_SUPPORTED", ":", "load_configuration", "(", "linter", ")" ]
Registering additional checkers.
[ "Registering", "additional", "checkers", "." ]
0bbee433519f48134df4a797341c4196546a454e
https://github.com/PyCQA/pylint-django/blob/0bbee433519f48134df4a797341c4196546a454e/pylint_django/plugin.py#L24-L41
train
05bit/peewee-async
peewee_async.py
create_object
async def create_object(model, **data): """Create object asynchronously. :param model: mode class :param data: data for initializing object :return: new object saved to database """ # NOTE! Here are internals involved: # # - obj._data # - obj._get_pk_value() # - obj._set_pk_value() # - obj._prepare_instance() # warnings.warn("create_object() is deprecated, Manager.create() " "should be used instead", DeprecationWarning) obj = model(**data) pk = await insert(model.insert(**dict(obj.__data__))) if obj._pk is None: obj._pk = pk return obj
python
async def create_object(model, **data): """Create object asynchronously. :param model: mode class :param data: data for initializing object :return: new object saved to database """ # NOTE! Here are internals involved: # # - obj._data # - obj._get_pk_value() # - obj._set_pk_value() # - obj._prepare_instance() # warnings.warn("create_object() is deprecated, Manager.create() " "should be used instead", DeprecationWarning) obj = model(**data) pk = await insert(model.insert(**dict(obj.__data__))) if obj._pk is None: obj._pk = pk return obj
[ "async", "def", "create_object", "(", "model", ",", "*", "*", "data", ")", ":", "# NOTE! Here are internals involved:", "#", "# - obj._data", "# - obj._get_pk_value()", "# - obj._set_pk_value()", "# - obj._prepare_instance()", "#", "warnings", ".", "warn", "(", "\"create_object() is deprecated, Manager.create() \"", "\"should be used instead\"", ",", "DeprecationWarning", ")", "obj", "=", "model", "(", "*", "*", "data", ")", "pk", "=", "await", "insert", "(", "model", ".", "insert", "(", "*", "*", "dict", "(", "obj", ".", "__data__", ")", ")", ")", "if", "obj", ".", "_pk", "is", "None", ":", "obj", ".", "_pk", "=", "pk", "return", "obj" ]
Create object asynchronously. :param model: mode class :param data: data for initializing object :return: new object saved to database
[ "Create", "object", "asynchronously", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L430-L454
train
05bit/peewee-async
peewee_async.py
get_object
async def get_object(source, *args): """Get object asynchronously. :param source: mode class or query to get object from :param args: lookup parameters :return: model instance or raises ``peewee.DoesNotExist`` if object not found """ warnings.warn("get_object() is deprecated, Manager.get() " "should be used instead", DeprecationWarning) if isinstance(source, peewee.Query): query = source model = query.model else: query = source.select() model = source # Return first object from query for obj in (await select(query.where(*args))): return obj # No objects found raise model.DoesNotExist
python
async def get_object(source, *args): """Get object asynchronously. :param source: mode class or query to get object from :param args: lookup parameters :return: model instance or raises ``peewee.DoesNotExist`` if object not found """ warnings.warn("get_object() is deprecated, Manager.get() " "should be used instead", DeprecationWarning) if isinstance(source, peewee.Query): query = source model = query.model else: query = source.select() model = source # Return first object from query for obj in (await select(query.where(*args))): return obj # No objects found raise model.DoesNotExist
[ "async", "def", "get_object", "(", "source", ",", "*", "args", ")", ":", "warnings", ".", "warn", "(", "\"get_object() is deprecated, Manager.get() \"", "\"should be used instead\"", ",", "DeprecationWarning", ")", "if", "isinstance", "(", "source", ",", "peewee", ".", "Query", ")", ":", "query", "=", "source", "model", "=", "query", ".", "model", "else", ":", "query", "=", "source", ".", "select", "(", ")", "model", "=", "source", "# Return first object from query", "for", "obj", "in", "(", "await", "select", "(", "query", ".", "where", "(", "*", "args", ")", ")", ")", ":", "return", "obj", "# No objects found", "raise", "model", ".", "DoesNotExist" ]
Get object asynchronously. :param source: mode class or query to get object from :param args: lookup parameters :return: model instance or raises ``peewee.DoesNotExist`` if object not found
[ "Get", "object", "asynchronously", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L457-L481
train
05bit/peewee-async
peewee_async.py
delete_object
async def delete_object(obj, recursive=False, delete_nullable=False): """Delete object asynchronously. :param obj: object to delete :param recursive: if ``True`` also delete all other objects depends on object :param delete_nullable: if `True` and delete is recursive then delete even 'nullable' dependencies For details please check out `Model.delete_instance()`_ in peewee docs. .. _Model.delete_instance(): http://peewee.readthedocs.io/en/latest/peewee/ api.html#Model.delete_instance """ warnings.warn("delete_object() is deprecated, Manager.delete() " "should be used instead", DeprecationWarning) # Here are private calls involved: # - obj._pk_expr() if recursive: dependencies = obj.dependencies(delete_nullable) for query, fk in reversed(list(dependencies)): model = fk.model if fk.null and not delete_nullable: await update(model.update(**{fk.name: None}).where(query)) else: await delete(model.delete().where(query)) result = await delete(obj.delete().where(obj._pk_expr())) return result
python
async def delete_object(obj, recursive=False, delete_nullable=False): """Delete object asynchronously. :param obj: object to delete :param recursive: if ``True`` also delete all other objects depends on object :param delete_nullable: if `True` and delete is recursive then delete even 'nullable' dependencies For details please check out `Model.delete_instance()`_ in peewee docs. .. _Model.delete_instance(): http://peewee.readthedocs.io/en/latest/peewee/ api.html#Model.delete_instance """ warnings.warn("delete_object() is deprecated, Manager.delete() " "should be used instead", DeprecationWarning) # Here are private calls involved: # - obj._pk_expr() if recursive: dependencies = obj.dependencies(delete_nullable) for query, fk in reversed(list(dependencies)): model = fk.model if fk.null and not delete_nullable: await update(model.update(**{fk.name: None}).where(query)) else: await delete(model.delete().where(query)) result = await delete(obj.delete().where(obj._pk_expr())) return result
[ "async", "def", "delete_object", "(", "obj", ",", "recursive", "=", "False", ",", "delete_nullable", "=", "False", ")", ":", "warnings", ".", "warn", "(", "\"delete_object() is deprecated, Manager.delete() \"", "\"should be used instead\"", ",", "DeprecationWarning", ")", "# Here are private calls involved:", "# - obj._pk_expr()", "if", "recursive", ":", "dependencies", "=", "obj", ".", "dependencies", "(", "delete_nullable", ")", "for", "query", ",", "fk", "in", "reversed", "(", "list", "(", "dependencies", ")", ")", ":", "model", "=", "fk", ".", "model", "if", "fk", ".", "null", "and", "not", "delete_nullable", ":", "await", "update", "(", "model", ".", "update", "(", "*", "*", "{", "fk", ".", "name", ":", "None", "}", ")", ".", "where", "(", "query", ")", ")", "else", ":", "await", "delete", "(", "model", ".", "delete", "(", ")", ".", "where", "(", "query", ")", ")", "result", "=", "await", "delete", "(", "obj", ".", "delete", "(", ")", ".", "where", "(", "obj", ".", "_pk_expr", "(", ")", ")", ")", "return", "result" ]
Delete object asynchronously. :param obj: object to delete :param recursive: if ``True`` also delete all other objects depends on object :param delete_nullable: if `True` and delete is recursive then delete even 'nullable' dependencies For details please check out `Model.delete_instance()`_ in peewee docs. .. _Model.delete_instance(): http://peewee.readthedocs.io/en/latest/peewee/ api.html#Model.delete_instance
[ "Delete", "object", "asynchronously", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L484-L513
train
05bit/peewee-async
peewee_async.py
update_object
async def update_object(obj, only=None): """Update object asynchronously. :param obj: object to update :param only: list or tuple of fields to updata, is `None` then all fields updated This function does the same as `Model.save()`_ for already saved object, but it doesn't invoke ``save()`` method on model class. That is important to know if you overrided save method for your model. .. _Model.save(): http://peewee.readthedocs.io/en/latest/peewee/ api.html#Model.save """ # Here are private calls involved: # # - obj._data # - obj._meta # - obj._prune_fields() # - obj._pk_expr() # - obj._dirty.clear() # warnings.warn("update_object() is deprecated, Manager.update() " "should be used instead", DeprecationWarning) field_dict = dict(obj.__data__) pk_field = obj._meta.primary_key if only: field_dict = obj._prune_fields(field_dict, only) if not isinstance(pk_field, peewee.CompositeKey): field_dict.pop(pk_field.name, None) else: field_dict = obj._prune_fields(field_dict, obj.dirty_fields) rows = await update(obj.update(**field_dict).where(obj._pk_expr())) obj._dirty.clear() return rows
python
async def update_object(obj, only=None): """Update object asynchronously. :param obj: object to update :param only: list or tuple of fields to updata, is `None` then all fields updated This function does the same as `Model.save()`_ for already saved object, but it doesn't invoke ``save()`` method on model class. That is important to know if you overrided save method for your model. .. _Model.save(): http://peewee.readthedocs.io/en/latest/peewee/ api.html#Model.save """ # Here are private calls involved: # # - obj._data # - obj._meta # - obj._prune_fields() # - obj._pk_expr() # - obj._dirty.clear() # warnings.warn("update_object() is deprecated, Manager.update() " "should be used instead", DeprecationWarning) field_dict = dict(obj.__data__) pk_field = obj._meta.primary_key if only: field_dict = obj._prune_fields(field_dict, only) if not isinstance(pk_field, peewee.CompositeKey): field_dict.pop(pk_field.name, None) else: field_dict = obj._prune_fields(field_dict, obj.dirty_fields) rows = await update(obj.update(**field_dict).where(obj._pk_expr())) obj._dirty.clear() return rows
[ "async", "def", "update_object", "(", "obj", ",", "only", "=", "None", ")", ":", "# Here are private calls involved:", "#", "# - obj._data", "# - obj._meta", "# - obj._prune_fields()", "# - obj._pk_expr()", "# - obj._dirty.clear()", "#", "warnings", ".", "warn", "(", "\"update_object() is deprecated, Manager.update() \"", "\"should be used instead\"", ",", "DeprecationWarning", ")", "field_dict", "=", "dict", "(", "obj", ".", "__data__", ")", "pk_field", "=", "obj", ".", "_meta", ".", "primary_key", "if", "only", ":", "field_dict", "=", "obj", ".", "_prune_fields", "(", "field_dict", ",", "only", ")", "if", "not", "isinstance", "(", "pk_field", ",", "peewee", ".", "CompositeKey", ")", ":", "field_dict", ".", "pop", "(", "pk_field", ".", "name", ",", "None", ")", "else", ":", "field_dict", "=", "obj", ".", "_prune_fields", "(", "field_dict", ",", "obj", ".", "dirty_fields", ")", "rows", "=", "await", "update", "(", "obj", ".", "update", "(", "*", "*", "field_dict", ")", ".", "where", "(", "obj", ".", "_pk_expr", "(", ")", ")", ")", "obj", ".", "_dirty", ".", "clear", "(", ")", "return", "rows" ]
Update object asynchronously. :param obj: object to update :param only: list or tuple of fields to updata, is `None` then all fields updated This function does the same as `Model.save()`_ for already saved object, but it doesn't invoke ``save()`` method on model class. That is important to know if you overrided save method for your model. .. _Model.save(): http://peewee.readthedocs.io/en/latest/peewee/ api.html#Model.save
[ "Update", "object", "asynchronously", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L516-L555
train
05bit/peewee-async
peewee_async.py
select
async def select(query): """Perform SELECT query asynchronously. """ assert isinstance(query, peewee.SelectQuery),\ ("Error, trying to run select coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) result = AsyncQueryWrapper(cursor=cursor, query=query) try: while True: await result.fetchone() except GeneratorExit: pass finally: await cursor.release() return result
python
async def select(query): """Perform SELECT query asynchronously. """ assert isinstance(query, peewee.SelectQuery),\ ("Error, trying to run select coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) result = AsyncQueryWrapper(cursor=cursor, query=query) try: while True: await result.fetchone() except GeneratorExit: pass finally: await cursor.release() return result
[ "async", "def", "select", "(", "query", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "SelectQuery", ")", ",", "(", "\"Error, trying to run select coroutine\"", "\"with wrong query class %s\"", "%", "str", "(", "query", ")", ")", "cursor", "=", "await", "_execute_query_async", "(", "query", ")", "result", "=", "AsyncQueryWrapper", "(", "cursor", "=", "cursor", ",", "query", "=", "query", ")", "try", ":", "while", "True", ":", "await", "result", ".", "fetchone", "(", ")", "except", "GeneratorExit", ":", "pass", "finally", ":", "await", "cursor", ".", "release", "(", ")", "return", "result" ]
Perform SELECT query asynchronously.
[ "Perform", "SELECT", "query", "asynchronously", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L558-L577
train
05bit/peewee-async
peewee_async.py
insert
async def insert(query): """Perform INSERT query asynchronously. Returns last insert ID. This function is called by object.create for single objects only. """ assert isinstance(query, peewee.Insert),\ ("Error, trying to run insert coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) try: if query._returning: row = await cursor.fetchone() result = row[0] else: database = _query_db(query) last_id = await database.last_insert_id_async(cursor) result = last_id finally: await cursor.release() return result
python
async def insert(query): """Perform INSERT query asynchronously. Returns last insert ID. This function is called by object.create for single objects only. """ assert isinstance(query, peewee.Insert),\ ("Error, trying to run insert coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) try: if query._returning: row = await cursor.fetchone() result = row[0] else: database = _query_db(query) last_id = await database.last_insert_id_async(cursor) result = last_id finally: await cursor.release() return result
[ "async", "def", "insert", "(", "query", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Insert", ")", ",", "(", "\"Error, trying to run insert coroutine\"", "\"with wrong query class %s\"", "%", "str", "(", "query", ")", ")", "cursor", "=", "await", "_execute_query_async", "(", "query", ")", "try", ":", "if", "query", ".", "_returning", ":", "row", "=", "await", "cursor", ".", "fetchone", "(", ")", "result", "=", "row", "[", "0", "]", "else", ":", "database", "=", "_query_db", "(", "query", ")", "last_id", "=", "await", "database", ".", "last_insert_id_async", "(", "cursor", ")", "result", "=", "last_id", "finally", ":", "await", "cursor", ".", "release", "(", ")", "return", "result" ]
Perform INSERT query asynchronously. Returns last insert ID. This function is called by object.create for single objects only.
[ "Perform", "INSERT", "query", "asynchronously", ".", "Returns", "last", "insert", "ID", ".", "This", "function", "is", "called", "by", "object", ".", "create", "for", "single", "objects", "only", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L580-L601
train
05bit/peewee-async
peewee_async.py
update
async def update(query): """Perform UPDATE query asynchronously. Returns number of rows updated. """ assert isinstance(query, peewee.Update),\ ("Error, trying to run update coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) rowcount = cursor.rowcount await cursor.release() return rowcount
python
async def update(query): """Perform UPDATE query asynchronously. Returns number of rows updated. """ assert isinstance(query, peewee.Update),\ ("Error, trying to run update coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) rowcount = cursor.rowcount await cursor.release() return rowcount
[ "async", "def", "update", "(", "query", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Update", ")", ",", "(", "\"Error, trying to run update coroutine\"", "\"with wrong query class %s\"", "%", "str", "(", "query", ")", ")", "cursor", "=", "await", "_execute_query_async", "(", "query", ")", "rowcount", "=", "cursor", ".", "rowcount", "await", "cursor", ".", "release", "(", ")", "return", "rowcount" ]
Perform UPDATE query asynchronously. Returns number of rows updated.
[ "Perform", "UPDATE", "query", "asynchronously", ".", "Returns", "number", "of", "rows", "updated", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L604-L615
train
05bit/peewee-async
peewee_async.py
delete
async def delete(query): """Perform DELETE query asynchronously. Returns number of rows deleted. """ assert isinstance(query, peewee.Delete),\ ("Error, trying to run delete coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) rowcount = cursor.rowcount await cursor.release() return rowcount
python
async def delete(query): """Perform DELETE query asynchronously. Returns number of rows deleted. """ assert isinstance(query, peewee.Delete),\ ("Error, trying to run delete coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) rowcount = cursor.rowcount await cursor.release() return rowcount
[ "async", "def", "delete", "(", "query", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Delete", ")", ",", "(", "\"Error, trying to run delete coroutine\"", "\"with wrong query class %s\"", "%", "str", "(", "query", ")", ")", "cursor", "=", "await", "_execute_query_async", "(", "query", ")", "rowcount", "=", "cursor", ".", "rowcount", "await", "cursor", ".", "release", "(", ")", "return", "rowcount" ]
Perform DELETE query asynchronously. Returns number of rows deleted.
[ "Perform", "DELETE", "query", "asynchronously", ".", "Returns", "number", "of", "rows", "deleted", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L618-L629
train
05bit/peewee-async
peewee_async.py
sync_unwanted
def sync_unwanted(database): """Context manager for preventing unwanted sync queries. `UnwantedSyncQueryError` exception will raise on such query. NOTE: sync_unwanted() context manager is **deprecated**, use database's `.allow_sync()` context manager or `Manager.allow_sync()` context manager. """ warnings.warn("sync_unwanted() context manager is deprecated, " "use database's `.allow_sync()` context manager or " "`Manager.allow_sync()` context manager. ", DeprecationWarning) old_allow_sync = database._allow_sync database._allow_sync = False yield database._allow_sync = old_allow_sync
python
def sync_unwanted(database): """Context manager for preventing unwanted sync queries. `UnwantedSyncQueryError` exception will raise on such query. NOTE: sync_unwanted() context manager is **deprecated**, use database's `.allow_sync()` context manager or `Manager.allow_sync()` context manager. """ warnings.warn("sync_unwanted() context manager is deprecated, " "use database's `.allow_sync()` context manager or " "`Manager.allow_sync()` context manager. ", DeprecationWarning) old_allow_sync = database._allow_sync database._allow_sync = False yield database._allow_sync = old_allow_sync
[ "def", "sync_unwanted", "(", "database", ")", ":", "warnings", ".", "warn", "(", "\"sync_unwanted() context manager is deprecated, \"", "\"use database's `.allow_sync()` context manager or \"", "\"`Manager.allow_sync()` context manager. \"", ",", "DeprecationWarning", ")", "old_allow_sync", "=", "database", ".", "_allow_sync", "database", ".", "_allow_sync", "=", "False", "yield", "database", ".", "_allow_sync", "=", "old_allow_sync" ]
Context manager for preventing unwanted sync queries. `UnwantedSyncQueryError` exception will raise on such query. NOTE: sync_unwanted() context manager is **deprecated**, use database's `.allow_sync()` context manager or `Manager.allow_sync()` context manager.
[ "Context", "manager", "for", "preventing", "unwanted", "sync", "queries", ".", "UnwantedSyncQueryError", "exception", "will", "raise", "on", "such", "query", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1287-L1302
train
05bit/peewee-async
peewee_async.py
Manager.get
async def get(self, source_, *args, **kwargs): """Get the model instance. :param source_: model or base query for lookup Example:: async def my_async_func(): obj1 = await objects.get(MyModel, id=1) obj2 = await objects.get(MyModel, MyModel.id==1) obj3 = await objects.get(MyModel.select().where(MyModel.id==1)) All will return `MyModel` instance with `id = 1` """ await self.connect() if isinstance(source_, peewee.Query): query = source_ model = query.model else: query = source_.select() model = source_ conditions = list(args) + [(getattr(model, k) == v) for k, v in kwargs.items()] if conditions: query = query.where(*conditions) try: result = await self.execute(query) return list(result)[0] except IndexError: raise model.DoesNotExist
python
async def get(self, source_, *args, **kwargs): """Get the model instance. :param source_: model or base query for lookup Example:: async def my_async_func(): obj1 = await objects.get(MyModel, id=1) obj2 = await objects.get(MyModel, MyModel.id==1) obj3 = await objects.get(MyModel.select().where(MyModel.id==1)) All will return `MyModel` instance with `id = 1` """ await self.connect() if isinstance(source_, peewee.Query): query = source_ model = query.model else: query = source_.select() model = source_ conditions = list(args) + [(getattr(model, k) == v) for k, v in kwargs.items()] if conditions: query = query.where(*conditions) try: result = await self.execute(query) return list(result)[0] except IndexError: raise model.DoesNotExist
[ "async", "def", "get", "(", "self", ",", "source_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "connect", "(", ")", "if", "isinstance", "(", "source_", ",", "peewee", ".", "Query", ")", ":", "query", "=", "source_", "model", "=", "query", ".", "model", "else", ":", "query", "=", "source_", ".", "select", "(", ")", "model", "=", "source_", "conditions", "=", "list", "(", "args", ")", "+", "[", "(", "getattr", "(", "model", ",", "k", ")", "==", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "]", "if", "conditions", ":", "query", "=", "query", ".", "where", "(", "*", "conditions", ")", "try", ":", "result", "=", "await", "self", ".", "execute", "(", "query", ")", "return", "list", "(", "result", ")", "[", "0", "]", "except", "IndexError", ":", "raise", "model", ".", "DoesNotExist" ]
Get the model instance. :param source_: model or base query for lookup Example:: async def my_async_func(): obj1 = await objects.get(MyModel, id=1) obj2 = await objects.get(MyModel, MyModel.id==1) obj3 = await objects.get(MyModel.select().where(MyModel.id==1)) All will return `MyModel` instance with `id = 1`
[ "Get", "the", "model", "instance", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L147-L180
train
05bit/peewee-async
peewee_async.py
Manager.create
async def create(self, model_, **data): """Create a new object saved to database. """ inst = model_(**data) query = model_.insert(**dict(inst.__data__)) pk = await self.execute(query) if inst._pk is None: inst._pk = pk return inst
python
async def create(self, model_, **data): """Create a new object saved to database. """ inst = model_(**data) query = model_.insert(**dict(inst.__data__)) pk = await self.execute(query) if inst._pk is None: inst._pk = pk return inst
[ "async", "def", "create", "(", "self", ",", "model_", ",", "*", "*", "data", ")", ":", "inst", "=", "model_", "(", "*", "*", "data", ")", "query", "=", "model_", ".", "insert", "(", "*", "*", "dict", "(", "inst", ".", "__data__", ")", ")", "pk", "=", "await", "self", ".", "execute", "(", "query", ")", "if", "inst", ".", "_pk", "is", "None", ":", "inst", ".", "_pk", "=", "pk", "return", "inst" ]
Create a new object saved to database.
[ "Create", "a", "new", "object", "saved", "to", "database", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L182-L191
train
05bit/peewee-async
peewee_async.py
Manager.get_or_create
async def get_or_create(self, model_, defaults=None, **kwargs): """Try to get an object or create it with the specified defaults. Return 2-tuple containing the model instance and a boolean indicating whether the instance was created. """ try: return (await self.get(model_, **kwargs)), False except model_.DoesNotExist: data = defaults or {} data.update({k: v for k, v in kwargs.items() if '__' not in k}) return (await self.create(model_, **data)), True
python
async def get_or_create(self, model_, defaults=None, **kwargs): """Try to get an object or create it with the specified defaults. Return 2-tuple containing the model instance and a boolean indicating whether the instance was created. """ try: return (await self.get(model_, **kwargs)), False except model_.DoesNotExist: data = defaults or {} data.update({k: v for k, v in kwargs.items() if '__' not in k}) return (await self.create(model_, **data)), True
[ "async", "def", "get_or_create", "(", "self", ",", "model_", ",", "defaults", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "(", "await", "self", ".", "get", "(", "model_", ",", "*", "*", "kwargs", ")", ")", ",", "False", "except", "model_", ".", "DoesNotExist", ":", "data", "=", "defaults", "or", "{", "}", "data", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "'__'", "not", "in", "k", "}", ")", "return", "(", "await", "self", ".", "create", "(", "model_", ",", "*", "*", "data", ")", ")", ",", "True" ]
Try to get an object or create it with the specified defaults. Return 2-tuple containing the model instance and a boolean indicating whether the instance was created.
[ "Try", "to", "get", "an", "object", "or", "create", "it", "with", "the", "specified", "defaults", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L193-L204
train
05bit/peewee-async
peewee_async.py
Manager.create_or_get
async def create_or_get(self, model_, **kwargs): """Try to create new object with specified data. If object already exists, then try to get it by unique fields. """ try: return (await self.create(model_, **kwargs)), True except IntegrityErrors: query = [] for field_name, value in kwargs.items(): field = getattr(model_, field_name) if field.unique or field.primary_key: query.append(field == value) return (await self.get(model_, *query)), False
python
async def create_or_get(self, model_, **kwargs): """Try to create new object with specified data. If object already exists, then try to get it by unique fields. """ try: return (await self.create(model_, **kwargs)), True except IntegrityErrors: query = [] for field_name, value in kwargs.items(): field = getattr(model_, field_name) if field.unique or field.primary_key: query.append(field == value) return (await self.get(model_, *query)), False
[ "async", "def", "create_or_get", "(", "self", ",", "model_", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "(", "await", "self", ".", "create", "(", "model_", ",", "*", "*", "kwargs", ")", ")", ",", "True", "except", "IntegrityErrors", ":", "query", "=", "[", "]", "for", "field_name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "field", "=", "getattr", "(", "model_", ",", "field_name", ")", "if", "field", ".", "unique", "or", "field", ".", "primary_key", ":", "query", ".", "append", "(", "field", "==", "value", ")", "return", "(", "await", "self", ".", "get", "(", "model_", ",", "*", "query", ")", ")", ",", "False" ]
Try to create new object with specified data. If object already exists, then try to get it by unique fields.
[ "Try", "to", "create", "new", "object", "with", "specified", "data", ".", "If", "object", "already", "exists", "then", "try", "to", "get", "it", "by", "unique", "fields", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L249-L261
train
05bit/peewee-async
peewee_async.py
Manager._subclassed
def _subclassed(base, *classes): """Check if all classes are subclassed from base. """ return all(map(lambda obj: isinstance(obj, base), classes))
python
def _subclassed(base, *classes): """Check if all classes are subclassed from base. """ return all(map(lambda obj: isinstance(obj, base), classes))
[ "def", "_subclassed", "(", "base", ",", "*", "classes", ")", ":", "return", "all", "(", "map", "(", "lambda", "obj", ":", "isinstance", "(", "obj", ",", "base", ")", ",", "classes", ")", ")" ]
Check if all classes are subclassed from base.
[ "Check", "if", "all", "classes", "are", "subclassed", "from", "base", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L382-L385
train
05bit/peewee-async
peewee_async.py
AsyncQueryWrapper._get_result_wrapper
def _get_result_wrapper(self, query): """Get result wrapper class. """ cursor = RowsCursor(self._rows, self._cursor.description) return query._get_cursor_wrapper(cursor)
python
def _get_result_wrapper(self, query): """Get result wrapper class. """ cursor = RowsCursor(self._rows, self._cursor.description) return query._get_cursor_wrapper(cursor)
[ "def", "_get_result_wrapper", "(", "self", ",", "query", ")", ":", "cursor", "=", "RowsCursor", "(", "self", ".", "_rows", ",", "self", ".", "_cursor", ".", "description", ")", "return", "query", ".", "_get_cursor_wrapper", "(", "cursor", ")" ]
Get result wrapper class.
[ "Get", "result", "wrapper", "class", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L775-L779
train
05bit/peewee-async
peewee_async.py
AsyncQueryWrapper.fetchone
async def fetchone(self): """Fetch single row from the cursor. """ row = await self._cursor.fetchone() if not row: raise GeneratorExit self._rows.append(row)
python
async def fetchone(self): """Fetch single row from the cursor. """ row = await self._cursor.fetchone() if not row: raise GeneratorExit self._rows.append(row)
[ "async", "def", "fetchone", "(", "self", ")", ":", "row", "=", "await", "self", ".", "_cursor", ".", "fetchone", "(", ")", "if", "not", "row", ":", "raise", "GeneratorExit", "self", ".", "_rows", ".", "append", "(", "row", ")" ]
Fetch single row from the cursor.
[ "Fetch", "single", "row", "from", "the", "cursor", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L781-L787
train
05bit/peewee-async
peewee_async.py
AsyncDatabase.connect_async
async def connect_async(self, loop=None, timeout=None): """Set up async connection on specified event loop or on default event loop. """ if self.deferred: raise Exception("Error, database not properly initialized " "before opening connection") if self._async_conn: return elif self._async_wait: await self._async_wait else: self._loop = loop self._async_wait = asyncio.Future(loop=self._loop) conn = self._async_conn_cls( database=self.database, loop=self._loop, timeout=timeout, **self.connect_params_async) try: await conn.connect() except Exception as e: if not self._async_wait.done(): self._async_wait.set_exception(e) self._async_wait = None raise else: self._task_data = TaskLocals(loop=self._loop) self._async_conn = conn self._async_wait.set_result(True)
python
async def connect_async(self, loop=None, timeout=None): """Set up async connection on specified event loop or on default event loop. """ if self.deferred: raise Exception("Error, database not properly initialized " "before opening connection") if self._async_conn: return elif self._async_wait: await self._async_wait else: self._loop = loop self._async_wait = asyncio.Future(loop=self._loop) conn = self._async_conn_cls( database=self.database, loop=self._loop, timeout=timeout, **self.connect_params_async) try: await conn.connect() except Exception as e: if not self._async_wait.done(): self._async_wait.set_exception(e) self._async_wait = None raise else: self._task_data = TaskLocals(loop=self._loop) self._async_conn = conn self._async_wait.set_result(True)
[ "async", "def", "connect_async", "(", "self", ",", "loop", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "deferred", ":", "raise", "Exception", "(", "\"Error, database not properly initialized \"", "\"before opening connection\"", ")", "if", "self", ".", "_async_conn", ":", "return", "elif", "self", ".", "_async_wait", ":", "await", "self", ".", "_async_wait", "else", ":", "self", ".", "_loop", "=", "loop", "self", ".", "_async_wait", "=", "asyncio", ".", "Future", "(", "loop", "=", "self", ".", "_loop", ")", "conn", "=", "self", ".", "_async_conn_cls", "(", "database", "=", "self", ".", "database", ",", "loop", "=", "self", ".", "_loop", ",", "timeout", "=", "timeout", ",", "*", "*", "self", ".", "connect_params_async", ")", "try", ":", "await", "conn", ".", "connect", "(", ")", "except", "Exception", "as", "e", ":", "if", "not", "self", ".", "_async_wait", ".", "done", "(", ")", ":", "self", ".", "_async_wait", ".", "set_exception", "(", "e", ")", "self", ".", "_async_wait", "=", "None", "raise", "else", ":", "self", ".", "_task_data", "=", "TaskLocals", "(", "loop", "=", "self", ".", "_loop", ")", "self", ".", "_async_conn", "=", "conn", "self", ".", "_async_wait", ".", "set_result", "(", "True", ")" ]
Set up async connection on specified event loop or on default event loop.
[ "Set", "up", "async", "connection", "on", "specified", "event", "loop", "or", "on", "default", "event", "loop", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L820-L852
train
05bit/peewee-async
peewee_async.py
AsyncDatabase.cursor_async
async def cursor_async(self): """Acquire async cursor. """ await self.connect_async(loop=self._loop) if self.transaction_depth_async() > 0: conn = self.transaction_conn_async() else: conn = None try: return (await self._async_conn.cursor(conn=conn)) except: await self.close_async() raise
python
async def cursor_async(self): """Acquire async cursor. """ await self.connect_async(loop=self._loop) if self.transaction_depth_async() > 0: conn = self.transaction_conn_async() else: conn = None try: return (await self._async_conn.cursor(conn=conn)) except: await self.close_async() raise
[ "async", "def", "cursor_async", "(", "self", ")", ":", "await", "self", ".", "connect_async", "(", "loop", "=", "self", ".", "_loop", ")", "if", "self", ".", "transaction_depth_async", "(", ")", ">", "0", ":", "conn", "=", "self", ".", "transaction_conn_async", "(", ")", "else", ":", "conn", "=", "None", "try", ":", "return", "(", "await", "self", ".", "_async_conn", ".", "cursor", "(", "conn", "=", "conn", ")", ")", "except", ":", "await", "self", ".", "close_async", "(", ")", "raise" ]
Acquire async cursor.
[ "Acquire", "async", "cursor", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L854-L868
train
05bit/peewee-async
peewee_async.py
AsyncDatabase.close_async
async def close_async(self): """Close async connection. """ if self._async_wait: await self._async_wait if self._async_conn: conn = self._async_conn self._async_conn = None self._async_wait = None self._task_data = None await conn.close()
python
async def close_async(self): """Close async connection. """ if self._async_wait: await self._async_wait if self._async_conn: conn = self._async_conn self._async_conn = None self._async_wait = None self._task_data = None await conn.close()
[ "async", "def", "close_async", "(", "self", ")", ":", "if", "self", ".", "_async_wait", ":", "await", "self", ".", "_async_wait", "if", "self", ".", "_async_conn", ":", "conn", "=", "self", ".", "_async_conn", "self", ".", "_async_conn", "=", "None", "self", ".", "_async_wait", "=", "None", "self", ".", "_task_data", "=", "None", "await", "conn", ".", "close", "(", ")" ]
Close async connection.
[ "Close", "async", "connection", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L870-L880
train
05bit/peewee-async
peewee_async.py
AsyncDatabase.push_transaction_async
async def push_transaction_async(self): """Increment async transaction depth. """ await self.connect_async(loop=self.loop) depth = self.transaction_depth_async() if not depth: conn = await self._async_conn.acquire() self._task_data.set('conn', conn) self._task_data.set('depth', depth + 1)
python
async def push_transaction_async(self): """Increment async transaction depth. """ await self.connect_async(loop=self.loop) depth = self.transaction_depth_async() if not depth: conn = await self._async_conn.acquire() self._task_data.set('conn', conn) self._task_data.set('depth', depth + 1)
[ "async", "def", "push_transaction_async", "(", "self", ")", ":", "await", "self", ".", "connect_async", "(", "loop", "=", "self", ".", "loop", ")", "depth", "=", "self", ".", "transaction_depth_async", "(", ")", "if", "not", "depth", ":", "conn", "=", "await", "self", ".", "_async_conn", ".", "acquire", "(", ")", "self", ".", "_task_data", ".", "set", "(", "'conn'", ",", "conn", ")", "self", ".", "_task_data", ".", "set", "(", "'depth'", ",", "depth", "+", "1", ")" ]
Increment async transaction depth.
[ "Increment", "async", "transaction", "depth", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L882-L890
train
05bit/peewee-async
peewee_async.py
AsyncDatabase.pop_transaction_async
async def pop_transaction_async(self): """Decrement async transaction depth. """ depth = self.transaction_depth_async() if depth > 0: depth -= 1 self._task_data.set('depth', depth) if depth == 0: conn = self._task_data.get('conn') self._async_conn.release(conn) else: raise ValueError("Invalid async transaction depth value")
python
async def pop_transaction_async(self): """Decrement async transaction depth. """ depth = self.transaction_depth_async() if depth > 0: depth -= 1 self._task_data.set('depth', depth) if depth == 0: conn = self._task_data.get('conn') self._async_conn.release(conn) else: raise ValueError("Invalid async transaction depth value")
[ "async", "def", "pop_transaction_async", "(", "self", ")", ":", "depth", "=", "self", ".", "transaction_depth_async", "(", ")", "if", "depth", ">", "0", ":", "depth", "-=", "1", "self", ".", "_task_data", ".", "set", "(", "'depth'", ",", "depth", ")", "if", "depth", "==", "0", ":", "conn", "=", "self", ".", "_task_data", ".", "get", "(", "'conn'", ")", "self", ".", "_async_conn", ".", "release", "(", "conn", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid async transaction depth value\"", ")" ]
Decrement async transaction depth.
[ "Decrement", "async", "transaction", "depth", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L892-L903
train
05bit/peewee-async
peewee_async.py
AsyncDatabase.allow_sync
def allow_sync(self): """Allow sync queries within context. Close sync connection on exit if connected. Example:: with database.allow_sync(): PageBlock.create_table(True) """ old_allow_sync = self._allow_sync self._allow_sync = True try: yield except: raise finally: try: self.close() except self.Error: pass # already closed self._allow_sync = old_allow_sync
python
def allow_sync(self): """Allow sync queries within context. Close sync connection on exit if connected. Example:: with database.allow_sync(): PageBlock.create_table(True) """ old_allow_sync = self._allow_sync self._allow_sync = True try: yield except: raise finally: try: self.close() except self.Error: pass # already closed self._allow_sync = old_allow_sync
[ "def", "allow_sync", "(", "self", ")", ":", "old_allow_sync", "=", "self", ".", "_allow_sync", "self", ".", "_allow_sync", "=", "True", "try", ":", "yield", "except", ":", "raise", "finally", ":", "try", ":", "self", ".", "close", "(", ")", "except", "self", ".", "Error", ":", "pass", "# already closed", "self", ".", "_allow_sync", "=", "old_allow_sync" ]
Allow sync queries within context. Close sync connection on exit if connected. Example:: with database.allow_sync(): PageBlock.create_table(True)
[ "Allow", "sync", "queries", "within", "context", ".", "Close", "sync", "connection", "on", "exit", "if", "connected", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L940-L962
train
05bit/peewee-async
peewee_async.py
AsyncDatabase.execute_sql
def execute_sql(self, *args, **kwargs): """Sync execute SQL query, `allow_sync` must be set to True. """ assert self._allow_sync, ( "Error, sync query is not allowed! Call the `.set_allow_sync()` " "or use the `.allow_sync()` context manager.") if self._allow_sync in (logging.ERROR, logging.WARNING): logging.log(self._allow_sync, "Error, sync query is not allowed: %s %s" % (str(args), str(kwargs))) return super().execute_sql(*args, **kwargs)
python
def execute_sql(self, *args, **kwargs): """Sync execute SQL query, `allow_sync` must be set to True. """ assert self._allow_sync, ( "Error, sync query is not allowed! Call the `.set_allow_sync()` " "or use the `.allow_sync()` context manager.") if self._allow_sync in (logging.ERROR, logging.WARNING): logging.log(self._allow_sync, "Error, sync query is not allowed: %s %s" % (str(args), str(kwargs))) return super().execute_sql(*args, **kwargs)
[ "def", "execute_sql", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "_allow_sync", ",", "(", "\"Error, sync query is not allowed! Call the `.set_allow_sync()` \"", "\"or use the `.allow_sync()` context manager.\"", ")", "if", "self", ".", "_allow_sync", "in", "(", "logging", ".", "ERROR", ",", "logging", ".", "WARNING", ")", ":", "logging", ".", "log", "(", "self", ".", "_allow_sync", ",", "\"Error, sync query is not allowed: %s %s\"", "%", "(", "str", "(", "args", ")", ",", "str", "(", "kwargs", ")", ")", ")", "return", "super", "(", ")", ".", "execute_sql", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Sync execute SQL query, `allow_sync` must be set to True.
[ "Sync", "execute", "SQL", "query", "allow_sync", "must", "be", "set", "to", "True", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L964-L974
train
05bit/peewee-async
peewee_async.py
AsyncPostgresqlConnection.cursor
async def cursor(self, conn=None, *args, **kwargs): """Get a cursor for the specified transaction connection or acquire from the pool. """ in_transaction = conn is not None if not conn: conn = await self.acquire() cursor = await conn.cursor(*args, **kwargs) cursor.release = functools.partial( self.release_cursor, cursor, in_transaction=in_transaction) return cursor
python
async def cursor(self, conn=None, *args, **kwargs): """Get a cursor for the specified transaction connection or acquire from the pool. """ in_transaction = conn is not None if not conn: conn = await self.acquire() cursor = await conn.cursor(*args, **kwargs) cursor.release = functools.partial( self.release_cursor, cursor, in_transaction=in_transaction) return cursor
[ "async", "def", "cursor", "(", "self", ",", "conn", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "in_transaction", "=", "conn", "is", "not", "None", "if", "not", "conn", ":", "conn", "=", "await", "self", ".", "acquire", "(", ")", "cursor", "=", "await", "conn", ".", "cursor", "(", "*", "args", ",", "*", "*", "kwargs", ")", "cursor", ".", "release", "=", "functools", ".", "partial", "(", "self", ".", "release_cursor", ",", "cursor", ",", "in_transaction", "=", "in_transaction", ")", "return", "cursor" ]
Get a cursor for the specified transaction connection or acquire from the pool.
[ "Get", "a", "cursor", "for", "the", "specified", "transaction", "connection", "or", "acquire", "from", "the", "pool", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1017-L1028
train
05bit/peewee-async
peewee_async.py
AsyncPostgresqlMixin.connect_params_async
def connect_params_async(self): """Connection parameters for `aiopg.Connection` """ kwargs = self.connect_params.copy() kwargs.update({ 'minsize': self.min_connections, 'maxsize': self.max_connections, 'enable_json': self._enable_json, 'enable_hstore': self._enable_hstore, }) return kwargs
python
def connect_params_async(self): """Connection parameters for `aiopg.Connection` """ kwargs = self.connect_params.copy() kwargs.update({ 'minsize': self.min_connections, 'maxsize': self.max_connections, 'enable_json': self._enable_json, 'enable_hstore': self._enable_hstore, }) return kwargs
[ "def", "connect_params_async", "(", "self", ")", ":", "kwargs", "=", "self", ".", "connect_params", ".", "copy", "(", ")", "kwargs", ".", "update", "(", "{", "'minsize'", ":", "self", ".", "min_connections", ",", "'maxsize'", ":", "self", ".", "max_connections", ",", "'enable_json'", ":", "self", ".", "_enable_json", ",", "'enable_hstore'", ":", "self", ".", "_enable_hstore", ",", "}", ")", "return", "kwargs" ]
Connection parameters for `aiopg.Connection`
[ "Connection", "parameters", "for", "aiopg", ".", "Connection" ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1057-L1067
train
05bit/peewee-async
peewee_async.py
AsyncMySQLConnection.release_cursor
async def release_cursor(self, cursor, in_transaction=False): """Release cursor coroutine. Unless in transaction, the connection is also released back to the pool. """ conn = cursor.connection await cursor.close() if not in_transaction: self.release(conn)
python
async def release_cursor(self, cursor, in_transaction=False): """Release cursor coroutine. Unless in transaction, the connection is also released back to the pool. """ conn = cursor.connection await cursor.close() if not in_transaction: self.release(conn)
[ "async", "def", "release_cursor", "(", "self", ",", "cursor", ",", "in_transaction", "=", "False", ")", ":", "conn", "=", "cursor", ".", "connection", "await", "cursor", ".", "close", "(", ")", "if", "not", "in_transaction", ":", "self", ".", "release", "(", "conn", ")" ]
Release cursor coroutine. Unless in transaction, the connection is also released back to the pool.
[ "Release", "cursor", "coroutine", ".", "Unless", "in", "transaction", "the", "connection", "is", "also", "released", "back", "to", "the", "pool", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1195-L1202
train
05bit/peewee-async
peewee_async.py
MySQLDatabase.connect_params_async
def connect_params_async(self): """Connection parameters for `aiomysql.Connection` """ kwargs = self.connect_params.copy() kwargs.update({ 'minsize': self.min_connections, 'maxsize': self.max_connections, 'autocommit': True, }) return kwargs
python
def connect_params_async(self): """Connection parameters for `aiomysql.Connection` """ kwargs = self.connect_params.copy() kwargs.update({ 'minsize': self.min_connections, 'maxsize': self.max_connections, 'autocommit': True, }) return kwargs
[ "def", "connect_params_async", "(", "self", ")", ":", "kwargs", "=", "self", ".", "connect_params", ".", "copy", "(", ")", "kwargs", ".", "update", "(", "{", "'minsize'", ":", "self", ".", "min_connections", ",", "'maxsize'", ":", "self", ".", "max_connections", ",", "'autocommit'", ":", "True", ",", "}", ")", "return", "kwargs" ]
Connection parameters for `aiomysql.Connection`
[ "Connection", "parameters", "for", "aiomysql", ".", "Connection" ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1229-L1238
train
05bit/peewee-async
peewee_async.py
TaskLocals.get
def get(self, key, *val): """Get value stored for current running task. Optionally you may provide the default value. Raises `KeyError` when can't get the value and no default one is provided. """ data = self.get_data() if data is not None: return data.get(key, *val) if val: return val[0] raise KeyError(key)
python
def get(self, key, *val): """Get value stored for current running task. Optionally you may provide the default value. Raises `KeyError` when can't get the value and no default one is provided. """ data = self.get_data() if data is not None: return data.get(key, *val) if val: return val[0] raise KeyError(key)
[ "def", "get", "(", "self", ",", "key", ",", "*", "val", ")", ":", "data", "=", "self", ".", "get_data", "(", ")", "if", "data", "is", "not", "None", ":", "return", "data", ".", "get", "(", "key", ",", "*", "val", ")", "if", "val", ":", "return", "val", "[", "0", "]", "raise", "KeyError", "(", "key", ")" ]
Get value stored for current running task. Optionally you may provide the default value. Raises `KeyError` when can't get the value and no default one is provided.
[ "Get", "value", "stored", "for", "current", "running", "task", ".", "Optionally", "you", "may", "provide", "the", "default", "value", ".", "Raises", "KeyError", "when", "can", "t", "get", "the", "value", "and", "no", "default", "one", "is", "provided", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1475-L1485
train
05bit/peewee-async
peewee_async.py
TaskLocals.set
def set(self, key, val): """Set value stored for current running task. """ data = self.get_data(True) if data is not None: data[key] = val else: raise RuntimeError("No task is currently running")
python
def set(self, key, val): """Set value stored for current running task. """ data = self.get_data(True) if data is not None: data[key] = val else: raise RuntimeError("No task is currently running")
[ "def", "set", "(", "self", ",", "key", ",", "val", ")", ":", "data", "=", "self", ".", "get_data", "(", "True", ")", "if", "data", "is", "not", "None", ":", "data", "[", "key", "]", "=", "val", "else", ":", "raise", "RuntimeError", "(", "\"No task is currently running\"", ")" ]
Set value stored for current running task.
[ "Set", "value", "stored", "for", "current", "running", "task", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1487-L1494
train
05bit/peewee-async
peewee_async.py
TaskLocals.get_data
def get_data(self, create=False): """Get dict stored for current running task. Return `None` or an empty dict if no data was found depending on the `create` argument value. :param create: if argument is `True`, create empty dict for task, default: `False` """ task = asyncio_current_task(loop=self.loop) if task: task_id = id(task) if create and task_id not in self.data: self.data[task_id] = {} task.add_done_callback(self.del_data) return self.data.get(task_id) return None
python
def get_data(self, create=False): """Get dict stored for current running task. Return `None` or an empty dict if no data was found depending on the `create` argument value. :param create: if argument is `True`, create empty dict for task, default: `False` """ task = asyncio_current_task(loop=self.loop) if task: task_id = id(task) if create and task_id not in self.data: self.data[task_id] = {} task.add_done_callback(self.del_data) return self.data.get(task_id) return None
[ "def", "get_data", "(", "self", ",", "create", "=", "False", ")", ":", "task", "=", "asyncio_current_task", "(", "loop", "=", "self", ".", "loop", ")", "if", "task", ":", "task_id", "=", "id", "(", "task", ")", "if", "create", "and", "task_id", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "task_id", "]", "=", "{", "}", "task", ".", "add_done_callback", "(", "self", ".", "del_data", ")", "return", "self", ".", "data", ".", "get", "(", "task_id", ")", "return", "None" ]
Get dict stored for current running task. Return `None` or an empty dict if no data was found depending on the `create` argument value. :param create: if argument is `True`, create empty dict for task, default: `False`
[ "Get", "dict", "stored", "for", "current", "running", "task", ".", "Return", "None", "or", "an", "empty", "dict", "if", "no", "data", "was", "found", "depending", "on", "the", "create", "argument", "value", "." ]
d15f4629da1d9975da4ec37306188e68d288c862
https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1496-L1511
train
jpype-project/jpype
jpype/_linux.py
LinuxJVMFinder._get_from_bin
def _get_from_bin(self): """ Retrieves the Java library path according to the real installation of the java executable :return: The path to the JVM library, or None """ # Find the real interpreter installation path java_bin = os.path.realpath(self._java) if os.path.exists(java_bin): # Get to the home directory java_home = os.path.abspath(os.path.join(os.path.dirname(java_bin), '..')) # Look for the JVM library return self.find_libjvm(java_home)
python
def _get_from_bin(self): """ Retrieves the Java library path according to the real installation of the java executable :return: The path to the JVM library, or None """ # Find the real interpreter installation path java_bin = os.path.realpath(self._java) if os.path.exists(java_bin): # Get to the home directory java_home = os.path.abspath(os.path.join(os.path.dirname(java_bin), '..')) # Look for the JVM library return self.find_libjvm(java_home)
[ "def", "_get_from_bin", "(", "self", ")", ":", "# Find the real interpreter installation path", "java_bin", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "_java", ")", "if", "os", ".", "path", ".", "exists", "(", "java_bin", ")", ":", "# Get to the home directory", "java_home", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "java_bin", ")", ",", "'..'", ")", ")", "# Look for the JVM library", "return", "self", ".", "find_libjvm", "(", "java_home", ")" ]
Retrieves the Java library path according to the real installation of the java executable :return: The path to the JVM library, or None
[ "Retrieves", "the", "Java", "library", "path", "according", "to", "the", "real", "installation", "of", "the", "java", "executable" ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_linux.py#L49-L64
train
jpype-project/jpype
setupext/build_ext.py
BuildExtCommand.initialize_options
def initialize_options(self, *args): """omit -Wstrict-prototypes from CFLAGS since its only valid for C code.""" import distutils.sysconfig cfg_vars = distutils.sysconfig.get_config_vars() # if 'CFLAGS' in cfg_vars: # cfg_vars['CFLAGS'] = cfg_vars['CFLAGS'].replace('-Wstrict-prototypes', '') for k,v in cfg_vars.items(): if isinstance(v,str) and v.find("-Wstrict-prototypes"): v=v.replace('-Wstrict-prototypes', '') cfg_vars[k]=v if isinstance(v,str) and v.find("-Wimplicit-function-declaration"): v=v.replace('-Wimplicit-function-declaration', '') cfg_vars[k]=v build_ext.initialize_options(self)
python
def initialize_options(self, *args): """omit -Wstrict-prototypes from CFLAGS since its only valid for C code.""" import distutils.sysconfig cfg_vars = distutils.sysconfig.get_config_vars() # if 'CFLAGS' in cfg_vars: # cfg_vars['CFLAGS'] = cfg_vars['CFLAGS'].replace('-Wstrict-prototypes', '') for k,v in cfg_vars.items(): if isinstance(v,str) and v.find("-Wstrict-prototypes"): v=v.replace('-Wstrict-prototypes', '') cfg_vars[k]=v if isinstance(v,str) and v.find("-Wimplicit-function-declaration"): v=v.replace('-Wimplicit-function-declaration', '') cfg_vars[k]=v build_ext.initialize_options(self)
[ "def", "initialize_options", "(", "self", ",", "*", "args", ")", ":", "import", "distutils", ".", "sysconfig", "cfg_vars", "=", "distutils", ".", "sysconfig", ".", "get_config_vars", "(", ")", "# if 'CFLAGS' in cfg_vars:", "# cfg_vars['CFLAGS'] = cfg_vars['CFLAGS'].replace('-Wstrict-prototypes', '')", "for", "k", ",", "v", "in", "cfg_vars", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "str", ")", "and", "v", ".", "find", "(", "\"-Wstrict-prototypes\"", ")", ":", "v", "=", "v", ".", "replace", "(", "'-Wstrict-prototypes'", ",", "''", ")", "cfg_vars", "[", "k", "]", "=", "v", "if", "isinstance", "(", "v", ",", "str", ")", "and", "v", ".", "find", "(", "\"-Wimplicit-function-declaration\"", ")", ":", "v", "=", "v", ".", "replace", "(", "'-Wimplicit-function-declaration'", ",", "''", ")", "cfg_vars", "[", "k", "]", "=", "v", "build_ext", ".", "initialize_options", "(", "self", ")" ]
omit -Wstrict-prototypes from CFLAGS since its only valid for C code.
[ "omit", "-", "Wstrict", "-", "prototypes", "from", "CFLAGS", "since", "its", "only", "valid", "for", "C", "code", "." ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/setupext/build_ext.py#L37-L51
train
jpype-project/jpype
jpype/_classpath.py
addClassPath
def addClassPath(path1): """ Add a path to the java class path""" global _CLASSPATHS path1=_os.path.abspath(path1) if _sys.platform=='cygwin': path1=_posix2win(path1) _CLASSPATHS.add(str(path1))
python
def addClassPath(path1): """ Add a path to the java class path""" global _CLASSPATHS path1=_os.path.abspath(path1) if _sys.platform=='cygwin': path1=_posix2win(path1) _CLASSPATHS.add(str(path1))
[ "def", "addClassPath", "(", "path1", ")", ":", "global", "_CLASSPATHS", "path1", "=", "_os", ".", "path", ".", "abspath", "(", "path1", ")", "if", "_sys", ".", "platform", "==", "'cygwin'", ":", "path1", "=", "_posix2win", "(", "path1", ")", "_CLASSPATHS", ".", "add", "(", "str", "(", "path1", ")", ")" ]
Add a path to the java class path
[ "Add", "a", "path", "to", "the", "java", "class", "path" ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_classpath.py#L57-L63
train
jpype-project/jpype
jpype/_classpath.py
getClassPath
def getClassPath(): """ Get the full java class path. Includes user added paths and the environment CLASSPATH. """ global _CLASSPATHS global _SEP out=[] for path in _CLASSPATHS: if path=='': continue if path.endswith('*'): paths=_glob.glob(path+".jar") if len(path)==0: continue out.extend(paths) else: out.append(path) return _SEP.join(out)
python
def getClassPath(): """ Get the full java class path. Includes user added paths and the environment CLASSPATH. """ global _CLASSPATHS global _SEP out=[] for path in _CLASSPATHS: if path=='': continue if path.endswith('*'): paths=_glob.glob(path+".jar") if len(path)==0: continue out.extend(paths) else: out.append(path) return _SEP.join(out)
[ "def", "getClassPath", "(", ")", ":", "global", "_CLASSPATHS", "global", "_SEP", "out", "=", "[", "]", "for", "path", "in", "_CLASSPATHS", ":", "if", "path", "==", "''", ":", "continue", "if", "path", ".", "endswith", "(", "'*'", ")", ":", "paths", "=", "_glob", ".", "glob", "(", "path", "+", "\".jar\"", ")", "if", "len", "(", "path", ")", "==", "0", ":", "continue", "out", ".", "extend", "(", "paths", ")", "else", ":", "out", ".", "append", "(", "path", ")", "return", "_SEP", ".", "join", "(", "out", ")" ]
Get the full java class path. Includes user added paths and the environment CLASSPATH.
[ "Get", "the", "full", "java", "class", "path", "." ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_classpath.py#L65-L83
train
jpype-project/jpype
jpype/_jvmfinder.py
JVMFinder.find_libjvm
def find_libjvm(self, java_home): """ Recursively looks for the given file :param java_home: A Java home folder :param filename: Name of the file to find :return: The first found file path, or None """ found_jamvm = False non_supported_jvm = ('cacao', 'jamvm') found_non_supported_jvm = False # Look for the file for root, _, names in os.walk(java_home): if self._libfile in names: # Found it, but check for non supported jvms candidate = os.path.split(root)[1] if candidate in non_supported_jvm: found_non_supported_jvm = True continue # maybe we will find another one? return os.path.join(root, self._libfile) else: if found_non_supported_jvm: raise JVMNotSupportedException("Sorry '{0}' is known to be " "broken. Please ensure your " "JAVA_HOME contains at least " "another JVM implementation " "(eg. server)" .format(candidate)) # File not found raise JVMNotFoundException("Sorry no JVM could be found. " "Please ensure your JAVA_HOME " "environment variable is pointing " "to correct installation.")
python
def find_libjvm(self, java_home): """ Recursively looks for the given file :param java_home: A Java home folder :param filename: Name of the file to find :return: The first found file path, or None """ found_jamvm = False non_supported_jvm = ('cacao', 'jamvm') found_non_supported_jvm = False # Look for the file for root, _, names in os.walk(java_home): if self._libfile in names: # Found it, but check for non supported jvms candidate = os.path.split(root)[1] if candidate in non_supported_jvm: found_non_supported_jvm = True continue # maybe we will find another one? return os.path.join(root, self._libfile) else: if found_non_supported_jvm: raise JVMNotSupportedException("Sorry '{0}' is known to be " "broken. Please ensure your " "JAVA_HOME contains at least " "another JVM implementation " "(eg. server)" .format(candidate)) # File not found raise JVMNotFoundException("Sorry no JVM could be found. " "Please ensure your JAVA_HOME " "environment variable is pointing " "to correct installation.")
[ "def", "find_libjvm", "(", "self", ",", "java_home", ")", ":", "found_jamvm", "=", "False", "non_supported_jvm", "=", "(", "'cacao'", ",", "'jamvm'", ")", "found_non_supported_jvm", "=", "False", "# Look for the file", "for", "root", ",", "_", ",", "names", "in", "os", ".", "walk", "(", "java_home", ")", ":", "if", "self", ".", "_libfile", "in", "names", ":", "# Found it, but check for non supported jvms", "candidate", "=", "os", ".", "path", ".", "split", "(", "root", ")", "[", "1", "]", "if", "candidate", "in", "non_supported_jvm", ":", "found_non_supported_jvm", "=", "True", "continue", "# maybe we will find another one?", "return", "os", ".", "path", ".", "join", "(", "root", ",", "self", ".", "_libfile", ")", "else", ":", "if", "found_non_supported_jvm", ":", "raise", "JVMNotSupportedException", "(", "\"Sorry '{0}' is known to be \"", "\"broken. Please ensure your \"", "\"JAVA_HOME contains at least \"", "\"another JVM implementation \"", "\"(eg. server)\"", ".", "format", "(", "candidate", ")", ")", "# File not found", "raise", "JVMNotFoundException", "(", "\"Sorry no JVM could be found. \"", "\"Please ensure your JAVA_HOME \"", "\"environment variable is pointing \"", "\"to correct installation.\"", ")" ]
Recursively looks for the given file :param java_home: A Java home folder :param filename: Name of the file to find :return: The first found file path, or None
[ "Recursively", "looks", "for", "the", "given", "file" ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L48-L82
train
jpype-project/jpype
jpype/_jvmfinder.py
JVMFinder.find_possible_homes
def find_possible_homes(self, parents): """ Generator that looks for the first-level children folders that could be Java installations, according to their name :param parents: A list of parent directories :return: The possible JVM installation folders """ homes = [] java_names = ('jre', 'jdk', 'java') for parent in parents: for childname in sorted(os.listdir(parent)): # Compute the real path path = os.path.realpath(os.path.join(parent, childname)) if path in homes or not os.path.isdir(path): # Already known path, or not a directory -> ignore continue # Check if the path seems OK real_name = os.path.basename(path).lower() for java_name in java_names: if java_name in real_name: # Correct JVM folder name homes.append(path) yield path break
python
def find_possible_homes(self, parents): """ Generator that looks for the first-level children folders that could be Java installations, according to their name :param parents: A list of parent directories :return: The possible JVM installation folders """ homes = [] java_names = ('jre', 'jdk', 'java') for parent in parents: for childname in sorted(os.listdir(parent)): # Compute the real path path = os.path.realpath(os.path.join(parent, childname)) if path in homes or not os.path.isdir(path): # Already known path, or not a directory -> ignore continue # Check if the path seems OK real_name = os.path.basename(path).lower() for java_name in java_names: if java_name in real_name: # Correct JVM folder name homes.append(path) yield path break
[ "def", "find_possible_homes", "(", "self", ",", "parents", ")", ":", "homes", "=", "[", "]", "java_names", "=", "(", "'jre'", ",", "'jdk'", ",", "'java'", ")", "for", "parent", "in", "parents", ":", "for", "childname", "in", "sorted", "(", "os", ".", "listdir", "(", "parent", ")", ")", ":", "# Compute the real path", "path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "parent", ",", "childname", ")", ")", "if", "path", "in", "homes", "or", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "# Already known path, or not a directory -> ignore", "continue", "# Check if the path seems OK", "real_name", "=", "os", ".", "path", ".", "basename", "(", "path", ")", ".", "lower", "(", ")", "for", "java_name", "in", "java_names", ":", "if", "java_name", "in", "real_name", ":", "# Correct JVM folder name", "homes", ".", "append", "(", "path", ")", "yield", "path", "break" ]
Generator that looks for the first-level children folders that could be Java installations, according to their name :param parents: A list of parent directories :return: The possible JVM installation folders
[ "Generator", "that", "looks", "for", "the", "first", "-", "level", "children", "folders", "that", "could", "be", "Java", "installations", "according", "to", "their", "name" ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L85-L111
train
jpype-project/jpype
jpype/_jvmfinder.py
JVMFinder._get_from_java_home
def _get_from_java_home(self): """ Retrieves the Java library path according to the JAVA_HOME environment variable :return: The path to the JVM library, or None """ # Get the environment variable java_home = os.getenv("JAVA_HOME") if java_home and os.path.exists(java_home): # Get the real installation path java_home = os.path.realpath(java_home) # Cygwin has a bug in realpath if not os.path.exists(java_home): java_home = os.getenv("JAVA_HOME") # Look for the library file return self.find_libjvm(java_home)
python
def _get_from_java_home(self): """ Retrieves the Java library path according to the JAVA_HOME environment variable :return: The path to the JVM library, or None """ # Get the environment variable java_home = os.getenv("JAVA_HOME") if java_home and os.path.exists(java_home): # Get the real installation path java_home = os.path.realpath(java_home) # Cygwin has a bug in realpath if not os.path.exists(java_home): java_home = os.getenv("JAVA_HOME") # Look for the library file return self.find_libjvm(java_home)
[ "def", "_get_from_java_home", "(", "self", ")", ":", "# Get the environment variable", "java_home", "=", "os", ".", "getenv", "(", "\"JAVA_HOME\"", ")", "if", "java_home", "and", "os", ".", "path", ".", "exists", "(", "java_home", ")", ":", "# Get the real installation path", "java_home", "=", "os", ".", "path", ".", "realpath", "(", "java_home", ")", "# Cygwin has a bug in realpath", "if", "not", "os", ".", "path", ".", "exists", "(", "java_home", ")", ":", "java_home", "=", "os", ".", "getenv", "(", "\"JAVA_HOME\"", ")", "# Look for the library file", "return", "self", ".", "find_libjvm", "(", "java_home", ")" ]
Retrieves the Java library path according to the JAVA_HOME environment variable :return: The path to the JVM library, or None
[ "Retrieves", "the", "Java", "library", "path", "according", "to", "the", "JAVA_HOME", "environment", "variable" ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L156-L174
train
jpype-project/jpype
jpype/_jvmfinder.py
JVMFinder._get_from_known_locations
def _get_from_known_locations(self): """ Retrieves the first existing Java library path in the predefined known locations :return: The path to the JVM library, or None """ for home in self.find_possible_homes(self._locations): jvm = self.find_libjvm(home) if jvm is not None: return jvm
python
def _get_from_known_locations(self): """ Retrieves the first existing Java library path in the predefined known locations :return: The path to the JVM library, or None """ for home in self.find_possible_homes(self._locations): jvm = self.find_libjvm(home) if jvm is not None: return jvm
[ "def", "_get_from_known_locations", "(", "self", ")", ":", "for", "home", "in", "self", ".", "find_possible_homes", "(", "self", ".", "_locations", ")", ":", "jvm", "=", "self", ".", "find_libjvm", "(", "home", ")", "if", "jvm", "is", "not", "None", ":", "return", "jvm" ]
Retrieves the first existing Java library path in the predefined known locations :return: The path to the JVM library, or None
[ "Retrieves", "the", "first", "existing", "Java", "library", "path", "in", "the", "predefined", "known", "locations" ]
3ce953ae7b35244077249ce650b9acd0a7010d17
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L177-L187
train
graphql-python/gql
gql-checker/gql_checker/__init__.py
ImportVisitor.node_query
def node_query(self, node): """ Return the query for the gql call node """ if isinstance(node, ast.Call): assert node.args arg = node.args[0] if not isinstance(arg, ast.Str): return else: raise TypeError(type(node)) return arg.s
python
def node_query(self, node): """ Return the query for the gql call node """ if isinstance(node, ast.Call): assert node.args arg = node.args[0] if not isinstance(arg, ast.Str): return else: raise TypeError(type(node)) return arg.s
[ "def", "node_query", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "Call", ")", ":", "assert", "node", ".", "args", "arg", "=", "node", ".", "args", "[", "0", "]", "if", "not", "isinstance", "(", "arg", ",", "ast", ".", "Str", ")", ":", "return", "else", ":", "raise", "TypeError", "(", "type", "(", "node", ")", ")", "return", "arg", ".", "s" ]
Return the query for the gql call node
[ "Return", "the", "query", "for", "the", "gql", "call", "node" ]
3653bb5260b60a6c72d0bb0137874fb40969a826
https://github.com/graphql-python/gql/blob/3653bb5260b60a6c72d0bb0137874fb40969a826/gql-checker/gql_checker/__init__.py#L36-L49
train
SmileyChris/easy-thumbnails
easy_thumbnails/namers.py
default
def default(thumbnailer, prepared_options, source_filename, thumbnail_extension, **kwargs): """ Easy-thumbnails' default name processor. For example: ``source.jpg.100x100_q80_crop_upscale.jpg`` """ filename_parts = [source_filename] if ('%(opts)s' in thumbnailer.thumbnail_basedir or '%(opts)s' in thumbnailer.thumbnail_subdir): if thumbnail_extension != os.path.splitext(source_filename)[1][1:]: filename_parts.append(thumbnail_extension) else: filename_parts += ['_'.join(prepared_options), thumbnail_extension] return '.'.join(filename_parts)
python
def default(thumbnailer, prepared_options, source_filename, thumbnail_extension, **kwargs): """ Easy-thumbnails' default name processor. For example: ``source.jpg.100x100_q80_crop_upscale.jpg`` """ filename_parts = [source_filename] if ('%(opts)s' in thumbnailer.thumbnail_basedir or '%(opts)s' in thumbnailer.thumbnail_subdir): if thumbnail_extension != os.path.splitext(source_filename)[1][1:]: filename_parts.append(thumbnail_extension) else: filename_parts += ['_'.join(prepared_options), thumbnail_extension] return '.'.join(filename_parts)
[ "def", "default", "(", "thumbnailer", ",", "prepared_options", ",", "source_filename", ",", "thumbnail_extension", ",", "*", "*", "kwargs", ")", ":", "filename_parts", "=", "[", "source_filename", "]", "if", "(", "'%(opts)s'", "in", "thumbnailer", ".", "thumbnail_basedir", "or", "'%(opts)s'", "in", "thumbnailer", ".", "thumbnail_subdir", ")", ":", "if", "thumbnail_extension", "!=", "os", ".", "path", ".", "splitext", "(", "source_filename", ")", "[", "1", "]", "[", "1", ":", "]", ":", "filename_parts", ".", "append", "(", "thumbnail_extension", ")", "else", ":", "filename_parts", "+=", "[", "'_'", ".", "join", "(", "prepared_options", ")", ",", "thumbnail_extension", "]", "return", "'.'", ".", "join", "(", "filename_parts", ")" ]
Easy-thumbnails' default name processor. For example: ``source.jpg.100x100_q80_crop_upscale.jpg``
[ "Easy", "-", "thumbnails", "default", "name", "processor", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/namers.py#L7-L21
train
SmileyChris/easy-thumbnails
easy_thumbnails/namers.py
hashed
def hashed(source_filename, prepared_options, thumbnail_extension, **kwargs): """ Generate a short hashed thumbnail filename. Creates a 12 character url-safe base64 sha1 filename (plus the extension), for example: ``6qW1buHgLaZ9.jpg``. """ parts = ':'.join([source_filename] + prepared_options) short_sha = hashlib.sha1(parts.encode('utf-8')).digest() short_hash = base64.urlsafe_b64encode(short_sha[:9]).decode('utf-8') return '.'.join([short_hash, thumbnail_extension])
python
def hashed(source_filename, prepared_options, thumbnail_extension, **kwargs): """ Generate a short hashed thumbnail filename. Creates a 12 character url-safe base64 sha1 filename (plus the extension), for example: ``6qW1buHgLaZ9.jpg``. """ parts = ':'.join([source_filename] + prepared_options) short_sha = hashlib.sha1(parts.encode('utf-8')).digest() short_hash = base64.urlsafe_b64encode(short_sha[:9]).decode('utf-8') return '.'.join([short_hash, thumbnail_extension])
[ "def", "hashed", "(", "source_filename", ",", "prepared_options", ",", "thumbnail_extension", ",", "*", "*", "kwargs", ")", ":", "parts", "=", "':'", ".", "join", "(", "[", "source_filename", "]", "+", "prepared_options", ")", "short_sha", "=", "hashlib", ".", "sha1", "(", "parts", ".", "encode", "(", "'utf-8'", ")", ")", ".", "digest", "(", ")", "short_hash", "=", "base64", ".", "urlsafe_b64encode", "(", "short_sha", "[", ":", "9", "]", ")", ".", "decode", "(", "'utf-8'", ")", "return", "'.'", ".", "join", "(", "[", "short_hash", ",", "thumbnail_extension", "]", ")" ]
Generate a short hashed thumbnail filename. Creates a 12 character url-safe base64 sha1 filename (plus the extension), for example: ``6qW1buHgLaZ9.jpg``.
[ "Generate", "a", "short", "hashed", "thumbnail", "filename", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/namers.py#L34-L44
train
SmileyChris/easy-thumbnails
easy_thumbnails/namers.py
source_hashed
def source_hashed(source_filename, prepared_options, thumbnail_extension, **kwargs): """ Generate a thumbnail filename of the source filename and options separately hashed, along with the size. The format of the filename is a 12 character base64 sha1 hash of the source filename, the size surrounded by underscores, and an 8 character options base64 sha1 hash of the thumbnail options. For example: ``1xedFtqllFo9_100x100_QHCa6G1l.jpg``. """ source_sha = hashlib.sha1(source_filename.encode('utf-8')).digest() source_hash = base64.urlsafe_b64encode(source_sha[:9]).decode('utf-8') parts = ':'.join(prepared_options[1:]) parts_sha = hashlib.sha1(parts.encode('utf-8')).digest() options_hash = base64.urlsafe_b64encode(parts_sha[:6]).decode('utf-8') return '%s_%s_%s.%s' % ( source_hash, prepared_options[0], options_hash, thumbnail_extension)
python
def source_hashed(source_filename, prepared_options, thumbnail_extension, **kwargs): """ Generate a thumbnail filename of the source filename and options separately hashed, along with the size. The format of the filename is a 12 character base64 sha1 hash of the source filename, the size surrounded by underscores, and an 8 character options base64 sha1 hash of the thumbnail options. For example: ``1xedFtqllFo9_100x100_QHCa6G1l.jpg``. """ source_sha = hashlib.sha1(source_filename.encode('utf-8')).digest() source_hash = base64.urlsafe_b64encode(source_sha[:9]).decode('utf-8') parts = ':'.join(prepared_options[1:]) parts_sha = hashlib.sha1(parts.encode('utf-8')).digest() options_hash = base64.urlsafe_b64encode(parts_sha[:6]).decode('utf-8') return '%s_%s_%s.%s' % ( source_hash, prepared_options[0], options_hash, thumbnail_extension)
[ "def", "source_hashed", "(", "source_filename", ",", "prepared_options", ",", "thumbnail_extension", ",", "*", "*", "kwargs", ")", ":", "source_sha", "=", "hashlib", ".", "sha1", "(", "source_filename", ".", "encode", "(", "'utf-8'", ")", ")", ".", "digest", "(", ")", "source_hash", "=", "base64", ".", "urlsafe_b64encode", "(", "source_sha", "[", ":", "9", "]", ")", ".", "decode", "(", "'utf-8'", ")", "parts", "=", "':'", ".", "join", "(", "prepared_options", "[", "1", ":", "]", ")", "parts_sha", "=", "hashlib", ".", "sha1", "(", "parts", ".", "encode", "(", "'utf-8'", ")", ")", ".", "digest", "(", ")", "options_hash", "=", "base64", ".", "urlsafe_b64encode", "(", "parts_sha", "[", ":", "6", "]", ")", ".", "decode", "(", "'utf-8'", ")", "return", "'%s_%s_%s.%s'", "%", "(", "source_hash", ",", "prepared_options", "[", "0", "]", ",", "options_hash", ",", "thumbnail_extension", ")" ]
Generate a thumbnail filename of the source filename and options separately hashed, along with the size. The format of the filename is a 12 character base64 sha1 hash of the source filename, the size surrounded by underscores, and an 8 character options base64 sha1 hash of the thumbnail options. For example: ``1xedFtqllFo9_100x100_QHCa6G1l.jpg``.
[ "Generate", "a", "thumbnail", "filename", "of", "the", "source", "filename", "and", "options", "separately", "hashed", "along", "with", "the", "size", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/namers.py#L47-L64
train
SmileyChris/easy-thumbnails
easy_thumbnails/engine.py
save_image
def save_image(image, destination=None, filename=None, **options): """ Save a PIL image. """ if destination is None: destination = BytesIO() filename = filename or '' # Ensure plugins are fully loaded so that Image.EXTENSION is populated. Image.init() format = Image.EXTENSION.get(os.path.splitext(filename)[1].lower(), 'JPEG') if format in ('JPEG', 'WEBP'): options.setdefault('quality', 85) saved = False if format == 'JPEG': if image.mode.endswith('A'): # From PIL 4.2, saving an image with a transparency layer raises an # IOError, so explicitly remove it. image = image.convert(image.mode[:-1]) if settings.THUMBNAIL_PROGRESSIVE and ( max(image.size) >= settings.THUMBNAIL_PROGRESSIVE): options['progressive'] = True try: image.save(destination, format=format, optimize=1, **options) saved = True except IOError: # Try again, without optimization (PIL can't optimize an image # larger than ImageFile.MAXBLOCK, which is 64k by default). This # shouldn't be triggered very often these days, as recent versions # of pillow avoid the MAXBLOCK limitation. pass if not saved: image.save(destination, format=format, **options) if hasattr(destination, 'seek'): destination.seek(0) return destination
python
def save_image(image, destination=None, filename=None, **options): """ Save a PIL image. """ if destination is None: destination = BytesIO() filename = filename or '' # Ensure plugins are fully loaded so that Image.EXTENSION is populated. Image.init() format = Image.EXTENSION.get(os.path.splitext(filename)[1].lower(), 'JPEG') if format in ('JPEG', 'WEBP'): options.setdefault('quality', 85) saved = False if format == 'JPEG': if image.mode.endswith('A'): # From PIL 4.2, saving an image with a transparency layer raises an # IOError, so explicitly remove it. image = image.convert(image.mode[:-1]) if settings.THUMBNAIL_PROGRESSIVE and ( max(image.size) >= settings.THUMBNAIL_PROGRESSIVE): options['progressive'] = True try: image.save(destination, format=format, optimize=1, **options) saved = True except IOError: # Try again, without optimization (PIL can't optimize an image # larger than ImageFile.MAXBLOCK, which is 64k by default). This # shouldn't be triggered very often these days, as recent versions # of pillow avoid the MAXBLOCK limitation. pass if not saved: image.save(destination, format=format, **options) if hasattr(destination, 'seek'): destination.seek(0) return destination
[ "def", "save_image", "(", "image", ",", "destination", "=", "None", ",", "filename", "=", "None", ",", "*", "*", "options", ")", ":", "if", "destination", "is", "None", ":", "destination", "=", "BytesIO", "(", ")", "filename", "=", "filename", "or", "''", "# Ensure plugins are fully loaded so that Image.EXTENSION is populated.", "Image", ".", "init", "(", ")", "format", "=", "Image", ".", "EXTENSION", ".", "get", "(", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "lower", "(", ")", ",", "'JPEG'", ")", "if", "format", "in", "(", "'JPEG'", ",", "'WEBP'", ")", ":", "options", ".", "setdefault", "(", "'quality'", ",", "85", ")", "saved", "=", "False", "if", "format", "==", "'JPEG'", ":", "if", "image", ".", "mode", ".", "endswith", "(", "'A'", ")", ":", "# From PIL 4.2, saving an image with a transparency layer raises an", "# IOError, so explicitly remove it.", "image", "=", "image", ".", "convert", "(", "image", ".", "mode", "[", ":", "-", "1", "]", ")", "if", "settings", ".", "THUMBNAIL_PROGRESSIVE", "and", "(", "max", "(", "image", ".", "size", ")", ">=", "settings", ".", "THUMBNAIL_PROGRESSIVE", ")", ":", "options", "[", "'progressive'", "]", "=", "True", "try", ":", "image", ".", "save", "(", "destination", ",", "format", "=", "format", ",", "optimize", "=", "1", ",", "*", "*", "options", ")", "saved", "=", "True", "except", "IOError", ":", "# Try again, without optimization (PIL can't optimize an image", "# larger than ImageFile.MAXBLOCK, which is 64k by default). This", "# shouldn't be triggered very often these days, as recent versions", "# of pillow avoid the MAXBLOCK limitation.", "pass", "if", "not", "saved", ":", "image", ".", "save", "(", "destination", ",", "format", "=", "format", ",", "*", "*", "options", ")", "if", "hasattr", "(", "destination", ",", "'seek'", ")", ":", "destination", ".", "seek", "(", "0", ")", "return", "destination" ]
Save a PIL image.
[ "Save", "a", "PIL", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/engine.py#L44-L78
train
SmileyChris/easy-thumbnails
easy_thumbnails/engine.py
generate_source_image
def generate_source_image(source_file, processor_options, generators=None, fail_silently=True): """ Processes a source ``File`` through a series of source generators, stopping once a generator returns an image. The return value is this image instance or ``None`` if no generators return an image. If the source file cannot be opened, it will be set to ``None`` and still passed to the generators. """ processor_options = ThumbnailOptions(processor_options) # Keep record of whether the source file was originally closed. Not all # file-like objects provide this attribute, so just fall back to False. was_closed = getattr(source_file, 'closed', False) if generators is None: generators = [ utils.dynamic_import(name) for name in settings.THUMBNAIL_SOURCE_GENERATORS] exceptions = [] try: for generator in generators: source = source_file # First try to open the file. try: source.open() except Exception: # If that failed, maybe the file-like object doesn't support # reopening so just try seeking back to the start of the file. try: source.seek(0) except Exception: source = None try: image = generator(source, **processor_options) except Exception as e: if not fail_silently: if len(generators) == 1: raise exceptions.append(e) image = None if image: return image finally: # Attempt to close the file if it was closed originally (but fail # silently). if was_closed: try: source_file.close() except Exception: pass if exceptions and not fail_silently: raise NoSourceGenerator(*exceptions)
python
def generate_source_image(source_file, processor_options, generators=None, fail_silently=True): """ Processes a source ``File`` through a series of source generators, stopping once a generator returns an image. The return value is this image instance or ``None`` if no generators return an image. If the source file cannot be opened, it will be set to ``None`` and still passed to the generators. """ processor_options = ThumbnailOptions(processor_options) # Keep record of whether the source file was originally closed. Not all # file-like objects provide this attribute, so just fall back to False. was_closed = getattr(source_file, 'closed', False) if generators is None: generators = [ utils.dynamic_import(name) for name in settings.THUMBNAIL_SOURCE_GENERATORS] exceptions = [] try: for generator in generators: source = source_file # First try to open the file. try: source.open() except Exception: # If that failed, maybe the file-like object doesn't support # reopening so just try seeking back to the start of the file. try: source.seek(0) except Exception: source = None try: image = generator(source, **processor_options) except Exception as e: if not fail_silently: if len(generators) == 1: raise exceptions.append(e) image = None if image: return image finally: # Attempt to close the file if it was closed originally (but fail # silently). if was_closed: try: source_file.close() except Exception: pass if exceptions and not fail_silently: raise NoSourceGenerator(*exceptions)
[ "def", "generate_source_image", "(", "source_file", ",", "processor_options", ",", "generators", "=", "None", ",", "fail_silently", "=", "True", ")", ":", "processor_options", "=", "ThumbnailOptions", "(", "processor_options", ")", "# Keep record of whether the source file was originally closed. Not all", "# file-like objects provide this attribute, so just fall back to False.", "was_closed", "=", "getattr", "(", "source_file", ",", "'closed'", ",", "False", ")", "if", "generators", "is", "None", ":", "generators", "=", "[", "utils", ".", "dynamic_import", "(", "name", ")", "for", "name", "in", "settings", ".", "THUMBNAIL_SOURCE_GENERATORS", "]", "exceptions", "=", "[", "]", "try", ":", "for", "generator", "in", "generators", ":", "source", "=", "source_file", "# First try to open the file.", "try", ":", "source", ".", "open", "(", ")", "except", "Exception", ":", "# If that failed, maybe the file-like object doesn't support", "# reopening so just try seeking back to the start of the file.", "try", ":", "source", ".", "seek", "(", "0", ")", "except", "Exception", ":", "source", "=", "None", "try", ":", "image", "=", "generator", "(", "source", ",", "*", "*", "processor_options", ")", "except", "Exception", "as", "e", ":", "if", "not", "fail_silently", ":", "if", "len", "(", "generators", ")", "==", "1", ":", "raise", "exceptions", ".", "append", "(", "e", ")", "image", "=", "None", "if", "image", ":", "return", "image", "finally", ":", "# Attempt to close the file if it was closed originally (but fail", "# silently).", "if", "was_closed", ":", "try", ":", "source_file", ".", "close", "(", ")", "except", "Exception", ":", "pass", "if", "exceptions", "and", "not", "fail_silently", ":", "raise", "NoSourceGenerator", "(", "*", "exceptions", ")" ]
Processes a source ``File`` through a series of source generators, stopping once a generator returns an image. The return value is this image instance or ``None`` if no generators return an image. If the source file cannot be opened, it will be set to ``None`` and still passed to the generators.
[ "Processes", "a", "source", "File", "through", "a", "series", "of", "source", "generators", "stopping", "once", "a", "generator", "returns", "an", "image", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/engine.py#L81-L134
train
SmileyChris/easy-thumbnails
easy_thumbnails/conf.py
AppSettings.revert
def revert(self): """ Revert any changes made to settings. """ for attr, value in self._changed.items(): setattr(django_settings, attr, value) for attr in self._added: delattr(django_settings, attr) self._changed = {} self._added = [] if self.isolated: self._isolated_overrides = BaseSettings()
python
def revert(self): """ Revert any changes made to settings. """ for attr, value in self._changed.items(): setattr(django_settings, attr, value) for attr in self._added: delattr(django_settings, attr) self._changed = {} self._added = [] if self.isolated: self._isolated_overrides = BaseSettings()
[ "def", "revert", "(", "self", ")", ":", "for", "attr", ",", "value", "in", "self", ".", "_changed", ".", "items", "(", ")", ":", "setattr", "(", "django_settings", ",", "attr", ",", "value", ")", "for", "attr", "in", "self", ".", "_added", ":", "delattr", "(", "django_settings", ",", "attr", ")", "self", ".", "_changed", "=", "{", "}", "self", ".", "_added", "=", "[", "]", "if", "self", ".", "isolated", ":", "self", ".", "_isolated_overrides", "=", "BaseSettings", "(", ")" ]
Revert any changes made to settings.
[ "Revert", "any", "changes", "made", "to", "settings", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/conf.py#L32-L43
train
SmileyChris/easy-thumbnails
easy_thumbnails/source_generators.py
pil_image
def pil_image(source, exif_orientation=True, **options): """ Try to open the source file directly using PIL, ignoring any errors. exif_orientation If EXIF orientation data is present, perform any required reorientation before passing the data along the processing pipeline. """ # Use a BytesIO wrapper because if the source is an incomplete file like # object, PIL may have problems with it. For example, some image types # require tell and seek methods that are not present on all storage # File objects. if not source: return source = BytesIO(source.read()) image = Image.open(source) # Fully load the image now to catch any problems with the image contents. try: # An "Image file truncated" exception can occur for some images that # are still mostly valid -- we'll swallow the exception. image.load() except IOError: pass # Try a second time to catch any other potential exceptions. image.load() if exif_orientation: image = utils.exif_orientation(image) return image
python
def pil_image(source, exif_orientation=True, **options): """ Try to open the source file directly using PIL, ignoring any errors. exif_orientation If EXIF orientation data is present, perform any required reorientation before passing the data along the processing pipeline. """ # Use a BytesIO wrapper because if the source is an incomplete file like # object, PIL may have problems with it. For example, some image types # require tell and seek methods that are not present on all storage # File objects. if not source: return source = BytesIO(source.read()) image = Image.open(source) # Fully load the image now to catch any problems with the image contents. try: # An "Image file truncated" exception can occur for some images that # are still mostly valid -- we'll swallow the exception. image.load() except IOError: pass # Try a second time to catch any other potential exceptions. image.load() if exif_orientation: image = utils.exif_orientation(image) return image
[ "def", "pil_image", "(", "source", ",", "exif_orientation", "=", "True", ",", "*", "*", "options", ")", ":", "# Use a BytesIO wrapper because if the source is an incomplete file like", "# object, PIL may have problems with it. For example, some image types", "# require tell and seek methods that are not present on all storage", "# File objects.", "if", "not", "source", ":", "return", "source", "=", "BytesIO", "(", "source", ".", "read", "(", ")", ")", "image", "=", "Image", ".", "open", "(", "source", ")", "# Fully load the image now to catch any problems with the image contents.", "try", ":", "# An \"Image file truncated\" exception can occur for some images that", "# are still mostly valid -- we'll swallow the exception.", "image", ".", "load", "(", ")", "except", "IOError", ":", "pass", "# Try a second time to catch any other potential exceptions.", "image", ".", "load", "(", ")", "if", "exif_orientation", ":", "image", "=", "utils", ".", "exif_orientation", "(", "image", ")", "return", "image" ]
Try to open the source file directly using PIL, ignoring any errors. exif_orientation If EXIF orientation data is present, perform any required reorientation before passing the data along the processing pipeline.
[ "Try", "to", "open", "the", "source", "file", "directly", "using", "PIL", "ignoring", "any", "errors", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/source_generators.py#L14-L45
train
SmileyChris/easy-thumbnails
easy_thumbnails/optimize/post_processor.py
optimize_thumbnail
def optimize_thumbnail(thumbnail): '''Optimize thumbnail images by removing unnecessary data''' try: optimize_command = settings.THUMBNAIL_OPTIMIZE_COMMAND[ determinetype(thumbnail.path)] if not optimize_command: return except (TypeError, KeyError, NotImplementedError): return storage = thumbnail.storage try: with NamedTemporaryFile() as temp_file: thumbnail.seek(0) temp_file.write(thumbnail.read()) temp_file.flush() optimize_command = optimize_command.format(filename=temp_file.name) output = check_output( optimize_command, stderr=subprocess.STDOUT, shell=True) if output: logger.warning( '{0} returned {1}'.format(optimize_command, output)) else: logger.info('{0} returned nothing'.format(optimize_command)) with open(temp_file.name, 'rb') as f: thumbnail.file = ContentFile(f.read()) storage.delete(thumbnail.path) storage.save(thumbnail.path, thumbnail) except Exception as e: logger.error(e)
python
def optimize_thumbnail(thumbnail): '''Optimize thumbnail images by removing unnecessary data''' try: optimize_command = settings.THUMBNAIL_OPTIMIZE_COMMAND[ determinetype(thumbnail.path)] if not optimize_command: return except (TypeError, KeyError, NotImplementedError): return storage = thumbnail.storage try: with NamedTemporaryFile() as temp_file: thumbnail.seek(0) temp_file.write(thumbnail.read()) temp_file.flush() optimize_command = optimize_command.format(filename=temp_file.name) output = check_output( optimize_command, stderr=subprocess.STDOUT, shell=True) if output: logger.warning( '{0} returned {1}'.format(optimize_command, output)) else: logger.info('{0} returned nothing'.format(optimize_command)) with open(temp_file.name, 'rb') as f: thumbnail.file = ContentFile(f.read()) storage.delete(thumbnail.path) storage.save(thumbnail.path, thumbnail) except Exception as e: logger.error(e)
[ "def", "optimize_thumbnail", "(", "thumbnail", ")", ":", "try", ":", "optimize_command", "=", "settings", ".", "THUMBNAIL_OPTIMIZE_COMMAND", "[", "determinetype", "(", "thumbnail", ".", "path", ")", "]", "if", "not", "optimize_command", ":", "return", "except", "(", "TypeError", ",", "KeyError", ",", "NotImplementedError", ")", ":", "return", "storage", "=", "thumbnail", ".", "storage", "try", ":", "with", "NamedTemporaryFile", "(", ")", "as", "temp_file", ":", "thumbnail", ".", "seek", "(", "0", ")", "temp_file", ".", "write", "(", "thumbnail", ".", "read", "(", ")", ")", "temp_file", ".", "flush", "(", ")", "optimize_command", "=", "optimize_command", ".", "format", "(", "filename", "=", "temp_file", ".", "name", ")", "output", "=", "check_output", "(", "optimize_command", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "True", ")", "if", "output", ":", "logger", ".", "warning", "(", "'{0} returned {1}'", ".", "format", "(", "optimize_command", ",", "output", ")", ")", "else", ":", "logger", ".", "info", "(", "'{0} returned nothing'", ".", "format", "(", "optimize_command", ")", ")", "with", "open", "(", "temp_file", ".", "name", ",", "'rb'", ")", "as", "f", ":", "thumbnail", ".", "file", "=", "ContentFile", "(", "f", ".", "read", "(", ")", ")", "storage", ".", "delete", "(", "thumbnail", ".", "path", ")", "storage", ".", "save", "(", "thumbnail", ".", "path", ",", "thumbnail", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "e", ")" ]
Optimize thumbnail images by removing unnecessary data
[ "Optimize", "thumbnail", "images", "by", "removing", "unnecessary", "data" ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/optimize/post_processor.py#L37-L65
train
SmileyChris/easy-thumbnails
easy_thumbnails/templatetags/thumbnail.py
thumbnail
def thumbnail(parser, token): """ Creates a thumbnail of an ImageField. Basic tag Syntax:: {% thumbnail [source] [size] [options] %} *source* must be a ``File`` object, usually an Image/FileField of a model instance. *size* can either be: * the name of an alias * the size in the format ``[width]x[height]`` (for example, ``{% thumbnail person.photo 100x50 %}``) or * a variable containing a valid size (i.e. either a string in the ``[width]x[height]`` format or a tuple containing two integers): ``{% thumbnail person.photo size_var %}``. *options* are a space separated list of options which are used when processing the image to a thumbnail such as ``sharpen``, ``crop`` and ``quality=90``. If *size* is specified as an alias name, *options* are used to override and/or supplement the options defined in that alias. The thumbnail tag can also place a :class:`~easy_thumbnails.files.ThumbnailFile` object in the context, providing access to the properties of the thumbnail such as the height and width:: {% thumbnail [source] [size] [options] as [variable] %} When ``as [variable]`` is used, the tag doesn't output anything. Instead, use the variable like a standard ``ImageFieldFile`` object:: {% thumbnail obj.picture 200x200 upscale as thumb %} <img src="{{ thumb.url }}" width="{{ thumb.width }}" height="{{ thumb.height }}" /> **Debugging** By default, if there is an error creating the thumbnail or resolving the image variable then the thumbnail tag will just return an empty string (and if there was a context variable to be set then it will also be set to an empty string). For example, you will not see an error if the thumbnail could not be written to directory because of permissions error. To display those errors rather than failing silently, set ``THUMBNAIL_DEBUG = True`` in your Django project's settings module. """ args = token.split_contents() tag = args[0] # Check to see if we're setting to a context variable. if len(args) > 4 and args[-2] == 'as': context_name = args[-1] args = args[:-2] else: context_name = None if len(args) < 3: raise TemplateSyntaxError( "Invalid syntax. Expected " "'{%% %s source size [option1 option2 ...] %%}' or " "'{%% %s source size [option1 option2 ...] as variable %%}'" % (tag, tag)) opts = {} # The first argument is the source file. source_var = parser.compile_filter(args[1]) # The second argument is the requested size. If it's the static "10x10" # format, wrap it in quotes so that it is compiled correctly. size = args[2] match = RE_SIZE.match(size) if match: size = '"%s"' % size opts['size'] = parser.compile_filter(size) # All further arguments are options. args_list = split_args(args[3:]).items() for arg, value in args_list: if arg in VALID_OPTIONS: if value and value is not True: value = parser.compile_filter(value) opts[arg] = value else: raise TemplateSyntaxError("'%s' tag received a bad argument: " "'%s'" % (tag, arg)) return ThumbnailNode(source_var, opts=opts, context_name=context_name)
python
def thumbnail(parser, token): """ Creates a thumbnail of an ImageField. Basic tag Syntax:: {% thumbnail [source] [size] [options] %} *source* must be a ``File`` object, usually an Image/FileField of a model instance. *size* can either be: * the name of an alias * the size in the format ``[width]x[height]`` (for example, ``{% thumbnail person.photo 100x50 %}``) or * a variable containing a valid size (i.e. either a string in the ``[width]x[height]`` format or a tuple containing two integers): ``{% thumbnail person.photo size_var %}``. *options* are a space separated list of options which are used when processing the image to a thumbnail such as ``sharpen``, ``crop`` and ``quality=90``. If *size* is specified as an alias name, *options* are used to override and/or supplement the options defined in that alias. The thumbnail tag can also place a :class:`~easy_thumbnails.files.ThumbnailFile` object in the context, providing access to the properties of the thumbnail such as the height and width:: {% thumbnail [source] [size] [options] as [variable] %} When ``as [variable]`` is used, the tag doesn't output anything. Instead, use the variable like a standard ``ImageFieldFile`` object:: {% thumbnail obj.picture 200x200 upscale as thumb %} <img src="{{ thumb.url }}" width="{{ thumb.width }}" height="{{ thumb.height }}" /> **Debugging** By default, if there is an error creating the thumbnail or resolving the image variable then the thumbnail tag will just return an empty string (and if there was a context variable to be set then it will also be set to an empty string). For example, you will not see an error if the thumbnail could not be written to directory because of permissions error. To display those errors rather than failing silently, set ``THUMBNAIL_DEBUG = True`` in your Django project's settings module. """ args = token.split_contents() tag = args[0] # Check to see if we're setting to a context variable. if len(args) > 4 and args[-2] == 'as': context_name = args[-1] args = args[:-2] else: context_name = None if len(args) < 3: raise TemplateSyntaxError( "Invalid syntax. Expected " "'{%% %s source size [option1 option2 ...] %%}' or " "'{%% %s source size [option1 option2 ...] as variable %%}'" % (tag, tag)) opts = {} # The first argument is the source file. source_var = parser.compile_filter(args[1]) # The second argument is the requested size. If it's the static "10x10" # format, wrap it in quotes so that it is compiled correctly. size = args[2] match = RE_SIZE.match(size) if match: size = '"%s"' % size opts['size'] = parser.compile_filter(size) # All further arguments are options. args_list = split_args(args[3:]).items() for arg, value in args_list: if arg in VALID_OPTIONS: if value and value is not True: value = parser.compile_filter(value) opts[arg] = value else: raise TemplateSyntaxError("'%s' tag received a bad argument: " "'%s'" % (tag, arg)) return ThumbnailNode(source_var, opts=opts, context_name=context_name)
[ "def", "thumbnail", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "tag", "=", "args", "[", "0", "]", "# Check to see if we're setting to a context variable.", "if", "len", "(", "args", ")", ">", "4", "and", "args", "[", "-", "2", "]", "==", "'as'", ":", "context_name", "=", "args", "[", "-", "1", "]", "args", "=", "args", "[", ":", "-", "2", "]", "else", ":", "context_name", "=", "None", "if", "len", "(", "args", ")", "<", "3", ":", "raise", "TemplateSyntaxError", "(", "\"Invalid syntax. Expected \"", "\"'{%% %s source size [option1 option2 ...] %%}' or \"", "\"'{%% %s source size [option1 option2 ...] as variable %%}'\"", "%", "(", "tag", ",", "tag", ")", ")", "opts", "=", "{", "}", "# The first argument is the source file.", "source_var", "=", "parser", ".", "compile_filter", "(", "args", "[", "1", "]", ")", "# The second argument is the requested size. If it's the static \"10x10\"", "# format, wrap it in quotes so that it is compiled correctly.", "size", "=", "args", "[", "2", "]", "match", "=", "RE_SIZE", ".", "match", "(", "size", ")", "if", "match", ":", "size", "=", "'\"%s\"'", "%", "size", "opts", "[", "'size'", "]", "=", "parser", ".", "compile_filter", "(", "size", ")", "# All further arguments are options.", "args_list", "=", "split_args", "(", "args", "[", "3", ":", "]", ")", ".", "items", "(", ")", "for", "arg", ",", "value", "in", "args_list", ":", "if", "arg", "in", "VALID_OPTIONS", ":", "if", "value", "and", "value", "is", "not", "True", ":", "value", "=", "parser", ".", "compile_filter", "(", "value", ")", "opts", "[", "arg", "]", "=", "value", "else", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' tag received a bad argument: \"", "\"'%s'\"", "%", "(", "tag", ",", "arg", ")", ")", "return", "ThumbnailNode", "(", "source_var", ",", "opts", "=", "opts", ",", "context_name", "=", "context_name", ")" ]
Creates a thumbnail of an ImageField. Basic tag Syntax:: {% thumbnail [source] [size] [options] %} *source* must be a ``File`` object, usually an Image/FileField of a model instance. *size* can either be: * the name of an alias * the size in the format ``[width]x[height]`` (for example, ``{% thumbnail person.photo 100x50 %}``) or * a variable containing a valid size (i.e. either a string in the ``[width]x[height]`` format or a tuple containing two integers): ``{% thumbnail person.photo size_var %}``. *options* are a space separated list of options which are used when processing the image to a thumbnail such as ``sharpen``, ``crop`` and ``quality=90``. If *size* is specified as an alias name, *options* are used to override and/or supplement the options defined in that alias. The thumbnail tag can also place a :class:`~easy_thumbnails.files.ThumbnailFile` object in the context, providing access to the properties of the thumbnail such as the height and width:: {% thumbnail [source] [size] [options] as [variable] %} When ``as [variable]`` is used, the tag doesn't output anything. Instead, use the variable like a standard ``ImageFieldFile`` object:: {% thumbnail obj.picture 200x200 upscale as thumb %} <img src="{{ thumb.url }}" width="{{ thumb.width }}" height="{{ thumb.height }}" /> **Debugging** By default, if there is an error creating the thumbnail or resolving the image variable then the thumbnail tag will just return an empty string (and if there was a context variable to be set then it will also be set to an empty string). For example, you will not see an error if the thumbnail could not be written to directory because of permissions error. To display those errors rather than failing silently, set ``THUMBNAIL_DEBUG = True`` in your Django project's settings module.
[ "Creates", "a", "thumbnail", "of", "an", "ImageField", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/templatetags/thumbnail.py#L135-L232
train
SmileyChris/easy-thumbnails
easy_thumbnails/templatetags/thumbnail.py
thumbnail_url
def thumbnail_url(source, alias): """ Return the thumbnail url for a source file using an aliased set of thumbnail options. If no matching alias is found, returns an empty string. Example usage:: <img src="{{ person.photo|thumbnail_url:'small' }}" alt=""> """ try: thumb = get_thumbnailer(source)[alias] except Exception: return '' return thumb.url
python
def thumbnail_url(source, alias): """ Return the thumbnail url for a source file using an aliased set of thumbnail options. If no matching alias is found, returns an empty string. Example usage:: <img src="{{ person.photo|thumbnail_url:'small' }}" alt=""> """ try: thumb = get_thumbnailer(source)[alias] except Exception: return '' return thumb.url
[ "def", "thumbnail_url", "(", "source", ",", "alias", ")", ":", "try", ":", "thumb", "=", "get_thumbnailer", "(", "source", ")", "[", "alias", "]", "except", "Exception", ":", "return", "''", "return", "thumb", ".", "url" ]
Return the thumbnail url for a source file using an aliased set of thumbnail options. If no matching alias is found, returns an empty string. Example usage:: <img src="{{ person.photo|thumbnail_url:'small' }}" alt="">
[ "Return", "the", "thumbnail", "url", "for", "a", "source", "file", "using", "an", "aliased", "set", "of", "thumbnail", "options", "." ]
b08ab44883bf7b221a98dadb9b589cb95d35b0bf
https://github.com/SmileyChris/easy-thumbnails/blob/b08ab44883bf7b221a98dadb9b589cb95d35b0bf/easy_thumbnails/templatetags/thumbnail.py#L287-L302
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train