signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def hash ( self ) : """( property ) Returns a unique hash value for the result ."""
data_str = ';' . join ( [ str ( repr ( var ) ) for var in [ self . N , self . K , self . X , self . L , self . stat , self . cutoff , self . pval , self . pval_thresh , self . escore_pval_thresh ] ] ) data_str += ';' data = data_str . encode ( 'UTF-8' ) + self . indices . tobytes ( ) return str ( hashlib . md5 ( data )...
def Deserialize ( self , reader ) : """Deserialize full object . Args : reader ( neo . IO . BinaryReader ) :"""
self . AssetId = reader . ReadUInt256 ( ) self . Value = reader . ReadFixed8 ( ) self . ScriptHash = reader . ReadUInt160 ( ) if self . ScriptHash is None : raise Exception ( "Script hash is required from deserialize!!!!!!!!" )
def calculate_overlap ( self ) : """Create the array that describes how junctions overlap"""
overs = [ ] if not self . tx_obj1 . range . overlaps ( self . tx_obj2 . range ) : return [ ] # if they dont overlap wont find anything for i in range ( 0 , len ( self . j1 ) ) : for j in range ( 0 , len ( self . j2 ) ) : if self . j1 [ i ] . overlaps ( self . j2 [ j ] , tolerance = self . tolerance ...
def json_encode_default ( obj ) : '''Convert datetime . datetime to timestamp : param obj : value to ( possibly ) convert'''
if isinstance ( obj , ( datetime , date ) ) : result = dt2ts ( obj ) else : result = json_encoder . default ( obj ) return to_encoding ( result )
def readspec ( filename , read_scan = None ) : """Open a SPEC file and read its content Inputs : filename : string the file to open read _ scan : None , ' all ' or integer the index of scan to be read from the file . If None , no scan should be read . If ' all ' , all scans should be read . If a number ...
with open ( filename , 'rt' ) as f : sf = { 'motors' : [ ] , 'maxscannumber' : 0 } sf [ 'originalfilename' ] = filename lastscannumber = None while True : l = f . readline ( ) if l . startswith ( '#F' ) : sf [ 'filename' ] = l [ 2 : ] . strip ( ) elif l . startswith (...
def setup_network_agents ( self ) : """Initializes agents on nodes of graph and registers them to the SimPy environment"""
for i in self . env . G . nodes ( ) : self . env . G . node [ i ] [ 'agent' ] = self . agent_type ( environment = self . env , agent_id = i , state = deepcopy ( self . initial_states [ i ] ) )
def unaccentuate ( s ) : """Replace accentuated chars in string by their non accentuated equivalent ."""
return "" . join ( c for c in unicodedata . normalize ( "NFKD" , s ) if not unicodedata . combining ( c ) )
def evaluate ( references , estimates , win = 1 * 44100 , hop = 1 * 44100 , mode = 'v4' , padding = True ) : """BSS _ EVAL images evaluation using metrics module Parameters references : np . ndarray , shape = ( nsrc , nsampl , nchan ) array containing true reference sources estimates : np . ndarray , shape ...
estimates = np . array ( estimates ) references = np . array ( references ) if padding : references , estimates = pad_or_truncate ( references , estimates ) SDR , ISR , SIR , SAR , _ = metrics . bss_eval ( references , estimates , compute_permutation = False , window = win , hop = hop , framewise_filters = ( mode =...
def insertData ( self , tablename , list_value_pairs , list_SQLCMD_pairs = None ) : """insert data into table - ID : identifier of the updated value - list _ value _ pairs : contains the table field ID and the according value - list _ SQLCMD _ pairs : contains the table field ID and a SQL command"""
fields = self . _getFieldsInDB ( tablename ) lst_field = [ ] lst_value = [ ] # normal field - value - pairs for pair in list_value_pairs : if pair [ 0 ] in fields : lst_field . append ( pair [ 0 ] ) lst_value . append ( '"%s"' % pair [ 1 ] ) else : print "err: field %s can't be found in ...
def get_by_name ( config = None , name = None , name_label = 'name' ) : """Fetches a K8sDeployment by name . : param config : A K8sConfig object . : param name : The name we want . : param name _ label : The label key to use for name . : return : A list of K8sDeployment objects ."""
if name is None : raise SyntaxError ( 'Deployment: name: [ {0} ] cannot be None.' . format ( name ) ) if not isinstance ( name , str ) : raise SyntaxError ( 'Deployment: name: [ {0} ] must be a string.' . format ( name ) ) if config is not None and not isinstance ( config , K8sConfig ) : raise SyntaxError (...
def get_pending_withdrawals ( self , currency = None ) : """Used to view your pending withdrawals Endpoint : 1.1 NO EQUIVALENT 2.0 / key / balance / getpendingwithdrawals : param currency : String literal for the currency ( ie . BTC ) : type currency : str : return : pending withdrawals in JSON : rtyp...
return self . _api_query ( path_dict = { API_V2_0 : '/key/balance/getpendingwithdrawals' } , options = { 'currencyname' : currency } if currency else None , protection = PROTECTION_PRV )
def delete_speaker ( self , speaker_uri ) : """Delete an speaker from a collection : param speaker _ uri : the URI that references the speaker : type speaker _ uri : String : rtype : Boolean : returns : True if the speaker was deleted : raises : APIError if the request was not successful"""
response = self . api_request ( speaker_uri , method = 'DELETE' ) return self . __check_success ( response )
def create ( self ) : """Add backup files to select from"""
self . add_handlers ( { '^T' : self . quit } ) self . add ( npyscreen . Textfield , value = 'Pick a version to restore from: ' , editable = False , color = 'STANDOUT' ) self . dir_select = self . add ( npyscreen . SelectOne , values = self . display_vals , scroll_exit = True , rely = 4 )
def saliency_map ( output , input , name = "saliency_map" ) : """Produce a saliency map as described in the paper : ` Deep Inside Convolutional Networks : Visualising Image Classification Models and Saliency Maps < https : / / arxiv . org / abs / 1312.6034 > ` _ . The saliency map is the gradient of the max e...
max_outp = tf . reduce_max ( output , 1 ) saliency_op = tf . gradients ( max_outp , input ) [ : ] [ 0 ] return tf . identity ( saliency_op , name = name )
def get_xml ( pmc_id ) : """Returns XML for the article corresponding to a PMC ID ."""
if pmc_id . upper ( ) . startswith ( 'PMC' ) : pmc_id = pmc_id [ 3 : ] # Request params params = { } params [ 'verb' ] = 'GetRecord' params [ 'identifier' ] = 'oai:pubmedcentral.nih.gov:%s' % pmc_id params [ 'metadataPrefix' ] = 'pmc' # Submit the request res = requests . get ( pmc_url , params ) if not res . statu...
def get_version ( ) : """Return formatted version string . Returns : str : string with project version or empty string ."""
if all ( [ VERSION , UPDATED , any ( [ isinstance ( UPDATED , date ) , isinstance ( UPDATED , datetime ) , ] ) , ] ) : return FORMAT_STRING . format ( ** { "version" : VERSION , "updated" : UPDATED , } ) elif VERSION : return VERSION elif UPDATED : return localize ( UPDATED ) if any ( [ isinstance ( UPDATED...
def create_part ( self , parent , model , name = None , ** kwargs ) : """Create a new part instance from a given model under a given parent . In order to prevent the backend from updating the frontend you may add ` suppress _ kevents = True ` as additional keyword = value argument to this method . This will imp...
if parent . category != Category . INSTANCE : raise IllegalArgumentError ( "The parent should be an category 'INSTANCE'" ) if model . category != Category . MODEL : raise IllegalArgumentError ( "The models should be of category 'MODEL'" ) if not name : name = model . name data = { "name" : name , "parent" :...
def query_info ( self , what ) : """Way to extend the interface . in what of type int return result of type str"""
if not isinstance ( what , baseinteger ) : raise TypeError ( "what can only be an instance of type baseinteger" ) result = self . _call ( "queryInfo" , in_p = [ what ] ) return result
def compress_file ( inputfile , filename ) : """Compress input file using gzip and change its name . : param inputfile : File to compress : type inputfile : ` ` file ` ` like object : param filename : File ' s name : type filename : ` ` str ` ` : returns : Tuple with compressed file and new file ' s name ...
outputfile = create_spooled_temporary_file ( ) new_filename = filename + '.gz' zipfile = gzip . GzipFile ( filename = filename , fileobj = outputfile , mode = "wb" ) try : inputfile . seek ( 0 ) copyfileobj ( inputfile , zipfile , settings . TMP_FILE_READ_SIZE ) finally : zipfile . close ( ) return outputfi...
def append ( self , * values ) : """Append values at the end of the list Allow chaining . Args : values : values to be appened at the end . Example : > > > from ww import l > > > lst = l ( [ ] ) > > > lst . append ( 1) > > > lst > > > lst . append ( 2 , 3 ) . append ( 4,5) [1 , 2 , 3 , 4 , 5] ...
for value in values : list . append ( self , value ) return self
def dot_product_unmasked_attention_local_2d_tpu ( q , k , v , bias , max_relative_position = None , query_shape = ( 8 , 8 ) , dropout_rate = 0.0 , image_shapes = None , name = None , make_image_summary = False , dropout_broadcast_dims = None ) : """Calculate unmasked dot - product local self - attention 2d on tpu ....
if max_relative_position : raise ValueError ( "Relative local 2d attention not implemented" ) with tf . variable_scope ( name , default_name = "dot_product_unmasked_attention_local_2d_tpu" , values = [ q , k , v ] ) : # This calculation only works for self attention . # q , k and v must therefore have the same shap...
def _initialize_processes ( self , target , num_workers , description ) : # type : ( _ MultiprocessOffload , function , int , str ) - > None """Initialize processes : param _ MultiprocessOffload self : this : param function target : target function for process : param int num _ workers : number of worker proc...
if num_workers is None or num_workers < 1 : raise ValueError ( 'invalid num_workers: {}' . format ( num_workers ) ) logger . debug ( 'initializing {}{} processes' . format ( num_workers , ' ' + description if not None else '' ) ) for _ in range ( num_workers ) : proc = multiprocessing . Process ( target = targe...
def markdown_cell ( markdown ) : r"""Args : markdown ( str ) : Returns : str : json formatted ipython notebook markdown cell CommandLine : python - m ibeis . templates . generate _ notebook - - exec - markdown _ cell Example : > > > # DISABLE _ DOCTEST > > > from ibeis . templates . generate _ noteb...
import utool as ut markdown_header = ut . codeblock ( ''' { "cell_type": "markdown", "metadata": {}, "source": [ ''' ) markdown_footer = ut . codeblock ( ''' ] } ''' ) return ( markdown_header + '\n' + ut . indent ( repr_single_for_md ( mar...
def expr_order_key ( expr ) : """A default order key for arbitrary expressions"""
if hasattr ( expr , '_order_key' ) : return expr . _order_key try : if isinstance ( expr . kwargs , OrderedDict ) : key_vals = expr . kwargs . values ( ) else : key_vals = [ expr . kwargs [ key ] for key in sorted ( expr . kwargs ) ] return KeyTuple ( ( expr . __class__ . __name__ , ) + ...
def match_reg ( self , reg ) : """match the given regular expression object to the current text position . if a match occurs , update the current text and line position ."""
mp = self . match_position match = reg . match ( self . text , self . match_position ) if match : ( start , end ) = match . span ( ) if end == start : self . match_position = end + 1 else : self . match_position = end self . matched_lineno = self . lineno lines = re . findall ( r"\n"...
def build_node ( type , name , content ) : """Wrap up content in to a html node . : param type : content type ( e . g . , doc , section , text , figure ) : type path : str : param name : content name ( e . g . , the name of the section ) : type path : str : param name : actual content : type path : str ...
if type == "doc" : return f"<html>{content}</html>" if type == "section" : return f"<section name='{name}'>{content}</section>" if type == "text" : return f"<p name='{name}'>{content}</p>" if type == "figure" : return f"<img name='{name}' src='{content}'/>"
def _assign_curtailment ( curtailment , edisgo , generators , curtailment_key ) : """Helper function to write curtailment time series to generator objects . This function also writes a list of the curtailed generators to curtailment in : class : ` edisgo . grid . network . TimeSeries ` and : class : ` edisgo ...
gen_object_list = [ ] for gen in curtailment . columns : # get generator object from representative gen_object = generators . loc [ generators . gen_repr == gen ] . index [ 0 ] # assign curtailment to individual generators gen_object . curtailment = curtailment . loc [ : , gen ] gen_object_list . append...
def add_arrow_coord ( self , line , arrow_height , arrow_width , recess ) : """Determine the coordinates of an arrow head polygon with height ( h ) and width ( w ) and recess ( r ) pointing from the one but last to the last point of ( poly ) line ( line ) . Note that the coordinates of an SvgLine and an SvgPo...
# arrow = SvgPolygon ( _ maxlen = 4) if line . type == 'polyline' : xe = line . coordsX [ - 1 ] ye = line . coordsY [ - 1 ] xp = line . coordsX [ - 2 ] yp = line . coordsY [ - 2 ] else : xe = line . attributes [ 'x2' ] ye = line . attributes [ 'y2' ] xp = line . attributes [ 'x1' ] yp = ...
def l2traceroute_result_output_reason ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) l2traceroute_result = ET . Element ( "l2traceroute_result" ) config = l2traceroute_result output = ET . SubElement ( l2traceroute_result , "output" ) reason = ET . SubElement ( output , "reason" ) reason . text = kwargs . pop ( 'reason' ) callback = kwargs . pop ( 'callback' , self . ...
def _set_fallback ( elements , src_field , fallback , dest_field = None ) : """Helper function used to set the fallback attributes of an element when they are defined by the configuration as " None " or " - " ."""
if dest_field is None : dest_field = src_field if isinstance ( fallback , six . string_types ) : fallback = elements [ fallback ] attrs = elements [ src_field ] elements [ dest_field ] = ( attrs [ 0 ] if attrs [ 0 ] is not None else fallback [ 0 ] , attrs [ 1 ] if attrs [ 1 ] is not None else fallback [ 1 ] , a...
def infer_module_name ( filename , fspath ) : """Convert a python filename to a module relative to pythonpath ."""
filename , _ = os . path . splitext ( filename ) for f in fspath : short_name = f . relative_path ( filename ) if short_name : # The module name for _ _ init _ _ . py files is the directory . if short_name . endswith ( os . path . sep + "__init__" ) : short_name = short_name [ : short_name ....
def get_children_as_time_series ( self , json_children , time_field = [ 'entity' , 'occurred' ] ) : result = [ ] time_field_as_path_list = time_field . strip ( ) . split ( "." ) if len ( time_field_as_path_list ) == 0 : return result """FROM : " id " : " 60411677 " , " uri " : " https : / / ...
# get times result_dict = { } for child in json_children : time = self . get_time ( child [ 0 ] , time_field_as_path_list ) if time in result_dict : result_dict [ time ] += 1 else : result_dict [ time ] = 1 # turn lookup dict ( result _ dict ) into final list for key , value in result_dict ....
def not_ ( self , * query_expressions ) : '''Add a $ not expression to the query , negating the query expressions given . * * Examples * * : ` ` query . not _ ( SomeDocClass . age < = 18 ) ` ` becomes ` ` { ' age ' : { ' $ not ' : { ' $ gt ' : 18 } } } ` ` : param query _ expressions : Instances of : class : ...
for qe in query_expressions : self . filter ( qe . not_ ( ) ) return self
def get_eip_address_info ( addresses = None , allocation_ids = None , region = None , key = None , keyid = None , profile = None ) : '''Get ' interesting ' info about some , or all EIPs associated with the current account . addresses ( list ) - Optional list of addresses . If provided , only the addresses ass...
if type ( addresses ) == ( type ( 'string' ) ) : addresses = [ addresses ] if type ( allocation_ids ) == ( type ( 'string' ) ) : allocation_ids = [ allocation_ids ] ret = _get_all_eip_addresses ( addresses = addresses , allocation_ids = allocation_ids , region = region , key = key , keyid = keyid , profile = pr...
def get_attrs ( self ) : """retrieve our attributes"""
self . encoding = _ensure_encoding ( getattr ( self . attrs , 'encoding' , None ) ) self . errors = _ensure_decoded ( getattr ( self . attrs , 'errors' , 'strict' ) ) for n in self . attributes : setattr ( self , n , _ensure_decoded ( getattr ( self . attrs , n , None ) ) )
def _refresh_buckets_cache_file ( creds , cache_file , multiple_env , environment , prefix ) : '''Retrieve the content of all buckets and cache the metadata to the buckets cache file'''
# helper s3 query function def __get_s3_meta ( ) : return __utils__ [ 's3.query' ] ( key = creds . key , keyid = creds . keyid , kms_keyid = creds . kms_keyid , bucket = creds . bucket , service_url = creds . service_url , verify_ssl = creds . verify_ssl , location = creds . location , return_bin = False , params =...
def resource_url ( self ) : """str : Root URL for IBM Streams REST API"""
self . _resource_url = self . _resource_url or st . get_rest_api ( ) return self . _resource_url
def get_attr ( self , symbol , attrname ) : """Helper for getting symbol extension attributes"""
return symbol . extension_attributes . get ( self . extension_name , { } ) . get ( attrname , None )
def fetch ( self , is_dl_forced = False ) : """: return :"""
# create the connection details for Flybase cxn = { 'host' : 'chado.flybase.org' , 'database' : 'flybase' , 'port' : 5432 , 'user' : 'flybase' , 'password' : 'no password' } self . dataset . setFileAccessUrl ( '' . join ( ( 'jdbc:postgresql://' , cxn [ 'host' ] , ':' , str ( cxn [ 'port' ] ) , '/' , cxn [ 'database' ] ...
def strip_accents ( text ) : """Strip agents from a string ."""
normalized_str = unicodedata . normalize ( 'NFD' , text ) return '' . join ( [ c for c in normalized_str if unicodedata . category ( c ) != 'Mn' ] )
def clean ( self ) : '''Check to make sure password fields match .'''
data = super ( PasswordForm , self ) . clean ( ) if 'new_password' in data : if data [ 'new_password' ] != data . get ( 'confirm_password' , None ) : raise ValidationError ( _ ( 'Passwords do not match.' ) ) if data . get ( 'confirm_password' , None ) == data . get ( 'current_password' , None ) : ...
def _filter_plans ( attr , name , plans ) : '''Helper to return list of usage plan items matching the given attribute value .'''
return [ plan for plan in plans if plan [ attr ] == name ]
def do_list ( self , args ) : """List all connected resources ."""
try : resources = self . resource_manager . list_resources_info ( ) except Exception as e : print ( e ) else : self . resources = [ ] for ndx , ( resource_name , value ) in enumerate ( resources . items ( ) ) : if not args : print ( '({0:2d}) {1}' . format ( ndx , resource_name ) ) ...
def get_address ( name , hash , db , target = None ) : '''fetches the contract address of deployment : param hash : the contract file hash : return : ( string ) address of the contract error , if any'''
key = DB . pkey ( [ EZO . DEPLOYED , name , target , hash ] ) d , err = db . get ( key ) if err : return None , err if not d : return None , None return d [ 'address' ] . lower ( ) , None
def run_car_t_validity_assessment ( job , rsem_files , univ_options , reports_options ) : """A wrapper for assess _ car _ t _ validity . : param dict rsem _ files : Results from running rsem : param dict univ _ options : Dict of universal options used by almost all tools : param dict reports _ options : Optio...
return job . addChildJobFn ( assess_car_t_validity , rsem_files [ 'rsem.genes.results' ] , univ_options , reports_options ) . rv ( )
def references ( self ) : '''List of URLs of external links on a page . May include external links within page that aren ' t technically cited anywhere .'''
if not getattr ( self , '_references' , False ) : def add_protocol ( url ) : return url if url . startswith ( 'http' ) else 'http:' + url self . _references = [ add_protocol ( link [ '*' ] ) for link in self . __continued_query ( { 'prop' : 'extlinks' , 'ellimit' : 'max' } ) ] return self . _references
def remove_callback ( self , name , before = None , after = None ) : """Remove a beforeback , and afterback pair from this Spectator If ` ` before ` ` and ` ` after ` ` are None then all callbacks for the given method will be removed . Otherwise , only the exact callback pair will be removed . Parameters ...
if isinstance ( name , ( list , tuple ) ) : for name in name : self . remove_callback ( name , before , after ) elif before is None and after is None : del self . _callback_registry [ name ] else : if name in self . _callback_registry : callback_list = self . _callback_registry [ name ] ...
def times ( x , y ) : """Do something a random amount of times between x & y"""
def decorator ( fn ) : def wrapped ( * args , ** kwargs ) : n = random . randint ( x , y ) for z in range ( 1 , n ) : fn ( * args , ** kwargs ) return wrapped return decorator
def get_large_image ( self , page = 1 ) : """Downloads and returns the large sized image of a single page . The page kwarg specifies which page to return . One is the default ."""
url = self . get_large_image_url ( page = page ) return self . _get_url ( url )
def drawtree ( self ) : '''Loop over the object , process path attribute sets , and drawlines based on their current contents .'''
self . win . erase ( ) self . line = 0 for child , depth in self . traverse ( ) : child . curline = self . curline child . picked = self . picked child . expanded = self . expanded child . sized = self . sized if depth == 0 : continue if self . line == self . curline : self . col...
def _energy_distance_from_distance_matrices ( distance_xx , distance_yy , distance_xy ) : """Compute energy distance with precalculated distance matrices ."""
return ( 2 * np . mean ( distance_xy ) - np . mean ( distance_xx ) - np . mean ( distance_yy ) )
def load ( self , _path , regs = [ 'chr' , 'left' , 'right' , 'strand' ] , meta = [ ] , values = [ ] , full_load = False , file_extension = "gdm" ) : """Parses and loads the data into instance attributes . The indexes of the data and meta dataframes should be the same . : param path : The path to the dataset on...
if not full_load : warnings . warn ( "\n\nYou are using the optimized loading technique. " "All-zero rows are not going to be loaded into memory. " "To load all the data please set the full_load parameter equal to True." ) p = Parser ( _path ) self . meta = p . parse_meta ( meta ) self . data = p . parse_data ( reg...
def getConfig ( self , key ) : """Get a Config Value"""
if hasattr ( self , key ) : return getattr ( self , key ) else : return False
def WriteClientSnapshot ( self , snapshot , cursor = None ) : """Write new client snapshot ."""
insert_history_query = ( "INSERT INTO client_snapshot_history(client_id, timestamp, " "client_snapshot) VALUES (%s, FROM_UNIXTIME(%s), %s)" ) insert_startup_query = ( "INSERT INTO client_startup_history(client_id, timestamp, " "startup_info) VALUES(%s, FROM_UNIXTIME(%s), %s)" ) now = rdfvalue . RDFDatetime . Now ( ) cl...
def serialize ( self , q ) : """Serialize a Q object into a ( possibly nested ) dict ."""
children = [ ] for child in q . children : if isinstance ( child , Q ) : children . append ( self . serialize ( child ) ) else : children . append ( child ) serialized = q . __dict__ serialized [ 'children' ] = children return serialized
def from_domain ( cls , domain , * args , ** kwargs ) : """Try to download the hive file from the domain using the defined beekeeper spec of domain / api / hive . json ."""
version = kwargs . pop ( 'version' , None ) require = kwargs . pop ( 'require_https' , False ) return cls ( Hive . from_domain ( domain , version , require ) , * args , ** kwargs )
def libvlc_media_player_set_video_title_display ( p_mi , position , timeout ) : '''Set if , and how , the video title will be shown when media is played . @ param p _ mi : the media player . @ param position : position at which to display the title , or libvlc _ position _ disable to prevent the title from bein...
f = _Cfunctions . get ( 'libvlc_media_player_set_video_title_display' , None ) or _Cfunction ( 'libvlc_media_player_set_video_title_display' , ( ( 1 , ) , ( 1 , ) , ( 1 , ) , ) , None , None , MediaPlayer , Position , ctypes . c_int ) return f ( p_mi , position , timeout )
def multisplit ( s , seps = list ( string . punctuation ) + list ( string . whitespace ) , blank = True ) : r"""Just like str . split ( ) , except that a variety ( list ) of seperators is allowed . > > > multisplit ( r ' 1-2?3 , ; . 4 + - ' , string . punctuation ) [ ' 1 ' , ' 2 ' , ' 3 ' , ' ' , ' ' , ' 4 ' , ...
seps = str ( ) . join ( seps ) return [ s2 for s2 in s . translate ( str ( ) . join ( [ ( chr ( i ) if chr ( i ) not in seps else seps [ 0 ] ) for i in range ( 256 ) ] ) ) . split ( seps [ 0 ] ) if ( blank or s2 ) ]
def set_item ( self , index , new_item ) : """Changes item at index in collection . Emit dataChanged signal . : param index : Number of row or index of cell : param new _ item : Dict - like object"""
row = index . row ( ) if hasattr ( index , "row" ) else index self . collection [ row ] = new_item self . dataChanged . emit ( self . index ( row , 0 ) , self . index ( row , self . rowCount ( ) - 1 ) )
def businesstime_hours ( self , d1 , d2 ) : """Returns a datetime . timedelta of business hours between d1 and d2, based on the length of the businessday"""
open_hours = self . open_hours . seconds / 3600 btd = self . businesstimedelta ( d1 , d2 ) btd_hours = btd . seconds / 3600 return datetime . timedelta ( hours = ( btd . days * open_hours + btd_hours ) )
def format_time ( start , end ) : """Returns string with relevant time information formatted properly"""
try : cpu_usr = end [ 0 ] - start [ 0 ] cpu_sys = end [ 1 ] - start [ 1 ] except TypeError : # ` clock ( ) [ 1 ] = = None ` so subtraction results in a TypeError return 'Time elapsed: {}' . format ( human_time ( cpu_usr ) ) else : times = ( human_time ( x ) for x in ( cpu_usr , cpu_sys , cpu_usr + cpu_s...
def add_double_proxy_for ( self , label : str , shape : Collection [ int ] = None ) -> Vertex : """Creates a proxy vertex for the given label and adds to the sequence item"""
if shape is None : return Vertex . _from_java_vertex ( self . unwrap ( ) . addDoubleProxyFor ( _VertexLabel ( label ) . unwrap ( ) ) ) else : return Vertex . _from_java_vertex ( self . unwrap ( ) . addDoubleProxyFor ( _VertexLabel ( label ) . unwrap ( ) , shape ) )
def remove_name ( self ) : """Removes the name ( short _ description node ) from the metadata node , if present . : return : True if the node is removed . False is the node is node is not present ."""
short_description_node = self . metadata . find ( 'short_description' ) if short_description_node is not None : self . metadata . remove ( short_description_node ) return True return False
def traverse_parents ( self , visit , * args , ** kwargs ) : """Traverse the hierarchy upwards , visiting all parents and their children except self . See " visitor pattern " in literature . This is implemented in pre - order fashion . Example : parents = [ ] self . traverse _ parents ( parents . append ) ...
if self . has_parent ( ) : self . __visited = True self . _parent_ . traverse_parents ( visit , * args , ** kwargs ) self . _parent_ . traverse ( visit , * args , ** kwargs ) self . __visited = False
def get_absolute_url ( self ) : """Get model url"""
return reverse ( 'trionyx:model-view' , kwargs = { 'app' : self . _meta . app_label , 'model' : self . _meta . model_name , 'pk' : self . id } )
def _get_conversion_factor ( old_units , new_units , dtype ) : """Get the conversion factor between two units of equivalent dimensions . This is the number you multiply data by to convert from values in ` old _ units ` to values in ` new _ units ` . Parameters old _ units : str or Unit object The current ...
if old_units . dimensions != new_units . dimensions : raise UnitConversionError ( old_units , old_units . dimensions , new_units , new_units . dimensions ) ratio = old_units . base_value / new_units . base_value if old_units . base_offset == 0 and new_units . base_offset == 0 : return ( ratio , None ) else : # ...
def setup_array_pars ( self ) : """main entry point for setting up array multipler parameters"""
mlt_df = self . prep_mlt_arrays ( ) if mlt_df is None : return mlt_df . loc [ : , "tpl_file" ] = mlt_df . mlt_file . apply ( lambda x : os . path . split ( x ) [ - 1 ] + ".tpl" ) # mlt _ df . loc [ mlt _ df . tpl _ file . apply ( lambda x : pd . notnull ( x . pp _ file ) ) , " tpl _ file " ] = np . NaN mlt_files = ...
def _set_get_vnetwork_vms ( self , v , load = False ) : """Setter method for get _ vnetwork _ vms , mapped from YANG variable / brocade _ vswitch _ rpc / get _ vnetwork _ vms ( rpc ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ get _ vnetwork _ vms is considered as a...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = get_vnetwork_vms . get_vnetwork_vms , is_leaf = True , yang_name = "get-vnetwork-vms" , rest_name = "get-vnetwork-vms" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = F...
def _mul8 ( ins ) : """Multiplies 2 las values from the stack . Optimizations : * If any of the ops is ZERO , then do A = 0 = = > XOR A , cause A * 0 = 0 * A = 0 * If any ot the ops is ONE , do NOTHING A * 1 = 1 * A = A"""
op1 , op2 = tuple ( ins . quad [ 2 : ] ) if _int_ops ( op1 , op2 ) is not None : op1 , op2 = _int_ops ( op1 , op2 ) output = _8bit_oper ( op1 ) if op2 == 1 : # A * 1 = 1 * A = A output . append ( 'push af' ) return output if op2 == 0 : output . append ( 'xor a' ) output ....
def store_data_blob ( self , hexdata , wifs , change_address = None , txouts = None , fee = 10000 , lock_time = 0 , dust_limit = common . DUST_LIMIT ) : """TODO add docstring"""
rawtx = self . create_tx ( txouts = txouts , lock_time = lock_time ) rawtx = self . add_data_blob ( rawtx , hexdata , dust_limit = dust_limit ) rawtx = self . add_inputs ( rawtx , wifs , change_address = change_address , fee = fee ) return self . publish ( rawtx )
def as_iterable ( iterable_or_scalar ) : """Utility for converting an object to an iterable . Parameters iterable _ or _ scalar : anything Returns l : iterable If ` obj ` was None , return the empty tuple . If ` obj ` was not iterable returns a 1 - tuple containing ` obj ` . Otherwise return ` obj ` ...
if iterable_or_scalar is None : return ( ) elif isinstance ( iterable_or_scalar , string_types ) : return ( iterable_or_scalar , ) elif hasattr ( iterable_or_scalar , "__iter__" ) : return iterable_or_scalar else : return ( iterable_or_scalar , )
def get_records_with_attachments ( attachment_table , rel_object_field = "REL_OBJECTID" ) : """returns a list of ObjectIDs for rows in the attachment table"""
if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) OIDs = [ ] with arcpy . da . SearchCursor ( attachment_table , [ rel_object_field ] ) as rows : for row in rows : if not str ( row [ 0 ] ) in OIDs : OIDs . append ( "%s" % str ( row [ 0 ] ) ) del ro...
def encode_max_apdu_length_accepted ( arg ) : """Return the encoding of the highest encodable value less than the value of the arg ."""
for i in range ( 5 , - 1 , - 1 ) : if ( arg >= _max_apdu_length_encoding [ i ] ) : return i raise ValueError ( "invalid max APDU length accepted: %r" % ( arg , ) )
def get_money_format ( self , amount ) : """: type amount : int or float or str Usage : > > > currency = Currency ( ' USD ' ) > > > currency . get _ money _ format ( 13) > > > ' $ 13' > > > currency . get _ money _ format ( 13.99) > > > ' $ 13.99' > > > currency . get _ money _ format ( ' 13,2313,33 '...
return self . money_formats [ self . get_money_currency ( ) ] [ 'money_format' ] . format ( amount = amount )
def _should_send_property ( self , key , value ) : """Check the property lock ( property _ lock )"""
to_json = self . trait_metadata ( key , 'to_json' , self . _trait_to_json ) if key in self . _property_lock : # model _ state , buffer _ paths , buffers split_value = _remove_buffers ( { key : to_json ( value , self ) } ) split_lock = _remove_buffers ( { key : self . _property_lock [ key ] } ) # A roundtrip...
def download_url ( url ) : '''download a URL and return the content'''
import urllib2 try : resp = urllib2 . urlopen ( url ) headers = resp . info ( ) except urllib2 . URLError as e : print ( 'Error downloading %s' % url ) return None return resp . read ( )
def mse ( exp , obs ) : """Mean Squared Error : param exp : expected values : type exp : list of float : param obs : observed values : type obs : list of float"""
assert len ( exp ) == len ( obs ) return numpy . mean ( ( numpy . array ( exp ) - numpy . array ( obs ) ) ** 2 )
def prettify ( name , blank = " " ) : """Prettify name of path : param name : path Name : to edit : param blank : default blanks in name : return : Prettier name from given one : replace bad chars with good ones"""
if name . startswith ( "." ) : # remove starting name = name [ 1 : ] for bad_char in BAD_CHARS : name = name . replace ( bad_char , blank ) # remove token name = String ( name ) . remove_all ( blank ) for i in range ( 1 , len ( name ) - 2 ) : try : are_blanks = name [ i - 1 ] == blank and name [ i +...
def _next_page ( self ) : """Get the next page in the iterator . Wraps the response from the : class : ` ~ google . gax . PageIterator ` in a : class : ` Page ` instance and captures some state at each page . Returns : Optional [ Page ] : The next page in the iterator or : data : ` None ` if there are no ...
try : items = six . next ( self . _gax_page_iter ) page = Page ( self , items , self . item_to_value ) self . next_page_token = self . _gax_page_iter . page_token or None return page except StopIteration : return None
def disconnect_handler ( remote , * args , ** kwargs ) : """Handle unlinking of remote account . This default handler will just delete the remote account link . You may wish to extend this module to perform clean - up in the remote service before removing the link ( e . g . removing install webhooks ) . : p...
if not current_user . is_authenticated : return current_app . login_manager . unauthorized ( ) with db . session . begin_nested ( ) : account = RemoteAccount . get ( user_id = current_user . get_id ( ) , client_id = remote . consumer_key ) if account : account . delete ( ) db . session . commit ( ) ...
async def save ( self ) : """Save this interface ."""
if set ( self . tags ) != set ( self . _orig_data [ 'tags' ] ) : self . _changed_data [ 'tags' ] = ',' . join ( self . tags ) elif 'tags' in self . _changed_data : del self . _changed_data [ 'tags' ] orig_params = self . _orig_data [ 'params' ] if not isinstance ( orig_params , dict ) : orig_params = { } pa...
def generate_digest ( self ) : """RFC 2617."""
from hashlib import md5 ha1 = self . username + ':' + self . realm + ':' + self . password HA1 = md5 ( ha1 . encode ( 'UTF-8' ) ) . hexdigest ( ) ha2 = self . method + ':' + self . url HA2 = md5 ( ha2 . encode ( 'UTF-8' ) ) . hexdigest ( ) encrypt_response = HA1 + ':' + self . nonce + ':' + HA2 response = md5 ( encrypt...
def _gcd_array ( X ) : """Return the largest real value h such that all elements in x are integer multiples of h ."""
greatest_common_divisor = 0.0 for x in X : greatest_common_divisor = _gcd ( greatest_common_divisor , x ) return greatest_common_divisor
def _get_vars_to_collections ( variables ) : """Returns a dict mapping variables to the collections they appear in ."""
var_to_collections = collections . defaultdict ( lambda : [ ] ) if isinstance ( variables , dict ) : variables = list ( v for _ , v in variable_map_items ( variables ) ) for graph in set ( v . graph for v in variables ) : for collection_name in list ( graph . collections ) : entries = set ( entry for en...
def _get_count_pagination ( self , base , oldest_neighbor , newest_neighbor ) : """Compute the pagination for count - based views"""
count = self . spec [ 'count' ] out_spec = { ** base , 'count' : count , 'order' : self . _order_by } if self . _order_by == 'newest' : older_view = View ( { ** out_spec , 'last' : oldest_neighbor } ) if oldest_neighbor else None newer_count = View ( { ** base , 'first' : newest_neighbor , 'order' : 'oldest' , ...
def map_remove ( self , key , mapkey , ** kwargs ) : """Remove an item from a map . : param str key : The document ID : param str mapkey : The key in the map : param kwargs : See : meth : ` mutate _ in ` for options : raise : : exc : ` IndexError ` if the mapkey does not exist : raise : : cb _ exc : ` Not...
op = SD . remove ( mapkey ) sdres = self . mutate_in ( key , op , ** kwargs ) return self . _wrap_dsop ( sdres )
def encode ( self ) : """Encodes this SeqCmdAttrs to binary and returns a bytearray ."""
byte = self . default for bit , name , value0 , value1 , default in SeqCmdAttrs . Table : if name in self . attrs : value = self . attrs [ name ] byte = setBit ( byte , bit , value == value1 ) return struct . pack ( 'B' , byte )
def _list_records_internal ( self , identifier = None , rtype = None , name = None , content = None ) : """Lists all records by the specified criteria"""
response = self . _request_get_dns_zone ( ) if 'records' in response : # Interpret empty string as None because zeep does so too content_check = content if content != "" else None name_check = self . _relative_name ( name ) # Stringize the identifier to prevent any rtype differences identifier_check = s...
def sendrpc ( self , argv = [ ] ) : self . _aArgv += argv _operation = '' try : self . _cParams . parser ( self . _aArgv , self . _dOptions ) # set rpc operation handler while self . _cParams . get ( 'operation' ) not in rpc . operations . keys ( ) : self . _cParams . set...
def run_canu ( self ) : '''Runs canu instead of spades'''
cmd = self . _make_canu_command ( self . outdir , 'canu' ) ok , errs = common . syscall ( cmd , verbose = self . verbose , allow_fail = False ) if not ok : raise Error ( 'Error running Canu.' ) original_contigs = os . path . join ( self . outdir , 'canu.contigs.fasta' ) renamed_contigs = os . path . join ( self . o...
def _scalar_from_string ( self , value : str , ) -> Union [ Period , Timestamp , Timedelta , NaTType ] : """Construct a scalar type from a string . Parameters value : str Returns Period , Timestamp , or Timedelta , or NaT Whatever the type of ` ` self . _ scalar _ type ` ` is . Notes This should call ...
raise AbstractMethodError ( self )
def get ( self , path , default_value ) : """Get value for config item into a string value ; leading slash is optional and ignored ."""
return lib . zconfig_get ( self . _as_parameter_ , path , default_value )
def get_size ( self ) : """Get the size of the tree . Returns : tupel : ( width , height )"""
rec = self . get_rectangle ( ) return ( int ( rec [ 2 ] - rec [ 0 ] ) , int ( rec [ 3 ] - rec [ 1 ] ) )
def replace_option_set_by_id ( cls , option_set_id , option_set , ** kwargs ) : """Replace OptionSet Replace all attributes of OptionSet This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . replace _ option _ set _ by ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _replace_option_set_by_id_with_http_info ( option_set_id , option_set , ** kwargs ) else : ( data ) = cls . _replace_option_set_by_id_with_http_info ( option_set_id , option_set , ** kwargs ) return data
def two_sat ( formula ) : """Solving a 2 - SAT boolean formula : param formula : list of clauses , a clause is pair of literals over X1 , . . . , Xn for some n . a literal is an integer , for example - 1 = not X1 , 3 = X3 : returns : table with boolean assignment satisfying the formula or None : complexit...
# - - n is the number of variables n = max ( abs ( clause [ p ] ) for p in ( 0 , 1 ) for clause in formula ) graph = [ [ ] for node in range ( 2 * n ) ] for x , y in formula : # x or y graph [ _vertex ( - x ) ] . append ( _vertex ( y ) ) # - x = > y graph [ _vertex ( - y ) ] . append ( _vertex ( x ) ) #...
def createRect ( self , x , y , width , height , rx = None , ry = None , strokewidth = 1 , stroke = 'black' , fill = 'none' ) : """Creates a Rectangle @ type x : string or int @ param x : starting x - coordinate @ type y : string or int @ param y : starting y - coordinate @ type width : string or int @ ...
style_dict = { 'fill' : fill , 'stroke-width' : strokewidth , 'stroke' : stroke } myStyle = StyleBuilder ( style_dict ) r = Rect ( x , y , width , height , rx , ry ) r . set_style ( myStyle . getStyle ( ) ) return r
def listify ( val , return_type = tuple ) : """Examples : > > > listify ( ' abc ' , return _ type = list ) [ ' abc ' ] > > > listify ( None ) > > > listify ( False ) ( False , ) > > > listify ( ( ' a ' , ' b ' , ' c ' ) , return _ type = list ) [ ' a ' , ' b ' , ' c ' ]"""
# TODO : flatlistify ( ( 1 , 2 , 3 ) , 4 , ( 5 , 6 , 7 ) ) if val is None : return return_type ( ) elif isiterable ( val ) : return return_type ( val ) else : return return_type ( ( val , ) )
def generate_data ( timeseries_length , timeseries_params ) : """Generates synthetic timeseries using input parameters . Each generated timeseries has timeseries _ length data points . Parameters for each timeseries are specified by timeseries _ params . Args : timeseries _ length : Number of data points to...
x = range ( timeseries_length ) multi_timeseries = [ ] for p in timeseries_params : # Trend y1 = [ p [ "m" ] * i + p [ "b" ] for i in x ] # Period y2 = [ p [ "A" ] * p [ "fn" ] ( i / p [ "freqcoeff" ] ) for i in x ] # Noise y3 = np . random . normal ( 0 , p [ "rndA" ] , timeseries_length ) . tolist ...
def is_sortable_index ( self , index_name , catalog ) : """Returns whether the index is sortable"""
index = self . get_index ( index_name , catalog ) if not index : return False return index . meta_type in [ "FieldIndex" , "DateIndex" ]
def run_sixteens ( self ) : """Run the 16S analyses using the filtered database"""
SixteensFull ( args = self , pipelinecommit = self . commit , startingtime = self . starttime , scriptpath = self . homepath , analysistype = 'sixteens_full' , cutoff = 0.985 )