idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
247,100
def simplify ( self ) : expr = self . expr self . expr = _cancel_mul ( expr , self . registry ) return self
Return a new equivalent unit object with a simplified unit expression
247,101
def _auto_positive_symbol ( tokens , local_dict , global_dict ) : result = [ ] tokens . append ( ( None , None ) ) for tok , nextTok in zip ( tokens , tokens [ 1 : ] ) : tokNum , tokVal = tok nextTokNum , nextTokVal = nextTok if tokNum == token . NAME : name = tokVal if name in global_dict : obj = global_dict [ name ] if isinstance ( obj , ( Basic , type ) ) or callable ( obj ) : result . append ( ( token . NAME , name ) ) continue try : used_name = inv_name_alternatives [ str ( name ) ] except KeyError : used_name = str ( name ) result . extend ( [ ( token . NAME , "Symbol" ) , ( token . OP , "(" ) , ( token . NAME , repr ( used_name ) ) , ( token . OP , "," ) , ( token . NAME , "positive" ) , ( token . OP , "=" ) , ( token . NAME , "True" ) , ( token . OP , ")" ) , ] ) else : result . append ( ( tokNum , tokVal ) ) return result
Inserts calls to Symbol for undefined variables . Passes in positive = True as a keyword argument . Adapted from sympy . sympy . parsing . sympy_parser . auto_symbol
247,102
def intersection ( self , range ) : if self . worksheet != range . worksheet : return None start = ( max ( self . _start [ 0 ] , range . _start [ 0 ] ) , max ( self . _start [ 1 ] , range . _start [ 1 ] ) ) end = ( min ( self . _end [ 0 ] , range . _end [ 0 ] ) , min ( self . _end [ 1 ] , range . _end [ 1 ] ) ) if end [ 0 ] < start [ 0 ] or end [ 1 ] < start [ 1 ] : return None return Range ( start , end , self . worksheet , validate = False )
Calculates the intersection with another range object
247,103
def interprocess_locked ( path ) : lock = InterProcessLock ( path ) def decorator ( f ) : @ six . wraps ( f ) def wrapper ( * args , ** kwargs ) : with lock : return f ( * args , ** kwargs ) return wrapper return decorator
Acquires & releases a interprocess lock around call into decorated function .
247,104
def acquire ( self , blocking = True , delay = DELAY_INCREMENT , max_delay = MAX_DELAY , timeout = None ) : if delay < 0 : raise ValueError ( "Delay must be greater than or equal to zero" ) if timeout is not None and timeout < 0 : raise ValueError ( "Timeout must be greater than or equal to zero" ) if delay >= max_delay : max_delay = delay self . _do_open ( ) watch = _utils . StopWatch ( duration = timeout ) r = _utils . Retry ( delay , max_delay , sleep_func = self . sleep_func , watch = watch ) with watch : gotten = r ( self . _try_acquire , blocking , watch ) if not gotten : self . acquired = False return False else : self . acquired = True self . logger . log ( _utils . BLATHER , "Acquired file lock `%s` after waiting %0.3fs [%s" " attempts were required]" , self . path , watch . elapsed ( ) , r . attempts ) return True
Attempt to acquire the given lock .
247,105
def release ( self ) : if not self . acquired : raise threading . ThreadError ( "Unable to release an unacquired" " lock" ) try : self . unlock ( ) except IOError : self . logger . exception ( "Could not unlock the acquired lock opened" " on `%s`" , self . path ) else : self . acquired = False try : self . _do_close ( ) except IOError : self . logger . exception ( "Could not close the file handle" " opened on `%s`" , self . path ) else : self . logger . log ( _utils . BLATHER , "Unlocked and closed file lock open on" " `%s`" , self . path )
Release the previously acquired lock .
247,106
def canonicalize_path ( path ) : if isinstance ( path , six . binary_type ) : return path if isinstance ( path , six . text_type ) : return _fsencode ( path ) else : return canonicalize_path ( str ( path ) )
Canonicalizes a potential path .
247,107
def read_locked ( * args , ** kwargs ) : def decorator ( f ) : attr_name = kwargs . get ( 'lock' , '_lock' ) @ six . wraps ( f ) def wrapper ( self , * args , ** kwargs ) : rw_lock = getattr ( self , attr_name ) with rw_lock . read_lock ( ) : return f ( self , * args , ** kwargs ) return wrapper if kwargs or not args : return decorator else : if len ( args ) == 1 : return decorator ( args [ 0 ] ) else : return decorator
Acquires & releases a read lock around call into decorated method .
247,108
def write_locked ( * args , ** kwargs ) : def decorator ( f ) : attr_name = kwargs . get ( 'lock' , '_lock' ) @ six . wraps ( f ) def wrapper ( self , * args , ** kwargs ) : rw_lock = getattr ( self , attr_name ) with rw_lock . write_lock ( ) : return f ( self , * args , ** kwargs ) return wrapper if kwargs or not args : return decorator else : if len ( args ) == 1 : return decorator ( args [ 0 ] ) else : return decorator
Acquires & releases a write lock around call into decorated method .
247,109
def is_writer ( self , check_pending = True ) : me = self . _current_thread ( ) if self . _writer == me : return True if check_pending : return me in self . _pending_writers else : return False
Returns if the caller is the active writer or a pending writer .
247,110
def owner ( self ) : if self . _writer is not None : return self . WRITER if self . _readers : return self . READER return None
Returns whether the lock is locked by a writer or reader .
247,111
def read_lock ( self ) : me = self . _current_thread ( ) if me in self . _pending_writers : raise RuntimeError ( "Writer %s can not acquire a read lock" " while waiting for the write lock" % me ) with self . _cond : while True : if self . _writer is None or self . _writer == me : try : self . _readers [ me ] = self . _readers [ me ] + 1 except KeyError : self . _readers [ me ] = 1 break self . _cond . wait ( ) try : yield self finally : with self . _cond : try : me_instances = self . _readers [ me ] if me_instances > 1 : self . _readers [ me ] = me_instances - 1 else : self . _readers . pop ( me ) except KeyError : pass self . _cond . notify_all ( )
Context manager that grants a read lock .
247,112
def write_lock ( self ) : me = self . _current_thread ( ) i_am_writer = self . is_writer ( check_pending = False ) if self . is_reader ( ) and not i_am_writer : raise RuntimeError ( "Reader %s to writer privilege" " escalation not allowed" % me ) if i_am_writer : yield self else : with self . _cond : self . _pending_writers . append ( me ) while True : if len ( self . _readers ) == 0 and self . _writer is None : if self . _pending_writers [ 0 ] == me : self . _writer = self . _pending_writers . popleft ( ) break self . _cond . wait ( ) try : yield self finally : with self . _cond : self . _writer = None self . _cond . notify_all ( )
Context manager that grants a write lock .
247,113
def send_sms ( self , text , ** kw ) : params = { 'user' : self . _user , 'pass' : self . _passwd , 'msg' : text } kw . setdefault ( "verify" , False ) if not kw [ "verify" ] : requests . packages . urllib3 . disable_warnings ( InsecureRequestWarning ) res = requests . get ( FreeClient . BASE_URL , params = params , ** kw ) return FreeResponse ( res . status_code )
Send an SMS . Since Free only allows us to send SMSes to ourselves you don t have to provide your phone number .
247,114
def create_filebase_name ( self , group_info , extension = 'gz' , file_name = None ) : dirname = self . filebase . formatted_dirname ( groups = group_info ) if not file_name : file_name = self . filebase . prefix_template + '.' + extension return dirname , file_name
Return tuple of resolved destination folder name and file name
247,115
def write_batch ( self , batch ) : for item in batch : for key in item : self . aggregated_info [ 'occurrences' ] [ key ] += 1 self . increment_written_items ( ) if self . items_limit and self . items_limit == self . get_metadata ( 'items_count' ) : raise ItemsLimitReached ( 'Finishing job after items_limit reached: {} items written.' . format ( self . get_metadata ( 'items_count' ) ) ) self . logger . debug ( 'Wrote items' )
Receives the batch and writes it . This method is usually called from a manager .
247,116
def _get_aggregated_info ( self ) : agg_results = { } for key in self . aggregated_info [ 'occurrences' ] : agg_results [ key ] = { 'occurrences' : self . aggregated_info [ 'occurrences' ] . get ( key ) , 'coverage' : ( float ( self . aggregated_info [ 'occurrences' ] . get ( key ) ) / float ( self . get_metadata ( 'items_count' ) ) ) * 100 } return agg_results
Keeps track of aggregated info in a dictionary called self . aggregated_info
247,117
def create_document_batches ( jsonlines , id_field , max_batch_size = CLOUDSEARCH_MAX_BATCH_SIZE ) : batch = [ ] fixed_initial_size = 2 def create_entry ( line ) : try : record = json . loads ( line ) except : raise ValueError ( 'Could not parse JSON from: %s' % line ) key = record [ id_field ] return '{"type":"add","id":%s,"fields":%s}' % ( json . dumps ( key ) , line ) current_size = fixed_initial_size for line in jsonlines : entry = create_entry ( line ) entry_size = len ( entry ) + 1 if max_batch_size > ( current_size + entry_size ) : current_size += entry_size batch . append ( entry ) else : yield '[' + ',' . join ( batch ) + ']' batch = [ entry ] current_size = fixed_initial_size + entry_size if batch : yield '[' + ',' . join ( batch ) + ']'
Create batches in expected AWS Cloudsearch format limiting the byte size per batch according to given max_batch_size
247,118
def _post_document_batch ( self , batch ) : target_batch = '/2013-01-01/documents/batch' url = self . endpoint_url + target_batch return requests . post ( url , data = batch , headers = { 'Content-type' : 'application/json' } )
Send a batch to Cloudsearch endpoint
247,119
def _create_path_if_not_exist ( self , path ) : if path and not os . path . exists ( path ) : os . makedirs ( path )
Creates a folders path if it doesn t exist
247,120
def close ( self ) : if self . read_option ( 'save_pointer' ) : self . _update_last_pointer ( ) super ( S3Writer , self ) . close ( )
Called to clean all possible tmp files created during the process .
247,121
def get_boto_connection ( aws_access_key_id , aws_secret_access_key , region = None , bucketname = None , host = None ) : m = _AWS_ACCESS_KEY_ID_RE . match ( aws_access_key_id ) if m is None or m . group ( ) != aws_access_key_id : logging . error ( 'The provided aws_access_key_id is not in the correct format. It must \ be alphanumeric and contain between 16 and 32 characters.' ) if len ( aws_access_key_id ) > len ( aws_secret_access_key ) : logging . warn ( "The AWS credential keys aren't in the usual size," " are you using the correct ones?" ) import boto from boto . s3 . connection import OrdinaryCallingFormat extra_args = { } if host is not None : extra_args [ 'host' ] = host if bucketname is not None and '.' in bucketname : extra_args [ 'calling_format' ] = OrdinaryCallingFormat ( ) if region is None : return boto . connect_s3 ( aws_access_key_id , aws_secret_access_key , ** extra_args ) return boto . s3 . connect_to_region ( region , aws_access_key_id = aws_access_key_id , aws_secret_access_key = aws_secret_access_key , ** extra_args )
Conection parameters must be different only if bucket name has a period
247,122
def maybe_cast_list ( value , types ) : if not isinstance ( value , list ) : return value if type ( types ) not in ( list , tuple ) : types = ( types , ) for list_type in types : if issubclass ( list_type , list ) : try : return list_type ( value ) except ( TypeError , ValueError ) : pass return value
Try to coerce list values into more specific list subclasses in types .
247,123
def iterate_chunks ( file , chunk_size ) : chunk = file . read ( chunk_size ) while chunk : yield chunk chunk = file . read ( chunk_size )
Iterate chunks of size chunk_size from a file - like object
247,124
def unshift ( self , chunk ) : if chunk : self . _pos -= len ( chunk ) self . _unconsumed . append ( chunk )
Pushes a chunk of data back into the internal buffer . This is useful in certain situations where a stream is being consumed by code that needs to un - consume some amount of data that it has optimistically pulled out of the source so that the data can be passed on to some other party .
247,125
def readline ( self ) : line = "" n_pos = - 1 try : while n_pos < 0 : line += self . next_chunk ( ) n_pos = line . find ( '\n' ) except StopIteration : pass if n_pos >= 0 : line , extra = line [ : n_pos + 1 ] , line [ n_pos + 1 : ] self . unshift ( extra ) return line
Read until a new - line character is encountered
247,126
def close ( self ) : if callable ( getattr ( self . _file , 'close' , None ) ) : self . _iterator . close ( ) self . _iterator = None self . _unconsumed = None self . closed = True
Disable al operations and close the underlying file - like object if any
247,127
def configuration_from_uri ( uri , uri_regex ) : file_path = re . match ( uri_regex , uri ) . groups ( ) [ 0 ] with open ( file_path ) as f : configuration = pickle . load ( f ) [ 'configuration' ] configuration = yaml . safe_load ( configuration ) configuration [ 'exporter_options' ] [ 'resume' ] = True persistence_state_id = file_path . split ( os . path . sep ) [ - 1 ] configuration [ 'exporter_options' ] [ 'persistence_state_id' ] = persistence_state_id return configuration
returns a configuration object .
247,128
def buffer ( self , item ) : key = self . get_key_from_item ( item ) if not self . grouping_info . is_first_file_item ( key ) : self . items_group_files . add_item_separator_to_file ( key ) self . grouping_info . ensure_group_info ( key ) self . items_group_files . add_item_to_file ( item , key )
Receive an item and write it .
247,129
def parse_persistence_uri ( cls , persistence_uri ) : regex = cls . persistence_uri_re match = re . match ( regex , persistence_uri ) if not match : raise ValueError ( "Couldn't parse persistence URI: %s -- regex: %s)" % ( persistence_uri , regex ) ) conn_params = match . groupdict ( ) missing = { 'proto' , 'job_id' , 'database' } - set ( conn_params ) if missing : raise ValueError ( 'Missing required parameters: %s (given params: %s)' % ( tuple ( missing ) , conn_params ) ) persistence_state_id = int ( conn_params . pop ( 'job_id' ) ) db_uri = cls . build_db_conn_uri ( ** conn_params ) return db_uri , persistence_state_id
Parse a database URI and the persistence state ID from the given persistence URI
247,130
def configuration_from_uri ( cls , persistence_uri ) : db_uri , persistence_state_id = cls . parse_persistence_uri ( persistence_uri ) engine = create_engine ( db_uri ) Base . metadata . create_all ( engine ) Base . metadata . bind = engine DBSession = sessionmaker ( bind = engine ) session = DBSession ( ) job = session . query ( Job ) . filter ( Job . id == persistence_state_id ) . first ( ) configuration = job . configuration configuration = yaml . safe_load ( configuration ) configuration [ 'exporter_options' ] [ 'resume' ] = True configuration [ 'exporter_options' ] [ 'persistence_state_id' ] = persistence_state_id return configuration
Return a configuration object .
247,131
def _get_input_files ( cls , input_specification ) : if isinstance ( input_specification , ( basestring , dict ) ) : input_specification = [ input_specification ] elif not isinstance ( input_specification , list ) : raise ConfigurationError ( "Input specification must be string, list or dict." ) out = [ ] for input_unit in input_specification : if isinstance ( input_unit , basestring ) : out . append ( input_unit ) elif isinstance ( input_unit , dict ) : missing = object ( ) directory = input_unit . get ( 'dir' , missing ) dir_pointer = input_unit . get ( 'dir_pointer' , missing ) if directory is missing and dir_pointer is missing : raise ConfigurationError ( 'Input directory dict must contain' ' "dir" or "dir_pointer" element (but not both)' ) if directory is not missing and dir_pointer is not missing : raise ConfigurationError ( 'Input directory dict must not contain' ' both "dir" and "dir_pointer" elements' ) if dir_pointer is not missing : directory = cls . _get_pointer ( dir_pointer ) out . extend ( cls . _get_directory_files ( directory = directory , pattern = input_unit . get ( 'pattern' ) , include_dot_files = input_unit . get ( 'include_dot_files' , False ) ) ) else : raise ConfigurationError ( 'Input must only contain strings or dicts' ) return out
Get list of input files according to input definition .
247,132
def consume_messages ( self , batchsize ) : if not self . _reservoir : self . finished = True return for msg in self . _reservoir [ : batchsize ] : yield msg self . _reservoir = self . _reservoir [ batchsize : ]
Get messages batch from the reservoir
247,133
def decompress_messages ( self , offmsgs ) : for offmsg in offmsgs : yield offmsg . message . key , self . decompress_fun ( offmsg . message . value )
Decompress pre - defined compressed fields for each message . Msgs should be unpacked before this step .
247,134
def filter_batch ( self , batch ) : for item in batch : if self . filter ( item ) : yield item else : self . set_metadata ( 'filtered_out' , self . get_metadata ( 'filtered_out' ) + 1 ) self . total += 1 self . _log_progress ( )
Receives the batch filters it and returns it .
247,135
def write_batch ( self , batch ) : for item in batch : self . write_buffer . buffer ( item ) key = self . write_buffer . get_key_from_item ( item ) if self . write_buffer . should_write_buffer ( key ) : self . _write_current_buffer_for_group_key ( key ) self . increment_written_items ( ) self . _check_items_limit ( )
Buffer a batch of items to be written and update internal counters .
247,136
def _check_items_limit ( self ) : if self . items_limit and self . items_limit == self . get_metadata ( 'items_count' ) : raise ItemsLimitReached ( 'Finishing job after items_limit reached:' ' {} items written.' . format ( self . get_metadata ( 'items_count' ) ) )
Raise ItemsLimitReached if the writer reached the configured items limit .
247,137
def flush ( self ) : for key in self . grouping_info . keys ( ) : if self . _should_flush ( key ) : self . _write_current_buffer_for_group_key ( key )
Ensure all remaining buffers are written .
247,138
def has_manifest ( app , filename = 'manifest.json' ) : try : return pkg_resources . resource_exists ( app , filename ) except ImportError : return os . path . isabs ( filename ) and os . path . exists ( filename )
Verify the existance of a JSON assets manifest
247,139
def register_manifest ( app , filename = 'manifest.json' ) : if current_app . config . get ( 'TESTING' ) : return if not has_manifest ( app , filename ) : msg = '{filename} not found for {app}' . format ( ** locals ( ) ) raise ValueError ( msg ) manifest = _manifests . get ( app , { } ) manifest . update ( load_manifest ( app , filename ) ) _manifests [ app ] = manifest
Register an assets json manifest
247,140
def load_manifest ( app , filename = 'manifest.json' ) : if os . path . isabs ( filename ) : path = filename else : path = pkg_resources . resource_filename ( app , filename ) with io . open ( path , mode = 'r' , encoding = 'utf8' ) as stream : data = json . load ( stream ) _registered_manifests [ app ] = path return data
Load an assets json manifest
247,141
def from_manifest ( app , filename , raw = False , ** kwargs ) : cfg = current_app . config if current_app . config . get ( 'TESTING' ) : return path = _manifests [ app ] [ filename ] if not raw and cfg . get ( 'CDN_DOMAIN' ) and not cfg . get ( 'CDN_DEBUG' ) : scheme = 'https' if cfg . get ( 'CDN_HTTPS' ) else request . scheme prefix = '{}://' . format ( scheme ) if not path . startswith ( '/' ) : path = '/' + path return '' . join ( ( prefix , cfg [ 'CDN_DOMAIN' ] , path ) ) elif not raw and kwargs . get ( 'external' , False ) : if path . startswith ( '/' ) : path = path [ 1 : ] return '' . join ( ( request . host_url , path ) ) return path
Get the path to a static file for a given app entry of a given type .
247,142
def cdn_for ( endpoint , ** kwargs ) : if current_app . config [ 'CDN_DOMAIN' ] : if not current_app . config . get ( 'CDN_DEBUG' ) : kwargs . pop ( '_external' , None ) return cdn_url_for ( endpoint , ** kwargs ) return url_for ( endpoint , ** kwargs )
Get a CDN URL for a static assets .
247,143
def get_or_create ( self , write_concern = None , auto_save = True , * q_objs , ** query ) : defaults = query . pop ( 'defaults' , { } ) try : doc = self . get ( * q_objs , ** query ) return doc , False except self . _document . DoesNotExist : query . update ( defaults ) doc = self . _document ( ** query ) if auto_save : doc . save ( write_concern = write_concern ) return doc , True
Retrieve unique object or create if it doesn t exist .
247,144
def generic_in ( self , ** kwargs ) : query = { } for key , value in kwargs . items ( ) : if not value : continue if isinstance ( value , ( list , tuple ) ) and len ( value ) == 1 : value = value [ 0 ] if isinstance ( value , ( list , tuple ) ) : if all ( isinstance ( v , basestring ) for v in value ) : ids = [ ObjectId ( v ) for v in value ] query [ '{0}._ref.$id' . format ( key ) ] = { '$in' : ids } elif all ( isinstance ( v , DBRef ) for v in value ) : query [ '{0}._ref' . format ( key ) ] = { '$in' : value } elif all ( isinstance ( v , ObjectId ) for v in value ) : query [ '{0}._ref.$id' . format ( key ) ] = { '$in' : value } elif isinstance ( value , ObjectId ) : query [ '{0}._ref.$id' . format ( key ) ] = value elif isinstance ( value , basestring ) : query [ '{0}._ref.$id' . format ( key ) ] = ObjectId ( value ) else : self . error ( 'expect a list of string, ObjectId or DBRef' ) return self ( __raw__ = query )
Bypass buggy GenericReferenceField querying issue
247,145
def issues_notifications ( user ) : notifications = [ ] qs = issues_for ( user ) . only ( 'id' , 'title' , 'created' , 'subject' ) for issue in qs . no_dereference ( ) : notifications . append ( ( issue . created , { 'id' : issue . id , 'title' : issue . title , 'subject' : { 'id' : issue . subject [ '_ref' ] . id , 'type' : issue . subject [ '_cls' ] . lower ( ) , } } ) ) return notifications
Notify user about open issues
247,146
def get_config ( key ) : key = 'AVATAR_{0}' . format ( key . upper ( ) ) local_config = current_app . config . get ( key ) return local_config or getattr ( theme . current , key , DEFAULTS [ key ] )
Get an identicon configuration parameter .
247,147
def get_provider ( ) : name = get_config ( 'provider' ) available = entrypoints . get_all ( 'udata.avatars' ) if name not in available : raise ValueError ( 'Unknown avatar provider: {0}' . format ( name ) ) return available [ name ]
Get the current provider from config
247,148
def generate_pydenticon ( identifier , size ) : blocks_size = get_internal_config ( 'size' ) foreground = get_internal_config ( 'foreground' ) background = get_internal_config ( 'background' ) generator = pydenticon . Generator ( blocks_size , blocks_size , digest = hashlib . sha1 , foreground = foreground , background = background ) padding = int ( round ( get_internal_config ( 'padding' ) * size / 100. ) ) size = size - 2 * padding padding = ( padding , ) * 4 return generator . generate ( identifier , size , size , padding = padding , output_format = 'png' )
Use pydenticon to generate an identicon image . All parameters are extracted from configuration .
247,149
def adorable ( identifier , size ) : url = ADORABLE_AVATARS_URL . format ( identifier = identifier , size = size ) return redirect ( url )
Adorable Avatars provider
247,150
def licenses ( source = DEFAULT_LICENSE_FILE ) : if source . startswith ( 'http' ) : json_licenses = requests . get ( source ) . json ( ) else : with open ( source ) as fp : json_licenses = json . load ( fp ) if len ( json_licenses ) : log . info ( 'Dropping existing licenses' ) License . drop_collection ( ) for json_license in json_licenses : flags = [ ] for field , flag in FLAGS_MAP . items ( ) : if json_license . get ( field , False ) : flags . append ( flag ) license = License . objects . create ( id = json_license [ 'id' ] , title = json_license [ 'title' ] , url = json_license [ 'url' ] or None , maintainer = json_license [ 'maintainer' ] or None , flags = flags , active = json_license . get ( 'active' , False ) , alternate_urls = json_license . get ( 'alternate_urls' , [ ] ) , alternate_titles = json_license . get ( 'alternate_titles' , [ ] ) , ) log . info ( 'Added license "%s"' , license . title ) try : License . objects . get ( id = DEFAULT_LICENSE [ 'id' ] ) except License . DoesNotExist : License . objects . create ( ** DEFAULT_LICENSE ) log . info ( 'Added license "%s"' , DEFAULT_LICENSE [ 'title' ] ) success ( 'Done' )
Feed the licenses from a JSON file
247,151
def fetch_objects ( self , geoids ) : zones = [ ] no_match = [ ] for geoid in geoids : zone = GeoZone . objects . resolve ( geoid ) if zone : zones . append ( zone ) else : no_match . append ( geoid ) if no_match : msg = _ ( 'Unknown geoid(s): {identifiers}' ) . format ( identifiers = ', ' . join ( str ( id ) for id in no_match ) ) raise validators . ValidationError ( msg ) return zones
Custom object retrieval .
247,152
def lrun ( command , * args , ** kwargs ) : return run ( 'cd {0} && {1}' . format ( ROOT , command ) , * args , ** kwargs )
Run a local command from project root
247,153
def initialize ( self ) : fmt = guess_format ( self . source . url ) if not fmt : response = requests . head ( self . source . url ) mime_type = response . headers . get ( 'Content-Type' , '' ) . split ( ';' , 1 ) [ 0 ] if not mime_type : msg = 'Unable to detect format from extension or mime type' raise ValueError ( msg ) fmt = guess_format ( mime_type ) if not fmt : msg = 'Unsupported mime type "{0}"' . format ( mime_type ) raise ValueError ( msg ) graph = self . parse_graph ( self . source . url , fmt ) self . job . data = { 'graph' : graph . serialize ( format = 'json-ld' , indent = None ) }
List all datasets for a given ...
247,154
def get_tasks ( ) : return { name : get_task_queue ( name , cls ) for name , cls in celery . tasks . items ( ) if not name . startswith ( 'celery.' ) and not name . startswith ( 'test-' ) }
Get a list of known tasks with their routing queue
247,155
def tasks ( ) : tasks = get_tasks ( ) longest = max ( tasks . keys ( ) , key = len ) size = len ( longest ) for name , queue in sorted ( tasks . items ( ) ) : print ( '* {0}: {1}' . format ( name . ljust ( size ) , queue ) )
Display registered tasks with their queue
247,156
def status ( queue , munin , munin_config ) : if munin_config : return status_print_config ( queue ) queues = get_queues ( queue ) for queue in queues : status_print_queue ( queue , munin = munin ) if not munin : print ( '-' * 40 )
List queued tasks aggregated by name
247,157
def pre_validate ( self , form ) : for preprocessor in self . _preprocessors : preprocessor ( form , self ) super ( FieldHelper , self ) . pre_validate ( form )
Calls preprocessors before pre_validation
247,158
def process_formdata ( self , valuelist ) : super ( EmptyNone , self ) . process_formdata ( valuelist ) self . data = self . data or None
Replace empty values by None
247,159
def fetch_objects ( self , oids ) : objects = self . model . objects . in_bulk ( oids ) if len ( objects . keys ( ) ) != len ( oids ) : non_existants = set ( oids ) - set ( objects . keys ( ) ) msg = _ ( 'Unknown identifiers: {identifiers}' ) . format ( identifiers = ', ' . join ( str ( ne ) for ne in non_existants ) ) raise validators . ValidationError ( msg ) return [ objects [ id ] for id in oids ]
This methods is used to fetch models from a list of identifiers .
247,160
def validate ( self , form , extra_validators = tuple ( ) ) : if not self . has_data : return True if self . is_list_data : if not isinstance ( self . _formdata [ self . name ] , ( list , tuple ) ) : return False return super ( NestedModelList , self ) . validate ( form , extra_validators )
Perform validation only if data has been submitted
247,161
def _add_entry ( self , formdata = None , data = unset_value , index = None ) : if formdata : prefix = '-' . join ( ( self . name , str ( index ) ) ) basekey = '-' . join ( ( prefix , '{0}' ) ) idkey = basekey . format ( 'id' ) if prefix in formdata : formdata [ idkey ] = formdata . pop ( prefix ) if hasattr ( self . nested_model , 'id' ) and idkey in formdata : id = self . nested_model . id . to_python ( formdata [ idkey ] ) data = get_by ( self . initial_data , 'id' , id ) initial = flatten_json ( self . nested_form , data . to_mongo ( ) , prefix ) for key , value in initial . items ( ) : if key not in formdata : formdata [ key ] = value else : data = None return super ( NestedModelList , self ) . _add_entry ( formdata , data , index )
Fill the form with previous data if necessary to handle partial update
247,162
def parse ( self , data ) : self . field_errors = { } return dict ( ( k , self . _parse_value ( k , v ) ) for k , v in data . items ( ) )
Parse fields and store individual errors
247,163
def update ( site = False , organizations = False , users = False , datasets = False , reuses = False ) : do_all = not any ( ( site , organizations , users , datasets , reuses ) ) if do_all or site : log . info ( 'Update site metrics' ) update_site_metrics ( ) if do_all or datasets : log . info ( 'Update datasets metrics' ) for dataset in Dataset . objects . timeout ( False ) : update_metrics_for ( dataset ) if do_all or reuses : log . info ( 'Update reuses metrics' ) for reuse in Reuse . objects . timeout ( False ) : update_metrics_for ( reuse ) if do_all or organizations : log . info ( 'Update organizations metrics' ) for organization in Organization . objects . timeout ( False ) : update_metrics_for ( organization ) if do_all or users : log . info ( 'Update user metrics' ) for user in User . objects . timeout ( False ) : update_metrics_for ( user ) success ( 'All metrics have been updated' )
Update all metrics for the current date
247,164
def list ( ) : for cls , metrics in metric_catalog . items ( ) : echo ( white ( cls . __name__ ) ) for metric in metrics . keys ( ) : echo ( '> {0}' . format ( metric ) )
List all known metrics
247,165
def json_to_file ( data , filename , pretty = False ) : kwargs = dict ( indent = 4 ) if pretty else { } dirname = os . path . dirname ( filename ) if not os . path . exists ( dirname ) : os . makedirs ( dirname ) dump = json . dumps ( api . __schema__ , ** kwargs ) with open ( filename , 'wb' ) as f : f . write ( dump . encode ( 'utf-8' ) )
Dump JSON data to a file
247,166
def postman ( filename , pretty , urlvars , swagger ) : data = api . as_postman ( urlvars = urlvars , swagger = swagger ) json_to_file ( data , filename , pretty )
Dump the API as a Postman collection
247,167
def notify_badge_added_certified ( sender , kind = '' ) : if kind == CERTIFIED and isinstance ( sender , Organization ) : recipients = [ member . user for member in sender . members ] subject = _ ( 'Your organization "%(name)s" has been certified' , name = sender . name ) mail . send ( subject , recipients , 'badge_added_certified' , organization = sender , badge = sender . get_badge ( kind ) )
Send an email when a CERTIFIED badge is added to an Organization
247,168
def discussions_notifications ( user ) : notifications = [ ] qs = discussions_for ( user ) . only ( 'id' , 'created' , 'title' , 'subject' ) for discussion in qs . no_dereference ( ) : notifications . append ( ( discussion . created , { 'id' : discussion . id , 'title' : discussion . title , 'subject' : { 'id' : discussion . subject [ '_ref' ] . id , 'type' : discussion . subject [ '_cls' ] . lower ( ) , } } ) ) return notifications
Notify user about open discussions
247,169
def send_signal ( signal , request , user , ** kwargs ) : params = { 'user_ip' : request . remote_addr } params . update ( kwargs ) if user . is_authenticated : params [ 'uid' ] = user . id signal . send ( request . url , ** params )
Generic method to send signals to Piwik
247,170
def membership_request_notifications ( user ) : orgs = [ o for o in user . organizations if o . is_admin ( user ) ] notifications = [ ] for org in orgs : for request in org . pending_requests : notifications . append ( ( request . created , { 'id' : request . id , 'organization' : org . id , 'user' : { 'id' : request . user . id , 'fullname' : request . user . fullname , 'avatar' : str ( request . user . avatar ) } } ) ) return notifications
Notify user about pending membership requests
247,171
def validate ( identifier ) : source = actions . validate_source ( identifier ) log . info ( 'Source %s (%s) has been validated' , source . slug , str ( source . id ) )
Validate a source given its identifier
247,172
def delete ( identifier ) : log . info ( 'Deleting source "%s"' , identifier ) actions . delete_source ( identifier ) log . info ( 'Deleted source "%s"' , identifier )
Delete a harvest source
247,173
def sources ( scheduled = False ) : sources = actions . list_sources ( ) if scheduled : sources = [ s for s in sources if s . periodic_task ] if sources : for source in sources : msg = '{source.name} ({source.backend}): {cron}' if source . periodic_task : cron = source . periodic_task . schedule_display else : cron = 'not scheduled' log . info ( msg . format ( source = source , cron = cron ) ) elif scheduled : log . info ( 'No sources scheduled yet' ) else : log . info ( 'No sources defined yet' )
List all harvest sources
247,174
def backends ( ) : log . info ( 'Available backends:' ) for backend in actions . list_backends ( ) : log . info ( '%s (%s)' , backend . name , backend . display_name or backend . name )
List available backends
247,175
def schedule ( identifier , ** kwargs ) : source = actions . schedule ( identifier , ** kwargs ) msg = 'Scheduled {source.name} with the following crontab: {cron}' log . info ( msg . format ( source = source , cron = source . periodic_task . crontab ) )
Schedule a harvest job to run periodically
247,176
def unschedule ( identifier ) : source = actions . unschedule ( identifier ) log . info ( 'Unscheduled harvest source "%s"' , source . name )
Unschedule a periodical harvest job
247,177
def attach ( domain , filename ) : log . info ( 'Attaching datasets for domain %s' , domain ) result = actions . attach ( domain , filename ) log . info ( 'Attached %s datasets to %s' , result . success , domain )
Attach existing datasets to their harvest remote id
247,178
def request_transfer ( subject , recipient , comment ) : TransferPermission ( subject ) . test ( ) if recipient == ( subject . organization or subject . owner ) : raise ValueError ( 'Recipient should be different than the current owner' ) transfer = Transfer . objects . create ( owner = subject . organization or subject . owner , recipient = recipient , subject = subject , comment = comment ) return transfer
Initiate a transfer request
247,179
def accept_transfer ( transfer , comment = None ) : TransferResponsePermission ( transfer ) . test ( ) transfer . responded = datetime . now ( ) transfer . responder = current_user . _get_current_object ( ) transfer . status = 'accepted' transfer . response_comment = comment transfer . save ( ) subject = transfer . subject recipient = transfer . recipient if isinstance ( recipient , Organization ) : subject . organization = recipient elif isinstance ( recipient , User ) : subject . owner = recipient subject . save ( ) return transfer
Accept an incoming a transfer request
247,180
def refuse_transfer ( transfer , comment = None ) : TransferResponsePermission ( transfer ) . test ( ) transfer . responded = datetime . now ( ) transfer . responder = current_user . _get_current_object ( ) transfer . status = 'refused' transfer . response_comment = comment transfer . save ( ) return transfer
Refuse an incoming a transfer request
247,181
def clean ( self ) : if not self . metrics : self . metrics = dict ( ( name , spec . default ) for name , spec in ( metric_catalog . get ( self . __class__ , { } ) . items ( ) ) ) return super ( WithMetrics , self ) . clean ( )
Fill metrics with defaults on create
247,182
def build_catalog ( site , datasets , format = None ) : site_url = url_for ( 'site.home_redirect' , _external = True ) catalog_url = url_for ( 'site.rdf_catalog' , _external = True ) graph = Graph ( namespace_manager = namespace_manager ) catalog = graph . resource ( URIRef ( catalog_url ) ) catalog . set ( RDF . type , DCAT . Catalog ) catalog . set ( DCT . title , Literal ( site . title ) ) catalog . set ( DCT . language , Literal ( current_app . config [ 'DEFAULT_LANGUAGE' ] ) ) catalog . set ( FOAF . homepage , URIRef ( site_url ) ) publisher = graph . resource ( BNode ( ) ) publisher . set ( RDF . type , FOAF . Organization ) publisher . set ( FOAF . name , Literal ( current_app . config [ 'SITE_AUTHOR' ] ) ) catalog . set ( DCT . publisher , publisher ) for dataset in datasets : catalog . add ( DCAT . dataset , dataset_to_rdf ( dataset , graph ) ) if isinstance ( datasets , Paginable ) : if not format : raise ValueError ( 'Pagination requires format' ) catalog . add ( RDF . type , HYDRA . Collection ) catalog . set ( HYDRA . totalItems , Literal ( datasets . total ) ) kwargs = { 'format' : format , 'page_size' : datasets . page_size , '_external' : True , } first_url = url_for ( 'site.rdf_catalog_format' , page = 1 , ** kwargs ) page_url = url_for ( 'site.rdf_catalog_format' , page = datasets . page , ** kwargs ) last_url = url_for ( 'site.rdf_catalog_format' , page = datasets . pages , ** kwargs ) pagination = graph . resource ( URIRef ( page_url ) ) pagination . set ( RDF . type , HYDRA . PartialCollectionView ) pagination . set ( HYDRA . first , URIRef ( first_url ) ) pagination . set ( HYDRA . last , URIRef ( last_url ) ) if datasets . has_next : next_url = url_for ( 'site.rdf_catalog_format' , page = datasets . page + 1 , ** kwargs ) pagination . set ( HYDRA . next , URIRef ( next_url ) ) if datasets . has_prev : prev_url = url_for ( 'site.rdf_catalog_format' , page = datasets . page - 1 , ** kwargs ) pagination . set ( HYDRA . previous , URIRef ( prev_url ) ) catalog . set ( HYDRA . view , pagination ) return catalog
Build the DCAT catalog for this site
247,183
def sendmail_proxy ( subject , email , template , ** context ) : sendmail . delay ( subject . value , email , template , ** context )
Cast the lazy_gettext ed subject to string before passing to Celery
247,184
def collect ( path , no_input ) : if exists ( path ) : msg = '"%s" directory already exists and will be erased' log . warning ( msg , path ) if not no_input : click . confirm ( 'Are you sure?' , abort = True ) log . info ( 'Deleting static directory "%s"' , path ) shutil . rmtree ( path ) prefix = current_app . static_url_path or current_app . static_folder if prefix . startswith ( '/' ) : prefix = prefix [ 1 : ] destination = join ( path , prefix ) log . info ( 'Copying application assets into "%s"' , destination ) shutil . copytree ( current_app . static_folder , destination ) for blueprint in current_app . blueprints . values ( ) : if blueprint . has_static_folder : prefix = current_app . static_prefixes . get ( blueprint . name ) prefix = prefix or blueprint . url_prefix or '' prefix += blueprint . static_url_path or '' if prefix . startswith ( '/' ) : prefix = prefix [ 1 : ] log . info ( 'Copying %s assets to %s' , blueprint . name , prefix ) destination = join ( path , prefix ) copy_recursive ( blueprint . static_folder , destination ) for prefix , source in current_app . config [ 'STATIC_DIRS' ] : log . info ( 'Copying %s to %s' , source , prefix ) destination = join ( path , prefix ) copy_recursive ( source , destination ) log . info ( 'Done' )
Collect static files
247,185
def validate_harvester_notifications ( user ) : if not user . sysadmin : return [ ] notifications = [ ] qs = HarvestSource . objects ( validation__state = VALIDATION_PENDING ) qs = qs . only ( 'id' , 'created_at' , 'name' ) for source in qs : notifications . append ( ( source . created_at , { 'id' : source . id , 'name' : source . name , } ) ) return notifications
Notify admins about pending harvester validation
247,186
def get ( app , name ) : backend = get_all ( app ) . get ( name ) if not backend : msg = 'Harvest backend "{0}" is not registered' . format ( name ) raise EntrypointError ( msg ) return backend
Get a backend given its name
247,187
def search ( self ) : s = super ( TopicSearchMixin , self ) . search ( ) s = s . filter ( 'bool' , should = [ Q ( 'term' , tags = tag ) for tag in self . topic . tags ] ) return s
Override search to match on topic tags
247,188
def clean ( self ) : if not self . urlhash or 'url' in self . _get_changed_fields ( ) : self . urlhash = hash_url ( self . url ) super ( Reuse , self ) . clean ( )
Auto populate urlhash from url
247,189
def serve ( info , host , port , reload , debugger , eager_loading , with_threads ) : logger = logging . getLogger ( 'werkzeug' ) logger . setLevel ( logging . INFO ) logger . handlers = [ ] debug = current_app . config [ 'DEBUG' ] if reload is None : reload = bool ( debug ) if debugger is None : debugger = bool ( debug ) if eager_loading is None : eager_loading = not reload app = DispatchingApp ( info . load_app , use_eager_loading = eager_loading ) settings = os . environ . get ( 'UDATA_SETTINGS' , os . path . join ( os . getcwd ( ) , 'udata.cfg' ) ) extra_files = [ settings ] if reload : extra_files . extend ( assets . manifests_paths ( ) ) run_simple ( host , port , app , use_reloader = reload , use_debugger = debugger , threaded = with_threads , extra_files = extra_files )
Runs a local udata development server .
247,190
def enforce_filetype_file ( form , field ) : if form . _fields . get ( 'filetype' ) . data != RESOURCE_FILETYPE_FILE : return domain = urlparse ( field . data ) . netloc allowed_domains = current_app . config [ 'RESOURCES_FILE_ALLOWED_DOMAINS' ] allowed_domains += [ current_app . config . get ( 'SERVER_NAME' ) ] if current_app . config . get ( 'CDN_DOMAIN' ) : allowed_domains . append ( current_app . config [ 'CDN_DOMAIN' ] ) if '*' in allowed_domains : return if domain and domain not in allowed_domains : message = _ ( 'Domain "{domain}" not allowed for filetype "{filetype}"' ) raise validators . ValidationError ( message . format ( domain = domain , filetype = RESOURCE_FILETYPE_FILE ) )
Only allowed domains in resource . url when filetype is file
247,191
def map_legacy_frequencies ( form , field ) : if field . data in LEGACY_FREQUENCIES : field . data = LEGACY_FREQUENCIES [ field . data ]
Map legacy frequencies to new ones
247,192
def resources_availability ( self ) : availabilities = list ( chain ( * [ org . check_availability ( ) for org in self . organizations ] ) ) availabilities = [ a for a in availabilities if type ( a ) is bool ] if availabilities : return round ( 100. * sum ( availabilities ) / len ( availabilities ) , 2 ) return 100
Return the percentage of availability for resources .
247,193
def datasets_org_count ( self ) : from udata . models import Dataset return sum ( Dataset . objects ( organization = org ) . visible ( ) . count ( ) for org in self . organizations )
Return the number of datasets of user s organizations .
247,194
def followers_org_count ( self ) : from udata . models import Follow return sum ( Follow . objects ( following = org ) . count ( ) for org in self . organizations )
Return the number of followers of user s organizations .
247,195
def get_badge ( self , kind ) : candidates = [ b for b in self . badges if b . kind == kind ] return candidates [ 0 ] if candidates else None
Get a badge given its kind if present
247,196
def add_badge ( self , kind ) : badge = self . get_badge ( kind ) if badge : return badge if kind not in getattr ( self , '__badges__' , { } ) : msg = 'Unknown badge type for {model}: {kind}' raise db . ValidationError ( msg . format ( model = self . __class__ . __name__ , kind = kind ) ) badge = Badge ( kind = kind ) if current_user . is_authenticated : badge . created_by = current_user . id self . update ( __raw__ = { '$push' : { 'badges' : { '$each' : [ badge . to_mongo ( ) ] , '$position' : 0 } } } ) self . reload ( ) post_save . send ( self . __class__ , document = self ) on_badge_added . send ( self , kind = kind ) return self . get_badge ( kind )
Perform an atomic prepend for a new badge
247,197
def remove_badge ( self , kind ) : self . update ( __raw__ = { '$pull' : { 'badges' : { 'kind' : kind } } } ) self . reload ( ) on_badge_removed . send ( self , kind = kind ) post_save . send ( self . __class__ , document = self )
Perform an atomic removal for a given badge
247,198
def toggle_badge ( self , kind ) : badge = self . get_badge ( kind ) if badge : return self . remove_badge ( kind ) else : return self . add_badge ( kind )
Toggle a bdage given its kind
247,199
def badge_label ( self , badge ) : kind = badge . kind if isinstance ( badge , Badge ) else badge return self . __badges__ [ kind ]
Display the badge label for a given kind