idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
43,700 | def _get_xml_doc ( self , endpoint , query , is_post = False ) : response = self . _get_response ( endpoint , query , is_post = is_post ) return minidom . parse ( response . text ) | Return False if connection could not be made . Otherwise return a minidom Document . |
43,701 | def _make_candidate_from_result ( self , result ) : candidate = Candidate ( ) candidate . match_addr = result [ 'formatted_address' ] candidate . x = result [ 'geometry' ] [ 'location' ] [ 'lng' ] candidate . y = result [ 'geometry' ] [ 'location' ] [ 'lat' ] candidate . locator = self . LOCATOR_MAPPING . get ( result [ 'geometry' ] [ 'location_type' ] , '' ) candidate . entity_types = result [ 'types' ] candidate . partial_match = result . get ( 'partial_match' , False ) component_lookups = { 'city' : { 'type' : 'locality' , 'key' : 'long_name' } , 'subregion' : { 'type' : 'administrative_area_level_2' , 'key' : 'long_name' } , 'region' : { 'type' : 'administrative_area_level_1' , 'key' : 'short_name' } , 'postal' : { 'type' : 'postal_code' , 'key' : 'long_name' } , 'country' : { 'type' : 'country' , 'key' : 'short_name' } , } for ( field , lookup ) in component_lookups . items ( ) : setattr ( candidate , 'match_' + field , self . _get_component_from_result ( result , lookup ) ) candidate . geoservice = self . __class__ . __name__ return candidate | Make a Candidate from a Google geocoder results dictionary . |
43,702 | def _get_component_from_result ( self , result , lookup ) : for component in result [ 'address_components' ] : if lookup [ 'type' ] in component [ 'types' ] : return component . get ( lookup [ 'key' ] , '' ) return '' | Helper function to get a particular address component from a Google result . |
43,703 | def install_requirements ( self ) : print ( 'Installing Requirements' ) print ( platform . dist ( ) ) if platform . dist ( ) [ 0 ] in [ 'Ubuntu' , 'LinuxMint' ] : command = 'sudo apt-get install -y gcc git python3-dev zlib1g-dev make zip libssl-dev libbz2-dev liblzma-dev libcurl4-openssl-dev build-essential libxml2-dev apache2 zlib1g-dev bcftools build-essential cpanminus curl git libbz2-dev libcurl4-openssl-dev liblocal-lib-perl liblzma-dev libmysqlclient-dev libpng-dev libpq-dev libssl-dev manpages mysql-client openssl perl perl-base pkg-config python3-dev python3-pip python3-setuptools sed tabix unzip vcftools vim wget zlib1g-dev apache2 build-essential cpanminus curl git libmysqlclient-dev libpng-dev libssl-dev locales manpages mysql-client openssl perl perl-base unzip vim wget libgd-dev' sts = call ( command , shell = True ) try : subprocess . call ( [ 'java' , '-version' ] ) except : command = sts = call ( command , shell = True ) elif platform . dist ( ) [ 0 ] in [ 'debian' ] : command = 'sudo apt-get update' sts = call ( command , shell = True ) command = 'sudo apt-get install -y libmodule-install-perl apache2 bcftools build-essential cpanminus curl git libbz2-dev libcurl4-openssl-dev liblocal-lib-perl liblzma-dev default-libmysqlclient-dev libpng-dev libpq-dev libssl-dev manpages mysql-client openssl perl perl-base pkg-config python3-dev python3-pip python3-setuptools sed tabix unzip vcftools vim wget zlib1g-dev apache2 build-essential cpanminus curl git libpng-dev libssl-dev locales manpages mysql-client openssl perl perl-base unzip vim wget libgd-dev libxml-libxml-perl libgd-dev' sts = call ( command , shell = True ) command = 'sudo apt-get install -y default-jre default-jdk' sts = call ( command , shell = True ) elif platform . dist ( ) [ 0 ] in [ 'redhat' , 'centos' ] : command = 'sudo yum install libcurl-devel sed vcftools bcftools tabix zlib-devel postgresql96-libs perl-local-lib perl-App-cpanminus curl unzip wget' sts = call ( command , shell = True ) command = sts = call ( command , shell = True ) command = sts = call ( command , shell = True ) try : subprocess . call ( [ 'java' , '-version' ] ) except : command = "sudo yum install -y java-1.8.0-openjdk" sts = call ( command , shell = True ) command = "sudo cpanm DBI DBD::mysql File::Copy::Recursive Archive::Extract Archive::Zip LWP::Simple Bio::Root::Version LWP::Protocol::https Bio::DB::Fasta CGI Test::utf8 Test::File inc::Module::Install XML::DOM::XPath XML::LibXML" sts = call ( command , shell = True ) command = "sudo cpanm --local-lib=~/perl5 local::lib && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)" sts = call ( command , shell = True ) | Install Ubuntu Requirements |
43,704 | def search ( self , query : Optional [ dict ] = None , offset : Optional [ int ] = None , limit : Optional [ int ] = None , order_by : Union [ None , list , tuple ] = None ) -> Sequence [ 'IModel' ] : raise NotImplementedError | return search result based on specified rulez query |
43,705 | def aggregate ( self , query : Optional [ dict ] = None , group : Optional [ dict ] = None , order_by : Union [ None , list , tuple ] = None ) -> list : raise NotImplementedError | return aggregation result based on specified rulez query and group |
43,706 | def put_blob ( self , field : str , fileobj : BinaryIO , filename : str , mimetype : Optional [ str ] = None , size : Optional [ int ] = None , encoding : Optional [ str ] = None ) -> IBlob : raise NotImplementedError | Receive and store blob object |
43,707 | def search ( self , query : Optional [ dict ] = None , offset : int = 0 , limit : Optional [ int ] = None , order_by : Optional [ tuple ] = None , secure : bool = False ) -> List [ IModel ] : raise NotImplementedError | Search for models |
43,708 | def aggregate ( self , query : Optional [ dict ] = None , group : Optional [ dict ] = None , order_by : Optional [ tuple ] = None ) -> List [ IModel ] : raise NotImplementedError | Get aggregated results |
43,709 | def to_bing_str ( self ) : vb = self . convert_srs ( 4326 ) return '%s,%s,%s,%s' % ( vb . bottom , vb . left , vb . top , vb . right ) | Convert Viewbox object to a string that can be used by Bing as a query parameter . |
43,710 | def to_pelias_dict ( self ) : vb = self . convert_srs ( 4326 ) return { 'boundary.rect.min_lat' : vb . bottom , 'boundary.rect.min_lon' : vb . left , 'boundary.rect.max_lat' : vb . top , 'boundary.rect.max_lon' : vb . right } | Convert Viewbox object to a string that can be used by Pelias as a query parameter . |
43,711 | def to_esri_wgs_json ( self ) : try : return ( '{ "xmin" : %s, ' '"ymin" : %s, ' '"xmax" : %s, ' '"ymax" : %s, ' '"spatialReference" : {"wkid" : %d} }' % ( self . left , self . bottom , self . right , self . top , self . wkid ) ) except ValueError : raise Exception ( 'One or more values could not be cast to a number. ' 'Four bounding points must be real numbers. ' 'WKID must be an integer.' ) | Convert Viewbox object to a JSON string that can be used by the ESRI World Geocoding Service as a parameter . |
43,712 | def register ( context , request , load ) : data = request . json res = validate ( data , dataclass_to_jsl ( RegistrationSchema ) . get_schema ( ) ) if res : @ request . after def set_error ( response ) : response . status = 422 return { 'status' : 'error' , 'field_errors' : [ { 'message' : res [ x ] } for x in res . keys ( ) ] } if data [ 'password' ] != data [ 'password_validate' ] : @ request . after def adjust_response ( response ) : response . status = 422 return { 'status' : 'error' , 'message' : 'Password confirmation does not match' } if 'state' not in data . keys ( ) or not data [ 'state' ] : data [ 'state' ] = request . app . settings . application . new_user_state del data [ 'password_validate' ] obj = context . create ( data ) return { 'status' : 'success' } | Validate the username and password and create the user . |
43,713 | def process_login ( context , request ) : username = request . json [ 'username' ] password = request . json [ 'password' ] user = context . authenticate ( username , password ) if not user : @ request . after def adjust_status ( response ) : response . status = 401 return { 'status' : 'error' , 'error' : { 'code' : 401 , 'message' : 'Invalid Username / Password' } } @ request . after def remember ( response ) : response . headers . add ( 'Access-Control-Expose-Headers' , 'Authorization' ) identity = user . identity request . app . remember_identity ( response , request , identity ) return { 'status' : 'success' } | Authenticate username and password and log in user |
43,714 | def list_members ( context , request ) : members = context . members ( ) return { 'users' : [ { 'username' : m . identifier , 'userid' : m . userid , 'roles' : context . get_member_roles ( m . userid ) , 'links' : [ rellink ( m , request ) ] } for m in members ] } | Return the list of users in the group . |
43,715 | def grant_member ( context , request ) : mapping = request . json [ 'mapping' ] for entry in mapping : user = entry [ 'user' ] roles = entry [ 'roles' ] username = user . get ( 'username' , None ) userid = user . get ( 'userid' , None ) if userid : u = context . get_user_by_userid ( userid ) elif username : u = context . get_user_by_username ( username ) else : u = None if u is None : raise UnprocessableError ( 'User %s does not exists' % ( userid or username ) ) for rolename in roles : context . grant_member_role ( u . userid , rolename ) return { 'status' : 'success' } | Grant member roles in the group . |
43,716 | def revoke_member ( context , request ) : mapping = request . json [ 'mapping' ] for entry in mapping : user = entry [ 'user' ] roles = entry [ 'roles' ] username = user . get ( 'username' , None ) userid = user . get ( 'userid' , None ) if userid : u = context . get_user_by_userid ( userid ) elif username : u = context . get_user_by_username ( username ) else : u = None if u is None : raise UnprocessableError ( 'User %s does not exists' % ( userid or username ) ) for rolename in roles : context . revoke_member_role ( u . userid , rolename ) return { 'status' : 'success' } | Revoke member roles in the group . |
43,717 | def call_MediaInfo ( file_name , mediainfo_path = None ) : if mediainfo_path is None : mediainfo_path = find_MediaInfo ( ) result = subprocess . check_output ( [ mediainfo_path , "-f" , file_name ] , universal_newlines = True ) D = collections . defaultdict ( dict ) for line in result . splitlines ( ) : line = line . split ( ':' , 1 ) if line [ 0 ] == '' : continue elif len ( line ) == 1 : section = line [ 0 ] . strip ( ) else : k = line [ 0 ] . strip ( ) v = line [ 1 ] . strip ( ) if k not in D [ section ] : D [ section ] [ k ] = v return D | Returns a dictionary of dictionaries with the output of MediaInfo - f file_name |
43,718 | def check_video ( file_name , mediainfo_path = None ) : D = call_MediaInfo ( file_name , mediainfo_path ) err_msg = "Could not determine all video paramters" if ( "General" not in D ) or ( "Video" not in D ) : raise MediaInfoError ( err_msg ) general_keys = ( "Count of audio streams" , "File size" , "Overall bit rate" ) if any ( k not in D [ "General" ] for k in general_keys ) : raise MediaInfoError ( err_msg ) video_keys = ( "Format profile" , "Commercial name" , "Frame rate" , "Height" , "Scan type" , ) if any ( k not in D [ "Video" ] for k in video_keys ) : raise MediaInfoError ( err_msg ) return D | Scans the given file with MediaInfo and returns the video and audio codec information if all the required parameters were found . |
43,719 | def check_picture ( file_name , mediainfo_path = None ) : D = call_MediaInfo ( file_name , mediainfo_path ) if ( ( "Image" not in D ) or ( "Width" not in D [ "Image" ] ) or ( "Height" not in D [ "Image" ] ) ) : raise MediaInfoError ( "Could not determine all picture paramters" ) return D | Scans the given file with MediaInfo and returns the picture information if all the required parameters were found . |
43,720 | def _get_attributes ( schema , location ) : schema = DottedNameResolver ( __name__ ) . maybe_resolve ( schema ) def _filter ( attr ) : if not hasattr ( attr , "location" ) : valid_location = 'body' in location else : valid_location = attr . location in to_list ( location ) return valid_location return list ( filter ( _filter , schema ( ) . children ) ) | Return the schema s children filtered by location . |
43,721 | def is_acquired ( self ) : values = self . client . get ( self . key ) return six . b ( self . _uuid ) in values | Check if the lock is acquired |
43,722 | def get_url ( self , path ) : host = ( '[' + self . host + ']' if ( self . host . find ( ':' ) != - 1 ) else self . host ) base_url = self . protocol + '://' + host + ':' + str ( self . port ) return base_url + '/v3alpha/' + path . lstrip ( "/" ) | Construct a full url to the v3alpha API given a specific path |
43,723 | def post ( self , * args , ** kwargs ) : try : resp = self . session . post ( * args , ** kwargs ) if resp . status_code in _EXCEPTIONS_BY_CODE : raise _EXCEPTIONS_BY_CODE [ resp . status_code ] ( resp . reason ) if resp . status_code != requests . codes [ 'ok' ] : raise exceptions . Etcd3Exception ( resp . reason ) except requests . exceptions . Timeout as ex : raise exceptions . ConnectionTimeoutError ( six . text_type ( ex ) ) except requests . exceptions . ConnectionError as ex : raise exceptions . ConnectionFailedError ( six . text_type ( ex ) ) return resp . json ( ) | helper method for HTTP POST |
43,724 | def lease ( self , ttl = DEFAULT_TIMEOUT ) : result = self . post ( self . get_url ( "/lease/grant" ) , json = { "TTL" : ttl , "ID" : 0 } ) return Lease ( int ( result [ 'ID' ] ) , client = self ) | Create a Lease object given a timeout |
43,725 | def lock ( self , id = str ( uuid . uuid4 ( ) ) , ttl = DEFAULT_TIMEOUT ) : return Lock ( id , ttl = ttl , client = self ) | Create a Lock object given an ID and timeout |
43,726 | def create ( self , key , value ) : base64_key = _encode ( key ) base64_value = _encode ( value ) txn = { 'compare' : [ { 'key' : base64_key , 'result' : 'EQUAL' , 'target' : 'CREATE' , 'create_revision' : 0 } ] , 'success' : [ { 'request_put' : { 'key' : base64_key , 'value' : base64_value , } } ] , 'failure' : [ ] } result = self . transaction ( txn ) if 'succeeded' in result : return result [ 'succeeded' ] return False | Atomically create the given key only if the key doesn t exist . |
43,727 | def put ( self , key , value , lease = None ) : payload = { "key" : _encode ( key ) , "value" : _encode ( value ) } if lease : payload [ 'lease' ] = lease . id self . post ( self . get_url ( "/kv/put" ) , json = payload ) return True | Put puts the given key into the key - value store . |
43,728 | def delete ( self , key , ** kwargs ) : payload = { "key" : _encode ( key ) , } payload . update ( kwargs ) result = self . post ( self . get_url ( "/kv/deleterange" ) , json = payload ) if 'deleted' in result : return True return False | DeleteRange deletes the given range from the key - value store . |
43,729 | def transaction ( self , txn ) : return self . post ( self . get_url ( "/kv/txn" ) , data = json . dumps ( txn ) ) | Txn processes multiple requests in a single transaction . |
43,730 | def watch_prefix ( self , key_prefix , ** kwargs ) : kwargs [ 'range_end' ] = _increment_last_byte ( key_prefix ) return self . watch ( key_prefix , ** kwargs ) | The same as watch but watches a range of keys with a prefix . |
43,731 | def watch_prefix_once ( self , key_prefix , timeout = None , ** kwargs ) : kwargs [ 'range_end' ] = _increment_last_byte ( key_prefix ) return self . watch_once ( key_prefix , timeout = timeout , ** kwargs ) | Watches a range of keys with a prefix similar to watch_once |
43,732 | def create_timer ( cb : Callable [ [ float ] , None ] , interval : float , delay_policy : TimerDelayPolicy = TimerDelayPolicy . DEFAULT , loop : Optional [ asyncio . BaseEventLoop ] = None ) -> asyncio . Task : if not loop : loop = asyncio . get_event_loop ( ) async def _timer ( ) : fired_tasks = [ ] try : while True : if delay_policy == TimerDelayPolicy . CANCEL : for t in fired_tasks : if not t . done ( ) : t . cancel ( ) await t fired_tasks . clear ( ) else : fired_tasks [ : ] = [ t for t in fired_tasks if not t . done ( ) ] t = loop . create_task ( cb ( interval = interval ) ) fired_tasks . append ( t ) await asyncio . sleep ( interval ) except asyncio . CancelledError : for t in fired_tasks : t . cancel ( ) await asyncio . gather ( * fired_tasks ) return loop . create_task ( _timer ( ) ) | Schedule a timer with the given callable and the interval in seconds . The interval value is also passed to the callable . If the callable takes longer than the timer interval all accumulated callable s tasks will be cancelled when the timer is cancelled . |
43,733 | def revoke ( self ) : self . client . post ( self . client . get_url ( "/kv/lease/revoke" ) , json = { "ID" : self . id } ) return True | LeaseRevoke revokes a lease . |
43,734 | def ttl ( self ) : result = self . client . post ( self . client . get_url ( "/kv/lease/timetolive" ) , json = { "ID" : self . id } ) return int ( result [ 'TTL' ] ) | LeaseTimeToLive retrieves lease information . |
43,735 | def keys ( self ) : result = self . client . post ( self . client . get_url ( "/kv/lease/timetolive" ) , json = { "ID" : self . id , "keys" : True } ) keys = result [ 'keys' ] if 'keys' in result else [ ] return [ _decode ( key ) for key in keys ] | Get the keys associated with this lease . |
43,736 | def get_services ( self ) : if self . services : return self . services url = 'http://api.embed.ly/1/services/python' http = httplib2 . Http ( timeout = self . timeout ) headers = { 'User-Agent' : self . user_agent , 'Connection' : 'close' } resp , content = http . request ( url , headers = headers ) if resp [ 'status' ] == '200' : resp_data = json . loads ( content . decode ( 'utf-8' ) ) self . services = resp_data _regex = [ ] for each in self . services : _regex . append ( '|' . join ( each . get ( 'regex' , [ ] ) ) ) self . _regex = re . compile ( '|' . join ( _regex ) ) return self . services | get_services makes call to services end point of api . embed . ly to fetch the list of supported providers and their regexes |
43,737 | def _get ( self , version , method , url_or_urls , ** kwargs ) : if not url_or_urls : raise ValueError ( '%s requires a url or a list of urls given: %s' % ( method . title ( ) , url_or_urls ) ) multi = isinstance ( url_or_urls , list ) if multi and len ( url_or_urls ) > 20 : raise ValueError ( 'Embedly accepts only 20 urls at a time. Url ' 'Count:%s' % len ( url_or_urls ) ) query = '' key = kwargs . get ( 'key' , self . key ) if not key : raise ValueError ( 'Requires a key. None given: %s' % key ) kwargs [ 'key' ] = key query += urlencode ( kwargs ) if multi : query += '&urls=%s&' % ',' . join ( [ quote ( url ) for url in url_or_urls ] ) else : query += '&url=%s' % quote ( url_or_urls ) url = 'http://api.embed.ly/%s/%s?%s' % ( version , method , query ) http = httplib2 . Http ( timeout = self . timeout ) headers = { 'User-Agent' : self . user_agent , 'Connection' : 'close' } resp , content = http . request ( url , headers = headers ) if resp [ 'status' ] == '200' : data = json . loads ( content . decode ( 'utf-8' ) ) if kwargs . get ( 'raw' , False ) : data [ 'raw' ] = content else : data = { 'type' : 'error' , 'error' : True , 'error_code' : int ( resp [ 'status' ] ) } if multi : return map ( lambda url , data : Url ( data , method , url ) , url_or_urls , data ) return Url ( data , method , url_or_urls ) | _get makes the actual call to api . embed . ly |
43,738 | def _encode ( data ) : if not isinstance ( data , bytes_types ) : data = six . b ( str ( data ) ) return base64 . b64encode ( data ) . decode ( "utf-8" ) | Encode the given data using base - 64 |
43,739 | def _decode ( data ) : if not isinstance ( data , bytes_types ) : data = six . b ( str ( data ) ) return base64 . b64decode ( data . decode ( "utf-8" ) ) | Decode the base - 64 encoded string |
43,740 | def _increment_last_byte ( data ) : if not isinstance ( data , bytes_types ) : if isinstance ( data , six . string_types ) : data = data . encode ( 'utf-8' ) else : data = six . b ( str ( data ) ) s = bytearray ( data ) s [ - 1 ] = s [ - 1 ] + 1 return bytes ( s ) | Get the last byte in the array and increment it |
43,741 | def metadata ( self ) : self . metadata_path = os . path . join ( self . path , 'metadata.rb' ) if not os . path . isfile ( self . metadata_path ) : raise ValueError ( "Cookbook needs metadata.rb, %s" % self . metadata_path ) if not self . _metadata : self . _metadata = MetadataRb ( open ( self . metadata_path , 'r+' ) ) return self . _metadata | Return dict representation of this cookbook s metadata . rb . |
43,742 | def berksfile ( self ) : self . berks_path = os . path . join ( self . path , 'Berksfile' ) if not self . _berksfile : if not os . path . isfile ( self . berks_path ) : raise ValueError ( "No Berksfile found at %s" % self . berks_path ) self . _berksfile = Berksfile ( open ( self . berks_path , 'r+' ) ) return self . _berksfile | Return this cookbook s Berksfile instance . |
43,743 | def from_dict ( cls , dictionary ) : cookbooks = set ( ) groups = [ cookbooks ] for key , val in dictionary . items ( ) : if key == 'depends' : cookbooks . update ( { cls . depends_statement ( cbn , meta ) for cbn , meta in val . items ( ) } ) body = '' for group in groups : if group : body += '\n' body += '\n' . join ( group ) return cls . from_string ( body ) | Create a MetadataRb instance from a dict . |
43,744 | def depends_statement ( cookbook_name , metadata = None ) : line = "depends '%s'" % cookbook_name if metadata : if not isinstance ( metadata , dict ) : raise TypeError ( "Stencil dependency options for %s " "should be a dict of options, not %s." % ( cookbook_name , metadata ) ) if metadata : line = "%s '%s'" % ( line , "', '" . join ( metadata ) ) return line | Return a valid Ruby depends statement for the metadata . rb file . |
43,745 | def parse ( self ) : data = utils . ruby_lines ( self . readlines ( ) ) data = [ tuple ( j . strip ( ) for j in line . split ( None , 1 ) ) for line in data ] depends = { } for line in data : if not len ( line ) == 2 : continue key , value = line if key == 'depends' : value = value . split ( ',' ) lib = utils . ruby_strip ( value [ 0 ] ) detail = [ utils . ruby_strip ( j ) for j in value [ 1 : ] ] depends [ lib ] = detail datamap = { key : utils . ruby_strip ( val ) for key , val in data } if depends : datamap [ 'depends' ] = depends self . seek ( 0 ) return datamap | Parse the metadata . rb into a dict . |
43,746 | def merge ( self , other ) : if not isinstance ( other , MetadataRb ) : raise TypeError ( "MetadataRb to merge should be a 'MetadataRb' " "instance, not %s." , type ( other ) ) current = self . to_dict ( ) new = other . to_dict ( ) meta_writelines = [ '%s\n' % self . depends_statement ( cbn , meta ) for cbn , meta in new . get ( 'depends' , { } ) . items ( ) if cbn not in current . get ( 'depends' , { } ) ] self . write_statements ( meta_writelines ) return self . to_dict ( ) | Add requirements from other metadata . rb into this one . |
43,747 | def parse ( self ) : self . flush ( ) self . seek ( 0 ) data = utils . ruby_lines ( self . readlines ( ) ) data = [ tuple ( j . strip ( ) for j in line . split ( None , 1 ) ) for line in data ] datamap = { } for line in data : if len ( line ) == 1 : datamap [ line [ 0 ] ] = True elif len ( line ) == 2 : key , value = line if key == 'cookbook' : datamap . setdefault ( 'cookbook' , { } ) value = [ utils . ruby_strip ( v ) for v in value . split ( ',' ) ] lib , detail = value [ 0 ] , value [ 1 : ] datamap [ 'cookbook' ] . setdefault ( lib , { } ) if detail and not any ( "" . join ( detail ) . startswith ( o ) for o in self . berks_options ) : constraint , detail = detail [ 0 ] , detail [ 1 : ] datamap [ 'cookbook' ] [ lib ] [ 'constraint' ] = constraint if detail : for deet in detail : opt , val = [ utils . ruby_strip ( i ) for i in deet . split ( ':' , 1 ) ] if not any ( opt == o for o in self . berks_options ) : raise ValueError ( "Cookbook detail '%s' does not specify " "one of '%s'" % ( opt , self . berks_options ) ) else : datamap [ 'cookbook' ] [ lib ] [ opt . strip ( ':' ) ] = ( utils . ruby_strip ( val ) ) elif key == 'source' : datamap . setdefault ( key , [ ] ) datamap [ key ] . append ( utils . ruby_strip ( value ) ) elif key : datamap [ key ] = utils . ruby_strip ( value ) self . seek ( 0 ) return datamap | Parse this Berksfile into a dict . |
43,748 | def from_dict ( cls , dictionary ) : cookbooks = set ( ) sources = set ( ) other = set ( ) groups = [ sources , cookbooks , other ] for key , val in dictionary . items ( ) : if key == 'cookbook' : cookbooks . update ( { cls . cookbook_statement ( cbn , meta ) for cbn , meta in val . items ( ) } ) elif key == 'source' : sources . update ( { "source '%s'" % src for src in val } ) elif key == 'metadata' : other . add ( 'metadata' ) body = '' for group in groups : if group : body += '\n' body += '\n' . join ( group ) return cls . from_string ( body ) | Create a Berksfile instance from a dict . |
43,749 | def cookbook_statement ( cookbook_name , metadata = None ) : line = "cookbook '%s'" % cookbook_name if metadata : if not isinstance ( metadata , dict ) : raise TypeError ( "Berksfile dependency hash for %s " "should be a dict of options, not %s." % ( cookbook_name , metadata ) ) if 'constraint' in metadata : line += ", '%s'" % metadata . pop ( 'constraint' ) for opt , spec in metadata . items ( ) : line += ", %s: '%s'" % ( opt , spec ) return line | Return a valid Ruby cookbook statement for the Berksfile . |
43,750 | def merge ( self , other ) : if not isinstance ( other , Berksfile ) : raise TypeError ( "Berksfile to merge should be a 'Berksfile' " "instance, not %s." , type ( other ) ) current = self . to_dict ( ) new = other . to_dict ( ) berks_writelines = [ '%s\n' % self . cookbook_statement ( cbn , meta ) for cbn , meta in new . get ( 'cookbook' , { } ) . items ( ) if cbn not in current . get ( 'cookbook' , { } ) ] berks_writelines . extend ( [ "source '%s'\n" % src for src in new . get ( 'source' , [ ] ) if src not in current . get ( 'source' , [ ] ) ] ) self . write_statements ( berks_writelines ) return self . to_dict ( ) | Add requirements from other Berksfile into this one . |
43,751 | def manifest ( self ) : if not self . _manifest : with open ( self . manifest_path ) as man : self . _manifest = json . load ( man ) return self . _manifest | The manifest definition of the stencilset as a dict . |
43,752 | def stencils ( self ) : if not self . _stencils : self . _stencils = self . manifest [ 'stencils' ] return self . _stencils | List of stencils . |
43,753 | def get_stencil ( self , stencil_name , ** options ) : if stencil_name not in self . manifest . get ( 'stencils' , { } ) : raise ValueError ( "Stencil '%s' not declared in StencilSet " "manifest." % stencil_name ) stencil = copy . deepcopy ( self . manifest ) allstencils = stencil . pop ( 'stencils' ) stencil . pop ( 'default_stencil' , None ) override = allstencils [ stencil_name ] utils . deepupdate ( stencil , override ) for opt , data in stencil . get ( 'options' , { } ) . items ( ) : if opt not in options : options [ opt ] = data . get ( 'default' , '' ) stencil [ 'options' ] = options name = stencil [ 'options' ] . get ( 'name' ) files = stencil [ 'files' ] . copy ( ) for fil , templ in files . items ( ) : if '<NAME>' in fil : if not name : raise ValueError ( "Stencil does not include a name option" ) stencil [ 'files' ] . pop ( fil ) fil = fil . replace ( '<NAME>' , name ) stencil [ 'files' ] [ fil ] = templ return stencil | Return a Stencil instance given a stencil name . |
43,754 | def _determine_selected_stencil ( stencil_set , stencil_definition ) : if 'stencil' not in stencil_definition : selected_stencil_name = stencil_set . manifest . get ( 'default_stencil' ) else : selected_stencil_name = stencil_definition . get ( 'stencil' ) if not selected_stencil_name : raise ValueError ( "No stencil name, within stencil set %s, specified." % stencil_definition [ 'name' ] ) return selected_stencil_name | Determine appropriate stencil name for stencil definition . |
43,755 | def _build_template_map ( cookbook , cookbook_name , stencil ) : template_map = { 'cookbook' : { "name" : cookbook_name } , 'options' : stencil [ 'options' ] } try : template_map [ 'cookbook' ] = cookbook . metadata . to_dict ( ) . copy ( ) except ValueError : pass template_map [ 'cookbook' ] [ 'year' ] = datetime . datetime . now ( ) . year return template_map | Build a map of variables for this generated cookbook and stencil . |
43,756 | def _render_binaries ( files , written_files ) : for source_path , target_path in files . items ( ) : needdir = os . path . dirname ( target_path ) assert needdir , "Target should have valid parent dir" try : os . makedirs ( needdir ) except OSError as err : if err . errno != errno . EEXIST : raise if os . path . isfile ( target_path ) : if target_path in written_files : LOG . warning ( "Previous stencil has already written file %s." , target_path ) else : print ( "Skipping existing file %s" % target_path ) LOG . info ( "Skipping existing file %s" , target_path ) continue print ( "Writing rendered file %s" % target_path ) LOG . info ( "Writing rendered file %s" , target_path ) shutil . copy ( source_path , target_path ) if os . path . exists ( target_path ) : written_files . append ( target_path ) | Write binary contents from filetable into files . |
43,757 | def _render_templates ( files , filetable , written_files , force , open_mode = 'w' ) : for tpl_path , content in filetable : target_path = files [ tpl_path ] needdir = os . path . dirname ( target_path ) assert needdir , "Target should have valid parent dir" try : os . makedirs ( needdir ) except OSError as err : if err . errno != errno . EEXIST : raise if os . path . isfile ( target_path ) : if force : LOG . warning ( "Forcing overwrite of existing file %s." , target_path ) elif target_path in written_files : LOG . warning ( "Previous stencil has already written file %s." , target_path ) else : print ( "Skipping existing file %s" % target_path ) LOG . info ( "Skipping existing file %s" , target_path ) continue with open ( target_path , open_mode ) as newfile : print ( "Writing rendered file %s" % target_path ) LOG . info ( "Writing rendered file %s" , target_path ) newfile . write ( content ) written_files . append ( target_path ) | Write template contents from filetable into files . |
43,758 | def build_cookbook ( build_config , templatepack_path , cookbooks_home , force = False ) : with open ( build_config ) as cfg : cfg = json . load ( cfg ) cookbook_name = cfg [ 'name' ] template_pack = pack . TemplatePack ( templatepack_path ) written_files = [ ] cookbook = create_new_cookbook ( cookbook_name , cookbooks_home ) for stencil_definition in cfg [ 'stencils' ] : selected_stencil_set_name = stencil_definition . get ( 'stencil_set' ) stencil_set = template_pack . load_stencil_set ( selected_stencil_set_name ) selected_stencil_name = _determine_selected_stencil ( stencil_set , stencil_definition ) stencil = stencil_set . get_stencil ( selected_stencil_name , ** stencil_definition ) updated_cookbook = process_stencil ( cookbook , cookbook_name , template_pack , force , stencil_set , stencil , written_files ) return written_files , updated_cookbook | Build a cookbook from a fastfood . json file . |
43,759 | def process_stencil ( cookbook , cookbook_name , template_pack , force_argument , stencil_set , stencil , written_files ) : force = force_argument or stencil [ 'options' ] . get ( 'force' , False ) stencil [ 'files' ] = stencil . get ( 'files' ) or { } files = { os . path . join ( stencil_set . path , tpl ) : os . path . join ( cookbook . path , tgt ) for tgt , tpl in stencil [ 'files' ] . items ( ) } stencil [ 'partials' ] = stencil . get ( 'partials' ) or { } partials = { os . path . join ( stencil_set . path , tpl ) : os . path . join ( cookbook . path , tgt ) for tgt , tpl in stencil [ 'partials' ] . items ( ) } stencil [ 'binaries' ] = stencil . get ( 'binaries' ) or { } binaries = { os . path . join ( stencil_set . path , tpl ) : os . path . join ( cookbook . path , tgt ) for tgt , tpl in stencil [ 'binaries' ] . items ( ) } template_map = _build_template_map ( cookbook , cookbook_name , stencil ) filetable = templating . render_templates ( * files . keys ( ) , ** template_map ) _render_templates ( files , filetable , written_files , force ) parttable = templating . render_templates ( * partials . keys ( ) , ** template_map ) _render_templates ( partials , parttable , written_files , force , open_mode = 'a' ) _render_binaries ( binaries , written_files ) stencil_metadata_deps = { 'depends' : stencil . get ( 'dependencies' , { } ) } stencil_metadata = book . MetadataRb . from_dict ( stencil_metadata_deps ) cookbook . metadata . merge ( stencil_metadata ) stencil_berks_deps = { 'cookbook' : stencil . get ( 'berks_dependencies' , { } ) } stencil_berks = book . Berksfile . from_dict ( stencil_berks_deps ) cookbook . berksfile . merge ( stencil_berks ) return cookbook | Process the stencil requested writing any missing files as needed . |
43,760 | def create_new_cookbook ( cookbook_name , cookbooks_home ) : cookbooks_home = utils . normalize_path ( cookbooks_home ) if not os . path . exists ( cookbooks_home ) : raise ValueError ( "Target cookbook dir %s does not exist." % os . path . relpath ( cookbooks_home ) ) target_dir = os . path . join ( cookbooks_home , cookbook_name ) LOG . debug ( "Creating dir -> %s" , target_dir ) try : os . makedirs ( target_dir ) except OSError as err : if err . errno != errno . EEXIST : raise else : LOG . info ( "Skipping existing directory %s" , target_dir ) cookbook_path = os . path . join ( cookbooks_home , cookbook_name ) cookbook = book . CookBook ( cookbook_path ) return cookbook | Create a new cookbook . |
43,761 | def deepupdate ( original , update , levels = 5 ) : if not isinstance ( update , dict ) : update = dict ( update ) if not levels > 0 : original . update ( update ) else : for key , val in update . items ( ) : if isinstance ( original . get ( key ) , dict ) : if not isinstance ( val , dict ) : raise TypeError ( "Trying to update dict %s with " "non-dict %s" % ( original [ key ] , val ) ) deepupdate ( original [ key ] , val , levels = levels - 1 ) else : original . update ( { key : val } ) | Update like dict . update but deeper . |
43,762 | def write_statements ( self , statements ) : self . seek ( 0 ) original_content_lines = self . readlines ( ) new_content_lines = copy . copy ( original_content_lines ) statements = sorted ( [ stmnt for stmnt in statements if stmnt ] ) uniqs = { stmnt . split ( None , 1 ) [ 0 ] for stmnt in statements } insert_locations = { } for line in reversed ( original_content_lines ) : if not uniqs : break if not line : continue for word in uniqs . copy ( ) : if line . startswith ( word ) : index = original_content_lines . index ( line ) + 1 insert_locations [ word ] = index uniqs . remove ( word ) for statement in statements : print ( "writing to %s : %s" % ( self , statement ) ) startswith = statement . split ( None , 1 ) [ 0 ] new_content_lines . insert ( insert_locations . get ( startswith , len ( new_content_lines ) ) , statement ) if new_content_lines != original_content_lines : self . seek ( 0 ) self . writelines ( new_content_lines ) self . flush ( ) | Insert the statements into the file neatly . |
43,763 | def _fastfood_build ( args ) : written_files , cookbook = food . build_cookbook ( args . config_file , args . template_pack , args . cookbooks , args . force ) if len ( written_files ) > 0 : print ( "%s: %s files written" % ( cookbook , len ( written_files ) ) ) else : print ( "%s up to date" % cookbook ) return written_files , cookbook | Run on fastfood build . |
43,764 | def _fastfood_list ( args ) : template_pack = pack . TemplatePack ( args . template_pack ) if args . stencil_set : stencil_set = template_pack . load_stencil_set ( args . stencil_set ) print ( "Available Stencils for %s:" % args . stencil_set ) for stencil in stencil_set . stencils : print ( " %s" % stencil ) else : print ( 'Available Stencil Sets:' ) for name , vals in template_pack . stencil_sets . items ( ) : print ( " %12s - %12s" % ( name , vals [ 'help' ] ) ) | Run on fastfood list . |
43,765 | def _fastfood_show ( args ) : template_pack = pack . TemplatePack ( args . template_pack ) if args . stencil_set : stencil_set = template_pack . load_stencil_set ( args . stencil_set ) print ( "Stencil Set %s:" % args . stencil_set ) print ( ' Stencils:' ) for stencil in stencil_set . stencils : print ( " %s" % stencil ) print ( ' Options:' ) for opt , vals in stencil_set . manifest [ 'options' ] . items ( ) : print ( " %s - %s" % ( opt , vals [ 'help' ] ) ) | Run on fastfood show . |
43,766 | def _release_info ( ) : pypi_url = 'http://pypi.python.org/pypi/fastfood/json' headers = { 'Accept' : 'application/json' , } request = urllib . Request ( pypi_url , headers = headers ) response = urllib . urlopen ( request ) . read ( ) . decode ( 'utf_8' ) data = json . loads ( response ) return data | Check latest fastfood release info from PyPI . |
43,767 | def getenv ( option_name , default = None ) : env = "%s_%s" % ( NAMESPACE . upper ( ) , option_name . upper ( ) ) return os . environ . get ( env , default ) | Return the option from the environment in the FASTFOOD namespace . |
43,768 | def _validate ( self , key , cls = None ) : if key not in self . manifest : raise ValueError ( "Manifest %s requires '%s'." % ( self . manifest_path , key ) ) if cls : if not isinstance ( self . manifest [ key ] , cls ) : raise TypeError ( "Manifest value '%s' should be %s, not %s" % ( key , cls , type ( self . manifest [ key ] ) ) ) | Verify the manifest schema . |
43,769 | def stencil_sets ( self ) : if not self . _stencil_sets : self . _stencil_sets = self . manifest [ 'stencil_sets' ] return self . _stencil_sets | List of stencil sets . |
43,770 | def load_stencil_set ( self , stencilset_name ) : if stencilset_name not in self . _stencil_sets : if stencilset_name not in self . manifest [ 'stencil_sets' ] . keys ( ) : raise exc . FastfoodStencilSetNotListed ( "Stencil set '%s' not listed in %s under stencil_sets." % ( stencilset_name , self . manifest_path ) ) stencil_path = os . path . join ( self . path , 'stencils' , stencilset_name ) self . _stencil_sets [ stencilset_name ] = ( stencil_module . StencilSet ( stencil_path ) ) return self . _stencil_sets [ stencilset_name ] | Return the Stencil Set from this template pack . |
43,771 | def qstring ( option ) : if ( re . match ( NODE_ATTR_RE , option ) is None and re . match ( CHEF_CONST_RE , option ) is None ) : return "'%s'" % option else : return option | Custom quoting method for jinja . |
43,772 | def render_templates_generator ( * files , ** template_map ) : for path in files : if not os . path . isfile ( path ) : raise ValueError ( "Template file %s not found" % os . path . relpath ( path ) ) else : try : with codecs . open ( path , encoding = 'utf-8' ) as f : text = f . read ( ) template = JINJA_ENV . from_string ( text ) except jinja2 . TemplateSyntaxError as err : msg = ( "Error rendering jinja2 template for file %s " "on line %s. Error: %s" % ( path , err . lineno , err . message ) ) raise type ( err ) ( msg , err . lineno , filename = os . path . basename ( path ) ) result = template . render ( ** template_map ) if not result . endswith ( '\n' ) : result += '\n' yield path , result | Render jinja templates according to template_map . |
43,773 | def run ( self , element , outfolder ) : filepath = self . relative_path_for_element ( element ) if outfolder and not os . path . isabs ( filepath ) : filepath = os . path . join ( outfolder , filepath ) _logger . debug ( '{!r} . format ( element , filepath ) ) self . ensure_folder ( filepath ) self . generate_file ( element , filepath ) | Apply this task to model element . |
43,774 | def create_template_context ( self , element , ** kwargs ) : context = dict ( element = element , ** kwargs ) if self . global_context : context . update ( ** self . global_context ) return context | Code generation context specific to template and current element . |
43,775 | def create_environment ( self , ** kwargs ) : return jinja2 . Environment ( loader = jinja2 . FileSystemLoader ( self . templates_path ) , ** kwargs ) | Return a new Jinja environment . Derived classes may override method to pass additional parameters or to change the template loader type . |
43,776 | def pairs ( a ) : a = np . asarray ( a ) return as_strided ( a , shape = ( a . size - 1 , 2 ) , strides = a . strides * 2 ) | Return array of pairs of adjacent elements in a . |
43,777 | def predict_epitopes_from_args ( args ) : mhc_model = mhc_binding_predictor_from_args ( args ) variants = variant_collection_from_args ( args ) gene_expression_dict = rna_gene_expression_dict_from_args ( args ) transcript_expression_dict = rna_transcript_expression_dict_from_args ( args ) predictor = TopiaryPredictor ( mhc_model = mhc_model , padding_around_mutation = args . padding_around_mutation , ic50_cutoff = args . ic50_cutoff , percentile_cutoff = args . percentile_cutoff , min_transcript_expression = args . rna_min_transcript_expression , min_gene_expression = args . rna_min_gene_expression , only_novel_epitopes = args . only_novel_epitopes , raise_on_error = not args . skip_variant_errors ) return predictor . predict_from_variants ( variants = variants , transcript_expression_dict = transcript_expression_dict , gene_expression_dict = gene_expression_dict ) | Returns an epitope collection from the given commandline arguments . |
43,778 | def get_random_word ( dictionary , min_word_length = 3 , max_word_length = 8 ) : while True : word = choice ( dictionary ) if len ( word ) >= min_word_length and len ( word ) <= max_word_length : break return word | Returns a random word from the dictionary |
43,779 | def pw ( min_word_length = 3 , max_word_length = 8 , max_int_value = 1000 , number_of_elements = 4 , no_special_characters = False ) : int_position = set_int_position ( number_of_elements ) dictionary = load_dictionary ( ) password = '' for i in range ( number_of_elements ) : if i == int_position : password += str ( get_random_int ( max_int_value ) ) else : password += get_random_word ( dictionary , min_word_length , max_word_length ) . title ( ) if i != number_of_elements - 1 : password += get_random_separator ( no_special_characters ) return password | Generate a password |
43,780 | def check_padding_around_mutation ( given_padding , epitope_lengths ) : min_required_padding = max ( epitope_lengths ) - 1 if not given_padding : return min_required_padding else : require_integer ( given_padding , "Padding around mutation" ) if given_padding < min_required_padding : raise ValueError ( "Padding around mutation %d cannot be less than %d " "for epitope lengths %s" % ( given_padding , min_required_padding , epitope_lengths ) ) return given_padding | If user doesn t provide any padding around the mutation we need to at least include enough of the surrounding non - mutated esidues to construct candidate epitopes of the specified lengths . |
43,781 | def peptide_mutation_interval ( peptide_start_in_protein , peptide_length , mutation_start_in_protein , mutation_end_in_protein ) : if peptide_start_in_protein > mutation_end_in_protein : raise ValueError ( "Peptide starts after mutation" ) elif peptide_start_in_protein + peptide_length < mutation_start_in_protein : raise ValueError ( "Peptide ends before mutation" ) peptide_mutation_start_offset = min ( peptide_length , max ( 0 , mutation_start_in_protein - peptide_start_in_protein ) ) peptide_mutation_end_offset = min ( peptide_length , max ( 0 , mutation_end_in_protein - peptide_start_in_protein ) ) return ( peptide_mutation_start_offset , peptide_mutation_end_offset ) | Half - open interval of mutated residues in the peptide determined from the mutation interval in the original protein sequence . |
43,782 | def from_dict ( cls , indicator ) : tags = indicator . get ( 'tags' ) if tags is not None : tags = [ Tag . from_dict ( tag ) for tag in tags ] return Indicator ( value = indicator . get ( 'value' ) , type = indicator . get ( 'indicatorType' ) , priority_level = indicator . get ( 'priorityLevel' ) , correlation_count = indicator . get ( 'correlationCount' ) , whitelisted = indicator . get ( 'whitelisted' ) , weight = indicator . get ( 'weight' ) , reason = indicator . get ( 'reason' ) , first_seen = indicator . get ( 'firstSeen' ) , last_seen = indicator . get ( 'lastSeen' ) , sightings = indicator . get ( 'sightings' ) , source = indicator . get ( 'source' ) , notes = indicator . get ( 'notes' ) , tags = tags , enclave_ids = indicator . get ( 'enclaveIds' ) ) | Create an indicator object from a dictionary . |
43,783 | def to_dict ( self , remove_nones = False ) : if remove_nones : return super ( ) . to_dict ( remove_nones = True ) tags = None if self . tags is not None : tags = [ tag . to_dict ( remove_nones = remove_nones ) for tag in self . tags ] return { 'value' : self . value , 'indicatorType' : self . type , 'priorityLevel' : self . priority_level , 'correlationCount' : self . correlation_count , 'whitelisted' : self . whitelisted , 'weight' : self . weight , 'reason' : self . reason , 'firstSeen' : self . first_seen , 'lastSeen' : self . last_seen , 'source' : self . source , 'notes' : self . notes , 'tags' : tags , 'enclaveIds' : self . enclave_ids } | Creates a dictionary representation of the indicator . |
43,784 | def apply_filter ( filter_fn , collection , result_fn = None , filter_name = "" , collection_name = "" ) : n_before = len ( collection ) filtered = [ x for x in collection if filter_fn ( x ) ] n_after = len ( filtered ) if not collection_name : collection_name = collection . __class__ . __name__ logging . info ( "%s filtering removed %d/%d entries of %s" , filter_name , ( n_before - n_after ) , n_before , collection_name ) return result_fn ( filtered ) if result_fn else collection . __class__ ( filtered ) | Apply filter to effect collection and print number of dropped elements |
43,785 | def filter_silent_and_noncoding_effects ( effects ) : return apply_filter ( filter_fn = lambda effect : isinstance ( effect , NonsilentCodingMutation ) , collection = effects , result_fn = effects . clone_with_new_elements , filter_name = "Silent mutation" ) | Keep only variant effects which result in modified proteins . |
43,786 | def apply_variant_expression_filters ( variants , gene_expression_dict , gene_expression_threshold , transcript_expression_dict , transcript_expression_threshold ) : if gene_expression_dict : variants = apply_filter ( lambda variant : any ( gene_expression_dict . get ( gene_id , 0.0 ) >= gene_expression_threshold for gene_id in variant . gene_ids ) , variants , result_fn = variants . clone_with_new_elements , filter_name = "Variant gene expression (min=%0.4f)" % gene_expression_threshold ) if transcript_expression_dict : variants = apply_filter ( lambda variant : any ( transcript_expression_dict . get ( transcript_id , 0.0 ) >= transcript_expression_threshold for transcript_id in variant . transcript_ids ) , variants , result_fn = variants . clone_with_new_elements , filter_name = ( "Variant transcript expression (min=%0.4f)" % ( transcript_expression_threshold , ) ) ) return variants | Filter a collection of variants by gene and transcript expression thresholds |
43,787 | def apply_effect_expression_filters ( effects , gene_expression_dict , gene_expression_threshold , transcript_expression_dict , transcript_expression_threshold ) : if gene_expression_dict : effects = apply_filter ( lambda effect : ( gene_expression_dict . get ( effect . gene_id , 0.0 ) >= gene_expression_threshold ) , effects , result_fn = effects . clone_with_new_elements , filter_name = "Effect gene expression (min = %0.4f)" % gene_expression_threshold ) if transcript_expression_dict : effects = apply_filter ( lambda effect : ( transcript_expression_dict . get ( effect . transcript_id , 0.0 ) >= transcript_expression_threshold ) , effects , result_fn = effects . clone_with_new_elements , filter_name = ( "Effect transcript expression (min=%0.4f)" % ( transcript_expression_threshold , ) ) ) return effects | Filter collection of varcode effects by given gene and transcript expression thresholds . |
43,788 | def get_indicators ( self , from_time = None , to_time = None , enclave_ids = None , included_tag_ids = None , excluded_tag_ids = None , start_page = 0 , page_size = None ) : indicators_page_generator = self . _get_indicators_page_generator ( from_time = from_time , to_time = to_time , enclave_ids = enclave_ids , included_tag_ids = included_tag_ids , excluded_tag_ids = excluded_tag_ids , page_number = start_page , page_size = page_size ) indicators_generator = Page . get_generator ( page_generator = indicators_page_generator ) return indicators_generator | Creates a generator from the |get_indicators_page| method that returns each successive indicator as an |Indicator| object containing values for the value and type attributes only ; all other |Indicator| object attributes will contain Null values . |
43,789 | def _get_indicators_page_generator ( self , from_time = None , to_time = None , page_number = 0 , page_size = None , enclave_ids = None , included_tag_ids = None , excluded_tag_ids = None ) : get_page = functools . partial ( self . get_indicators_page , from_time = from_time , to_time = to_time , page_number = page_number , page_size = page_size , enclave_ids = enclave_ids , included_tag_ids = included_tag_ids , excluded_tag_ids = excluded_tag_ids ) return Page . get_page_generator ( get_page , page_number , page_size ) | Creates a generator from the |get_indicators_page| method that returns each successive page . |
43,790 | def get_indicators_page ( self , from_time = None , to_time = None , page_number = None , page_size = None , enclave_ids = None , included_tag_ids = None , excluded_tag_ids = None ) : params = { 'from' : from_time , 'to' : to_time , 'pageSize' : page_size , 'pageNumber' : page_number , 'enclaveIds' : enclave_ids , 'tagIds' : included_tag_ids , 'excludedTagIds' : excluded_tag_ids } resp = self . _client . get ( "indicators" , params = params ) page_of_indicators = Page . from_dict ( resp . json ( ) , content_type = Indicator ) return page_of_indicators | Get a page of indicators matching the provided filters . |
43,791 | def search_indicators ( self , search_term = None , enclave_ids = None , from_time = None , to_time = None , indicator_types = None , tags = None , excluded_tags = None ) : return Page . get_generator ( page_generator = self . _search_indicators_page_generator ( search_term , enclave_ids , from_time , to_time , indicator_types , tags , excluded_tags ) ) | Uses the |search_indicators_page| method to create a generator that returns each successive indicator . |
43,792 | def _search_indicators_page_generator ( self , search_term = None , enclave_ids = None , from_time = None , to_time = None , indicator_types = None , tags = None , excluded_tags = None , start_page = 0 , page_size = None ) : get_page = functools . partial ( self . search_indicators_page , search_term , enclave_ids , from_time , to_time , indicator_types , tags , excluded_tags ) return Page . get_page_generator ( get_page , start_page , page_size ) | Creates a generator from the |search_indicators_page| method that returns each successive page . |
43,793 | def search_indicators_page ( self , search_term = None , enclave_ids = None , from_time = None , to_time = None , indicator_types = None , tags = None , excluded_tags = None , page_size = None , page_number = None ) : body = { 'searchTerm' : search_term } params = { 'enclaveIds' : enclave_ids , 'from' : from_time , 'to' : to_time , 'entityTypes' : indicator_types , 'tags' : tags , 'excludedTags' : excluded_tags , 'pageSize' : page_size , 'pageNumber' : page_number } resp = self . _client . post ( "indicators/search" , params = params , data = json . dumps ( body ) ) return Page . from_dict ( resp . json ( ) , content_type = Indicator ) | Search for indicators containing a search term . |
43,794 | def get_related_indicators ( self , indicators = None , enclave_ids = None ) : return Page . get_generator ( page_generator = self . _get_related_indicators_page_generator ( indicators , enclave_ids ) ) | Uses the |get_related_indicators_page| method to create a generator that returns each successive report . |
43,795 | def get_indicator_metadata ( self , value ) : result = self . get_indicators_metadata ( [ Indicator ( value = value ) ] ) if len ( result ) > 0 : indicator = result [ 0 ] return { 'indicator' : indicator , 'tags' : indicator . tags , 'enclaveIds' : indicator . enclave_ids } else : return None | Provide metadata associated with a single indicators including value indicatorType noteCount sightings lastSeen enclaveIds and tags . The metadata is determined based on the enclaves the user making the request has READ access to . |
43,796 | def get_indicators_metadata ( self , indicators ) : data = [ { 'value' : i . value , 'indicatorType' : i . type } for i in indicators ] resp = self . _client . post ( "indicators/metadata" , data = json . dumps ( data ) ) return [ Indicator . from_dict ( x ) for x in resp . json ( ) ] | Provide metadata associated with an list of indicators including value indicatorType noteCount sightings lastSeen enclaveIds and tags . The metadata is determined based on the enclaves the user making the request has READ access to . |
43,797 | def add_terms_to_whitelist ( self , terms ) : resp = self . _client . post ( "whitelist" , json = terms ) return [ Indicator . from_dict ( indicator ) for indicator in resp . json ( ) ] | Add a list of terms to the user s company s whitelist . |
43,798 | def delete_indicator_from_whitelist ( self , indicator ) : params = indicator . to_dict ( ) self . _client . delete ( "whitelist" , params = params ) | Delete an indicator from the user s company s whitelist . |
43,799 | def get_community_trends ( self , indicator_type = None , days_back = None ) : params = { 'type' : indicator_type , 'daysBack' : days_back } resp = self . _client . get ( "indicators/community-trending" , params = params ) body = resp . json ( ) return [ Indicator . from_dict ( indicator ) for indicator in body ] | Find indicators that are trending in the community . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.