idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
246,300 | def get ( self , id ) : args = parser . parse_args ( ) model = self . model . objects . only ( 'id' ) . get_or_404 ( id = id ) qs = Follow . objects ( following = model , until = None ) return qs . paginate ( args [ 'page' ] , args [ 'page_size' ] ) | List all followers for a given object | 80 | 7 |
246,301 | def post ( self , id ) : model = self . model . objects . only ( 'id' ) . get_or_404 ( id = id ) follow , created = Follow . objects . get_or_create ( follower = current_user . id , following = model , until = None ) count = Follow . objects . followers ( model ) . count ( ) if not current_app . config [ 'TESTING' ] : ... | Follow an object given its ID | 126 | 6 |
246,302 | def delete ( self , id ) : model = self . model . objects . only ( 'id' ) . get_or_404 ( id = id ) follow = Follow . objects . get_or_404 ( follower = current_user . id , following = model , until = None ) follow . until = datetime . now ( ) follow . save ( ) count = Follow . objects . followers ( model ) . count ( ) r... | Unfollow an object given its ID | 101 | 7 |
246,303 | def error ( msg , details = None ) : msg = '{0} {1}' . format ( red ( KO ) , white ( safe_unicode ( msg ) ) ) msg = safe_unicode ( msg ) if details : msg = b'\n' . join ( ( msg , safe_unicode ( details ) ) ) echo ( format_multiline ( msg ) ) | Display an error message with optional details | 84 | 7 |
246,304 | def main ( self , * args , * * kwargs ) : obj = kwargs . get ( 'obj' ) if obj is None : obj = ScriptInfo ( create_app = self . create_app ) # This is the import line: allows create_app to access the settings obj . settings = kwargs . pop ( 'settings' , 'udata.settings.Defaults' ) kwargs [ 'obj' ] = obj return super ( U... | Instanciate ScriptInfo before parent does to ensure the settings parameters is available to create_app | 117 | 20 |
246,305 | def get_plugins_dists ( app , name = None ) : if name : plugins = set ( e . name for e in iter_all ( name ) if e . name in app . config [ 'PLUGINS' ] ) else : plugins = set ( app . config [ 'PLUGINS' ] ) return [ d for d in known_dists ( ) if any ( set ( v . keys ( ) ) & plugins for v in d . get_entry_map ( ) . values ... | Return a list of Distributions with enabled udata plugins | 110 | 11 |
246,306 | def lazy_raise_or_redirect ( ) : if not request . view_args : return for name , value in request . view_args . items ( ) : if isinstance ( value , NotFound ) : request . routing_exception = value break elif isinstance ( value , LazyRedirect ) : new_args = request . view_args new_args [ name ] = value . arg new_url = ur... | Raise exception lazily to ensure request . endpoint is set Also perform redirect if needed | 112 | 17 |
246,307 | def to_python ( self , value ) : if '/' not in value : return level , code = value . split ( '/' ) [ : 2 ] # Ignore optional slug geoid = GeoZone . SEPARATOR . join ( [ level , code ] ) zone = GeoZone . objects . resolve ( geoid ) if not zone and GeoZone . SEPARATOR not in level : # Try implicit default prefix level = ... | value has slashs in it that s why we inherit from PathConverter . | 147 | 17 |
246,308 | def to_url ( self , obj ) : level_name = getattr ( obj , 'level_name' , None ) if not level_name : raise ValueError ( 'Unable to serialize "%s" to url' % obj ) code = getattr ( obj , 'code' , None ) slug = getattr ( obj , 'slug' , None ) validity = getattr ( obj , 'validity' , None ) if code and slug : return '{level_n... | Reconstruct the URL from level name code or datagouv id and slug . | 181 | 18 |
246,309 | def job ( name , * * kwargs ) : return task ( name = name , schedulable = True , base = JobTask , bind = True , * * kwargs ) | A shortcut decorator for declaring jobs | 40 | 7 |
246,310 | def apply_async ( self , entry , * * kwargs ) : result = super ( Scheduler , self ) . apply_async ( entry , * * kwargs ) entry . _task . last_run_id = result . id return result | A MongoScheduler storing the last task_id | 56 | 11 |
246,311 | def config ( ) : if hasattr ( current_app , 'settings_file' ) : log . info ( 'Loaded configuration from %s' , current_app . settings_file ) log . info ( white ( 'Current configuration' ) ) for key in sorted ( current_app . config ) : if key . startswith ( '__' ) or not key . isupper ( ) : continue echo ( '{0}: {1}' . f... | Display some details about the local configuration | 114 | 7 |
246,312 | def plugins ( ) : plugins = current_app . config [ 'PLUGINS' ] for name , description in entrypoints . ENTRYPOINTS . items ( ) : echo ( '{0} ({1})' . format ( white ( description ) , name ) ) if name == 'udata.themes' : actives = [ current_app . config [ 'THEME' ] ] elif name == 'udata.avatars' : actives = [ avatar_con... | Display some details about the local plugins | 169 | 7 |
246,313 | def can ( self , * args , * * kwargs ) : if isinstance ( self . require , auth . Permission ) : return self . require . can ( ) elif callable ( self . require ) : return self . require ( ) elif isinstance ( self . require , bool ) : return self . require else : return True | Overwrite this method to implement custom contextual permissions | 73 | 9 |
246,314 | def extension ( filename ) : filename = os . path . basename ( filename ) extension = None while '.' in filename : filename , ext = os . path . splitext ( filename ) if ext . startswith ( '.' ) : ext = ext [ 1 : ] extension = ext if not extension else ext + '.' + extension return extension | Properly extract the extension from filename | 73 | 8 |
246,315 | def theme_static_with_version ( ctx , filename , external = False ) : if current_app . theme_manager . static_folder : url = assets . cdn_for ( '_themes.static' , filename = current . identifier + '/' + filename , _external = external ) else : url = assets . cdn_for ( '_themes.static' , themeid = current . identifier ,... | Override the default theme static to add cache burst | 175 | 9 |
246,316 | def render ( template , * * context ) : theme = current_app . config [ 'THEME' ] return render_theme_template ( get_theme ( theme ) , template , * * context ) | Render a template with uData frontend specifics | 44 | 9 |
246,317 | def context ( name ) : def wrapper ( func ) : g . theme . context_processors [ name ] = func return func return wrapper | A decorator for theme context processors | 29 | 7 |
246,318 | def variant ( self ) : variant = current_app . config [ 'THEME_VARIANT' ] if variant not in self . variants : log . warning ( 'Unkown theme variant: %s' , variant ) return 'default' else : return variant | Get the current theme variant | 57 | 5 |
246,319 | def resource_redirect ( id ) : resource = get_resource ( id ) return redirect ( resource . url . strip ( ) ) if resource else abort ( 404 ) | Redirect to the latest version of a resource given its identifier . | 35 | 13 |
246,320 | def group_resources_by_type ( resources ) : groups = defaultdict ( list ) for resource in resources : groups [ getattr ( resource , 'type' ) ] . append ( resource ) ordered = OrderedDict ( ) for rtype , rtype_label in RESOURCE_TYPES . items ( ) : if groups [ rtype ] : ordered [ ( rtype , rtype_label ) ] = groups [ rtyp... | Group a list of resources by type with order | 96 | 9 |
246,321 | def aggregate ( self , start , end ) : last = self . objects ( level = 'daily' , date__lte = self . iso ( end ) , date__gte = self . iso ( start ) ) . order_by ( '-date' ) . first ( ) return last . values [ self . name ] | This method encpsualte the metric aggregation logic . Override this method when you inherit this class . By default it takes the last value . | 69 | 29 |
246,322 | def paginate_sources ( owner = None , page = 1 , page_size = DEFAULT_PAGE_SIZE ) : sources = _sources_queryset ( owner = owner ) page = max ( page or 1 , 1 ) return sources . paginate ( page , page_size ) | Paginate harvest sources | 64 | 5 |
246,323 | def update_source ( ident , data ) : source = get_source ( ident ) source . modify ( * * data ) signals . harvest_source_updated . send ( source ) return source | Update an harvest source | 40 | 4 |
246,324 | def validate_source ( ident , comment = None ) : source = get_source ( ident ) source . validation . on = datetime . now ( ) source . validation . comment = comment source . validation . state = VALIDATION_ACCEPTED if current_user . is_authenticated : source . validation . by = current_user . _get_current_object ( ) so... | Validate a source for automatic harvesting | 120 | 7 |
246,325 | def reject_source ( ident , comment ) : source = get_source ( ident ) source . validation . on = datetime . now ( ) source . validation . comment = comment source . validation . state = VALIDATION_REFUSED if current_user . is_authenticated : source . validation . by = current_user . _get_current_object ( ) source . sav... | Reject a source for automatic harvesting | 85 | 7 |
246,326 | def delete_source ( ident ) : source = get_source ( ident ) source . deleted = datetime . now ( ) source . save ( ) signals . harvest_source_deleted . send ( source ) return source | Delete an harvest source | 46 | 4 |
246,327 | def run ( ident ) : source = get_source ( ident ) cls = backends . get ( current_app , source . backend ) backend = cls ( source ) backend . harvest ( ) | Launch or resume an harvesting for a given source if none is running | 42 | 13 |
246,328 | def preview ( ident ) : source = get_source ( ident ) cls = backends . get ( current_app , source . backend ) max_items = current_app . config [ 'HARVEST_PREVIEW_MAX_ITEMS' ] backend = cls ( source , dryrun = True , max_items = max_items ) return backend . harvest ( ) | Preview an harvesting for a given source | 81 | 7 |
246,329 | def preview_from_config ( name , url , backend , description = None , frequency = DEFAULT_HARVEST_FREQUENCY , owner = None , organization = None , config = None , ) : if owner and not isinstance ( owner , User ) : owner = User . get ( owner ) if organization and not isinstance ( organization , Organization ) : organiza... | Preview an harvesting from a source created with the given parameters | 204 | 11 |
246,330 | def schedule ( ident , cron = None , minute = '*' , hour = '*' , day_of_week = '*' , day_of_month = '*' , month_of_year = '*' ) : source = get_source ( ident ) if cron : minute , hour , day_of_month , month_of_year , day_of_week = cron . split ( ) crontab = PeriodicTask . Crontab ( minute = str ( minute ) , hour = str ... | Schedule an harvesting on a source given a crontab | 280 | 12 |
246,331 | def unschedule ( ident ) : source = get_source ( ident ) if not source . periodic_task : msg = 'Harvesting on source {0} is ot scheduled' . format ( source . name ) raise ValueError ( msg ) source . periodic_task . delete ( ) signals . harvest_source_unscheduled . send ( source ) return source | Unschedule an harvesting on a source | 78 | 8 |
246,332 | def attach ( domain , filename ) : count = 0 errors = 0 with open ( filename ) as csvfile : reader = csv . DictReader ( csvfile , delimiter = b';' , quotechar = b'"' ) for row in reader : try : dataset = Dataset . objects . get ( id = ObjectId ( row [ 'local' ] ) ) except : # noqa (Never stop on failure) log . warning ... | Attach existing dataset to their harvest remote id before harvesting . | 266 | 11 |
246,333 | def register ( self , key , dbtype ) : if not issubclass ( dbtype , ( BaseField , EmbeddedDocument ) ) : msg = 'ExtrasField can only register MongoEngine fields' raise TypeError ( msg ) self . registered [ key ] = dbtype | Register a DB type to add constraint on a given extra key | 58 | 12 |
246,334 | def delete ( ) : email = click . prompt ( 'Email' ) user = User . objects ( email = email ) . first ( ) if not user : exit_with_error ( 'Invalid user' ) user . delete ( ) success ( 'User deleted successfully' ) | Delete an existing user | 57 | 4 |
246,335 | def set_admin ( email ) : user = datastore . get_user ( email ) log . info ( 'Adding admin role to user %s (%s)' , user . fullname , user . email ) role = datastore . find_or_create_role ( 'admin' ) datastore . add_role_to_user ( user , role ) success ( 'User %s (%s) is now administrator' % ( user . fullname , user . e... | Set an user as administrator | 104 | 5 |
246,336 | def combine_chunks ( storage , args , prefix = None ) : uuid = args [ 'uuid' ] # Normalize filename including extension target = utils . normalize ( args [ 'filename' ] ) if prefix : target = os . path . join ( prefix , target ) with storage . open ( target , 'wb' ) as out : for i in xrange ( args [ 'totalparts' ] ) : ... | Combine a chunked file into a whole file again . Goes through each part in order and appends that part s bytes to another destination file . Chunks are stored in the chunks storage . | 138 | 39 |
246,337 | def resolve_model ( self , model ) : if not model : raise ValueError ( 'Unsupported model specifications' ) if isinstance ( model , basestring ) : classname = model elif isinstance ( model , dict ) and 'class' in model : classname = model [ 'class' ] else : raise ValueError ( 'Unsupported model specifications' ) try : ... | Resolve a model given a name or dict with class entry . | 117 | 13 |
246,338 | def tooltip_ellipsis ( source , length = 0 ) : try : length = int ( length ) except ValueError : # invalid literal for int() return source # Fail silently. ellipsis = '<a href v-tooltip title="{0}">...</a>' . format ( source ) return Markup ( ( source [ : length ] + ellipsis ) if len ( source ) > length and length > 0 ... | return the plain text representation of markdown encoded text . That is the texted without any html tags . If length is 0 then it will not be truncated . | 95 | 32 |
246,339 | def filesize ( value ) : suffix = 'o' for unit in '' , 'K' , 'M' , 'G' , 'T' , 'P' , 'E' , 'Z' : if abs ( value ) < 1024.0 : return "%3.1f%s%s" % ( value , unit , suffix ) value /= 1024.0 return "%.1f%s%s" % ( value , 'Y' , suffix ) | Display a human readable filesize | 100 | 6 |
246,340 | def negociate_content ( default = 'json-ld' ) : mimetype = request . accept_mimetypes . best_match ( ACCEPTED_MIME_TYPES . keys ( ) ) return ACCEPTED_MIME_TYPES . get ( mimetype , default ) | Perform a content negociation on the format given the Accept header | 67 | 13 |
246,341 | def url_from_rdf ( rdf , prop ) : value = rdf . value ( prop ) if isinstance ( value , ( URIRef , Literal ) ) : return value . toPython ( ) elif isinstance ( value , RdfResource ) : return value . identifier . toPython ( ) | Try to extract An URL from a resource property . It can be expressed in many forms as a URIRef or a Literal | 67 | 26 |
246,342 | def graph_response ( graph , format ) : fmt = guess_format ( format ) if not fmt : abort ( 404 ) headers = { 'Content-Type' : RDF_MIME_TYPES [ fmt ] } kwargs = { } if fmt == 'json-ld' : kwargs [ 'context' ] = context if isinstance ( graph , RdfResource ) : graph = graph . graph return graph . serialize ( format = fmt ,... | Return a proper flask response for a RDF resource given an expected format . | 109 | 15 |
246,343 | def valid_at ( self , valid_date ) : is_valid = db . Q ( validity__end__gt = valid_date , validity__start__lte = valid_date ) no_validity = db . Q ( validity = None ) return self ( is_valid | no_validity ) | Limit current QuerySet to zone valid at a given date | 66 | 11 |
246,344 | def resolve ( self , geoid , id_only = False ) : level , code , validity = geoids . parse ( geoid ) qs = self ( level = level , code = code ) if id_only : qs = qs . only ( 'id' ) if validity == 'latest' : result = qs . latest ( ) else : result = qs . valid_at ( validity ) . first ( ) return result . id if id_only and r... | Resolve a GeoZone given a GeoID . | 103 | 10 |
246,345 | def keys_values ( self ) : keys_values = [ ] for value in self . keys . values ( ) : if isinstance ( value , list ) : keys_values += value elif isinstance ( value , basestring ) and not value . startswith ( '-' ) : # Avoid -99. Should be fixed in geozones keys_values . append ( value ) elif isinstance ( value , int ) a... | Key values might be a list or not always return a list . | 123 | 13 |
246,346 | def level_i18n_name ( self ) : for level , name in spatial_granularities : if self . level == level : return name return self . level_name | In use within templates for dynamic translations . | 38 | 8 |
246,347 | def ancestors_objects ( self ) : ancestors_objects = [ ] for ancestor in self . ancestors : try : ancestor_object = GeoZone . objects . get ( id = ancestor ) except GeoZone . DoesNotExist : continue ancestors_objects . append ( ancestor_object ) ancestors_objects . sort ( key = lambda a : a . name ) return ancestors_ob... | Ancestors objects sorted by name . | 77 | 8 |
246,348 | def child_level ( self ) : HANDLED_LEVELS = current_app . config . get ( 'HANDLED_LEVELS' ) try : return HANDLED_LEVELS [ HANDLED_LEVELS . index ( self . level ) - 1 ] except ( IndexError , ValueError ) : return None | Return the child level given handled levels . | 73 | 8 |
246,349 | def harvest ( self ) : if self . perform_initialization ( ) is not None : self . process_items ( ) self . finalize ( ) return self . job | Start the harvesting process | 36 | 4 |
246,350 | def perform_initialization ( self ) : log . debug ( 'Initializing backend' ) factory = HarvestJob if self . dryrun else HarvestJob . objects . create self . job = factory ( status = 'initializing' , started = datetime . now ( ) , source = self . source ) before_harvest_job . send ( self ) try : self . initialize ( ) se... | Initialize the harvesting for a given job | 326 | 8 |
246,351 | def validate ( self , data , schema ) : try : return schema ( data ) except MultipleInvalid as ie : errors = [ ] for error in ie . errors : if error . path : field = '.' . join ( str ( p ) for p in error . path ) path = error . path value = data while path : attr = path . pop ( 0 ) try : if isinstance ( value , ( list ... | Perform a data validation against a given schema . | 263 | 10 |
246,352 | def add ( obj ) : Form = badge_form ( obj . __class__ ) form = api . validate ( Form ) kind = form . kind . data badge = obj . get_badge ( kind ) if badge : return badge else : return obj . add_badge ( kind ) , 201 | Handle a badge add API . | 63 | 6 |
246,353 | def remove ( obj , kind ) : if not obj . get_badge ( kind ) : api . abort ( 404 , 'Badge does not exists' ) obj . remove_badge ( kind ) return '' , 204 | Handle badge removal API | 47 | 4 |
246,354 | def check_for_territories ( query ) : if not query or not current_app . config . get ( 'ACTIVATE_TERRITORIES' ) : return [ ] dbqs = db . Q ( ) query = query . lower ( ) is_digit = query . isdigit ( ) query_length = len ( query ) for level in current_app . config . get ( 'HANDLED_LEVELS' ) : if level == 'country' : cont... | Return a geozone queryset of territories given the query . | 415 | 14 |
246,355 | def build ( level , code , validity = None ) : spatial = ':' . join ( ( level , code ) ) if not validity : return spatial elif isinstance ( validity , basestring ) : return '@' . join ( ( spatial , validity ) ) elif isinstance ( validity , datetime ) : return '@' . join ( ( spatial , validity . date ( ) . isoformat ( )... | Serialize a GeoID from its parts | 151 | 8 |
246,356 | def from_zone ( zone ) : validity = zone . validity . start if zone . validity else None return build ( zone . level , zone . code , validity ) | Build a GeoID from a given zone | 34 | 8 |
246,357 | def temporal_from_rdf ( period_of_time ) : try : if isinstance ( period_of_time , Literal ) : return temporal_from_literal ( str ( period_of_time ) ) elif isinstance ( period_of_time , RdfResource ) : return temporal_from_resource ( period_of_time ) except Exception : # There are a lot of cases where parsing could/shou... | Failsafe parsing of a temporal coverage | 134 | 8 |
246,358 | def title_from_rdf ( rdf , url ) : title = rdf_value ( rdf , DCT . title ) if title : return title if url : last_part = url . split ( '/' ) [ - 1 ] if '.' in last_part and '?' not in last_part : return last_part fmt = rdf_value ( rdf , DCT . term ( 'format' ) ) lang = current_app . config [ 'DEFAULT_LANGUAGE' ] with i1... | Try to extract a distribution title from a property . As it s not a mandatory property it fallback on building a title from the URL then the format and in last ressort a generic resource name . | 163 | 40 |
246,359 | def check_url_does_not_exists ( form , field ) : if field . data != field . object_data and Reuse . url_exists ( field . data ) : raise validators . ValidationError ( _ ( 'This URL is already registered' ) ) | Ensure a reuse URL is not yet registered | 60 | 9 |
246,360 | def obj_to_string ( obj ) : if not obj : return None elif isinstance ( obj , bytes ) : return obj . decode ( 'utf-8' ) elif isinstance ( obj , basestring ) : return obj elif is_lazy_string ( obj ) : return obj . value elif hasattr ( obj , '__html__' ) : return obj . __html__ ( ) else : return str ( obj ) | Render an object into a unicode string if possible | 96 | 10 |
246,361 | def add_filter ( self , filter_values ) : field = self . _params [ 'field' ] # Build a `AND` query on values wihtout the OR operator. # and a `OR` query for each value containing the OR operator. filters = [ Q ( 'bool' , should = [ Q ( 'term' , * * { field : v } ) for v in value . split ( OR_SEPARATOR ) ] ) if OR_SEPAR... | Improve the original one to deal with OR cases . | 148 | 10 |
246,362 | def get_values ( self , data , filter_values ) : values = super ( ModelTermsFacet , self ) . get_values ( data , filter_values ) ids = [ key for ( key , doc_count , selected ) in values ] # Perform a model resolution: models are feched from DB # We use model field to cast IDs ids = [ self . model_field . to_mongo ( id ... | Turn the raw bucket data into a list of tuples containing the object number of documents and a flag indicating whether this value has been selected or not . | 155 | 30 |
246,363 | def save ( self , commit = True , * * kwargs ) : org = super ( OrganizationForm , self ) . save ( commit = False , * * kwargs ) if not org . id : user = current_user . _get_current_object ( ) member = Member ( user = user , role = 'admin' ) org . members . append ( member ) if commit : org . save ( ) return org | Register the current user as admin on creation | 90 | 8 |
246,364 | def get_cache_key ( path ) : # Python 2/3 support for path hashing try : path_hash = hashlib . md5 ( path ) . hexdigest ( ) except TypeError : path_hash = hashlib . md5 ( path . encode ( 'utf-8' ) ) . hexdigest ( ) return settings . cache_key_prefix + path_hash | Create a cache key by concatenating the prefix with a hash of the path . | 82 | 17 |
246,365 | def get_remote_etag ( storage , prefixed_path ) : normalized_path = safe_join ( storage . location , prefixed_path ) . replace ( '\\' , '/' ) try : return storage . bucket . get_key ( normalized_path ) . etag except AttributeError : pass try : return storage . bucket . Object ( normalized_path ) . e_tag except : pass r... | Get etag of path from S3 using boto or boto3 . | 89 | 16 |
246,366 | def get_etag ( storage , path , prefixed_path ) : cache_key = get_cache_key ( path ) etag = cache . get ( cache_key , False ) if etag is False : etag = get_remote_etag ( storage , prefixed_path ) cache . set ( cache_key , etag ) return etag | Get etag of path from cache or S3 - in that order . | 78 | 15 |
246,367 | def get_file_hash ( storage , path ) : contents = storage . open ( path ) . read ( ) file_hash = hashlib . md5 ( contents ) . hexdigest ( ) # Check if content should be gzipped and hash gzipped content content_type = mimetypes . guess_type ( path ) [ 0 ] or 'application/octet-stream' if settings . is_gzipped and conten... | Create md5 hash from file contents . | 252 | 8 |
246,368 | def has_matching_etag ( remote_storage , source_storage , path , prefixed_path ) : storage_etag = get_etag ( remote_storage , path , prefixed_path ) local_etag = get_file_hash ( source_storage , path ) return storage_etag == local_etag | Compare etag of path in source storage with remote . | 73 | 11 |
246,369 | def should_copy_file ( remote_storage , path , prefixed_path , source_storage ) : if has_matching_etag ( remote_storage , source_storage , path , prefixed_path ) : logger . info ( "%s: Skipping based on matching file hashes" % path ) return False # Invalidate cached versions of lookup before copy destroy_etag ( path ) ... | Returns True if the file should be copied otherwise False . | 102 | 11 |
246,370 | def set_options ( self , * * options ) : ignore_etag = options . pop ( 'ignore_etag' , False ) disable = options . pop ( 'disable_collectfast' , False ) if ignore_etag : warnings . warn ( "--ignore-etag is deprecated since 0.5.0, use " "--disable-collectfast instead." ) if ignore_etag or disable : self . collectfast_en... | Set options and handle deprecation . | 112 | 8 |
246,371 | def handle ( self , * * options ) : super ( Command , self ) . handle ( * * options ) return "{} static file{} copied." . format ( self . num_copied_files , '' if self . num_copied_files == 1 else 's' ) | Override handle to supress summary output | 61 | 7 |
246,372 | def do_copy_file ( self , args ) : path , prefixed_path , source_storage = args reset_connection ( self . storage ) if self . collectfast_enabled and not self . dry_run : try : if not should_copy_file ( self . storage , path , prefixed_path , source_storage ) : return False except Exception as e : if settings . debug :... | Determine if file should be copied or not and handle exceptions . | 166 | 14 |
246,373 | def copy_file ( self , path , prefixed_path , source_storage ) : args = ( path , prefixed_path , source_storage ) if settings . threads : self . tasks . append ( args ) else : self . do_copy_file ( args ) | Appends path to task queue if threads are enabled otherwise copies the file with a blocking call . | 58 | 19 |
246,374 | def delete_file ( self , path , prefixed_path , source_storage ) : if not self . collectfast_enabled : return super ( Command , self ) . delete_file ( path , prefixed_path , source_storage ) if not self . dry_run : self . log ( "Deleting '%s'" % path ) self . storage . delete ( prefixed_path ) else : self . log ( "Pret... | Override delete_file to skip modified time and exists lookups . | 106 | 13 |
246,375 | def join ( rasters ) : raster = rasters [ 0 ] # using the first raster to understand what is the type of data we have mask_band = None nodata = None with raster . _raster_opener ( raster . source_file ) as r : nodata = r . nodata mask_flags = r . mask_flag_enums per_dataset_mask = all ( [ rasterio . enums . MaskFlags .... | This method takes a list of rasters and returns a raster that is constructed of all of them | 172 | 20 |
246,376 | def merge_all ( rasters , roi = None , dest_resolution = None , merge_strategy = MergeStrategy . UNION , shape = None , ul_corner = None , crs = None , pixel_strategy = PixelStrategy . FIRST , resampling = Resampling . nearest ) : first_raster = rasters [ 0 ] if roi : crs = crs or roi . crs dest_resolution = dest_resol... | Merge a list of rasters cropping by a region of interest . There are cases that the roi is not precise enough for this cases one can use the upper left corner the shape and crs to precisely define the roi . When roi is provided the ul_corner shape and crs are ignored | 397 | 64 |
246,377 | def _merge_common_bands ( rasters ) : # type: (List[_Raster]) -> List[_Raster] # Compute band order all_bands = IndexedSet ( [ rs . band_names [ 0 ] for rs in rasters ] ) def key ( rs ) : return all_bands . index ( rs . band_names [ 0 ] ) rasters_final = [ ] # type: List[_Raster] for band_name , rasters_group in groupb... | Combine the common bands . | 148 | 6 |
246,378 | def _explode_raster ( raster , band_names = [ ] ) : # type: (_Raster, Iterable[str]) -> List[_Raster] # Using band_names=[] does no harm because we are not mutating it in place # and it makes MyPy happy if not band_names : band_names = raster . band_names else : band_names = list ( IndexedSet ( raster . band_names ) . ... | Splits a raster into multiband rasters . | 147 | 11 |
246,379 | def _fill_pixels ( one , other ) : # type: (_Raster, _Raster) -> _Raster assert len ( one . band_names ) == len ( other . band_names ) == 1 , "Rasters are not single band" # We raise an error in the intersection is empty. # Other options include returning an "empty" raster or just None. # The problem with the former is... | Merges two single band rasters with the same band by filling the pixels according to depth . | 563 | 19 |
246,380 | def _stack_bands ( one , other ) : # type: (_Raster, _Raster) -> _Raster assert set ( one . band_names ) . intersection ( set ( other . band_names ) ) == set ( ) # We raise an error in the bands are the same. See above. if one . band_names == other . band_names : raise ValueError ( "rasters have the same bands, use ano... | Merges two rasters with non overlapping bands by stacking the bands . | 363 | 14 |
246,381 | def merge_two ( one , other , merge_strategy = MergeStrategy . UNION , silent = False , pixel_strategy = PixelStrategy . FIRST ) : # type: (GeoRaster2, GeoRaster2, MergeStrategy, bool, PixelStrategy) -> GeoRaster2 other_res = _prepare_other_raster ( one , other ) if other_res is None : if silent : return one else : rai... | Merge two rasters into one . | 357 | 8 |
246,382 | def _set_image ( self , image , nodata = None ) : # convert to masked array: if isinstance ( image , np . ma . core . MaskedArray ) : masked = image elif isinstance ( image , np . core . ndarray ) : masked = self . _build_masked_array ( image , nodata ) else : raise GeoRaster2NotImplementedError ( 'only ndarray or mask... | Set self . _image . | 247 | 6 |
246,383 | def from_wms ( cls , filename , vector , resolution , destination_file = None ) : doc = wms_vrt ( filename , bounds = vector , resolution = resolution ) . tostring ( ) filename = cls . _save_to_destination_file ( doc , destination_file ) return GeoRaster2 . open ( filename ) | Create georaster from the web service definition file . | 76 | 11 |
246,384 | def from_rasters ( cls , rasters , relative_to_vrt = True , destination_file = None , nodata = None , mask_band = None ) : if isinstance ( rasters , list ) : doc = raster_list_vrt ( rasters , relative_to_vrt , nodata , mask_band ) . tostring ( ) else : doc = raster_collection_vrt ( rasters , relative_to_vrt , nodata , ... | Create georaster out of a list of rasters . | 146 | 12 |
246,385 | def open ( cls , filename , band_names = None , lazy_load = True , mutable = False , * * kwargs ) : if mutable : geo_raster = MutableGeoRaster ( filename = filename , band_names = band_names , * * kwargs ) else : geo_raster = cls ( filename = filename , band_names = band_names , * * kwargs ) if not lazy_load : geo_rast... | Read a georaster from a file . | 128 | 9 |
246,386 | def tags ( cls , filename , namespace = None ) : return cls . _raster_opener ( filename ) . tags ( ns = namespace ) | Extract tags from file . | 33 | 6 |
246,387 | def image ( self ) : if self . _image is None : self . _populate_from_rasterio_object ( read_image = True ) return self . _image | Raster bitmap in numpy array . | 39 | 9 |
246,388 | def crs ( self ) : # type: () -> CRS if self . _crs is None : self . _populate_from_rasterio_object ( read_image = False ) return self . _crs | Raster crs . | 49 | 5 |
246,389 | def shape ( self ) : if self . _shape is None : self . _populate_from_rasterio_object ( read_image = False ) return self . _shape | Raster shape . | 39 | 4 |
246,390 | def source_file ( self ) : if self . _filename is None : self . _filename = self . _as_in_memory_geotiff ( ) . _filename return self . _filename | When using open returns the filename used | 43 | 7 |
246,391 | def blockshapes ( self ) : if self . _blockshapes is None : if self . _filename : self . _populate_from_rasterio_object ( read_image = False ) else : # if no file is attached to the raster set the shape of each band to be the data array size self . _blockshapes = [ ( self . height , self . width ) for z in range ( self... | Raster all bands block shape . | 104 | 7 |
246,392 | def get ( self , point ) : if not ( isinstance ( point , GeoVector ) and point . type == 'Point' ) : raise TypeError ( 'expect GeoVector(Point), got %s' % ( point , ) ) target = self . to_raster ( point ) return self . image [ : , int ( target . y ) , int ( target . x ) ] | Get the pixel values at the requested point . | 83 | 9 |
246,393 | def copy ( self , mutable = False ) : if self . not_loaded ( ) : _cls = self . __class__ if mutable : _cls = MutableGeoRaster return _cls . open ( self . _filename ) return self . copy_with ( mutable = mutable ) | Return a copy of this GeoRaster with no modifications . | 68 | 12 |
246,394 | def _resize ( self , ratio_x , ratio_y , resampling ) : new_width = int ( np . ceil ( self . width * ratio_x ) ) new_height = int ( np . ceil ( self . height * ratio_y ) ) dest_affine = self . affine * Affine . scale ( 1 / ratio_x , 1 / ratio_y ) if self . not_loaded ( ) : window = rasterio . windows . Window ( 0 , 0 ,... | Return raster resized by ratio . | 195 | 8 |
246,395 | def to_pillow_image ( self , return_mask = False ) : img = np . rollaxis ( np . rollaxis ( self . image . data , 2 ) , 2 ) img = Image . fromarray ( img [ : , : , 0 ] ) if img . shape [ 2 ] == 1 else Image . fromarray ( img ) if return_mask : mask = np . ma . getmaskarray ( self . image ) mask = Image . fromarray ( np ... | Return Pillow . Image and optionally also mask . | 141 | 10 |
246,396 | def from_bytes ( cls , image_bytes , affine , crs , band_names = None ) : b = io . BytesIO ( image_bytes ) image = imageio . imread ( b ) roll = np . rollaxis ( image , 2 ) if band_names is None : band_names = [ 0 , 1 , 2 ] elif isinstance ( band_names , str ) : band_names = [ band_names ] return GeoRaster2 ( image = r... | Create GeoRaster from image BytesIo object . | 135 | 12 |
246,397 | def _repr_html_ ( self ) : TileServer . run_tileserver ( self , self . footprint ( ) ) capture = "raster: %s" % self . _filename mp = TileServer . folium_client ( self , self . footprint ( ) , capture = capture ) return mp . _repr_html_ ( ) | Required for jupyter notebook to show raster as an interactive map . | 75 | 16 |
246,398 | def image_corner ( self , corner ) : if corner not in self . corner_types ( ) : raise GeoRaster2Error ( 'corner %s invalid, expected: %s' % ( corner , self . corner_types ( ) ) ) x = 0 if corner [ 1 ] == 'l' else self . width y = 0 if corner [ 0 ] == 'u' else self . height return Point ( x , y ) | Return image corner in pixels as shapely . Point . | 94 | 11 |
246,399 | def center ( self ) : image_center = Point ( self . width / 2 , self . height / 2 ) return self . to_world ( image_center ) | Return footprint center in world coordinates as GeoVector . | 35 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.