idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
241,500
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' , 'django.forms.forms.Form' , '.Form' , 'django.forms.models.ModelForm' , '.ModelForm' ) return node_is_subclass ( node . parent , * p...
Checks that node is derivative of MPTTMeta class .
241,501
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 if node_is_subclass ( cls , * parents ) or cls . qname ( ) in pa...
Checks that node is an attribute used inside one of allowed parents
241,502
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 .
241,503
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...
Checks that node is get or post method of the View class .
241,504
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 .
241,505
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 .
241,506
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 .
241,507
def load_configuration ( linter ) : name_checker = get_checker ( linter , NameChecker ) name_checker . config . good_names += ( 'qs' , 'urlpatterns' , 'register' , 'app_name' , 'handler500' ) linter . config . black_list += ( 'migrations' , 'south_migrations' )
Amend existing checker config .
241,508
def register ( linter ) : register_checkers ( linter ) try : from pylint_django . augmentations import apply_augmentations apply_augmentations ( linter ) except ImportError : pass if not compat . LOAD_CONFIGURATION_SUPPORTED : load_configuration ( linter )
Registering additional checkers .
241,509
async def create_object ( model , ** data ) : 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 .
241,510
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 for obj in ( await select ( query ....
Get object asynchronously .
241,511
async def delete_object ( obj , recursive = False , delete_nullable = False ) : warnings . warn ( "delete_object() is deprecated, Manager.delete() " "should be used instead" , DeprecationWarning ) if recursive : dependencies = obj . dependencies ( delete_nullable ) for query , fk in reversed ( list ( dependencies ) ) :...
Delete object asynchronously .
241,512
async def update_object ( obj , only = None ) : 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 isinstanc...
Update object asynchronously .
241,513
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 . fetchon...
Perform SELECT query asynchronously .
241,514
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_d...
Perform INSERT query asynchronously . Returns last insert ID . This function is called by object . create for single objects only .
241,515
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 .
241,516
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 .
241,517
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 ...
Context manager for preventing unwanted sync queries . UnwantedSyncQueryError exception will raise on such query .
241,518
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 condi...
Get the model instance .
241,519
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 .
241,520
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 ) ...
Try to get an object or create it with the specified defaults .
241,521
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 == valu...
Try to create new object with specified data . If object already exists then try to get it by unique fields .
241,522
def _subclassed ( base , * classes ) : return all ( map ( lambda obj : isinstance ( obj , base ) , classes ) )
Check if all classes are subclassed from base .
241,523
def _get_result_wrapper ( self , query ) : cursor = RowsCursor ( self . _rows , self . _cursor . description ) return query . _get_cursor_wrapper ( cursor )
Get result wrapper class .
241,524
async def fetchone ( self ) : row = await self . _cursor . fetchone ( ) if not row : raise GeneratorExit self . _rows . append ( row )
Fetch single row from the cursor .
241,525
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 . F...
Set up async connection on specified event loop or on default event loop .
241,526
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 .
241,527
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 .
241,528
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 .
241,529
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 .
241,530
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 self . _allow_sync = old_allow_sync
Allow sync queries within context . Close sync connection on exit if connected .
241,531
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 no...
Sync execute SQL query allow_sync must be set to True .
241,532
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 .
241,533
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
241,534
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 .
241,535
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
241,536
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 .
241,537
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 .
241,538
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 .
241,539
def _get_from_bin ( self ) : java_bin = os . path . realpath ( self . _java ) if os . path . exists ( java_bin ) : java_home = os . path . abspath ( os . path . join ( os . path . dirname ( java_bin ) , '..' ) ) return self . find_libjvm ( java_home )
Retrieves the Java library path according to the real installation of the java executable
241,540
def initialize_options ( self , * args ) : import distutils . sysconfig cfg_vars = distutils . sysconfig . get_config_vars ( ) 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 ...
omit - Wstrict - prototypes from CFLAGS since its only valid for C code .
241,541
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
241,542
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 .
241,543
def find_libjvm ( self , java_home ) : found_jamvm = False non_supported_jvm = ( 'cacao' , 'jamvm' ) found_non_supported_jvm = False for root , _ , names in os . walk ( java_home ) : if self . _libfile in names : candidate = os . path . split ( root ) [ 1 ] if candidate in non_supported_jvm : found_non_supported_jvm = ...
Recursively looks for the given file
241,544
def find_possible_homes ( self , parents ) : homes = [ ] java_names = ( 'jre' , 'jdk' , 'java' ) for parent in parents : for childname in sorted ( os . listdir ( parent ) ) : path = os . path . realpath ( os . path . join ( parent , childname ) ) if path in homes or not os . path . isdir ( path ) : continue real_name =...
Generator that looks for the first - level children folders that could be Java installations according to their name
241,545
def _get_from_java_home ( self ) : java_home = os . getenv ( "JAVA_HOME" ) if java_home and os . path . exists ( java_home ) : java_home = os . path . realpath ( java_home ) if not os . path . exists ( java_home ) : java_home = os . getenv ( "JAVA_HOME" ) return self . find_libjvm ( java_home )
Retrieves the Java library path according to the JAVA_HOME environment variable
241,546
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
241,547
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
241,548
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 : ...
Easy - thumbnails default name processor .
241,549
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 ...
Generate a short hashed thumbnail filename .
241,550
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 = ...
Generate a thumbnail filename of the source filename and options separately hashed along with the size .
241,551
def save_image ( image , destination = None , filename = None , ** options ) : if destination is None : destination = BytesIO ( ) filename = filename or '' Image . init ( ) format = Image . EXTENSION . get ( os . path . splitext ( filename ) [ 1 ] . lower ( ) , 'JPEG' ) if format in ( 'JPEG' , 'WEBP' ) : options . setd...
Save a PIL image .
241,552
def generate_source_image ( source_file , processor_options , generators = None , fail_silently = True ) : processor_options = ThumbnailOptions ( processor_options ) was_closed = getattr ( source_file , 'closed' , False ) if generators is None : generators = [ utils . dynamic_import ( name ) for name in settings . THUM...
Processes a source File through a series of source generators stopping once a generator returns an image .
241,553
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 .
241,554
def pil_image ( source , exif_orientation = True , ** options ) : if not source : return source = BytesIO ( source . read ( ) ) image = Image . open ( source ) try : image . load ( ) except IOError : pass image . load ( ) if exif_orientation : image = utils . exif_orientation ( image ) return image
Try to open the source file directly using PIL ignoring any errors .
241,555
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 : thum...
Optimize thumbnail images by removing unnecessary data
241,556
def thumbnail ( parser , token ) : args = token . split_contents ( ) tag = args [ 0 ] 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 op...
Creates a thumbnail of an ImageField .
241,557
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 .
241,558
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 , ...
This filter will return the base64 encoded data URI for a given thumbnail object .
241,559
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 .
241,560
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 . ...
Return a dictionary referencing all files which match the thumbnail format .
241,561
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 . THU...
Return a list of dictionaries one for each thumbnail belonging to the source image .
241,562
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 .
241,563
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 .
241,564
def signal_committed_filefields ( sender , instance , ** kwargs ) : for field_name in getattr ( instance , '_uncommitted_filefields' , ( ) ) : fieldfile = getattr ( instance , field_name ) 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 .
241,565
def generate_aliases ( fieldfile , ** kwargs ) : 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 .
241,566
def generate_aliases_global ( fieldfile , ** kwargs ) : 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 .
241,567
def colorspace ( im , bw = False , replace_alpha = False , ** kwargs ) : if im . mode == 'I' : 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...
Convert images to the correct color space .
241,568
def autocrop ( im , autocrop = False , ** kwargs ) : if autocrop : 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' ) bw = no_alpha . convert ( 'L' ) bg = Image . new ( 'L' , im . size , 2...
Remove any unnecessary whitespace from the edges of the source image .
241,569
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 .
241,570
def background ( im , size , background = None , ** kwargs ) : if not background : return im if not size [ 0 ] or not size [ 1 ] : return im x , y = im . size if x >= size [ 0 ] and y >= size [ 1 ] : return im im = colorspace ( im , replace_alpha = background , ** kwargs ) new_im = Image . new ( 'RGB' , size , backgrou...
Add borders of a certain color to make the resized image fit exactly within the dimensions given .
241,571
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 .
241,572
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 .
241,573
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 .
241,574
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 .
241,575
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' ] min_dim , max_dim = 0 , 0 for dim in orig_size : try : dim = int ( dim ) except ( TypeError , ValueErr...
Return an unsaved ThumbnailFile containing a thumbnail image .
241,576
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_...
Return a ThumbnailFile containing an existing thumbnail for a set of thumbnail options or None if not found .
241,577
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 generat...
Return a ThumbnailFile containing a thumbnail .
241,578
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 ) if settings . THUMBNAI...
Save a thumbnail to the thumbnail_storage .
241,579
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 = sou...
Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail .
241,580
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 .
241,581
def delete ( self , * args , ** kwargs ) : source_cache = self . get_source_cache ( ) self . delete_thumbnails ( source_cache ) super ( ThumbnailerFieldFile , self ) . delete ( * args , ** kwargs ) if source_cache and source_cache . pk is not None : source_cache . delete ( )
Delete the image along with any generated thumbnails .
241,582
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 ( ) : if thumbnail_cache . storage_hash == thumbnail_stora...
Delete any thumbnails generated from the source image .
241,583
def get_thumbnails ( self , * args , ** kwargs ) : 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 ( ) : if thumbnail_cache . storage_hash == thumbnail_storage_hash : yield ...
Return an iterator which returns ThumbnailFile instances .
241,584
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 ) orig_name , ext = os . path . splite...
Save the image .
241,585
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...
The queryset iterator helps to keep the memory consumption down . And also making it easier to process for weaker computers .
241,586
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} ...
Print statistics about the cleanup performed .
241,587
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 .
241,588
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 .
241,589
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 .
241,590
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 .
241,591
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 .
241,592
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 .
241,593
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_...
Internal method to coerce a target to a string .
241,594
def image_entropy ( im ) : if not isinstance ( im , Image . Image ) : 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 .
241,595
def dynamic_import ( import_string ) : 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 ( p...
Dynamically import a module or object .
241,596
def is_transparent ( image ) : if not isinstance ( image , Image . Image ) : 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 .
241,597
def is_progressive ( image ) : if not isinstance ( image , Image . Image ) : return False return ( 'progressive' in image . info ) or ( 'progression' in image . info )
Check to see if an image is progressive .
241,598
def get_modified_time ( storage , name ) : try : try : 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 ...
Get modified time from storage ensuring the result is a timezone - aware datetime .
241,599
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...
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 a...