signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse_phlat_file ( phlatfile , mhc_alleles ) : """Parse the input phlat file to pull out the alleles it contains : param phlatfile : Open file descriptor for a phlat output sum file : param mhc _ alleles : dictionary of alleles ."""
for line in phlatfile : if line . startswith ( 'Locus' ) : continue line = line . strip ( ) . split ( ) if line [ 0 ] . startswith ( 'HLA_D' ) : line [ 0 ] = line [ 0 ] [ : - 1 ] # strip the last character # Sometimes we get an error saying there was insufficient read # conve...
def consume ( self , expect_class = None ) : """Retrieve the current token , then advance the parser . If an expected class is provided , it will assert that the current token matches that class ( is an instance ) . Note that when calling a token ' s nud ( ) or led ( ) functions , the " current " token is t...
if expect_class and not isinstance ( self . current_token , expect_class ) : raise InvalidTokenError ( "Unexpected token at %d: got %r, expected %s" % ( self . current_pos , self . current_token , expect_class . __name__ ) ) current_token = self . current_token self . _forward ( ) return current_token
def delete ( self , user ) : """Delete a resource"""
if user : can_delete = yield self . can_delete ( user ) else : can_delete = False if not can_delete : raise exceptions . Unauthorized ( 'User may not delete the resource' ) doc = { '_id' : self . id , '_deleted' : True } try : doc [ '_rev' ] = self . _rev except AttributeError : pass db = self . db_...
def get_resource ( resource_name ) : """Return a resource in current directory or in frozen package"""
resource_path = None if hasattr ( sys , "frozen" ) : resource_path = os . path . normpath ( os . path . join ( os . path . dirname ( sys . executable ) , resource_name ) ) elif not hasattr ( sys , "frozen" ) and pkg_resources . resource_exists ( "gns3server" , resource_name ) : resource_path = pkg_resources . r...
def get_climate ( self , device_label ) : """Get climate history Args : device _ label : device label of climate device"""
response = None try : response = requests . get ( urls . climate ( self . _giid ) , headers = { 'Accept' : 'application/json, text/javascript, */*; q=0.01' , 'Cookie' : 'vid={}' . format ( self . _vid ) } , params = { "deviceLabel" : device_label } ) except requests . exceptions . RequestException as ex : raise...
def make_dbsource ( ** kwargs ) : """Returns a mapnik PostGIS or SQLite Datasource ."""
if 'spatialite' in connection . settings_dict . get ( 'ENGINE' ) : kwargs . setdefault ( 'file' , connection . settings_dict [ 'NAME' ] ) return mapnik . SQLite ( wkb_format = 'spatialite' , ** kwargs ) names = ( ( 'dbname' , 'NAME' ) , ( 'user' , 'USER' ) , ( 'password' , 'PASSWORD' ) , ( 'host' , 'HOST' ) , (...
def from_code ( cls , environment , code , globals , uptodate = None ) : """Creates a template object from compiled code and the globals . This is used by the loaders and environment to create a template object ."""
namespace = { 'environment' : environment , '__file__' : code . co_filename } exec code in namespace rv = cls . _from_namespace ( environment , namespace , globals ) rv . _uptodate = uptodate return rv
def add_options ( self ) : """Add program options ."""
self . add_bool_option ( "--reveal" , help = "show full announce URL including keys" ) self . add_bool_option ( "--raw" , help = "print the metafile's raw content in all detail" ) self . add_bool_option ( "-V" , "--skip-validation" , help = "show broken metafiles with an invalid structure" ) self . add_value_option ( "...
def getURL ( self , size = 'Medium' , urlType = 'url' ) : """Retrieves a url for the photo . ( flickr . photos . getSizes ) urlType - ' url ' or ' source ' ' url ' - flickr page of photo ' source ' - image file"""
method = 'flickr.photos.getSizes' data = _doget ( method , photo_id = self . id ) for psize in data . rsp . sizes . size : if psize . label == size : return getattr ( psize , urlType ) raise FlickrError , "No URL found"
def _remote_status ( session , service_id , uuid , url , interval = 3 ) : """Poll for remote command status ."""
_LOGGER . info ( 'polling for status' ) resp = session . get ( url , params = { 'remoteServiceRequestID' : service_id , 'uuid' : uuid } ) . json ( ) if resp [ 'status' ] == 'SUCCESS' : return 'completed' time . sleep ( interval ) return _remote_status ( session , service_id , uuid , url )
def resolve_election_tie ( self , candidates ) : """call callback to resolve a tie between candidates"""
sorted_candidate_ids = list ( sorted ( candidates , key = self . candidate_order_fn ) ) return sorted_candidate_ids [ self . election_tie_cb ( candidates ) ]
def list ( path , filename = None , start = None , stop = None , recursive = False , directories = False ) : """List files specified by dataPath . Datapath may include a single wildcard ( ' * ' ) in the filename specifier . Returns sorted list of absolute path strings ."""
path = uri_to_path ( path ) if not filename and recursive : return listrecursive ( path ) if filename : if os . path . isdir ( path ) : path = os . path . join ( path , filename ) else : path = os . path . join ( os . path . dirname ( path ) , filename ) else : if os . path . isdir ( pat...
def uclust_fasta_sort_from_filepath ( fasta_filepath , output_filepath = None , tmp_dir = gettempdir ( ) , HALT_EXEC = False ) : """Generates sorted fasta file via uclust - - mergesort ."""
if not output_filepath : _ , output_filepath = mkstemp ( dir = tmp_dir , prefix = 'uclust_fasta_sort' , suffix = '.fasta' ) app = Uclust ( params = { '--tmpdir' : tmp_dir } , TmpDir = tmp_dir , HALT_EXEC = HALT_EXEC ) app_result = app ( data = { '--mergesort' : fasta_filepath , '--output' : output_filepath } ) retu...
def groupby ( self , by = None , axis = 0 , level = None , as_index = True , sort = True , group_keys = True , squeeze = False , observed = False , ** kwargs ) : """Group DataFrame or Series using a mapper or by a Series of columns . A groupby operation involves some combination of splitting the object , applyi...
from pandas . core . groupby . groupby import groupby if level is None and by is None : raise TypeError ( "You have to supply one of 'by' and 'level'" ) axis = self . _get_axis_number ( axis ) return groupby ( self , by = by , axis = axis , level = level , as_index = as_index , sort = sort , group_keys = group_keys...
def ji_windows ( self , ij_win ) : # what can be given to ij _ win NOT intuitive / right name by now ! ! ! """For a given specific window , i . e . an element of : attr : ` windows ` , get the windows of all resolutions . Arguments : ij _ win { int } - - The index specifying the window for which to return the r...
ji_windows = { } transform_src = self . _layer_meta [ self . _res_indices [ self . _windows_res ] [ 0 ] ] [ "transform" ] for res in self . _res_indices : transform_dst = self . _layer_meta [ self . _res_indices [ res ] [ 0 ] ] [ "transform" ] ji_windows [ res ] = window_from_window ( window_src = self . window...
def buscar ( self , id_vlan ) : """Get VLAN by its identifier . : param id _ vlan : VLAN identifier . : return : Following dictionary : { ' vlan ' : { ' id ' : < id _ vlan > , ' nome ' : < nome _ vlan > , ' num _ vlan ' : < num _ vlan > , ' id _ ambiente ' : < id _ ambiente > , ' id _ tipo _ rede ' : ...
if not is_valid_int_param ( id_vlan ) : raise InvalidParameterError ( u'Vlan id is invalid or was not informed.' ) url = 'vlan/' + str ( id_vlan ) + '/' code , xml = self . submit ( None , 'GET' , url ) return self . response ( code , xml )
def _from_dict ( cls , _dict ) : """Initialize a Configuration object from a json dictionary ."""
args = { } if 'configuration_id' in _dict : args [ 'configuration_id' ] = _dict . get ( 'configuration_id' ) if 'name' in _dict : args [ 'name' ] = _dict . get ( 'name' ) else : raise ValueError ( 'Required property \'name\' not present in Configuration JSON' ) if 'created' in _dict : args [ 'created' ]...
def list_features ( self , dataset , reverse = False , start = None , limit = None ) : """Lists features in a dataset . Parameters dataset : str The dataset id . reverse : str , optional List features in reverse order . Possible value is " true " . start : str , optional The id of the feature after ...
uri = URITemplate ( self . baseuri + '/{owner}/{id}/features' ) . expand ( owner = self . username , id = dataset ) params = { } if reverse : params [ 'reverse' ] = 'true' if start : params [ 'start' ] = start if limit : params [ 'limit' ] = int ( limit ) return self . session . get ( uri , params = params ...
def _apply_workspaces ( self , combination , mode ) : """Allows user to force move a comma separated list of workspaces to the given output when it ' s activated . Example : - DP1 _ workspaces = " 1,2,3" """
if len ( combination ) > 1 and mode == "extend" : sleep ( 3 ) for output in combination : workspaces = getattr ( self , "{}_workspaces" . format ( output ) , "" ) . split ( "," ) for workspace in workspaces : if not workspace : continue # switch to workspa...
def plot_run_nlive ( method_names , run_dict , ** kwargs ) : """Plot the allocations of live points as a function of logX for the input sets of nested sampling runs of the type used in the dynamic nested sampling paper ( Higson et al . 2019 ) . Plots also include analytically calculated distributions of relat...
logx_given_logl = kwargs . pop ( 'logx_given_logl' , None ) logl_given_logx = kwargs . pop ( 'logl_given_logx' , None ) logx_min = kwargs . pop ( 'logx_min' , None ) ymax = kwargs . pop ( 'ymax' , None ) npoints = kwargs . pop ( 'npoints' , 100 ) figsize = kwargs . pop ( 'figsize' , ( 6.4 , 2 ) ) post_mass_norm = kwarg...
def toeplitz ( vect ) : """Find the toeplitz matrix as a list of lists given its first line / column ."""
return [ [ vect [ abs ( i - j ) ] for i in xrange ( len ( vect ) ) ] for j in xrange ( len ( vect ) ) ]
def removePlugin ( self , package ) : """Remove a plugin : param package : The plugin package name ."""
res = dict ( code = 1 , msg = None ) if package and isinstance ( package , string_types ) : path = os . path . join ( self . plugin_abspath , package ) if os . path . isdir ( path ) : try : shutil . rmtree ( path ) except Exception as e : res . update ( msg = str ( e ) ) ...
def instantiateSong ( fileName ) : """Create an AudioSegment with the data from the given file"""
ext = detectFormat ( fileName ) if ( ext == "mp3" ) : return pd . AudioSegment . from_mp3 ( fileName ) elif ( ext == "wav" ) : return pd . AudioSegment . from_wav ( fileName ) elif ( ext == "ogg" ) : return pd . AudioSegment . from_ogg ( fileName ) elif ( ext == "flv" ) : return pd . AudioSegment . from...
async def _wait_for_data ( self , current_command , number_of_bytes ) : """This is a private utility method . This method accumulates the requested number of bytes and then returns the full command : param current _ command : command id : param number _ of _ bytes : how many bytes to wait for : returns : ...
while number_of_bytes : next_command_byte = await self . read ( ) current_command . append ( next_command_byte ) number_of_bytes -= 1 return current_command
def _speak_as_spell_out_inherit ( self , element ) : """Speak one letter at a time for each word for elements and descendants . : param element : The element . : type element : hatemile . util . html . htmldomelement . HTMLDOMElement"""
self . _reverse_speak_as ( element , 'spell-out' ) self . _isolate_text_node ( element ) self . _visit ( element , self . _speak_as_spell_out )
def generate_api_docs ( package , api_dir , clean = False , printlog = True ) : """Generate a module level API documentation of a python package . Description Generates markdown API files for each module in a Python package whereas the structure is as follows : ` package / package . subpackage / package . s...
if printlog : print ( '\n\nGenerating Module Files\n%s\n' % ( 50 * '=' ) ) prefix = package . __name__ + "." # clear the previous version if clean : if os . path . isdir ( api_dir ) : shutil . rmtree ( api_dir ) # get subpackages api_docs = { } for importer , pkg_name , is_pkg in pkgutil . iter_modules ...
def remove_object_metadata_key ( self , container , obj , key , prefix = None ) : """Removes the specified key from the storage object ' s metadata . If the key does not exist in the metadata , nothing is done ."""
self . set_object_metadata ( container , obj , { key : "" } , prefix = prefix )
def _split_lines ( self ) : '''Creates the parsed _ lines dict which keeps all record data in document order indexed by the record type .'''
parsed_lines = { } for rt in all_record_types : parsed_lines [ rt ] = [ ] parsed_lines [ 0 ] = [ ] for line in self . lines : linetype = line [ 0 : 6 ] if linetype in all_record_types : parsed_lines [ linetype ] . append ( line ) else : parsed_lines [ 0 ] . append ( line ) self . parsed_...
def get_one_optional ( self , locator ) : """Gets an optional component reference that matches specified locator . : param locator : the locator to find references by . : return : a matching component reference or null if nothing was found ."""
try : components = self . find ( locator , False ) return components [ 0 ] if len ( components ) > 0 else None except Exception as ex : return None
def add ( self , path , compress = None ) : """Add ` path ` to the MAR file . If ` path ` is a file , it will be added directly . If ` path ` is a directory , it will be traversed recursively and all files inside will be added . Args : path ( str ) : path to file or directory on disk to add to this MAR ...
if os . path . isdir ( path ) : self . add_dir ( path , compress ) else : self . add_file ( path , compress )
def _print_cline ( self , buf , i , icol ) : """Print clines after multirow - blocks are finished"""
for cl in self . clinebuf : if cl [ 0 ] == i : buf . write ( '\\cline{{{cl:d}-{icol:d}}}\n' . format ( cl = cl [ 1 ] , icol = icol ) ) # remove entries that have been written to buffer self . clinebuf = [ x for x in self . clinebuf if x [ 0 ] != i ]
def _get_all_file_version_ids ( self , secure_data_path , limit = None ) : """Convenience function that returns a generator that will paginate over the file version ids secure _ data _ path - - full path to the file in the safety deposit box limit - - Default ( 100 ) , limits how many records to be returned fro...
offset = 0 # Prime the versions dictionary so that all the logic can happen in the loop versions = { 'has_next' : True , 'next_offset' : 0 } while ( versions [ 'has_next' ] ) : offset = versions [ 'next_offset' ] versions = self . get_file_versions ( secure_data_path , limit , offset ) for summary in versio...
def get ( self , request , * args , ** kwargs ) : """Method for handling GET requests . Passes the following arguments to the context : * * * obj * * - The object to publish * * * done _ url * * - The result of the ` get _ done _ url ` method"""
self . object = self . get_object ( ) return self . render ( request , obj = self . object , done_url = self . get_done_url ( ) )
def fastqIterator ( fn , verbose = False , allowNameMissmatch = False ) : """A generator function which yields FastqSequence objects read from a file or stream . This is a general function which wraps fastqIteratorSimple . In future releases , we may allow dynamic switching of which base iterator is used . ...
it = fastqIteratorSimple ( fn , verbose = verbose , allowNameMissmatch = allowNameMissmatch ) for s in it : yield s
def decode_html_entities ( s ) : """Replaces html entities with the character they represent . > > > print ( decode _ html _ entities ( " & lt ; 3 & amp ; " ) )"""
parser = HTMLParser . HTMLParser ( ) def unesc ( m ) : return parser . unescape ( m . group ( ) ) return re . sub ( r'(&[^;]+;)' , unesc , ensure_unicode ( s ) )
def get_api_connector ( cls ) : """Initialize an api connector for future use ."""
if cls . _api is None : # pragma : no cover cls . load_config ( ) cls . debug ( 'initialize connection to remote server' ) apihost = cls . get ( 'api.host' ) if not apihost : raise MissingConfiguration ( ) apienv = cls . get ( 'api.env' ) if apienv and apienv in cls . apienvs : a...
def handle_send ( entity : BaseEntity , author_user : UserType , recipients : List [ Dict ] , parent_user : UserType = None , ) -> None : """Send an entity to remote servers . Using this we will build a list of payloads per protocol . After that , each recipient will get the generated protocol payload delivered...
payloads = [ ] public_payloads = { "activitypub" : { "auth" : None , "payload" : None , "urls" : set ( ) , } , "diaspora" : { "auth" : None , "payload" : None , "urls" : set ( ) , } , } # Flatten to unique recipients unique_recipients = unique_everseen ( recipients ) # Generate payloads and collect urls for recipient i...
def updatePlayer ( name , settings ) : """update an existing PlayerRecord setting and save to disk file"""
player = delPlayer ( name ) # remove the existing record _validate ( settings ) player . update ( settings ) player . save ( ) getKnownPlayers ( ) [ player . name ] = player return player
def _is_link ( fs , path ) : """Check that the given path is a symbolic link . Note that unlike ` os . path . islink ` , we * do * propagate file system errors other than a non - existent path or non - existent directory component . E . g . , should EPERM or ELOOP be raised , an exception will bubble up ."""
try : return stat . S_ISLNK ( fs . lstat ( path ) . st_mode ) except exceptions . FileNotFound : return False
def get_all ( self ) : """Gets all items in file ."""
logger . debug ( 'Fetching items. Path: {data_file}' . format ( data_file = self . data_file ) ) return load_file ( self . data_file )
def finalize ( self ) : """Disconnects signals and frees resources"""
self . model ( ) . sigItemChanged . disconnect ( self . repoTreeItemChanged ) selectionModel = self . selectionModel ( ) # need to store reference to prevent crash in PySide selectionModel . currentChanged . disconnect ( self . currentItemChanged )
def approvewitness ( ctx , witnesses , account ) : """Approve witness ( es )"""
pprint ( ctx . peerplays . approvewitness ( witnesses , account = account ) )
def kill_running_submission ( self , submissionid , user_check = True ) : """Attempt to kill the remote job associated with this submission id . : param submissionid : : param user _ check : Check if the current user owns this submission : return : True if the job was killed , False if an error occurred"""
submission = self . get_submission ( submissionid , user_check ) if not submission : return False if "jobid" not in submission : return False return self . _client . kill_job ( submission [ "jobid" ] )
def magicrun ( text , shell , prompt_template = "default" , aliases = None , envvars = None , extra_commands = None , speed = 1 , test_mode = False , commentecho = False , ) : """Echo out each character in ` ` text ` ` as keyboard characters are pressed , wait for a RETURN keypress , then run the ` ` text ` ` in ...
goto_regulartype = magictype ( text , prompt_template , speed ) if goto_regulartype : return goto_regulartype run_command ( text , shell , aliases = aliases , envvars = envvars , extra_commands = extra_commands , test_mode = test_mode , ) return goto_regulartype
def kill ( self ) : """Shut down the socket immediately ."""
self . _socket . shutdown ( socket . SHUT_RDWR ) self . _socket . close ( )
def FieldDefinitionProtosFromTuples ( field_def_tuples ) : """Converts ( field - name , type ) tuples to MetricFieldDefinition protos ."""
# TODO : This needs fixing for Python 3. field_def_protos = [ ] for field_name , field_type in field_def_tuples : if field_type in ( int , long ) : field_type = rdf_stats . MetricFieldDefinition . FieldType . INT elif issubclass ( field_type , Text ) : field_type = rdf_stats . MetricFieldDefinit...
async def load_field ( obj , elem_type , params = None , elem = None ) : """Loads a field from the reader , based on the field type specification . Demultiplexer . : param obj : : param elem _ type : : param params : : param elem : : return :"""
if issubclass ( elem_type , x . UVarintType ) or issubclass ( elem_type , x . IntType ) or isinstance ( obj , ( int , bool ) ) : return set_elem ( elem , obj ) elif issubclass ( elem_type , x . BlobType ) : fvalue = await load_blob ( obj , elem_type ) return set_elem ( elem , fvalue ) elif issubclass ( elem...
def raised_funds_by_project ( df ) : """Raised funds organized by project ."""
df [ 'CaptacaoReal' ] = df [ 'CaptacaoReal' ] . apply ( pd . to_numeric ) return ( df [ [ 'Pronac' , 'CaptacaoReal' ] ] . groupby ( [ 'Pronac' ] ) . sum ( ) )
def addDelay ( self , urlPattern = "" , delay = 0 , httpMethod = None ) : """Adds delays ."""
print ( "addDelay is deprecated please use delays instead" ) delay = { "urlPattern" : urlPattern , "delay" : delay } if httpMethod : delay [ "httpMethod" ] = httpMethod return self . delays ( delays = { "data" : [ delay ] } )
def listen ( self , port : int , address : str = "" , ** kwargs : Any ) -> HTTPServer : """Starts an HTTP server for this application on the given port . This is a convenience alias for creating an ` . HTTPServer ` object and calling its listen method . Keyword arguments not supported by ` HTTPServer . listen...
server = HTTPServer ( self , ** kwargs ) server . listen ( port , address ) return server
def add_menu ( self , menu ) : '''add to the default popup menu'''
from MAVProxy . modules . mavproxy_map import mp_slipmap self . default_popup . add ( menu ) self . map . add_object ( mp_slipmap . SlipDefaultPopup ( self . default_popup , combine = True ) )
def default_kms_key_name ( self , value ) : """Set default KMS encryption key for objects in the bucket . : type value : str or None : param value : new KMS key name ( None to clear any existing key ) ."""
encryption_config = self . _properties . get ( "encryption" , { } ) encryption_config [ "defaultKmsKeyName" ] = value self . _patch_property ( "encryption" , encryption_config )
def out_name ( stem , timestep = None ) : """Return StagPy out file name . Args : stem ( str ) : short description of file content . timestep ( int ) : timestep if relevant . Returns : str : the output file name . Other Parameters : conf . core . outname ( str ) : the generic name stem , defaults to ...
if timestep is not None : stem = ( stem + INT_FMT ) . format ( timestep ) return conf . core . outname + '_' + stem
def deprecate ( func ) : """A deprecation warning emmiter as a decorator ."""
@ wraps ( func ) def wrapper ( * args , ** kwargs ) : warn ( "Deprecated, this will be removed in the future" , DeprecationWarning ) return func ( * args , ** kwargs ) wrapper . __doc__ = "Deprecated.\n" + ( wrapper . __doc__ or "" ) return wrapper
def required_header ( header ) : """Function that verify if the header parameter is a essential header : param header : A string represented a header : returns : A boolean value that represent if the header is required"""
if header in IGNORE_HEADERS : return False if header . startswith ( 'HTTP_' ) or header == 'CONTENT_TYPE' : return True return False
def jackknife_indexes ( data ) : """Given data points data , where axis 0 is considered to delineate points , return a list of arrays where each array is a set of jackknife indexes . For a given set of data Y , the jackknife sample J [ i ] is defined as the data set Y with the ith data point deleted ."""
base = np . arange ( 0 , len ( data ) ) return ( np . delete ( base , i ) for i in base )
def mkconstraints ( ) : """Make constraint list for binary constraint problem ."""
constraints = [ ] for j in range ( 1 , 10 ) : vars = [ "%s%d" % ( i , j ) for i in uppercase [ : 9 ] ] constraints . extend ( ( c , const_different ) for c in combinations ( vars , 2 ) ) for i in uppercase [ : 9 ] : vars = [ "%s%d" % ( i , j ) for j in range ( 1 , 10 ) ] constraints . extend ( ( c , con...
def close ( self , name = None ) : """Closes the most recently opened element . : name : if given , this value must match the name given for the most recently opened element . This is primarily here for providing quick error checking for applications"""
tag = self . _open_elements . pop ( ) if name is not None and name != tag : raise Exception ( "Tag closing mismatch" ) self . _pad ( ) self . _writer . endElement ( _normalize_name ( tag ) ) self . _newline ( )
def _process_service_check ( self , data , url , tag_by_host = False , services_incl_filter = None , services_excl_filter = None , custom_tags = None ) : '''Report a service check , tagged by the service and the backend . Statuses are defined in ` STATUS _ TO _ SERVICE _ CHECK ` mapping .'''
custom_tags = [ ] if custom_tags is None else custom_tags service_name = data [ 'pxname' ] status = data [ 'status' ] haproxy_hostname = to_string ( self . hostname ) check_hostname = haproxy_hostname if tag_by_host else '' if self . _is_service_excl_filtered ( service_name , services_incl_filter , services_excl_filter...
def get_chinese_new_year ( self , year ) : """Compute Chinese New Year days . To return a list of holidays . By default , it ' ll at least return the Chinese New Year holidays chosen using the following options : * ` ` include _ chinese _ new _ year _ eve ` ` * ` ` include _ chinese _ new _ year ` ` ( on by...
days = [ ] lunar_first_day = ChineseNewYearCalendar . lunar ( year , 1 , 1 ) # Chinese new year ' s eve if self . include_chinese_new_year_eve : days . append ( ( lunar_first_day - timedelta ( days = 1 ) , self . chinese_new_year_eve_label ) ) # Chinese new year ( is included by default ) if self . include_chinese_...
def write_config_file ( self , f , comments ) : """This method write a sample file , with attributes , descriptions , sample values , required flags , using the configuration object properties ."""
if self . conf_hidden : return False if comments : f . write ( "\n" ) f . write ( "# Attribute (" ) f . write ( str ( self . e_type . __name__ ) ) f . write ( ") : " ) f . write ( self . _name . upper ( ) ) f . write ( "\n" ) if self . _desc and self . _desc != argparse . SUPPRESS : ...
def _summary ( self , name = None ) : """Return a summarized representation . Parameters name : str name to use in the summary representation Returns String with a summarized representation of the index"""
if len ( self ) > 0 : head = self [ 0 ] if hasattr ( head , 'format' ) and not isinstance ( head , str ) : head = head . format ( ) tail = self [ - 1 ] if hasattr ( tail , 'format' ) and not isinstance ( tail , str ) : tail = tail . format ( ) index_summary = ', %s to %s' % ( pprint_...
def hex_to_int ( value ) : """Convert hex string like " \x0A \xE3 " to 2787."""
if version_info . major >= 3 : return int . from_bytes ( value , "big" ) return int ( value . encode ( "hex" ) , 16 )
def store_zonefiles ( self , zonefile_names , zonefiles , zonefile_txids , zonefile_block_heights , peer_zonefile_hashes , peer_hostport , path , con = None ) : """Store a list of RPC - fetched zonefiles ( but only ones in peer _ zonefile _ hashes ) from the given peer _ hostport Return the list of zonefile hashe...
ret = [ ] with AtlasDBOpen ( con = con , path = path ) as dbcon : for fetched_zfhash , zonefile_txt in zonefiles . items ( ) : if fetched_zfhash not in peer_zonefile_hashes or fetched_zfhash not in zonefile_block_heights : # unsolicited log . warn ( "%s: Unsolicited zonefile %s" % ( self . hostp...
def channels_add_all ( self , room_id , ** kwargs ) : """Adds all of the users of the Rocket . Chat server to the channel ."""
return self . __call_api_post ( 'channels.addAll' , roomId = room_id , kwargs = kwargs )
def _distributeCells ( numCellsPop ) : '''distribute cells across compute nodes using round - robin'''
from . . import sim hostCells = { } for i in range ( sim . nhosts ) : hostCells [ i ] = [ ] for i in range ( numCellsPop ) : hostCells [ sim . nextHost ] . append ( i ) sim . nextHost += 1 if sim . nextHost >= sim . nhosts : sim . nextHost = 0 if sim . cfg . verbose : print ( ( "Distributed ...
def tau3_from_mass1_mass2 ( mass1 , mass2 , f_lower ) : r"""Returns : math : ` \ tau _ 3 ` from the component masses and given frequency ."""
mtotal = mass1 + mass2 eta = eta_from_mass1_mass2 ( mass1 , mass2 ) return tau3_from_mtotal_eta ( mtotal , eta , f_lower )
def convert_sshkey ( cls , sshkey ) : """Return dict param with valid entries for vm / paas methods ."""
params = { } if sshkey : params [ 'keys' ] = [ ] for ssh in sshkey : if os . path . exists ( os . path . expanduser ( ssh ) ) : if 'ssh_key' in params : cls . echo ( "Can't have more than one sshkey file." ) continue with open ( ssh ) as fdesc : ...
def renew_session ( self ) : """Have to be called on user actions to check and renew session"""
if ( ( not 'user_uid' in self . cookieInterface . cookies ) or self . cookieInterface . cookies [ 'user_uid' ] != self . session_uid ) and ( not self . expired ) : self . on_session_expired ( ) if self . expired : self . session_uid = str ( random . randint ( 1 , 999999999 ) ) self . cookieInterface . set_cooki...
def start ( self ) : """start command in background and does not wait for it . : rtype : self"""
if self . is_started : raise EasyProcessError ( self , 'process was started twice!' ) if self . use_temp_files : self . _stdout_file = tempfile . TemporaryFile ( prefix = 'stdout_' ) self . _stderr_file = tempfile . TemporaryFile ( prefix = 'stderr_' ) stdout = self . _stdout_file stderr = self . _s...
def search ( self , term ) : """Search for a user by name . : param str term : What to search for . : return : The results as a SearchWrapper iterator or None if no results . : rtype : SearchWrapper or None"""
r = requests . get ( self . apiurl + "/users" , params = { "filter[name]" : term } , headers = self . header ) if r . status_code != 200 : raise ServerError jsd = r . json ( ) if jsd [ 'meta' ] [ 'count' ] : return SearchWrapper ( jsd [ 'data' ] , jsd [ 'links' ] [ 'next' ] if 'next' in jsd [ 'links' ] else Non...
def _hm_form_message ( self , thermostat_id , protocol , source , function , start , payload ) : """Forms a message payload , excluding CRC"""
if protocol == constants . HMV3_ID : start_low = ( start & constants . BYTEMASK ) start_high = ( start >> 8 ) & constants . BYTEMASK if function == constants . FUNC_READ : payload_length = 0 length_low = ( constants . RW_LENGTH_ALL & constants . BYTEMASK ) length_high = ( constants ....
def docstr ( self , prefix = '' , include_label = True ) : """Returns a string summarizing the parameter . Format is : < prefix > ` ` name ` ` : { ` ` default ` ` , ` ` dtype ` ` } < prefix > ` ` description ` ` Label : ` ` label ` ` ."""
outstr = "%s%s : {%s, %s}\n" % ( prefix , self . name , str ( self . default ) , str ( self . dtype ) . replace ( "<type '" , '' ) . replace ( "'>" , '' ) ) + "%s %s" % ( prefix , self . description ) if include_label : outstr += " Label: %s" % ( self . label ) return outstr
def _pack_cwl ( unpacked_cwl ) : """Pack CWL into a single document for submission ."""
out_file = "%s-pack%s" % os . path . splitext ( unpacked_cwl ) cmd = "cwltool --pack {unpacked_cwl} > {out_file}" _run_tool ( cmd . format ( ** locals ( ) ) ) return out_file
def section ( self , ctx , optional = False ) : """Return section of the config for a specific context ( sub - command ) . Parameters : ctx ( Context ) : The Click context object . optional ( bool ) : If ` ` True ` ` , return an empty config object when section is missing . Returns : Section : The configu...
values = self . load ( ) try : return values [ ctx . info_name ] except KeyError : if optional : return configobj . ConfigObj ( { } , ** self . DEFAULT_CONFIG_OPTS ) raise LoggedFailure ( "Configuration section '{}' not found!" . format ( ctx . info_name ) )
def dangling ( self , targets : sos_targets ) : '''returns 1 . missing targets , which are missing from the DAG or from the provided targets 2 . existing targets of provided target list , not in DAG'''
existing = [ ] missing = [ ] if env . config [ 'trace_existing' ] : for x in self . _all_depends_files . keys ( ) : if x not in self . _all_output_files : if x . target_exists ( ) : existing . append ( x ) else : missing . append ( x ) else : missi...
def enable_chimera_inline ( ) : """Enable IPython magic commands to run some Chimera actions Currently supported : - % chimera _ export _ 3D [ < model > ] : Depicts the Chimera 3D canvas in a WebGL iframe . Requires a headless Chimera build and a Notebook instance . SLOW . - % chimera _ run < command > : ...
from IPython . display import IFrame from IPython . core . magic import register_line_magic import chimera import Midas @ register_line_magic def chimera_export_3D ( line ) : if chimera . viewer . __class__ . __name__ == 'NoGuiViewer' : print ( 'This magic requires a headless Chimera build. ' 'Check http://...
def log_once ( key ) : """Returns True if this is the " first " call for a given key . Various logging settings can adjust the definition of " first " . Example : > > > if log _ once ( " some _ key " ) : . . . logger . info ( " Some verbose logging statement " )"""
global _last_logged if _disabled : return False elif key not in _logged : _logged . add ( key ) _last_logged = time . time ( ) return True elif _periodic_log and time . time ( ) - _last_logged > 60.0 : _logged . clear ( ) _last_logged = time . time ( ) return False else : return False
def clean_dict ( data ) : """Remove None - valued keys from a dictionary , recursively ."""
if is_mapping ( data ) : out = { } for k , v in data . items ( ) : if v is not None : out [ k ] = clean_dict ( v ) return out elif is_sequence ( data ) : return [ clean_dict ( d ) for d in data if d is not None ] return data
def get_music_library_information ( self , search_type , start = 0 , max_items = 100 , full_album_art_uri = False , search_term = None , subcategories = None , complete_result = False ) : """Retrieve music information objects from the music library . This method is the main method to get music information items ,...
search = self . SEARCH_TRANSLATION [ search_type ] # Add sub categories if subcategories is not None : for category in subcategories : search += '/' + url_escape_path ( really_unicode ( category ) ) # Add fuzzy search if search_term is not None : search += ':' + url_escape_path ( really_unicode ( search...
def _set_result_from_operation ( self ) : """Set the result or exception from the operation if it is complete ."""
# This must be done in a lock to prevent the polling thread # and main thread from both executing the completion logic # at the same time . with self . _completion_lock : # If the operation isn ' t complete or if the result has already been # set , do not call set _ result / set _ exception again . # Note : self . _ re...
def refresh ( self , force_cache = False ) : """Perform a system refresh . : param force _ cache : Force an update of the camera cache"""
if self . check_if_ok_to_update ( ) or force_cache : for sync_name , sync_module in self . sync . items ( ) : _LOGGER . debug ( "Attempting refresh of sync %s" , sync_name ) sync_module . refresh ( force_cache = force_cache ) if not force_cache : # Prevents rapid clearing of motion detect proper...
def encode_function_call ( self , function_name , args ) : """Return the encoded function call . Args : function _ name ( str ) : One of the existing functions described in the contract interface . args ( List [ object ] ) : The function arguments that wll be encoded and used in the contract execution in ...
if function_name not in self . function_data : raise ValueError ( 'Unkown function {}' . format ( function_name ) ) description = self . function_data [ function_name ] function_selector = zpad ( encode_int ( description [ 'prefix' ] ) , 4 ) arguments = encode_abi ( description [ 'encode_types' ] , args ) return fu...
async def unicode_type ( self , elem ) : """Unicode type : param elem : : return :"""
if self . writing : await dump_uvarint ( self . iobj , len ( elem ) ) await self . iobj . awrite ( bytes ( elem , 'utf8' ) ) else : ivalue = await load_uvarint ( self . iobj ) if ivalue == 0 : return '' fvalue = bytearray ( ivalue ) await self . iobj . areadinto ( fvalue ) return str...
def payments ( self , virtual_account_id , data = { } , ** kwargs ) : """Fetch Payment for Virtual Account Id Args : virtual _ account _ id : Id for which Virtual Account objects has to be retrieved Returns : Payment dict for given Virtual Account Id"""
url = "{}/{}/payments" . format ( self . base_url , virtual_account_id ) return self . get_url ( url , data , ** kwargs )
def ingest_flash ( self ) : """Process post - flash ."""
self . flash = extract_flash ( self . hdulist [ 0 ] . header , self . hdulist [ 1 ] ) # Set post - flash to zeros if self . flash is None : self . flash = np . zeros_like ( self . science ) return # Apply the flash subtraction if necessary . # Not applied to ERR , to be consistent with ingest _ dark ( ) if self...
def parameter_list ( data ) : """Create a list of parameter objects from a dict . : param data : Dictionary to convert to parameter list . : type data : dict : return : Parameter list . : rtype : dict"""
items = [ ] for item in data : param = Parameter ( item [ 'name' ] , item [ 'value' ] ) if 'meta' in item : param . meta = item [ 'meta' ] items . append ( param ) return items
def _strip_counters ( self , sub_line ) : """Find the codeline end by taking out the counters and durations ."""
try : end = sub_line . rindex ( '}' ) except ValueError : return sub_line else : return sub_line [ : ( end + 1 ) ]
def connect ( self ) : """Get a connection to this peer . If an connection to the peer already exists ( either incoming or outgoing ) , that ' s returned . Otherwise , a new outgoing connection to this peer is created . : return : A future containing a connection to this host ."""
# Prefer incoming connections over outgoing connections . if self . connections : # First value is an incoming connection future = gen . Future ( ) future . set_result ( self . connections [ 0 ] ) return future if self . _connecting : # If we ' re in the process of connecting to the peer , just wait # and r...
def _summarize ( self ) : """Game summary implementation ."""
self . _achievements_summarized = True data = None if self . _postgame : data = self . _postgame . action game_type = 'DM' if self . _header . lobby . game_type == 'DM' else 'RM' self . _summary = { 'players' : list ( self . players ( data , game_type ) ) , 'diplomacy' : self . _diplomacy , 'rec_owner_index' : self...
def currentVersion ( self ) : """returns the current version of the site"""
if self . _currentVersion is None : self . __init ( self . _url ) return self . _currentVersion
def compute_chunk ( self , graph , dates , sids , initial_workspace ) : """Compute the Pipeline terms in the graph for the requested start and end dates . This is where we do the actual work of running a pipeline . Parameters graph : zipline . pipeline . graph . ExecutionPlan Dependency graph of the terms...
self . _validate_compute_chunk_params ( graph , dates , sids , initial_workspace , ) get_loader = self . _get_loader # Copy the supplied initial workspace so we don ' t mutate it in place . workspace = initial_workspace . copy ( ) refcounts = graph . initial_refcounts ( workspace ) execution_order = graph . execution_o...
def search ( self , template : str , first : bool = False ) -> _Result : """Search the : class : ` Element < Element > ` for the given parse template . : param template : The Parse template to use ."""
elements = [ r for r in findall ( template , self . xml ) ] return _get_first_or_list ( elements , first )
def set_scene_config ( self , scene_id , config ) : """reconfigure a scene by scene ID"""
if not scene_id in self . state . scenes : # does that scene _ id exist ? err_msg = "Requested to reconfigure scene {sceneNum}, which does not exist" . format ( sceneNum = scene_id ) logging . info ( err_msg ) return ( False , 0 , err_msg ) if scene_id == self . state . activeSceneId : pass # TODO :...
def install_os ( name , ** kwargs ) : '''Installs the given image on the device . After the installation is complete the device is rebooted , if reboot = True is given as a keyworded argument . . . code - block : : yaml salt : / / images / junos _ image . tgz : junos : - install _ os - timeout : 100 -...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } ret [ 'changes' ] = __salt__ [ 'junos.install_os' ] ( name , ** kwargs ) return ret
def meaculpa ( nick , rest ) : "Sincerely apologize"
if rest : rest = rest . strip ( ) if rest : return random . choice ( phrases . direct_apologies ) % dict ( a = nick , b = rest ) else : return random . choice ( phrases . apologies ) % dict ( a = nick )
def file ( self , owner = None , ** kwargs ) : """Create the File TI object . Args : owner : * * kwargs : Return :"""
return File ( self . tcex , owner = owner , ** kwargs )
def f_measure ( reference_beats , estimated_beats , f_measure_threshold = 0.07 ) : """Compute the F - measure of correct vs incorrectly predicted beats . " Correctness " is determined over a small window . Examples > > > reference _ beats = mir _ eval . io . load _ events ( ' reference . txt ' ) > > > refer...
validate ( reference_beats , estimated_beats ) # When estimated beats are empty , no beats are correct ; metric is 0 if estimated_beats . size == 0 or reference_beats . size == 0 : return 0. # Compute the best - case matching between reference and estimated locations matching = util . match_events ( reference_beats...
def _update_url_map ( self ) : '''Assemble any dynamic or configurable URLs'''
if HAS_WEBSOCKETS : self . url_map . update ( { 'ws' : WebsocketEndpoint , } ) # Allow the Webhook URL to be overridden from the conf . self . url_map . update ( { self . apiopts . get ( 'webhook_url' , 'hook' ) . lstrip ( '/' ) : Webhook , } ) # Enable the single - page JS app URL . self . url_map . update ( { sel...
def addsshkey ( self , title , key ) : """Add a new ssh key for the current user : param title : title of the new key : param key : the key itself : return : true if added , false if it didn ' t add it ( it could be because the name or key already exists )"""
data = { 'title' : title , 'key' : key } request = requests . post ( self . keys_url , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 201 : return True else : return False