signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def list_pkgs ( versions_as_list = False , ** kwargs ) : '''List the currently installed packages as a dict : : { ' < package _ name > ' : ' < version > ' } CLI Example : . . code - block : : bash salt ' * ' pkg . list _ pkgs'''
# not yet implemented or not applicable if any ( [ salt . utils . data . is_true ( kwargs . get ( x ) ) for x in ( 'removed' , 'purge_desired' ) ] ) : return { } if 'pkg.list_pkgs' in __context__ : if versions_as_list : return __context__ [ 'pkg.list_pkgs' ] else : ret = copy . deepcopy ( __...
def generate_key ( s , pattern = "%s.txt" ) : """Generates the cache key for the given string using the content in pattern to format the output string"""
h = hashlib . sha1 ( ) # h . update ( s ) h . update ( s . encode ( 'utf-8' ) ) return pattern % h . hexdigest ( )
def predict_dims ( self , q , dims_x , dims_y , dims_out , sigma = None , k = None ) : """Provide a prediction of q in the output space @ param xq an array of float of length dim _ x @ param estimated _ sigma if False ( default ) , sigma _ sq = self . sigma _ sq , else it is estimated from the neighbor distance...
assert len ( q ) == len ( dims_x ) + len ( dims_y ) sigma_sq = self . sigma_sq if sigma is None else sigma * sigma k = k or self . k dists , index = self . dataset . nn_dims ( q [ : len ( dims_x ) ] , q [ len ( dims_x ) : ] , dims_x , dims_y , k = k ) w = self . _weights ( dists , index , sigma_sq ) Xq = np . array ( n...
def verify_checksum ( file_id , pessimistic = False , chunk_size = None , throws = True , checksum_kwargs = None ) : """Verify checksum of a file instance . : param file _ id : The file ID ."""
f = FileInstance . query . get ( uuid . UUID ( file_id ) ) # Anything might happen during the task , so being pessimistic and marking # the file as unchecked is a reasonable precaution if pessimistic : f . clear_last_check ( ) db . session . commit ( ) f . verify_checksum ( progress_callback = progress_updater ...
def release ( ) : "check release before upload to PyPI"
sh ( "paver bdist_wheel" ) wheels = path ( "dist" ) . files ( "*.whl" ) if not wheels : error ( "\n*** ERROR: No release wheel was built!" ) sys . exit ( 1 ) if any ( ".dev" in i for i in wheels ) : error ( "\n*** ERROR: You're still using a 'dev' version!" ) sys . exit ( 1 ) # Check that source distrib...
def _start_stop ( item ) : """Find the start and stop indices of a _ _ getitem _ _ item . This is used only by ConcatenatedArrays . Only two cases are supported currently : * Single integer . * Contiguous slice in the first dimension only ."""
if isinstance ( item , tuple ) : item = item [ 0 ] if isinstance ( item , slice ) : # Slice . if item . step not in ( None , 1 ) : raise NotImplementedError ( ) return item . start , item . stop elif isinstance ( item , ( list , np . ndarray ) ) : # List or array of indices . return np . min ( i...
def cleanup_branch ( self , branch ) : """Remove the temporary backport branch . Switch to the default branch before that ."""
set_state ( WORKFLOW_STATES . REMOVING_BACKPORT_BRANCH ) self . checkout_default_branch ( ) try : self . delete_branch ( branch ) except subprocess . CalledProcessError : click . echo ( f"branch {branch} NOT deleted." ) set_state ( WORKFLOW_STATES . REMOVING_BACKPORT_BRANCH_FAILED ) else : click . echo ...
def drop ( self ) : """Drop the table and all tables that reference it , recursively . User is prompted for confirmation if config [ ' safemode ' ] is set to True ."""
if self . restriction : raise DataJointError ( 'A relation with an applied restriction condition cannot be dropped.' ' Call drop() on the unrestricted Table.' ) self . connection . dependencies . load ( ) do_drop = True tables = [ table for table in self . connection . dependencies . descendants ( self . full_table...
def true_positives ( links_true , links_pred ) : """Count the number of True Positives . Returns the number of correctly predicted links , also called the number of True Positives ( TP ) . Parameters links _ true : pandas . MultiIndex , pandas . DataFrame , pandas . Series The true ( or actual ) links . ...
links_true = _get_multiindex ( links_true ) links_pred = _get_multiindex ( links_pred ) return len ( links_true & links_pred )
def get_lin_constraint ( self , name ) : """Returns the constraint set with the given name ."""
for c in self . lin_constraints : if c . name == name : return c else : raise ValueError
def add_category ( self , name ) : """Adds a bayes category that we can later train : param name : name of the category : type name : str : return : the requested category : rtype : BayesCategory"""
category = BayesCategory ( name ) self . categories [ name ] = category return category
def with_argument_list ( * args : List [ Callable ] , preserve_quotes : bool = False ) -> Callable [ [ List ] , Optional [ bool ] ] : """A decorator to alter the arguments passed to a do _ * cmd2 method . Default passes a string of whatever the user typed . With this decorator , the decorated method will receive ...
import functools def arg_decorator ( func : Callable ) : @ functools . wraps ( func ) def cmd_wrapper ( cmd2_instance , statement : Union [ Statement , str ] ) : _ , parsed_arglist = cmd2_instance . statement_parser . get_command_arg_list ( command_name , statement , preserve_quotes ) return fun...
def usergroups_users_list ( self , * , usergroup : str , ** kwargs ) -> SlackResponse : """List all users in a User Group Args : usergroup ( str ) : The encoded ID of the User Group to update . e . g . ' S0604QSJC '"""
self . _validate_xoxp_token ( ) kwargs . update ( { "usergroup" : usergroup } ) return self . api_call ( "usergroups.users.list" , http_verb = "GET" , params = kwargs )
def outer_product ( vec ) : r"""Returns the outer product of a vector : math : ` v ` with itself , : math : ` v v ^ \ T ` ."""
return ( np . dot ( vec [ : , np . newaxis ] , vec [ np . newaxis , : ] ) if len ( vec . shape ) == 1 else np . dot ( vec , vec . T ) )
def completeMeasurement ( self , measurementId , deviceId ) : """Completes the measurement session . : param deviceId : the device id . : param measurementId : the measurement id . : return : true if it was completed ."""
am , handler = self . getDataHandler ( measurementId , deviceId ) if handler is not None : handler . stop ( measurementId ) am . updateDeviceStatus ( deviceId , RecordStatus . COMPLETE ) return True else : return False
def gen_key ( minion_id , dns_name = None , password = None , key_len = 2048 ) : '''Generate and return a private _ key . If a ` ` dns _ name ` ` is passed in , the private _ key will be cached under that name . CLI Example : . . code - block : : bash salt - run digicert . gen _ key < minion _ id > [ dns _ ...
keygen_type = 'RSA' if keygen_type == "RSA" : if HAS_M2 : gen = RSA . gen_key ( key_len , 65537 ) private_key = gen . as_pem ( cipher = 'des_ede3_cbc' , callback = lambda x : six . b ( password ) ) else : gen = RSA . generate ( bits = key_len ) private_key = gen . exportKey ( 'PE...
def arg_match ( m_arg , arg , comparator = eq , default = False ) : """: param m _ arg : value to match against or callable : param arg : arg to match : param comparator : function that returns True if m _ arg and arg match : param default : will be returned if m _ arg is None if m _ arg is a callable it wi...
if m_arg is None : return default if isinstance ( m_arg , dict ) : for name , value in m_arg . items ( ) : name , _comparator = arg_comparitor ( name ) subarg = getattr ( arg , name , InvalidArg ) if subarg is InvalidArg : return subarg matched = arg_match ( subarg , ...
def append_new_text ( destination , text , join_str = None ) : """This method provides the functionality of adding text appropriately underneath the destination node . This will be either to the destination ' s text attribute or to the tail attribute of the last child ."""
if join_str is None : join_str = ' ' if len ( destination ) > 0 : # Destination has children last = destination [ - 1 ] if last . tail is None : # Last child has no tail last . tail = text else : # Last child has a tail last . tail = join_str . join ( [ last . tail , text ] ) else : # De...
def create_dn_in_filter ( filter_class , filter_value , helper ) : """Creates filter object for given class name , and DN values ."""
in_filter = FilterFilter ( ) in_filter . AddChild ( create_dn_wcard_filter ( filter_class , filter_value ) ) return in_filter
def std ( self , values , axis = 0 , weights = None , dtype = None ) : """standard deviation over each group Parameters values : array _ like , [ keys , . . . ] values to take standard deviation of per group axis : int , optional alternative reduction axis for values Returns unique : ndarray , [ group...
unique , var = self . var ( values , axis , weights , dtype ) return unique , np . sqrt ( var )
def build_eval_path ( self , epoch , iteration ) : """Appends index of the current epoch and index of the current iteration to the name of the file with results . : param epoch : index of the current epoch : param iteration : index of the current iteration"""
if iteration is not None : eval_fname = f'eval_epoch_{epoch}_iter_{iteration}' else : eval_fname = f'eval_epoch_{epoch}' eval_path = os . path . join ( self . save_path , eval_fname ) return eval_path
def unzoom ( self , event = None , panel = 'top' ) : """zoom out 1 level , or to full data range"""
panel = self . get_panel ( panel ) panel . conf . unzoom ( event = event ) self . panel . set_viewlimits ( )
def _copy_required ( lib_path , copy_filt_func , copied_libs ) : """Copy libraries required for files in ` lib _ path ` to ` lib _ path ` Augment ` copied _ libs ` dictionary with any newly copied libraries , modifying ` copied _ libs ` in - place - see Notes . This is one pass of ` ` copy _ recurse ` ` Par...
# Paths will be prepended with ` lib _ path ` lib_dict = tree_libs ( lib_path ) # Map library paths after copy ( ' copied ' ) to path before copy ( ' orig ' ) rp_lp = realpath ( lib_path ) copied2orig = dict ( ( pjoin ( rp_lp , basename ( c ) ) , c ) for c in copied_libs ) for required , requirings in lib_dict . items ...
def use ( broker , debug = True , ** kwargs ) : """用于生成特定的券商对象 : param broker : 券商名支持 [ ' yh _ client ' , ' 银河客户端 ' ] [ ' ht _ client ' , ' 华泰客户端 ' ] : param debug : 控制 debug 日志的显示 , 默认为 True : param initial _ assets : [ 雪球参数 ] 控制雪球初始资金 , 默认为一百万 : return the class of trader Usage : : > > > import easytr...
if not debug : log . setLevel ( logging . INFO ) if broker . lower ( ) in [ "xq" , "雪球" ] : return XueQiuTrader ( ** kwargs ) if broker . lower ( ) in [ "yh_client" , "银河客户端" ] : from . yh_clienttrader import YHClientTrader return YHClientTrader ( ) if broker . lower ( ) in [ "ht_client" , "华泰客户端" ] : ...
def document_endpoint ( endpoint ) : """Extract the full documentation dictionary from the endpoint ."""
descr = clean_description ( py_doc_trim ( endpoint . __doc__ ) ) docs = { 'name' : endpoint . _route_name , 'http_method' : endpoint . _http_method , 'uri' : endpoint . _uri , 'description' : descr , 'arguments' : extract_endpoint_arguments ( endpoint ) , 'returns' : format_endpoint_returns_doc ( endpoint ) , } if hasa...
def label_absent ( name , node = None , apiserver_url = None ) : '''. . versionadded : : 2016.3.0 Delete label to the current node CLI Example : . . code - block : : bash salt ' * ' k8s . label _ absent hw / disktype salt ' * ' k8s . label _ absent hw / disktype kube - node . cluster . local http : / / ku...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } # Get salt minion ID node = _guess_node_id ( node ) # Try to get kubernetes master apiserver_url = _guess_apiserver ( apiserver_url ) if apiserver_url is None : return False # Get all labels old_labels = _get_labels ( node , apiserver_url ...
def get_mesh_hcurves ( oqparam ) : """Read CSV data in the format ` lon lat , v1 - vN , w1 - wN , . . . ` . : param oqparam : an : class : ` openquake . commonlib . oqvalidation . OqParam ` instance : returns : the mesh of points and the data as a dictionary imt - > array of curves for each site"""
imtls = oqparam . imtls lon_lats = set ( ) data = AccumDict ( ) # imt - > list of arrays ncols = len ( imtls ) + 1 # lon _ lat + curve _ per _ imt . . . csvfile = oqparam . inputs [ 'hazard_curves' ] for line , row in enumerate ( csv . reader ( csvfile ) , 1 ) : try : if len ( row ) != ncols : r...
def delete_lb_policy ( self , lb_name , policy_name ) : """Deletes a policy from the LoadBalancer . The specified policy must not be enabled for any listeners ."""
params = { 'LoadBalancerName' : lb_name , 'PolicyName' : policy_name , } return self . get_status ( 'DeleteLoadBalancerPolicy' , params )
def read ( self , params , args , data ) : """Modifies the parameters and adds metadata for read results ."""
result_count = None result_links = None if params is None : params = [ ] if args : args = args . copy ( ) else : args = { } ctx = self . _create_context ( params , args , data ) row_id = ctx . get_row_id ( ) if not row_id : self . _transform_list_args ( args ) if 'page' in args or 'limit' in args : ...
def runRelatedness ( inputPrefix , outPrefix , options ) : """Run the relatedness step of the data clean up . : param inputPrefix : the prefix of the input file . : param outPrefix : the prefix of the output file . : param options : the options : type inputPrefix : str : type outPrefix : str : type opti...
# The options new_options = [ "--bfile" , inputPrefix , "--genome-only" , "--min-nb-snp" , str ( options . min_nb_snp ) , "--maf" , options . maf , "--out" , "{}.ibs" . format ( outPrefix ) ] new_options += [ "--indep-pairwise" ] + options . indep_pairwise if options . sge : new_options . append ( "--sge" ) new...
def semester_feature ( catalog , soup ) : """The year and semester information that this xml file hold courses for ."""
raw = _text ( soup . findAll ( 'h3' ) ) . split ( '\n' ) [ 1 ] match = RE_SEMESTER_RANGE . match ( raw ) catalog . year = int ( match . group ( 'year' ) ) # month _ mapping = { ' Spring ' : 1 , ' Summer ' : 5 , ' Fall ' : 9} month_mapping = { 'january' : 1 , 'may' : 5 , 'august' : 9 } catalog . month = month_mapping [ ...
def list_pkgs ( versions_as_list = False , ** kwargs ) : '''List the packages currently installed as a dict : . . code - block : : python { ' < package _ name > ' : ' < version > ' } CLI Example : . . code - block : : bash salt ' * ' pkg . list _ pkgs'''
versions_as_list = salt . utils . data . is_true ( versions_as_list ) # not yet implemented or not applicable if any ( [ salt . utils . data . is_true ( kwargs . get ( x ) ) for x in ( 'removed' , 'purge_desired' ) ] ) : return { } if 'pkg.list_pkgs' in __context__ : if versions_as_list : return __conte...
def nodes_with_recipe ( recipename ) : """Configures a list of nodes that have the given recipe in their run list"""
nodes = [ n [ 'name' ] for n in lib . get_nodes_with_recipe ( recipename , env . chef_environment ) ] if not len ( nodes ) : print ( "No nodes found with recipe '{0}'" . format ( recipename ) ) sys . exit ( 0 ) return node ( * nodes )
def _copy_default ( cls , default ) : '''Return a copy of the default , or a new value if the default is specified by a function .'''
if not isinstance ( default , types . FunctionType ) : return copy ( default ) else : return default ( )
def scaled ( values , output_min , output_max , input_min = 0 , input_max = 1 ) : """Returns * values * scaled from * output _ min * to * output _ max * , assuming that all items in * values * lie between * input _ min * and * input _ max * ( which default to 0 and 1 respectively ) . For example , to control th...
values = _normalize ( values ) if input_min >= input_max : raise ValueError ( 'input_min must be smaller than input_max' ) input_size = input_max - input_min output_size = output_max - output_min for v in values : yield ( ( ( v - input_min ) / input_size ) * output_size ) + output_min
def make_stmt ( stmt_cls , tf_agent , target_agent , pmid ) : """Return a Statement based on its type , agents , and PMID ."""
ev = Evidence ( source_api = 'trrust' , pmid = pmid ) return stmt_cls ( deepcopy ( tf_agent ) , deepcopy ( target_agent ) , evidence = [ ev ] )
def fallback ( cache ) : """Caches content retrieved by the client , thus allowing the cached content to be used later if the live content cannot be retrieved ."""
log_filter = ThrottlingFilter ( cache = cache ) logger . filters = [ ] logger . addFilter ( log_filter ) def get_cache_response ( cache_key ) : content = cache . get ( cache_key ) if content : response = CacheResponse ( ) response . __setstate__ ( { 'status_code' : 200 , '_content' : content , }...
def replace_species ( self , species_mapping ) : """Swap species . Args : species _ mapping ( dict ) : dict of species to swap . Species can be elements too . E . g . , { Element ( " Li " ) : Element ( " Na " ) } performs a Li for Na substitution . The second species can be a sp _ and _ occu dict . For ex...
species_mapping = { get_el_sp ( k ) : v for k , v in species_mapping . items ( ) } sp_to_replace = set ( species_mapping . keys ( ) ) sp_in_structure = set ( self . composition . keys ( ) ) if not sp_in_structure . issuperset ( sp_to_replace ) : warnings . warn ( "Some species to be substituted are not present in "...
def p_DefaultValue_string ( p ) : """DefaultValue : STRING"""
p [ 0 ] = model . Value ( type = model . Value . STRING , value = p [ 1 ] )
def check_key_cert_match ( keyfile , certfile ) : """check if the ssl key matches the certificate : param keyfile : file path to the ssl key : param certfile : file path to the ssl certificate : returns : true or false"""
key_modulus = subprocess . check_output ( 'openssl rsa -noout -modulus -in {}' . format ( keyfile ) , shell = True ) cert_modulus = subprocess . check_output ( 'openssl x509 -noout -modulus -in {}' . format ( certfile ) , shell = True ) return key_modulus == cert_modulus
def _get_pages_with_headings ( self , pages : Dict ) -> Dict : '''Update ` ` pages ` ` section of ` ` mkdocs . yml ` ` file with the content of top - level headings of source Markdown files . param pages : Dictionary with the data of ` ` pages ` ` section returns : Updated dictionary'''
def _recursive_process_pages ( pages_subset , parent_is_dict ) : if isinstance ( pages_subset , dict ) : new_pages_subset = { } for key , value in pages_subset . items ( ) : if not key : key = self . _mkdocs_config . get ( 'default_subsection_title' , '…' ) ne...
def plot ( self , x , y , title , ylabel , scale = 'semilogy' , idx_lim = ( 1 , - 1 ) ) : """Plot the data . Parameters x : ndarray vector with frequencies y : ndarray vector with amplitudes title : str title of the plot , to appear above it ylabel : str label for the y - axis scale : str ' lo...
x = x [ slice ( * idx_lim ) ] y = y [ slice ( * idx_lim ) ] ax = self . figure . add_subplot ( 111 ) ax . set_title ( title ) ax . set_xlabel ( 'Frequency (Hz)' ) ax . set_ylabel ( ylabel ) if 'semilogy' == scale : ax . semilogy ( x , y , 'r-' ) elif 'loglog' == scale : ax . loglog ( x , y , 'r-' ) elif 'linear...
def auth_user_id ( self , value ) : """The auth _ user _ id property . Args : value ( string ) . the property value ."""
if value == self . _defaults [ 'ai.user.authUserId' ] and 'ai.user.authUserId' in self . _values : del self . _values [ 'ai.user.authUserId' ] else : self . _values [ 'ai.user.authUserId' ] = value
def vendor_runtime ( chroot , dest_basedir , label , root_module_names ) : """Includes portions of vendored distributions in a chroot . The portion to include is selected by root module name . If the module is a file , just it is included . If the module represents a package , the package and all its sub - pack...
vendor_module_names = { root_module_name : False for root_module_name in root_module_names } for spec in iter_vendor_specs ( ) : for root , dirs , files in os . walk ( spec . target_dir ) : if root == spec . target_dir : dirs [ : ] = [ pkg_name for pkg_name in dirs if pkg_name in vendor_module_n...
def setColor ( self , name , color , colorGroup = None ) : """Sets the color for the inputed name in the given color group . If no specific color group is found then the color will be set for all color groups . : param name | < str > color | < QColor > colorGroup | < str > | | None"""
self . _colors . setdefault ( str ( name ) , { } ) cmap = self . _colors . get ( str ( name ) ) if ( not colorGroup ) : for colorGroup in self . _colorGroups : cmap [ colorGroup ] = color else : cmap [ colorGroup ] = color
def wheelEvent ( self , ev , axis = None ) : """Reacts to mouse wheel movement , custom behaviour switches zoom axis when ctrl is pressed , and sets the locus of zoom , if zeroWheel is set ."""
state = None # ctrl reverses mouse operation axis if ev . modifiers ( ) == QtCore . Qt . ControlModifier : state = self . mouseEnabled ( ) self . setMouseEnabled ( not state [ 0 ] , not state [ 1 ] ) if self . _zeroWheel : ev . pos = lambda : self . mapViewToScene ( QtCore . QPoint ( 0 , 0 ) ) super ( Spike...
def update ( self , job ) : """Update last _ run , next _ run , and last _ run _ result for an existing job . : param dict job : The job dictionary : returns : True"""
self . cur . execute ( '''UPDATE jobs SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''' , ( job [ "last-run" ] , job [ "next-run" ] , job [ "last-run-result" ] , job [ "id" ] ) )
def cleanup ( ) : """Must be called before exit"""
temp_dirs = [ ] for key in ( 'headless' , 'headed' ) : if FIREFOX_INSTANCE [ key ] is not None : if FIREFOX_INSTANCE [ key ] . profile : temp_dirs . append ( FIREFOX_INSTANCE [ key ] . profile . profile_dir ) try : FIREFOX_INSTANCE [ key ] . quit ( ) FIREFOX_INSTA...
def execute ( self , * args , ** kwargs ) : """Called when run through ` call _ command ` . ` args ` are passed through , while ` kwargs ` is the _ _ dict _ _ of the return value of ` self . create _ parser ( ' ' , name ) ` updated with the kwargs passed to ` call _ command ` ."""
# Remove internal Django command handling machinery kwargs . pop ( 'skip_checks' , None ) parent_ctx = click . get_current_context ( silent = True ) with self . make_context ( '' , list ( args ) , parent = parent_ctx ) as ctx : # Rename kwargs to to the appropriate destination argument name opt_mapping = dict ( sel...
def get_lock_config ( self , device_label ) : """Get lock configuration Args : device _ label ( str ) : device label of lock"""
response = None try : response = requests . get ( urls . lockconfig ( self . _giid , device_label ) , headers = { 'Accept' : 'application/json, text/javascript, */*; q=0.01' , 'Cookie' : 'vid={}' . format ( self . _vid ) } ) except requests . exceptions . RequestException as ex : raise RequestError ( ex ) _vali...
def limit_dragpos ( self ) : '''limit dragpos to sane values'''
if self . dragpos . x < 0 : self . dragpos . x = 0 if self . dragpos . y < 0 : self . dragpos . y = 0 if self . img is None : return if self . dragpos . x >= self . img . GetWidth ( ) : self . dragpos . x = self . img . GetWidth ( ) - 1 if self . dragpos . y >= self . img . GetHeight ( ) : self . dr...
def validate ( data , schema , defined_keys = False ) : """Main entry point for the validation engine . : param data : The incoming data , as a dictionary object . : param schema : The schema from which data will be validated against"""
if isinstance ( data , dict ) : validator = Validator ( data , schema , defined_keys = defined_keys ) validator . validate ( ) else : raise TypeError ( 'expected data to be of type dict, but got: %s' % type ( data ) )
def get_definition_location ( self ) : """Returns a ( module , lineno ) tuple"""
if self . lineno is None and self . assignments : self . lineno = self . assignments [ 0 ] . get_lineno ( ) return ( self . module , self . lineno )
def get_node ( self , * node_ids , node_attr = NONE ) : """Returns a sub node of a dispatcher . : param node _ ids : A sequence of node ids or a single node id . The id order identifies a dispatcher sub - level . : type node _ ids : str : param node _ attr : Output node attr . If the searched node doe...
kw = { } from . sol import Solution if node_attr is NONE : node_attr = 'output' if isinstance ( self , Solution ) else 'auto' if isinstance ( self , Solution ) : kw [ 'solution' ] = self from . alg import get_sub_node dsp = getattr ( self , 'dsp' , self ) # Returns the node . return get_sub_node ( dsp , node_id...
def deserialize ( cls , file_path , ** kwargs ) : """Create a new TokenEmbedding from a serialized one . TokenEmbedding is serialized by converting the list of tokens , the array of word embeddings and other metadata to numpy arrays , saving all in a single ( optionally compressed ) Zipfile . See https : / ...
# idx _ to _ token is of dtype ' O ' so we need to allow pickle npz_dict = np . load ( file_path , allow_pickle = True ) unknown_token = npz_dict [ 'unknown_token' ] if not unknown_token : unknown_token = None else : if isinstance ( unknown_token , np . ndarray ) : if unknown_token . dtype . kind == 'S'...
def create ( self ) : """create the server ."""
logger . info ( "creating server" ) self . library . Srv_Create . restype = snap7 . snap7types . S7Object self . pointer = snap7 . snap7types . S7Object ( self . library . Srv_Create ( ) )
def download ( self , to_path = None , name = None , chunk_size = 'auto' , convert_to_pdf = False ) : """Downloads this file to the local drive . Can download the file in chunks with multiple requests to the server . : param to _ path : a path to store the downloaded file : type to _ path : str or Path : pa...
# TODO : Add download with more than one request ( chunk _ requests ) with # header ' Range ' . For example : ' Range ' : ' bytes = 0-1024' if to_path is None : to_path = Path ( ) else : if not isinstance ( to_path , Path ) : to_path = Path ( to_path ) if not to_path . exists ( ) : raise FileNotFoun...
def check ( self , url_data ) : """Run all SSL certificate checks that have not yet been done . OpenSSL already checked the SSL notBefore and notAfter dates ."""
host = url_data . urlparts [ 1 ] if host in self . checked_hosts : return self . checked_hosts . add ( host ) cert = url_data . ssl_cert config = url_data . aggregate . config if cert and 'notAfter' in cert : self . check_ssl_valid_date ( url_data , cert ) elif config [ 'sslverify' ] : msg = _ ( 'certificat...
def edit_filter ( self ) : """Edit name filters"""
filters , valid = QInputDialog . getText ( self , _ ( 'Edit filename filters' ) , _ ( 'Name filters:' ) , QLineEdit . Normal , ", " . join ( self . name_filters ) ) if valid : filters = [ f . strip ( ) for f in to_text_string ( filters ) . split ( ',' ) ] self . parent_widget . sig_option_changed . emit ( 'name...
def _add_neighbors ( self , settings ) : """Add BGP neighbors from the given settings . All valid neighbors are loaded . Miss - configured neighbors are ignored and errors are logged ."""
for neighbor_settings in settings : LOG . debug ( 'Adding neighbor settings: %s' , neighbor_settings ) try : self . speaker . neighbor_add ( ** neighbor_settings ) except RuntimeConfigError as e : LOG . exception ( e )
def transform ( self , blocks , y = None ) : """Transform an ordered sequence of blocks into a 2D features matrix with shape ( num blocks , num features ) and standardized feature values . Args : blocks ( List [ Block ] ) : as output by : class : ` Blockifier . blockify ` y ( None ) : This isn ' t used , it...
return self . scaler . transform ( self . feature . transform ( blocks ) )
def vspec_magic ( data ) : """Takes average vector of replicate measurements"""
vdata , Dirdata , step_meth = [ ] , [ ] , "" if len ( data ) == 0 : return vdata treat_init = [ "treatment_temp" , "treatment_temp_decay_rate" , "treatment_temp_dc_on" , "treatment_temp_dc_off" , "treatment_ac_field" , "treatment_ac_field_decay_rate" , "treatment_ac_field_dc_on" , "treatment_ac_field_dc_off" , "tre...
def register ( self , plugin , columnType = None , columnName = None ) : """Registers a plugin to handle particular column types and column names based on user selection . : param plugin | < XOrbQueryPlugin > columnType | < orb . ColumnType > | | None columnName | < str > | | None"""
self . _plugins [ ( columnType , columnName ) ] = plugin
def returnValue ( self , key , last = False ) : '''Return the key ' s value for the first entry in the current list . If ' last = True ' , then the last entry is referenced . " Returns None is the list is empty or the key is missing . Example of use : > > > test = [ . . . { " name " : " Jim " , " age " : ...
row = self . returnOneEntry ( last = last ) if not row : return None dict_row = internal . convert_to_dict ( row ) return dict_row . get ( key , None )
def create_turnover_tear_sheet ( factor_data , turnover_periods = None ) : """Creates a tear sheet for analyzing the turnover properties of a factor . Parameters factor _ data : pd . DataFrame - MultiIndex A MultiIndex DataFrame indexed by date ( level 0 ) and asset ( level 1 ) , containing the values for a...
if turnover_periods is None : turnover_periods = utils . get_forward_returns_columns ( factor_data . columns ) quantile_factor = factor_data [ 'factor_quantile' ] quantile_turnover = { p : pd . concat ( [ perf . quantile_turnover ( quantile_factor , q , p ) for q in range ( 1 , int ( quantile_factor . max ( ) ) + 1...
def new_annot ( self ) : """Action : create a new file for annotations ."""
if self . parent . info . filename is None : msg = 'No dataset loaded' self . parent . statusBar ( ) . showMessage ( msg ) lg . debug ( msg ) return filename = splitext ( self . parent . info . filename ) [ 0 ] + '_scores.xml' filename , _ = QFileDialog . getSaveFileName ( self , 'Create annotation file...
def sample ( self ) : '''Returns the stream ' s rows used as sample . These sample rows are used internally to infer characteristics of the source file ( e . g . encoding , headers , . . . ) .'''
sample = [ ] iterator = iter ( self . __sample_extended_rows ) iterator = self . __apply_processors ( iterator ) for row_number , headers , row in iterator : sample . append ( row ) return sample
def project ( self , axis ) : """Project this vector onto the given axis ."""
projection = self . get_projection ( axis ) self . assign ( projection )
def connect_ec2 ( aws_access_key_id = None , aws_secret_access_key = None , ** kwargs ) : """: type aws _ access _ key _ id : string : param aws _ access _ key _ id : Your AWS Access Key ID : type aws _ secret _ access _ key : string : param aws _ secret _ access _ key : Your AWS Secret Access Key : rtype :...
from boto . ec2 . connection import EC2Connection return EC2Connection ( aws_access_key_id , aws_secret_access_key , ** kwargs )
def success ( self , value ) : """The success property . Args : value ( bool ) . the property value ."""
if value == self . _defaults [ 'success' ] and 'success' in self . _values : del self . _values [ 'success' ] else : self . _values [ 'success' ] = value
async def can_run ( self , ctx ) : """| coro | Checks if the command can be executed by checking all the predicates inside the : attr : ` . checks ` attribute . Parameters ctx : : class : ` . Context ` The ctx of the command currently being invoked . Raises : class : ` CommandError ` Any command err...
original = ctx . command ctx . command = self try : if not await ctx . bot . can_run ( ctx ) : raise CheckFailure ( 'The global check functions for command {0.qualified_name} failed.' . format ( self ) ) cog = self . cog if cog is not None : local_check = Cog . _get_overridden_method ( cog ....
def xlsx_part ( self , xlsx_part ) : """Set the related | EmbeddedXlsxPart | to * xlsx _ part * . Assume one does not already exist ."""
rId = self . _chart_part . relate_to ( xlsx_part , RT . PACKAGE ) externalData = self . _chartSpace . get_or_add_externalData ( ) externalData . rId = rId
def remove_component ( self , entity : int , component_type : Any ) -> int : """Remove a Component instance from an Entity , by type . A Component instance can be removed by providing it ' s type . For example : world . delete _ component ( enemy _ a , Velocity ) will remove the Velocity instance from the Ent...
self . _components [ component_type ] . discard ( entity ) if not self . _components [ component_type ] : del self . _components [ component_type ] del self . _entities [ entity ] [ component_type ] if not self . _entities [ entity ] : del self . _entities [ entity ] self . clear_cache ( ) return entity
def get_segments ( self , addr , size ) : """Get a segmented memory region based on AbstractLocation information available from VSA . Here are some assumptions to make this method fast : - The entire memory region [ addr , addr + size ] is located within the same MemoryRegion - The address ' addr ' has only o...
address_wrappers = self . normalize_address ( addr , is_write = False ) # assert len ( address _ wrappers ) > 0 aw = address_wrappers [ 0 ] region_id = aw . region if region_id in self . regions : region = self . regions [ region_id ] alocs = region . get_abstract_locations ( aw . address , size ) # Collect...
def setColumns ( self , columns ) : """Sets the column count and list of columns to the inputed column list . : param columns | [ < str > , . . ]"""
self . setColumnCount ( len ( columns ) ) self . setHorizontalHeaderLabels ( columns )
def lookup ( values , name = None ) : """Creates the grammar for a Lookup ( L ) field , accepting only values from a list . Like in the Alphanumeric field , the result will be stripped of all heading and trailing whitespaces . : param values : values allowed : param name : name for the field : return : ...
if name is None : name = 'Lookup Field' if values is None : raise ValueError ( 'The values can no be None' ) # TODO : This should not be needed , it is just a patch . Fix this . try : v = values . asList ( ) values = v except AttributeError : values = values # Only the specified values are allowed l...
def copy ( self ) : '''Copy the text in the Entry ( ) and place it on the clipboard .'''
try : pygame . scrap . put ( SCRAP_TEXT , self . get ( ) ) return True except : # pygame . scrap is experimental , allow for changes return False
def import_data ( self , data ) : """Set the fields established in data to the instance"""
if self . get_read_only ( ) and self . is_locked ( ) : return if isinstance ( data , BaseModel ) : data = data . export_data ( ) if not isinstance ( data , ( dict , Mapping ) ) : raise TypeError ( 'Impossible to import data' ) self . _import_data ( data )
def tab ( self ) : """Advances the cursor position to the next ( soft ) tabstop ."""
soft_tabs = self . tabstop - ( ( self . _cx // self . _cw ) % self . tabstop ) for _ in range ( soft_tabs ) : self . putch ( " " )
def redivmod ( initial_value , factors ) : """Chop up C { initial _ value } according to the list of C { factors } and return a formatted string ."""
result = [ ] value = initial_value for divisor , label in factors : if not divisor : remainder = value if not remainder : break else : value , remainder = divmod ( value , divisor ) if not value and not remainder : break if remainder == 1 : # deplurali...
def _runshell ( cmd , exception ) : """Run a shell command . if fails , raise a proper exception ."""
p = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) if p . wait ( ) != 0 : raise BridgeException ( exception ) return p
def get_columns ( context , query ) : """Get list of cartoframes . columns . Column"""
table_info = context . sql_client . send ( query ) if 'fields' in table_info : return Column . from_sql_api_fields ( table_info [ 'fields' ] ) return None
def extend_by ( self , extension ) : """The path to the file changed to use the given extension > > > FilePath ( ' / path / to / fred ' ) . extend _ by ( ' . txt ' ) < FilePath ' / path / to / fred . txt ' > > > > FilePath ( ' / path / to / fred . txt ' ) . extend _ by ( ' . . tmp ' ) < FilePath ' / path / ...
copy = self [ : ] filename , _ = os . path . splitext ( copy ) return self . __class__ ( '%s.%s' % ( filename , extension . lstrip ( '.' ) ) )
def get_new_author ( self , api_author ) : """Instantiate a new Author from api data . : param api _ author : the api data for the Author : return : the new Author"""
return Author ( site_id = self . site_id , wp_id = api_author [ "ID" ] , ** self . api_object_data ( "author" , api_author ) )
def load_hash_configuration ( self , hash_name ) : """Loads and returns hash configuration"""
conf = self . mongo_object . find_one ( { 'hash_conf_name' : hash_name + '_conf' } ) return pickle . loads ( conf [ 'hash_configuration' ] ) if conf is not None else None
def PartitioningQueryIterable ( cls , client , query , options , database_link , partition_key ) : """Represents a client side partitioning query iterable . This constructor instantiates a QueryIterable for client side partitioning queries , and sets _ MultiCollectionQueryExecutionContext as the internal exec...
# This will call the base constructor ( _ _ init _ _ method above ) self = cls ( client , query , options , None , None ) self . _database_link = database_link self . _partition_key = partition_key return self
def get_font_matrix ( self ) : """Copies the current font matrix . See : meth : ` set _ font _ matrix ` . : returns : A new : class : ` Matrix ` ."""
matrix = Matrix ( ) cairo . cairo_get_font_matrix ( self . _pointer , matrix . _pointer ) self . _check_status ( ) return matrix
def isScheduleValid ( self , schedule , node_srvs , force ) -> ( bool , str ) : """Validates schedule of planned node upgrades : param schedule : dictionary of node ids and upgrade times : param node _ srvs : dictionary of node ids and services : return : a 2 - tuple of whether schedule valid or not and the r...
# flag " force = True " ignore basic checks ! only datetime format is # checked times = [ ] non_demoted_nodes = set ( [ k for k , v in node_srvs . items ( ) if v ] ) if not force and set ( schedule . keys ( ) ) != non_demoted_nodes : return False , 'Schedule should contain id of all nodes' now = datetime . utcnow (...
def setup ( self ) : """Initialize the driver by setting up GPIO interrupts and periodic statistics processing ."""
# Initialize the statistics variables . self . radiation_count = 0 self . noise_count = 0 self . count = 0 # Initialize count _ history [ ] . self . count_history = [ 0 ] * HISTORY_LENGTH self . history_index = 0 # Init measurement time . self . previous_time = millis ( ) self . previous_history_time = millis ( ) self ...
def mni2tal ( xin ) : """mni2tal for converting from ch2 / mni space to tal - very approximate . This is a standard approach but it ' s not very accurate . ANTsR function : ` mni2tal ` Arguments xin : tuple point in mni152 space . Returns tuple Example > > > import ants > > > ants . mni2tal ( ( ...
if ( not isinstance ( xin , ( tuple , list ) ) ) or ( len ( xin ) != 3 ) : raise ValueError ( 'xin must be tuple/list with 3 coordinates' ) x = list ( xin ) # The input image is in RAS coordinates but we use ITK which returns LPS # coordinates . So we need to flip the coordinates such that L = > R and P = > A to # ...
def get_dimension_by_unit_id ( unit_id , do_accept_unit_id_none = False , ** kwargs ) : """Return the physical dimension a given unit id refers to . if do _ accept _ unit _ id _ none is False , it raises an exception if unit _ id is not valid or None if do _ accept _ unit _ id _ none is True , and unit _ id is ...
if do_accept_unit_id_none == True and unit_id is None : # In this special case , the method returns a dimension with id None return get_empty_dimension ( ) try : dimension = db . DBSession . query ( Dimension ) . join ( Unit ) . filter ( Unit . id == unit_id ) . filter ( ) . one ( ) return get_dimension ( d...
def get_version ( * args ) : """Extract the version number from a Python module ."""
contents = get_contents ( * args ) metadata = dict ( re . findall ( '__([a-z]+)__ = [\'"]([^\'"]+)' , contents ) ) return metadata [ 'version' ]
def set_copyright ( self , copyright = None ) : """Sets the copyright . : param copyright : the new copyright : type copyright : ` ` string ` ` : raise : ` ` InvalidArgument ` ` - - ` ` copyright ` ` is invalid : raise : ` ` NoAccess ` ` - - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` : raise : ` ` ...
if copyright is None : raise NullArgument ( ) metadata = Metadata ( ** settings . METADATA [ 'copyright' ] ) if metadata . is_read_only ( ) : raise NoAccess ( ) if self . _is_valid_input ( copyright , metadata , array = False ) : self . _my_map [ 'copyright' ] [ 'text' ] = copyright else : raise Invalid...
def mavlink_packet ( self , m ) : '''handle an incoming mavlink packet'''
if m . get_type ( ) == "ADSB_VEHICLE" : id = 'ADSB-' + str ( m . ICAO_address ) if id not in self . threat_vehicles . keys ( ) : # check to see if the vehicle is in the dict # if not then add it self . threat_vehicles [ id ] = ADSBVehicle ( id = id , state = m . to_dict ( ) ) for mp in self ...
def from_genesis_header ( cls , base_db : BaseAtomicDB , genesis_header : BlockHeader ) -> 'BaseChain' : """Initializes the chain from the genesis header ."""
chaindb = cls . get_chaindb_class ( ) ( base_db ) chaindb . persist_header ( genesis_header ) return cls ( base_db )
def _get_by_id ( self , style_id , style_type ) : """Return the style of * style _ type * matching * style _ id * . Returns the default for * style _ type * if * style _ id * is not found or if the style having * style _ id * is not of * style _ type * ."""
style = self . _element . get_by_id ( style_id ) if style is None or style . type != style_type : return self . default ( style_type ) return StyleFactory ( style )
def rename ( self , columns ) : """Returns a new DataFrame with renamed columns . Currently a simplified version of Pandas ' rename . Parameters columns : dict Old names to new names . Returns DataFrame With columns renamed , if found ."""
new_data = OrderedDict ( ) for column_name in self : if column_name in columns . keys ( ) : column = self . _data [ column_name ] new_name = columns [ column_name ] new_data [ new_name ] = Series ( column . values , column . index , column . dtype , new_name ) else : new_data [ c...
def _get_asset_content ( self , asset_content_id ) : """stub"""
asset_content = None for asset in self . _asset_lookup_session . get_assets ( ) : for content in asset . get_asset_contents ( ) : if content . get_id ( ) == asset_content_id : asset_content = content break if asset_content is not None : break if asset_content is None : ...
def split ( self , bitindex ) : """Split a promise into two promises . A tail bit , and the ' rest ' . Same operation as the one on TDOPromise , except this works with a collection of promises and splits the appropriate one . Returns : The ' Rest ' and the ' Tail ' . The ' Rest ' is TDOPromiseCollection c...
if bitindex < 0 : raise ValueError ( "bitindex must be larger or equal to 0." ) if bitindex == 0 : return None , self lastend = 0 split_promise = False for splitindex , p in enumerate ( self . _promises ) : if bitindex in range ( lastend , p . _bitstart ) : split_promise = False break if...
def is_valid_file ( parser , arg ) : """verify the validity of the given file . Never trust the End - User"""
if not os . path . exists ( arg ) : parser . error ( "File %s not found" % arg ) else : return arg