signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_all_importing_namespace_hashes ( self ) : """Get the set of all preordered and revealed namespace hashes that have not expired ."""
cur = self . db . cursor ( ) namespace_hashes = namedb_get_all_importing_namespace_hashes ( cur , self . lastblock ) return namespace_hashes
def BytesIO ( * args , ** kwargs ) : """BytesIO constructor shim for the async wrapper ."""
raw = sync_io . BytesIO ( * args , ** kwargs ) return AsyncBytesIOWrapper ( raw )
def generate ( env ) : """Add Builders and construction variables for tar to an Environment ."""
try : bld = env [ 'BUILDERS' ] [ 'Tar' ] except KeyError : bld = TarBuilder env [ 'BUILDERS' ] [ 'Tar' ] = bld env [ 'TAR' ] = env . Detect ( tars ) or 'gtar' env [ 'TARFLAGS' ] = SCons . Util . CLVar ( '-c' ) env [ 'TARCOM' ] = '$TAR $TARFLAGS -f $TARGET $SOURCES' env [ 'TARSUFFIX' ] = '.tar'
def _dep_map ( self ) : """A map of extra to its list of ( direct ) requirements for this distribution , including the null extra ."""
try : return self . __dep_map except AttributeError : self . __dep_map = self . _filter_extras ( self . _build_dep_map ( ) ) return self . __dep_map
def process_flat_files ( id_mappings_file , complexes_file = None , ptm_file = None , ppi_file = None , seq_file = None , motif_window = 7 ) : """Get INDRA Statements from HPRD data . Of the arguments , ` id _ mappings _ file ` is required , and at least one of ` complexes _ file ` , ` ptm _ file ` , and ` ppi ...
id_df = pd . read_csv ( id_mappings_file , delimiter = '\t' , names = _hprd_id_cols , dtype = 'str' ) id_df = id_df . set_index ( 'HPRD_ID' ) if complexes_file is None and ptm_file is None and ppi_file is None : raise ValueError ( 'At least one of complexes_file, ptm_file, or ' 'ppi_file must be given.' ) if ptm_fi...
def notifications ( self ) : """Access the notifications : returns : twilio . rest . api . v2010 . account . notification . NotificationList : rtype : twilio . rest . api . v2010 . account . notification . NotificationList"""
if self . _notifications is None : self . _notifications = NotificationList ( self . _version , account_sid = self . _solution [ 'sid' ] , ) return self . _notifications
def measure_string ( self , text , fontname , fontsize , encoding = 0 ) : """Measure length of a string for a Base14 font ."""
return _fitz . Tools_measure_string ( self , text , fontname , fontsize , encoding )
def remove ( self , branch , turn , tick ) : """Delete all data from a specific tick"""
time_entity , parents , branches , keys , settings , presettings , remove_keycache , send = self . _remove_stuff parent , entity , key = time_entity [ branch , turn , tick ] branchkey = parent + ( entity , key ) keykey = parent + ( entity , ) if parent in parents : parentt = parents [ parent ] if entity in pare...
def patch_with_options ( request , options , parent_queue_item = None ) : """Patch the given request with the given options ( e . g . user agent ) . Args : request ( : class : ` nyawc . http . Request ` ) : The request to patch . options ( : class : ` nyawc . Options ` ) : The options to patch the request wit...
request . auth = copy . deepcopy ( options . identity . auth ) request . cookies = copy . deepcopy ( options . identity . cookies ) request . headers = copy . deepcopy ( options . identity . headers ) request . proxies = copy . deepcopy ( options . identity . proxies ) request . timeout = copy . copy ( options . perfor...
def add_variables_from ( self , linear , vartype = None ) : """Add variables and / or linear biases to a binary quadratic model . Args : linear ( dict [ variable , bias ] / iterable [ ( variable , bias ) ] ) : A collection of variables and their linear biases to add to the model . If a dict , keys are varia...
if isinstance ( linear , abc . Mapping ) : for v , bias in iteritems ( linear ) : self . add_variable ( v , bias , vartype = vartype ) else : try : for v , bias in linear : self . add_variable ( v , bias , vartype = vartype ) except TypeError : raise TypeError ( "expected...
def load_mo ( self , state , page_idx ) : """Loads a memory object from memory . : param page _ idx : the index into the page : returns : a tuple of the object"""
mo = self . _storage [ page_idx - self . _page_addr ] return self . _sinkhole if mo is None else mo
def configure_visual_baseline ( self ) : """Configure baseline directory"""
# Get baseline name baseline_name = self . config . get_optional ( 'VisualTests' , 'baseline_name' , '{Driver_type}' ) for section in self . config . sections ( ) : for option in self . config . options ( section ) : option_value = self . config . get ( section , option ) baseline_name = baseline_na...
def runner ( fun , arg = None , timeout = 5 ) : '''Execute a runner on the master and return the data from the runner function CLI Example : . . code - block : : bash salt publish . runner manage . down'''
arg = _parse_args ( arg ) if 'master_uri' not in __opts__ : return 'No access to master. If using salt-call with --local, please remove.' log . info ( 'Publishing runner \'%s\' to %s' , fun , __opts__ [ 'master_uri' ] ) auth = salt . crypt . SAuth ( __opts__ ) tok = auth . gen_token ( b'salt' ) load = { 'cmd' : 'mi...
def to_excel ( self , filename , recommended_only = False , include_io = True ) : """Return an Excel file for each model and dataset . Parameters filename : str or ExcelWriter object Either the file name ( string ) or an ExcelWriter object . recommended _ only : bool , optional If True , only recommended ...
df = self . to_df ( recommended_only , include_io ) if isinstance ( filename , string_types ) : filename = os . path . expanduser ( filename ) df . to_excel ( filename , index = False )
def _get_contents_between ( string , opener , closer ) : """Get the contents of a string between two characters"""
opener_location = string . index ( opener ) closer_location = string . index ( closer ) content = string [ opener_location + 1 : closer_location ] return content
def delete_ipv4 ( self , ipv4_id ) : """Delete ipv4"""
uri = 'api/ipv4/%s/' % ( ipv4_id ) return super ( ApiNetworkIPv4 , self ) . delete ( uri )
def system ( session ) : """Run the system test suite ."""
system_test_path = os . path . join ( "tests" , "system.py" ) system_test_folder_path = os . path . join ( "tests" , "system" ) # Sanity check : Only run tests if the environment variable is set . if not os . environ . get ( "GOOGLE_APPLICATION_CREDENTIALS" , "" ) : session . skip ( "Credentials must be set via env...
def _vector ( x , type = 'row' ) : """Convert an object to a row or column vector ."""
if isinstance ( x , ( list , tuple ) ) : x = np . array ( x , dtype = np . float32 ) elif not isinstance ( x , np . ndarray ) : x = np . array ( [ x ] , dtype = np . float32 ) assert x . ndim == 1 if type == 'column' : x = x [ : , None ] return x
def get_symbol ( x ) : """Retrieve recorded computation history as ` Symbol ` . Parameters x : NDArray Array representing the head of computation graph . Returns Symbol The retrieved Symbol ."""
hdl = SymbolHandle ( ) check_call ( _LIB . MXAutogradGetSymbol ( x . handle , ctypes . byref ( hdl ) ) ) return Symbol ( hdl )
def get_net_size ( mask ) : '''Turns an IPv4 netmask into it ' s corresponding prefix length (255.255.255.0 - > 24 as in 192.168.1.10/24 ) .'''
binary_str = '' for octet in mask . split ( '.' ) : binary_str += bin ( int ( octet ) ) [ 2 : ] . zfill ( 8 ) return len ( binary_str . rstrip ( '0' ) )
def file ( cls , uri_or_path ) : """Given either a URI like s3 : / / bucket / path . txt or a path like / path . txt , return a file object for it ."""
uri = urlparse ( uri_or_path ) if not uri . scheme : # Just a normal path return open ( uri_or_path , 'rb' ) else : it = cls ( uri_or_path ) . download_iter ( uri . path . lstrip ( '/' ) , skip_hash = True ) if not it : raise ValueError ( '{0} not found' . format ( uri_or_path ) ) tmp = tempfile...
def decrement ( self , column , amount = 1 , extras = None ) : """Decrement a column ' s value by a given amount : param column : The column to increment : type column : str : param amount : The amount by which to increment : type amount : int : param extras : Extra columns : type extras : dict : retu...
if extras is None : extras = { } extras = self . _add_updated_at_column ( extras ) return self . to_base ( ) . decrement ( column , amount , extras )
def get_plink_version ( ) : """Gets the Plink version from the binary . : returns : the version of the Plink software : rtype : str This function uses : py : class : ` subprocess . Popen ` to gather the version of the Plink binary . Since executing the software to gather the version creates an output file...
# Running the command tmp_fn = None with tempfile . NamedTemporaryFile ( delete = False ) as tmpfile : tmp_fn = tmpfile . name + "_pyGenClean" # The command to run command = [ "plink" , "--noweb" , "--out" , tmp_fn ] output = None try : proc = Popen ( command , stdout = PIPE , stderr = PIPE ) output = proc ...
def get_controller ( self ) : """Gets the configured OpenFlow controller address . This method is corresponding to the following ovs - vsctl command : : $ ovs - vsctl get - controller < bridge >"""
command = ovs_vsctl . VSCtlCommand ( 'get-controller' , [ self . br_name ] ) self . run_command ( [ command ] ) result = command . result return result [ 0 ] if len ( result ) == 1 else result
def change_group_name ( self , group_jid : str , new_name : str ) : """Changes the a group ' s name to something new : param group _ jid : The JID of the group whose name should be changed : param new _ name : The new name to give to the group"""
log . info ( "[+] Requesting a group name change for JID {} to '{}'" . format ( group_jid , new_name ) ) return self . _send_xmpp_element ( group_adminship . ChangeGroupNameRequest ( group_jid , new_name ) )
def start ( self , ** kwargs ) : """Present the PTY of the container inside the current process . This will take over the current process ' TTY until the container ' s PTY is closed ."""
pty_stdin , pty_stdout , pty_stderr = self . sockets ( ) pumps = [ ] if pty_stdin and self . interactive : pumps . append ( io . Pump ( io . Stream ( self . stdin ) , pty_stdin , wait_for_output = False ) ) if pty_stdout : pumps . append ( io . Pump ( pty_stdout , io . Stream ( self . stdout ) , propagate_close...
def monitor_session_span_command_dest_vlan_val ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) monitor = ET . SubElement ( config , "monitor" , xmlns = "urn:brocade.com:mgmt:brocade-span" ) session = ET . SubElement ( monitor , "session" ) session_number_key = ET . SubElement ( session , "session-number" ) session_number_key . text = kwargs . pop ( 'session_number' ) span_comma...
def _ParseAccountsData ( self , account_data ) : """Parse the SSH key data into a user map . Args : account _ data : string , the metadata server SSH key attributes data . Returns : dict , a mapping of the form : { ' username ' : [ ' sshkey1 , ' sshkey2 ' , . . . ] } ."""
if not account_data : return { } lines = [ line for line in account_data . splitlines ( ) if line ] user_map = { } for line in lines : if not all ( ord ( c ) < 128 for c in line ) : self . logger . info ( 'SSH key contains non-ascii character: %s.' , line ) continue split_line = line . split...
def MySend ( request_path , payload = None , content_type = "application/octet-stream" , timeout = None , force_auth = True , ** kwargs ) : """Run MySend1 maybe twice , because Rietveld is unreliable ."""
try : return MySend1 ( request_path , payload , content_type , timeout , force_auth , ** kwargs ) except Exception , e : if type ( e ) != urllib2 . HTTPError or e . code != 500 : # only retry on HTTP 500 error raise print >> sys . stderr , "Loading " + request_path + ": " + ExceptionDetail ( ) + "; ...
def v_lift_valve_Crane ( rho , D1 = None , D2 = None , style = 'swing check angled' ) : r'''Calculates the approximate minimum velocity required to lift the disk or other controlling element of a check valve to a fully open , stable , position according to the Crane method [ 1 ] _ . . . math : : v _ { min }...
specific_volume = 1. / rho if D1 is not None and D2 is not None : beta = D1 / D2 beta2 = beta * beta if style == 'swing check angled' : return 45.0 * specific_volume ** 0.5 elif style == 'swing check straight' : return 75.0 * specific_volume ** 0.5 elif style == 'swing check UL' : return 120.0 * spe...
def _printUUID ( uuid , detail = 'word' ) : """Return friendly abbreviated string for uuid ."""
if not isinstance ( detail , int ) : detail = detailNum [ detail ] if detail > detailNum [ 'word' ] : return uuid if uuid is None : return None return "%s...%s" % ( uuid [ : 4 ] , uuid [ - 4 : ] )
def SerializeFaultDetail ( self , val , info ) : """Serialize an object"""
self . _SerializeDataObject ( val , info , ' xsi:typ="{1}"' . format ( val . _wsdlName ) , self . defaultNS )
def operate_on_bulb ( self , method , params = None ) : """Build socket and send command to the bulb through it : param method : method you want to use : param params : parameters needed for this method ( can be a string if ony one parameter is needed ) : type method : str : type params : list of str"""
# Get the message self . command = YeelightCommand ( self . next_cmd_id ( ) , method , params ) # Send with socket tcp_socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) tcp_socket . connect ( ( self . ip , int ( self . port ) ) ) tcp_socket . send ( self . command . get_message ( ) . encode ( ) ) dat...
def losing_name ( self ) : """Returns a ` ` string ` ` of the losing team ' s name , such as ' Indiana ' Hoosiers ' ."""
if self . winner == HOME : if 'cbb/schools' not in str ( self . _away_name ) : return str ( self . _away_name ) return self . _away_name . text ( ) if 'cbb/schools' not in str ( self . _home_name ) : return str ( self . _home_name ) return self . _home_name . text ( )
def isSigned ( self , ns_uri , ns_key ) : """Return whether a particular key is signed , regardless of its namespace alias"""
return self . message . getKey ( ns_uri , ns_key ) in self . signed_fields
def close ( self ) : """Closes the serial port ."""
if self . pyb and self . pyb . serial : self . pyb . serial . close ( ) self . pyb = None
def generate_url_map ( yaml_path = TOC_PATH ) -> dict : """Generates mapping from each URL to its previous and next URLs in the textbook . The dictionary looks like : ' ch / 10 / some _ page . html ' : { ' prev ' : ' ch / 09 / foo . html ' , ' next ' : ' ch / 10 / bar . html ' ,"""
with open ( yaml_path ) as f : data = yaml . load ( f ) pipeline = [ t . remove ( _not_internal_link ) , flatmap ( _flatten_sections ) , t . map ( t . get ( 'url' ) ) , list , _sliding_three , t . map ( _adj_pages ) , t . merge ( ) ] return t . pipe ( data , * pipeline )
def get_file_versions ( self , secure_data_path , limit = None , offset = None ) : """Get versions of a particular file This is just a shim to get _ secret _ versions secure _ data _ path - - full path to the file in the safety deposit box limit - - Default ( 100 ) , limits how many records to be returned fro...
return self . get_secret_versions ( secure_data_path , limit , offset )
def sender ( self , body , stamp , url , sig ) : """Validate request is from Alexa . Verifying that the Request was Sent by Alexa : https : / / goo . gl / AcrzB5. Checking the Signature of the Request : https : / / goo . gl / FDkjBN . Checking the Timestamp of the Request : https : / / goo . gl / Z5JhqZ Arg...
if not timestamp ( stamp ) : return False if self . url != url : if not signature_cert_chain_url ( url ) : return False certs = retrieve ( url ) if not certs : return False if not cert_chain ( certs ) : return False self . url = url self . cert = certs [ 0 ] if not si...
def get_vpn ( self , vpn_name ) : """Returns a specific VPN name details from CPNR server ."""
request_url = self . _build_url ( [ 'VPN' , vpn_name ] ) return self . _do_request ( 'GET' , request_url )
def oop ( aa ) : """For cmd output ."""
return ( '%s %s %s %.2f %+.2f %s %s %s %s %+.2f %s %s %.2f %.4f %.4f' % ( aa . stock_no , aa . stock_name , aa . data_date [ - 1 ] , aa . raw_data [ - 1 ] , aa . range_per , aa . MAC ( 3 ) , aa . MAC ( 6 ) , aa . MAC ( 18 ) , aa . MAO ( 3 , 6 ) [ 1 ] , aa . MAO ( 3 , 6 ) [ 0 ] [ 1 ] [ - 1 ] , aa . MAO ( 3 , 6 ) [ 0 ] [...
def _parse_env_var_file ( data ) : """Parses a basic VAR = " value data " file contents into a dict : param data : A unicode string of the file data : return : A dict of parsed name / value data"""
output = { } for line in data . splitlines ( ) : line = line . strip ( ) if not line or '=' not in line : continue parts = line . split ( '=' ) if len ( parts ) != 2 : continue name = parts [ 0 ] value = parts [ 1 ] if len ( value ) > 1 : if value [ 0 ] == '"' and val...
def circle_line_intersection ( center , r , a , b ) : '''Computes two intersection points between the circle centered at < center > and radius < r > and a line given by two points a and b . If no intersection exists , or if a = = b , None is returned . If one intersection exists , it is repeated in the answer . ...
s = b - a # Quadratic eqn coefs A = np . linalg . norm ( s ) ** 2 if abs ( A ) < tol : return None B = 2 * np . dot ( a - center , s ) C = np . linalg . norm ( a - center ) ** 2 - r ** 2 disc = B ** 2 - 4 * A * C if disc < 0.0 : return None t1 = ( - B + np . sqrt ( disc ) ) / 2.0 / A t2 = ( - B - np . sqrt ( di...
def create ( name , allocated_storage , db_instance_class , engine , master_username , master_user_password , db_name = None , db_security_groups = None , vpc_security_group_ids = None , vpc_security_groups = None , availability_zone = None , db_subnet_group_name = None , preferred_maintenance_window = None , db_parame...
if not allocated_storage : raise SaltInvocationError ( 'allocated_storage is required' ) if not db_instance_class : raise SaltInvocationError ( 'db_instance_class is required' ) if not engine : raise SaltInvocationError ( 'engine is required' ) if not master_username : raise SaltInvocationError ( 'maste...
def plot ( data , xcats , ycats = None , pconfig = None ) : """Plot a 2D heatmap . : param data : List of lists , each a representing a row of values . : param xcats : Labels for x axis : param ycats : Labels for y axis . Defaults to same as x . : param pconfig : optional dict with config key : value pairs ...
if pconfig is None : pconfig = { } # Allow user to overwrite any given config for this plot if 'id' in pconfig and pconfig [ 'id' ] and pconfig [ 'id' ] in config . custom_plot_config : for k , v in config . custom_plot_config [ pconfig [ 'id' ] ] . items ( ) : pconfig [ k ] = v if ycats is None : y...
def department_create ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / chat / departments # create - department"
api_path = "/api/v2/departments" return self . call ( api_path , method = "POST" , data = data , ** kwargs )
def manage_permission_for ( brain_or_object , permission , roles , acquire = 0 ) : """Change the settings for the given permission . Code extracted from ` IRoleManager . manage _ permission ` : param brain _ or _ object : Catalog brain or object : param permission : The permission to be granted : param role...
obj = api . get_object ( brain_or_object ) if isinstance ( roles , basestring ) : roles = [ roles ] for item in obj . ac_inherited_permissions ( 1 ) : name , value = item [ : 2 ] if name == permission : permission = Permission ( name , value , obj ) if acquire : roles = list ( ro...
def compute_normals ( self , cell_normals = True , point_normals = True , split_vertices = False , flip_normals = False , consistent_normals = True , auto_orient_normals = False , non_manifold_traversal = True , feature_angle = 30.0 , inplace = False ) : """Compute point and / or cell normals for a mesh . The fil...
normal = vtk . vtkPolyDataNormals ( ) normal . SetComputeCellNormals ( cell_normals ) normal . SetComputePointNormals ( point_normals ) normal . SetSplitting ( split_vertices ) normal . SetFlipNormals ( flip_normals ) normal . SetConsistency ( consistent_normals ) normal . SetAutoOrientNormals ( auto_orient_normals ) n...
def _get_languages ( cls ) -> set : """Get supported languages ( by querying the server ) ."""
if not cls . _server_is_alive ( ) : cls . _start_server_on_free_port ( ) url = urllib . parse . urljoin ( cls . _url , 'Languages' ) languages = set ( ) for e in cls . _get_root ( url , num_tries = 1 ) : languages . add ( e . get ( 'abbr' ) ) languages . add ( e . get ( 'abbrWithVariant' ) ) return language...
def deconstruct ( self ) : """FK to version always points to a version table"""
name , path , args , kwargs = super ( FKToVersion , self ) . deconstruct ( ) if not kwargs [ 'to' ] . endswith ( '_version' ) : kwargs [ 'to' ] = '{0}_version' . format ( kwargs [ 'to' ] ) return name , path , args , kwargs
async def add_user ( self , username , password = None , display_name = None ) : """Add a user to this controller . : param str username : Username : param str password : Password : param str display _ name : Display name : returns : A : class : ` ~ juju . user . User ` instance"""
if not display_name : display_name = username user_facade = client . UserManagerFacade . from_connection ( self . connection ( ) ) users = [ client . AddUser ( display_name = display_name , username = username , password = password ) ] results = await user_facade . AddUser ( users ) secret_key = results . results [...
def acknowledge ( self , size , msg ) : """Acknowledge bytes received by a transfer target , scheduling new chunks to keep the window full . This should be called for every chunk received by the target ."""
stream = self . router . stream_by_id ( msg . src_id ) state = self . _state_by_stream [ stream ] state . lock . acquire ( ) try : if state . unacked < size : LOG . error ( '%r.acknowledge(src_id %d): unacked=%d < size %d' , self , msg . src_id , state . unacked , size ) state . unacked -= min ( state ....
def visit_Name ( self , node ) : """Turn global variable used not shadows to function call . We check it is a name from an assignment as import or functions use should not be turn into call ."""
if ( isinstance ( node . ctx , ast . Load ) and node . id not in self . local_decl and node . id in self . to_expand ) : self . update = True return ast . Call ( func = node , args = [ ] , keywords = [ ] ) return node
def get_encoding_from_reponse ( r ) : """获取requests库get或post返回的对象编码 Args : r : requests库get或post返回的对象 Returns : 对象编码"""
encoding = requests . utils . get_encodings_from_content ( r . text ) return encoding [ 0 ] if encoding else requests . utils . get_encoding_from_headers ( r . headers )
def tag_alert ( self , id , tags ) : """Append tags to tag list . Don ' t add same tag more than once ."""
response = self . get_db ( ) . alerts . update_one ( { '_id' : { '$regex' : '^' + id } } , { '$addToSet' : { 'tags' : { '$each' : tags } } } ) return response . matched_count > 0
def feature ( self , type_ = None , identifier = None , description = None , entry_name = None , limit = None , as_df = False ) : """Method to query : class : ` . models . Feature ` objects in database Check available features types with ` ` pyuniprot . query ( ) . feature _ types ` ` : param type _ : type ( s ...
q = self . session . query ( models . Feature ) model_queries_config = ( ( type_ , models . Feature . type_ ) , ( identifier , models . Feature . identifier ) , ( description , models . Feature . description ) ) q = self . get_model_queries ( q , model_queries_config ) q = self . get_one_to_many_queries ( q , ( ( entry...
def _get_registries ( self ) : """Return a list of registries that this build updated For orchestrator it should attempt to filter out non - pulp registries , on worker - return all registries"""
if self . workflow . buildstep_result . get ( PLUGIN_BUILD_ORCHESTRATE_KEY ) : registries = self . workflow . push_conf . pulp_registries if not registries : registries = self . workflow . push_conf . all_registries return registries else : return self . workflow . push_conf . all_registries
def generate_expand_search_database_from_contigs ( self , contig_files , output_database_file , search_method ) : '''Given a collection of search _ hmm _ files , search the contigs in contig _ files , and generate an HMM from the resulting hits , outputting it as output _ database _ file . Parameters contig...
ss = SequenceSearcher ( self . search_hmm_files ) seqio = SequenceIO ( ) if search_method == self . DIAMOND_SEARCH_METHOD : if self . diamond_database == None or self . unaligned_sequence_database == None : logging . warning ( "Cannot expand_search continue with no diamond database or unaligned sequences." ...
def _get_partition_info ( storage_system , device_path ) : '''Returns partition informations for a device path , of type vim . HostDiskPartitionInfo'''
try : partition_infos = storage_system . RetrieveDiskPartitionInfo ( devicePath = [ device_path ] ) except vim . fault . NoPermission as exc : log . exception ( exc ) raise salt . exceptions . VMwareApiError ( 'Not enough permissions. Required privilege: ' '{0}' . format ( exc . privilegeId ) ) except vim ....
def serialize ( self , value , ** kwargs ) : """Serialize the attribute of the input data . Gets the attribute value with accessor and converts it using the type serialization . Schema will place this serialized value into corresponding compartment of the HAL structure with the name of the attribute as a ke...
if types . Type . is_type ( self . attr_type ) : try : value = self . accessor . get ( value , ** kwargs ) except ( AttributeError , KeyError ) : if not hasattr ( self , "default" ) and self . required : raise value = self . default ( ) if callable ( self . default ) else sel...
def serialzeValueToTCL ( self , val , do_eval = False ) -> Tuple [ str , str , bool ] : """Serialize value to TCL : return : tuple ( serialized value , serialized evaluated value of value , value is constant flag )"""
return str ( val ) , str ( val ) , True
def getStorageEngines ( self ) : """Returns list of supported storage engines . @ return : List of storage engine names ."""
cur = self . _conn . cursor ( ) cur . execute ( """SHOW STORAGE ENGINES;""" ) rows = cur . fetchall ( ) if rows : return [ row [ 0 ] . lower ( ) for row in rows if row [ 1 ] in [ 'YES' , 'DEFAULT' ] ] else : return [ ]
def WriteGoogleTransitFeed ( self , file ) : """Output this schedule as a Google Transit Feed in file _ name . Args : file : path of new feed file ( a string ) or a file - like object Returns : None"""
# Compression type given when adding each file archive = zipfile . ZipFile ( file , 'w' ) if 'agency' in self . _table_columns : agency_string = StringIO . StringIO ( ) writer = util . CsvUnicodeWriter ( agency_string ) columns = self . GetTableColumns ( 'agency' ) writer . writerow ( columns ) for ...
def generate_nb_state_data ( means , weights , R ) : """Generates data according to the Negative Binomial Convex Mixture Model . Args : means ( array ) : Cell types - genes x clusters weights ( array ) : Cell cluster assignments - clusters x cells R ( array ) : dispersion parameter - 1 x genes Returns : ...
cells = weights . shape [ 1 ] # x _ true = true means x_true = np . dot ( means , weights ) # convert means into P R_ = np . tile ( R , ( cells , 1 ) ) . T P_true = x_true / ( R_ + x_true ) sample = np . random . negative_binomial ( np . tile ( R , ( cells , 1 ) ) . T , P_true ) return sample . astype ( float )
def execute ( self , input_data ) : '''Execute method'''
# Grab the raw bytes of the sample raw_bytes = input_data [ 'sample' ] [ 'raw_bytes' ] # Spin up the rekall session and render components session = MemSession ( raw_bytes ) renderer = WorkbenchRenderer ( session = session ) # Run the plugin session . RunPlugin ( self . plugin_name , renderer = renderer ) return rendere...
def load_window_settings ( self , prefix , default = False , section = 'main' ) : """Load window layout settings from userconfig - based configuration with * prefix * , under * section * default : if True , do not restore inner layout"""
get_func = CONF . get_default if default else CONF . get window_size = get_func ( section , prefix + 'size' ) prefs_dialog_size = get_func ( section , prefix + 'prefs_dialog_size' ) if default : hexstate = None else : hexstate = get_func ( section , prefix + 'state' , None ) pos = get_func ( section , prefix + ...
def classattribute ( func ) : """Wrap a function as a class attribute . This differs from attribute by identifying attributes explicitly listed in a class definition rather than those only defined on instances of a class ."""
attr = abc . abstractmethod ( func ) attr . __iclassattribute__ = True attr = _property ( attr ) return attr
def add_interim_values ( module , input , output ) : """The forward hook used to save interim tensors , detached from the graph . Used to calculate the multipliers"""
try : del module . x except AttributeError : pass try : del module . y except AttributeError : pass module_type = module . __class__ . __name__ if module_type in op_handler : func_name = op_handler [ module_type ] . __name__ # First , check for cases where we don ' t need to save the x and y ten...
def VerifyStructure ( self , parser_mediator , line ) : """Verify that this file is a Sophos Anti - Virus log file . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfVFS . line ( str ) : line from a text file . Returns : boo...
try : structure = self . _LOG_LINE . parseString ( line ) except pyparsing . ParseException : logger . debug ( 'Not a Sophos Anti-Virus log file' ) return False # Expect spaces at position 9 and 16. if ' ' not in ( line [ 8 ] , line [ 15 ] ) : logger . debug ( 'Not a Sophos Anti-Virus log file' ) re...
def dot_solve ( self , y ) : r"""Compute the inner product of a vector with the inverse of the covariance matrix applied to itself : . . math : : y \ , K ^ { - 1 } \ , y Args : y ( ndarray [ nsamples ] ) : The vector : math : ` y ` ."""
return np . dot ( y . T , cho_solve ( self . _factor , y ) )
def split_channels ( image ) : """Split channels of a multi - channel ANTsImage into a collection of scalar ANTsImage types Arguments image : ANTsImage multi - channel image to split Returns list of ANTsImage types Example > > > import ants > > > image = ants . image _ read ( ants . get _ ants _ d...
inpixeltype = image . pixeltype dimension = image . dimension components = 1 libfn = utils . get_lib_fn ( 'splitChannels%s' % image . _libsuffix ) itkimages = libfn ( image . pointer ) antsimages = [ iio . ANTsImage ( pixeltype = inpixeltype , dimension = dimension , components = components , pointer = itkimage ) for i...
def set_logging ( cfg_obj ) : """Enable or disable logging per config object parameter"""
log_status = cfg_obj [ 'LOGGING' ] [ 'ENABLE_LOGGING' ] if log_status : logger . disabled = False elif not log_status : logger . info ( '%s: Logging disabled per local configuration file (%s) parameters.' % ( inspect . stack ( ) [ 0 ] [ 3 ] , cfg_obj [ 'PROJECT' ] [ 'CONFIG_PATH' ] ) ) logger . disabled = T...
def btc_is_p2wpkh_address ( address ) : """Is the given address a p2wpkh address ?"""
wver , whash = segwit_addr_decode ( address ) if whash is None : return False if len ( whash ) != 20 : return False return True
def set_edge_label ( self , edge , label ) : """Set the label of an edge . @ type edge : edge @ param edge : One edge . @ type label : string @ param label : Edge label ."""
self . set_edge_properties ( edge , label = label ) if not self . DIRECTED : self . set_edge_properties ( ( edge [ 1 ] , edge [ 0 ] ) , label = label )
def custom_str ( self , sc_expr_str_fn ) : """Works like Symbol . _ _ str _ _ ( ) , but allows a custom format to be used for all symbol / choice references . See expr _ str ( ) ."""
return "\n\n" . join ( node . custom_str ( sc_expr_str_fn ) for node in self . nodes )
def _transform ( self , value ) : """Applies any defined transformation to the given value"""
if self . transform : try : value = self . transform ( value ) except : import sys exc_type , exc_obj , exc_tb = sys . exc_info ( ) raise AssertionError ( 'Error applying transformation <{0}>: {2}: {3}' . format ( self . transform . __name__ , value , exc_type . __name__ , exc_ob...
def permute_outputs ( Y , X ) : """Permute the output according to one of the inputs as in [ _ 2] References . . [ 2 ] Elmar Plischke ( 2010 ) " An effective algorithm for computing global sensitivity indices ( EASI ) Reliability Engineering & System Safety " , 95:4 , 354-360 . doi : 10.1016 / j . ress . 20...
permutation_index = np . argsort ( X ) permutation_index = np . concatenate ( [ permutation_index [ : : 2 ] , permutation_index [ 1 : : 2 ] [ : : - 1 ] ] ) return Y [ permutation_index ]
def sql ( self , query ) : """Perform a SQL query and create a L { DataFrame } of the result . The SQL query is run using Spark SQL . This is not intended for querying arbitrary databases , but rather querying Spark SQL tables . Parameters query : string The SQL query to pass to Spark SQL to execute . R...
return DataFrame . from_spark_rdd ( self . sql_ctx . sql ( query ) , self . sql_ctx )
def calculate_oobatake_dH ( seq , temp ) : """Get dH using Oobatake method in units cal / mol . Args : seq ( str , Seq , SeqRecord ) : Amino acid sequence temp ( float ) : Temperature in degrees C Returns : float : dH in units cal / mol"""
seq = ssbio . protein . sequence . utils . cast_to_str ( seq ) dH = 0 temp += 273.15 T0 = 298.15 for aa in seq : H0 = oobatake_dictionary [ aa ] [ 'dH' ] * 1000 dH += H0 return dH + _sum_of_dCp ( seq ) * ( temp - T0 )
def generate ( passphrase , trees = [ 'primary' ] ) : """Generate a seed for the primary tree of a Gem wallet . You may choose to store the passphrase for a user so the user doesn ' t have to type it in every time . This is okay ( although the security risks should be obvious ) but Gem strongly discourages st...
seeds , multi_wallet = MultiWallet . generate ( trees , entropy = True ) result = { } for tree in trees : result [ tree ] = dict ( private_seed = seeds [ tree ] , public_seed = multi_wallet . public_wif ( tree ) , encrypted_seed = PassphraseBox . encrypt ( passphrase , seeds [ tree ] ) ) return result
def scalac_classpath_entries ( self ) : """Returns classpath entries for the scalac classpath ."""
return ScalaPlatform . global_instance ( ) . compiler_classpath_entries ( self . context . products , self . context . _scheduler )
def pair ( p , q ) : """Computes the bilinear pairing e ( p , q ) . @ p must be a G1Element and @ q must be a G2Element . @ returns a GtElement"""
# Check types assertType ( p , G1Element ) assertType ( q , G2Element ) result = GtElement ( ) librelic . pc_map_abi ( byref ( result ) , byref ( p ) , byref ( q ) ) return result
def on_disconnect_request ( self , py_db , request ) : ''': param DisconnectRequest request :'''
self . api . set_enable_thread_notifications ( py_db , False ) self . api . remove_all_breakpoints ( py_db , filename = '*' ) self . api . remove_all_exception_breakpoints ( py_db ) self . api . request_resume_thread ( thread_id = '*' ) response = pydevd_base_schema . build_response ( request ) return NetCommand ( CMD_...
def load ( fin , dtype = np . float32 , max_vocab = None ) : """Load word embedding file . Args : fin ( File ) : File object to read . File should be open for reading ascii . dtype ( numpy . dtype ) : Element data type to use for the array . max _ vocab ( int ) : Number of vocabulary to read . Returns : ...
vocab = { } arr = None i = 0 for line in fin : if max_vocab is not None and i >= max_vocab : break try : token , v = _parse_line ( line , dtype ) except ( ValueError , IndexError ) : raise ParseError ( b'Parsing error in line: ' + line ) if token in vocab : parse_warn ( b...
def _ParseLogLine ( self , parser_mediator , structure , key ) : """Parse a single log line and produce an event object . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . key ( str ) : identifier of the structure of tokens...
time_elements_tuple = self . _GetTimeElementsTuple ( structure ) try : date_time = dfdatetime_time_elements . TimeElements ( time_elements_tuple = time_elements_tuple ) except ValueError : parser_mediator . ProduceExtractionWarning ( 'invalid date time value: {0!s}' . format ( structure . date_time ) ) retu...
def methods ( self ) : """Returns all documented methods as ` pydoc . Function ` objects in the class , sorted alphabetically with ` _ _ init _ _ ` always coming first . Unfortunately , this also includes class methods ."""
p = lambda o : ( isinstance ( o , Function ) and o . method and self . module . _docfilter ( o ) ) return filter ( p , self . doc . values ( ) )
def get_tensor_device ( self , tensor_name ) : """The device of a tensor . Note that only tf tensors have device assignments . Args : tensor _ name : a string , name of a tensor in the graph . Returns : a string or None , representing the device name ."""
tensor = self . _name_to_tensor ( tensor_name ) if isinstance ( tensor , tf . Tensor ) : return tensor . device else : # mtf . Tensor return None
def mk_dropdown_tree ( cls , model , root_node , for_node = None ) : '''Override of ` ` treebeard ` ` method to enforce the same root .'''
options = [ ] # The difference is that we only generate the subtree for the current root . logger . debug ( "Using root node pk of %s" % root_node . pk ) cls . add_subtree ( for_node , root_node , options ) return options [ 1 : ]
def set ( self , uri , content ) : """Cache node content for uri . No return ."""
key , value = self . _prepare_node ( uri , content ) self . _set ( key , value )
def start ( self ) : """Start the ssh client and connect to the host . It will wait until the ssh service is available during 90 seconds . If it doesn ' t succed to connect then the function will raise an SSHException ."""
if self . via_ip : connect_to = self . via_ip self . description = '[%s@%s via %s]' % ( self . _user , self . _hostname , self . via_ip ) else : connect_to = self . _hostname self . description = '[%s@%s]' % ( self . _user , self . _hostname ) exception = None for i in range ( 60 ) : try : s...
def _none_rejecter ( validation_callable # type : Callable ) : # type : ( . . . ) - > Callable """Wraps the given validation callable to reject None values . When a None value is received by the wrapper , it is not passed to the validation _ callable and instead this function will raise a WrappingFailure . When a...
# option ( a ) use the ` decorate ( ) ` helper method to preserve name and signature of the inner object # = = > NO , we want to support also non - function callable objects # option ( b ) simply create a wrapper manually def reject_none ( x ) : if x is not None : return validation_callable ( x ) else :...
def delete_password ( self , service , username ) : """Delete the password for the username of the service ."""
service = escape_for_ini ( service ) username = escape_for_ini ( username ) config = configparser . RawConfigParser ( ) if os . path . exists ( self . file_path ) : config . read ( self . file_path ) try : if not config . remove_option ( service , username ) : raise PasswordDeleteError ( "Password not f...
def make_map ( ) : """Create , configure and return the routes Mapper"""
map = Mapper ( directory = config [ 'pylons.paths' ] [ 'controllers' ] , always_scan = config [ 'debug' ] ) # The ErrorController route ( handles 404/500 error pages ) ; it should # likely stay at the top , ensuring it can always be resolved map . connect ( 'error/:action/:id' , controller = 'error' ) # CUSTOM ROUTES H...
def add_training_sample ( self , text = u'' , lang = '' ) : """Initial step for adding new sample to training data . You need to call ` save _ training _ samples ( ) ` afterwards . : param text : Sample text to be added . : param lang : Language label for the input text ."""
self . trainer . add ( text = text , lang = lang )
def get_satellites_list ( self , sat_type ) : """Get a sorted satellite list : master then spare : param sat _ type : type of the required satellites ( arbiters , schedulers , . . . ) : type sat _ type : str : return : sorted satellites list : rtype : list [ alignak . objects . satellitelink . SatelliteLink...
satellites_list = [ ] if sat_type in [ 'arbiters' , 'schedulers' , 'reactionners' , 'brokers' , 'receivers' , 'pollers' ] : for satellite in getattr ( self , sat_type ) : satellites_list . append ( satellite ) satellites_list = master_then_spare ( satellites_list ) return satellites_list
def _declare_namespace ( self , package_name ) : '''Mock for # pkg _ resources . declare _ namespace ( ) which calls # pkgutil . extend _ path ( ) afterwards as the original implementation doesn ' t seem to properly find all available namespace paths .'''
self . state [ 'declare_namespace' ] ( package_name ) mod = sys . modules [ package_name ] mod . __path__ = pkgutil . extend_path ( mod . __path__ , package_name )
def _get_netmiko_args ( optional_args ) : '''Check for Netmiko arguments that were passed in as NAPALM optional arguments . Return a dictionary of these optional args that will be passed into the Netmiko ConnectHandler call . . . note : : This is a port of the NAPALM helper for backwards compatibility with ...
if HAS_NETMIKO_HELPERS : return napalm . base . netmiko_helpers . netmiko_args ( optional_args ) # Older version don ' t have the netmiko _ helpers module , the following code is # simply a port from the NAPALM code base , for backwards compatibility : # https : / / github . com / napalm - automation / napalm / blo...
def list_members ( self , list_id = None , slug = None , owner_screen_name = None , owner_id = None ) : """Returns the members of a list . List id or ( slug and ( owner _ screen _ name or owner _ id ) ) are required"""
assert list_id or ( slug and ( owner_screen_name or owner_id ) ) url = 'https://api.twitter.com/1.1/lists/members.json' params = { 'cursor' : - 1 } if list_id : params [ 'list_id' ] = list_id else : params [ 'slug' ] = slug if owner_screen_name : params [ 'owner_screen_name' ] = owner_screen_name ...
def add_spectroscopy ( self , label = '0_0' , ** props ) : """Adds spectroscopic measurement to particular star ( s ) ( corresponding to individual model node ) Default 0_0 should be primary star legal inputs are ' Teff ' , ' logg ' , ' feh ' , and in form ( val , err )"""
if label not in self . leaf_labels : raise ValueError ( 'No model node named {} (must be in {}). Maybe define models first?' . format ( label , self . leaf_labels ) ) for k , v in props . items ( ) : if k not in self . spec_props : raise ValueError ( 'Illegal property {} (only {} allowed).' . format ( k...
def matches_extension ( path , extension ) : """Returns True if path has the given extension , or if the last path component matches the extension . Supports Unix glob matching . > > > matches _ extension ( " . / www / profile . php " , " php " ) True > > > matches _ extension ( " . / scripts / menu . js ...
_ , ext = os . path . splitext ( path ) if ext == '' : # If there is no extension , grab the file name and # compare it to the given extension . return os . path . basename ( path ) == extension else : # If the is an extension , drop the leading period and # compare it to the extension . return fnmatch . fnmatc...