signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def search ( self , terms ) : """Seraches the documents for the inputed terms . : param terms : return [ { ' url ' : < str > , ' title ' : < str > ' , ' strength ' : < int > } ]"""
# load the search information if not self . _searchurls : base = self . tempFilepath ( ) root_url = projex . text . underscore ( self . text ( 0 ) ) for root , folders , files in os . walk ( base ) : if '_static' in root : continue for file in files : if not file . en...
def launch_cli ( ) : """Launch the CLI ."""
# Create the CLI argument parser parser = argparse . ArgumentParser ( prog = "pylp" , description = "Call some tasks defined in your pylpfile." ) # Version of Pylp parser . add_argument ( "-v" , "--version" , action = "version" , version = "Pylp %s" % version , help = "get the Pylp version and exit" ) # Set the pylpfil...
def _indexable_tags ( self ) : """Index tag ids for tags defined in this Entity ' s default tags namespace ."""
tags = current_app . extensions . get ( "tags" ) if not tags or not tags . supports_taggings ( self ) : return "" default_ns = tags . entity_default_ns ( self ) return [ t for t in tags . entity_tags ( self ) if t . ns == default_ns ]
def delete_db_instance ( self , dbid ) : '''Delete DB'''
if not self . connect_to_aws_rds ( ) : return False try : database = self . rdsc . delete_dbinstance ( dbid , skip_final_snapshot = True ) print database except : return False else : return True
def _run_command ( self , command_constructor , args ) : """Run command _ constructor and call run ( args ) on the resulting object : param command _ constructor : class of an object that implements run ( args ) : param args : object arguments for specific command created by CommandParser"""
verify_terminal_encoding ( sys . stdout . encoding ) self . _check_pypi_version ( ) config = create_config ( allow_insecure_config_file = args . allow_insecure_config_file ) self . show_error_stack_trace = config . debug_mode command = command_constructor ( config ) command . run ( args )
def counter ( self , name , description , labels = None , ** kwargs ) : """Use a Counter to track the total number of invocations of the method . : param name : the name of the metric : param description : the description of the metric : param labels : a dictionary of ` { labelname : callable _ or _ value } `...
return self . _track ( Counter , lambda metric , time : metric . inc ( ) , kwargs , name , description , labels , registry = self . registry )
def lazy_approximate_personalized_pagerank ( s , r , w_i , a_i , out_degree , in_degree , seed_node , rho = 0.2 , epsilon = 0.00001 , laziness_factor = 0.5 ) : """Calculates the approximate personalized PageRank starting from a seed node with self - loops . Introduced in : Andersen , R . , Chung , F . , & Lang , ...
# Initialize approximate PageRank and residual distributions # s = np . zeros ( number _ of _ nodes , dtype = np . float64) # r = np . zeros ( number _ of _ nodes , dtype = np . float64) r [ seed_node ] = 1.0 # Initialize queue of nodes to be pushed pushable = deque ( ) pushable . append ( seed_node ) # Do one push any...
def get_etexts ( feature_name , value ) : """Looks up all the texts that have meta - data matching some criterion . Arguments : feature _ name ( str ) : The meta - data on which to select the texts . value ( str ) : The value of the meta - data on which to filter the texts . Returns : frozenset : The set ...
matching_etexts = MetadataExtractor . get ( feature_name ) . get_etexts ( value ) return frozenset ( matching_etexts )
def get_expected_image_size ( module_or_spec , signature = None , input_name = None ) : """Returns expected [ height , width ] dimensions of an image input . Args : module _ or _ spec : a Module or ModuleSpec that accepts image inputs . signature : a string with the key of the signature in question . If Non...
# First see if an attached ImageModuleInfo provides this information . image_module_info = get_image_module_info ( module_or_spec ) if image_module_info : size = image_module_info . default_image_size if size . height and size . width : return [ size . height , size . width ] # Else inspect the input sh...
def scan_file ( fullpath , relpath ) : """scan a file and put it into the index"""
load_metafile . cache_clear ( ) meta = load_metafile ( fullpath ) if not meta : return True # update the category meta file mapping category = meta . get ( 'Category' , utils . get_category ( relpath ) ) values = { 'category' : category , 'file_path' : fullpath , 'sort_name' : meta . get ( 'Sort-Name' , '' ) } logg...
def create_assembly_instance ( self , assembly_uri , part_uri , configuration ) : '''Insert a configurable part into an assembly . Args : - assembly ( dict ) : eid , wid , and did of the assembly into which will be inserted - part ( dict ) : eid and did of the configurable part - configuration ( dict ) : th...
payload = { "documentId" : part_uri [ "did" ] , "elementId" : part_uri [ "eid" ] , # could be added if needed : # " partId " : " String " , # " featureId " : " String " , # " microversionId " : " String " , "versionId" : part_uri [ "wvm" ] , # " microversionId " : " String " , "isAssembly" : False , "isWholePartStudio"...
def generate_schema ( table , export_fields , output_format , output_fobj ) : """Generate table schema for a specific output format and write Current supported output formats : ' txt ' , ' sql ' and ' django ' . The table name and all fields names pass for a slugifying process ( table name is taken from file ...
if output_format in ( "csv" , "txt" ) : from rows import plugins data = [ { "field_name" : fieldname , "field_type" : fieldtype . __name__ . replace ( "Field" , "" ) . lower ( ) , } for fieldname , fieldtype in table . fields . items ( ) if fieldname in export_fields ] table = plugins . dicts . import_from_...
def _dialate_array ( self , array , iterators ) : """' Dialates ' a to _ process / to _ protect array to include all subject and / or visits if the pipeline contains any joins over the corresponding iterators . Parameters array : np . array [ M , N ] The array to potentially dialate iterators : set [ st...
if not iterators : return array dialated = np . copy ( array ) if self . study . SUBJECT_ID in iterators : # If we join over subjects we should include all subjects for every # visit we want to process dialated [ : , dialated . any ( axis = 0 ) ] = True if self . study . VISIT_ID in iterators : # If we join ove...
def get_method ( self , name ) : """Get registered method callend ` name ` ."""
try : return self . funcs [ name ] except KeyError : try : return self . instance . _get_method ( name ) except AttributeError : return SimpleXMLRPCServer . resolve_dotted_attribute ( self . instance , name , self . allow_dotted_names )
def finalize ( self ) : """Called at clean up , when the editor is closed . Can be used to disconnect signals . This is often called after the client ( e . g . the inspector ) is updated . If you want to take action before the update , override prepareCommit instead . Be sure to call the finalize of the super...
for subEditor in self . _subEditors : self . removeSubEditor ( subEditor ) self . cti . model . sigItemChanged . disconnect ( self . modelItemChanged ) self . resetButton . clicked . disconnect ( self . resetEditorValue ) self . cti = None # just to make sure it ' s not used again . self . delegate = None
def locate_blocks ( self , codestr ) : """Returns all code blocks between ` { ` and ` } ` and a proper key that can be multilined as long as it ' s joined by ` , ` or enclosed in ` ( ` and ` ) ` . Returns the " lose " code that ' s not part of the block as a third item ."""
def _strip_selprop ( selprop , lineno ) : _lineno , _sep , selprop = selprop . partition ( SEPARATOR ) if _sep == SEPARATOR : lineno = _lineno . strip ( ) lineno = int ( lineno ) if lineno else 0 else : selprop = _lineno selprop = _nl_num_re . sub ( '\n' , selprop ) selprop =...
def getCPUuse ( self ) : """Return cpu time utilization in seconds . @ return : Dictionary of stats ."""
hz = os . sysconf ( 'SC_CLK_TCK' ) info_dict = { } try : fp = open ( cpustatFile , 'r' ) line = fp . readline ( ) fp . close ( ) except : raise IOError ( 'Failed reading stats from file: %s' % cpustatFile ) headers = [ 'user' , 'nice' , 'system' , 'idle' , 'iowait' , 'irq' , 'softirq' , 'steal' , 'guest...
def p_include_file ( p ) : """include _ file : include NEWLINE program _ ENDFILE _"""
global CURRENT_DIR p [ 0 ] = [ p [ 1 ] + p [ 2 ] ] + p [ 3 ] + [ p [ 4 ] ] CURRENT_FILE . pop ( ) # Remove top of the stack CURRENT_DIR = os . path . dirname ( CURRENT_FILE [ - 1 ] )
def shake_shake_block ( x , output_filters , stride , hparams ) : """Builds a full shake - shake sub layer ."""
is_training = hparams . mode == tf . estimator . ModeKeys . TRAIN batch_size = common_layers . shape_list ( x ) [ 0 ] # Generate random numbers for scaling the branches . rand_forward = [ tf . random_uniform ( [ batch_size , 1 , 1 , 1 ] , minval = 0 , maxval = 1 , dtype = tf . float32 ) for _ in range ( hparams . shake...
def _get_subparsers ( self ) : """Recursively get subparsers ."""
subparsers = [ ] for action in self . _actions : if isinstance ( action , argparse . _SubParsersAction ) : for _ , subparser in action . choices . items ( ) : subparsers . append ( subparser ) ret = subparsers for sp in subparsers : ret += sp . _get_subparsers ( ) return ret
def update_frame ( self , key , ranges = None , element = None ) : """Set the plot ( s ) to the given frame number . Operates by manipulating the matplotlib objects held in the self . _ handles dictionary . If n is greater than the number of available frames , update using the last available frame ."""
reused = isinstance ( self . hmap , DynamicMap ) and self . overlaid if not reused and element is None : element = self . _get_frame ( key ) elif element is not None : self . current_key = key self . current_frame = element if element is not None : self . param . set_param ( ** self . lookup_options ( e...
def DiffDoArrays ( self , oldObj , newObj , isElementLinks ) : """Diff two DataObject arrays"""
if len ( oldObj ) != len ( newObj ) : __Log__ . debug ( 'DiffDoArrays: Array lengths do not match %d != %d' % ( len ( oldObj ) , len ( newObj ) ) ) return False for i , j in zip ( oldObj , newObj ) : if isElementLinks : if i . GetKey ( ) != j . GetKey ( ) : __Log__ . debug ( 'DiffDoArray...
def _prepare_wsdl_objects ( self ) : """This sets the package identifier information . This may be a tracking number or a few different things as per the Fedex spec ."""
self . SelectionDetails = self . client . factory . create ( 'TrackSelectionDetail' ) # Default to Fedex self . SelectionDetails . CarrierCode = 'FDXE' track_package_id = self . client . factory . create ( 'TrackPackageIdentifier' ) # Default to tracking number . track_package_id . Type = 'TRACKING_NUMBER_OR_DOORTAG' s...
def _metric_alarm_to_dict ( alarm ) : '''Convert a boto . ec2 . cloudwatch . alarm . MetricAlarm into a dict . Convenience for pretty printing .'''
d = odict . OrderedDict ( ) fields = [ 'name' , 'metric' , 'namespace' , 'statistic' , 'comparison' , 'threshold' , 'period' , 'evaluation_periods' , 'unit' , 'description' , 'dimensions' , 'alarm_actions' , 'insufficient_data_actions' , 'ok_actions' ] for f in fields : if hasattr ( alarm , f ) : d [ f ] = ...
def verified ( self ) : """True if bug was verified in given time frame"""
for who , record in self . logs : if record [ "field_name" ] == "status" and record [ "added" ] == "VERIFIED" : return True return False
def loaded_instruments ( self ) -> Dict [ str , Optional [ 'InstrumentContext' ] ] : """Get the instruments that have been loaded into the protocol . : returns : A dict mapping mount names in lowercase to the instrument in that mount , or ` None ` if no instrument is present ."""
return { mount . name . lower ( ) : instr for mount , instr in self . _instruments . items ( ) }
def deterministic ( cls , mnemonic , passphrase = '' , lang = 'english' , index = 0 ) : """Generate a : class : ` Keypair ` object via a deterministic phrase . Using a mnemonic , such as one generated from : class : ` StellarMnemonic ` , generate a new keypair deterministically . Uses : class : ` StellarMnemo...
sm = StellarMnemonic ( lang ) seed = sm . to_seed ( mnemonic , passphrase = passphrase , index = index ) return cls . from_raw_seed ( seed )
def _max ( self , memory , addr , ** kwargs ) : """Gets the maximum solution of an address ."""
return memory . state . solver . max ( addr , exact = kwargs . pop ( 'exact' , self . _exact ) , ** kwargs )
def fitspoly ( self , n , x , y , sd = None , wt = 1.0 , fid = 0 ) : """Create normal equations from the specified condition equations , and solve the resulting normal equations . It is in essence a combination . The method expects that the properties of the fitter to be used have been initialized or set ( li...
a = max ( abs ( max ( x ) ) , abs ( min ( x ) ) ) if a == 0 : a = 1 a = 1.0 / a b = NUM . power ( a , range ( n + 1 ) ) if self . set ( n = n + 1 , fid = fid ) : self . linear ( poly ( n ) , x * a , y , sd , wt , fid ) self . _fitids [ fid ] [ "sol" ] *= b self . _fitids [ fid ] [ "error" ] *= b ret...
def fetch ( cls , client , _id , symbol ) : """fetch option chain for instrument"""
url = "https://api.robinhood.com/options/chains/" params = { "equity_instrument_ids" : _id , "state" : "active" , "tradability" : "tradable" } data = client . get ( url , params = params ) def filter_func ( x ) : return x [ "symbol" ] == symbol results = list ( filter ( filter_func , data [ "results" ] ) ) return r...
def fit_df ( self , dfs , pstate_col = PSTATE_COL ) : """Convenience function to fit a model from a list of dataframes"""
obs_cols = list ( self . emission_name ) obs = [ df [ df . columns . difference ( [ pstate_col ] ) ] [ obs_cols ] . values for df in dfs ] pstates = [ df [ pstate_col ] . values for df in dfs ] return self . fit ( obs , pstates )
def generate_sitemap ( self , path = 'sitemap.xml' , https = False ) : """Generate an XML sitemap . Args : path ( str ) : The name of the file to write to . https ( bool ) : If True , links inside the sitemap with relative scheme ( e . g . example . com / something ) will be set to HTTPS . If False ( the ...
sitemap = russell . sitemap . generate_sitemap ( self , https = https ) self . write_file ( path , sitemap )
def string ( s , salt = None ) : """获取一个字符串的 MD5 值 : param : * s : ( string ) 需要进行 hash 的字符串 * salt : ( string ) 随机字符串 , 默认为 None : return : * result : ( string ) 32 位小写 MD5 值"""
m = hashlib . md5 ( ) s = s . encode ( 'utf-8' ) + salt . encode ( 'utf-8' ) if salt is not None else s . encode ( 'utf-8' ) m . update ( s ) result = m . hexdigest ( ) return result
def _parse_criteria ( self , criteria ) : """Internal method to perform mapping of criteria to proper mongo queries using aliases , as well as some useful sanitization . For example , string formulas such as " Fe2O3 " are auto - converted to proper mongo queries of { " Fe " : 2 , " O " : 3 } . If ' criteria...
if criteria is None : return dict ( ) parsed_crit = dict ( ) for k , v in self . default_criteria . items ( ) : if k not in criteria : parsed_crit [ self . aliases . get ( k , k ) ] = v for key , crit in list ( criteria . items ( ) ) : if key in [ "normalized_formula" , "reduced_cell_formula" ] : ...
def get_token_and_data ( self , data ) : '''When we receive this , we have ' token ) : data ' '''
token = '' for c in data : if c != ')' : token = token + c else : break ; return token , data . lstrip ( token + '):' )
def create_key ( self , title , key ) : """Create a new key for the authenticated user . : param str title : ( required ) , key title : param key : ( required ) , actual key contents , accepts path as a string or file - like object : returns : : class : ` Key < github3 . users . Key > `"""
created = None if title and key : url = self . _build_url ( 'user' , 'keys' ) req = self . _post ( url , data = { 'title' : title , 'key' : key } ) json = self . _json ( req , 201 ) if json : created = Key ( json , self ) return created
def get_parent_id ( self ) : '''Returns parent id'''
parent_id = parsers . get_parent_id ( self . __chebi_id ) return None if math . isnan ( parent_id ) else 'CHEBI:' + str ( parent_id )
def get_value ( self , name ) : """Get the value of a variable"""
value = self . shellwidget . get_value ( name ) # Reset temporal variable where value is saved to # save memory self . shellwidget . _kernel_value = None return value
def start ( self , * args , ** kwargs ) : """Start execution of the function ."""
self . queue = Queue ( ) thread = Thread ( target = self . _threaded , args = args , kwargs = kwargs ) thread . start ( ) return Asynchronous . Result ( self . queue , thread )
def validate_table ( self , table_name , model ) : """Polls until a creating table is ready , then verifies the description against the model ' s requirements . The model may have a subset of all GSIs and LSIs on the table , but the key structure must be exactly the same . The table must have a stream if the mo...
actual = self . describe_table ( table_name ) if not compare_tables ( model , actual ) : raise TableMismatch ( "The expected and actual tables for {!r} do not match." . format ( model . __name__ ) ) # Fill in values that Meta doesn ' t know ahead of time ( such as arns ) . # These won ' t be populated unless Meta e...
def send_email ( recipients , subject , message , attachments = None ) : """Sends email . Args : recipients ( list of str ) : subject ( str ) : message ( str ) : attachments ( list of str ) : list containing full paths ( txt files only ) to attach to email ."""
if not attachments : attachments = [ ] if os . path . exists ( EMAIL_SETTINGS_FILE ) : email_settings = json . load ( open ( EMAIL_SETTINGS_FILE ) ) sender = email_settings . get ( 'sender' , 'ambry@localhost' ) use_tls = email_settings . get ( 'use_tls' ) username = email_settings [ 'username' ] ...
def cmd_update ( args ) : """Update a generator . Parameters args : ` argparse . Namespace ` Command arguments ."""
# args . output = None markov = load ( MarkovText , args . state , args ) read ( args . input , markov , args . progress ) if args . output is None : if args . type == SQLITE : save ( markov , None , args ) elif args . type == JSON : name , ext = path . splitext ( args . state ) tmp = na...
def getContacts ( self , ** kwargs ) : """Returns a list of all contacts . Optional Parameters : * limit - - Limits the number of returned contacts to the specified quantity . Type : Integer Default : 100 * offset - - Offset for listing ( requires limit . ) Type : Integer Default : 0 Returned stru...
# Warn user about unhandled parameters for key in kwargs : if key not in [ 'limit' , 'offset' ] : sys . stderr . write ( "'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n' ) return [ PingdomContact ( self , x ) for x in self . request ( "GET" , "notification_contacts" , kwargs ) . json ( ) [ ...
def handle_reboot ( self ) : """Properly manage the service life cycle when the device needs to temporarily disconnect . The device can temporarily lose adb connection due to user - triggered reboot . Use this function to make sure the services started by Mobly are properly stopped and restored afterwards ....
self . services . stop_all ( ) try : yield finally : self . wait_for_boot_completion ( ) if self . is_rootable : self . root_adb ( ) self . services . start_all ( )
def transform_sparql_update ( rdf , update_query ) : """Perform a SPARQL Update transformation on the RDF data ."""
logging . debug ( "performing SPARQL Update transformation" ) if update_query [ 0 ] == '@' : # actual query should be read from file update_query = file ( update_query [ 1 : ] ) . read ( ) logging . debug ( "update query: %s" , update_query ) rdf . update ( update_query )
def sim ( self , key , size = None ) : '''key : memory address ( int ) or register name ( str ) size : size of object in bytes'''
project = load_project ( ) if key in project . arch . registers : if size is None : size = project . arch . registers [ key ] [ 1 ] size *= 8 s = claripy . BVS ( "angrdbg_reg_" + str ( key ) , size ) setattr ( self . state . regs , key , s ) self . symbolics [ key ] = ( s , size ) elif isins...
def significant_format ( number , decimal_sep = '.' , thousand_sep = ',' , n = 3 ) : """Format a number according to a given number of significant figures ."""
str_number = significant ( number , n ) # sign if float ( number ) < 0 : sign = '-' else : sign = '' if str_number [ 0 ] == '-' : str_number = str_number [ 1 : ] if '.' in str_number : int_part , dec_part = str_number . split ( '.' ) else : int_part , dec_part = str_number , '' if dec_part : dec...
def generate ( env ) : """Add Builders and construction variables for rmic to an Environment ."""
env [ 'BUILDERS' ] [ 'RMIC' ] = RMICBuilder env [ 'RMIC' ] = 'rmic' env [ 'RMICFLAGS' ] = SCons . Util . CLVar ( '' ) env [ 'RMICCOM' ] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}' env [ 'JAVACLASSSUFFIX' ] = '.class'
def create_anisomagplot ( plotman , x , y , z , alpha , options ) : '''Plot the data of the tomodir in one overview plot .'''
sizex , sizez = getfigsize ( plotman ) # create figure f , ax = plt . subplots ( 2 , 3 , figsize = ( 3 * sizex , 2 * sizez ) ) if options . title is not None : plt . suptitle ( options . title , fontsize = 18 ) plt . subplots_adjust ( wspace = 1.5 , top = 2 ) # plot magnitue if options . cmaglin : cidx = pl...
def edited_message_handler ( self , * custom_filters , commands = None , regexp = None , content_types = None , state = None , run_task = None , ** kwargs ) : """Decorator for edited message handler You can use combination of different handlers . . code - block : : python3 @ dp . message _ handler ( ) @ dp ...
def decorator ( callback ) : self . register_edited_message_handler ( callback , * custom_filters , commands = commands , regexp = regexp , content_types = content_types , state = state , run_task = run_task , ** kwargs ) return callback return decorator
def lowess ( x , w , x0 , kernel = epanechnikov , l = 1 , robust = False ) : """Locally linear regression with the LOWESS algorithm . Parameters x : float n - d array Values of x for which f ( x ) is known ( e . g . measured ) . The shape of this is ( n , j ) , where n is the number the dimensions of the an...
if robust : # We use the procedure described in # Start by calling this function with robust set to false and the x0 # input being equal to the x input : w_est = lowess ( x , w , x , kernel = epanechnikov , l = 1 , robust = False ) resid = w_est - w median_resid = stats . nanmedian ( np . abs ( resid ) ) ...
def minimum_valid_values_in_any_group ( df , levels = None , n = 1 , invalid = np . nan ) : """Filter ` ` DataFrame ` ` by at least n valid values in at least one group . Taking a Pandas ` ` DataFrame ` ` with a ` ` MultiIndex ` ` column index , filters rows to remove rows where there are less than ` n ` valid ...
df = df . copy ( ) if levels is None : if 'Group' in df . columns . names : levels = [ df . columns . names . index ( 'Group' ) ] # Filter by at least 7 ( values in class : timepoint ) at least in at least one group if invalid is np . nan : dfx = ~ np . isnan ( df ) else : dfx = df != invalid dfc = ...
def _feed_buffer ( self , n = 1 ) : """Feed the data buffer by reading a Websocket message . : param n : if given , feed buffer until it contains at least n bytes"""
buffer = bytearray ( self . _stream . read ( ) ) while len ( buffer ) < n : try : message = yield from self . _protocol . recv ( ) except ConnectionClosed : message = None if message is None : break if not isinstance ( message , bytes ) : raise TypeError ( "message must b...
def _to_rest_includes ( models , includes ) : """Fetch the models to be included The includes should follow a few basic rules : * the include MUST not already be an array member of the included array ( no dupes ) * the include MUST not be the same as the primary data if the primary data is a single resour...
included = [ ] includes = includes or [ ] if not isinstance ( models , list ) : models = [ models ] for include in includes : for model in models : rel = getattr ( model , include ) if hasattr ( rel , 'model' ) and rel . model : rel_models = [ rel . model ] elif hasattr ( rel...
def file_audit_list ( self , project ) : """Gathers file name lists"""
project_list = False self . load_project_flag_list_file ( il . get ( 'project_exceptions' ) , project ) try : default_list = set ( ( fl [ 'file_audits' ] [ 'file_names' ] ) ) except KeyError : logger . error ( 'Key Error processing file_names list values' ) try : project_list = set ( ( fl [ 'file_audits' ] ...
def load_classes ( cls , fail_silently = True ) : """Load all the classes for a plugin . Produces a sequence containing the identifiers and their corresponding classes for all of the available instances of this plugin . fail _ silently causes the code to simply log warnings if a plugin cannot import . The g...
all_classes = itertools . chain ( pkg_resources . iter_entry_points ( cls . entry_point ) , ( entry_point for identifier , entry_point in cls . extra_entry_points ) , ) for class_ in all_classes : try : yield ( class_ . name , cls . _load_class_entry_point ( class_ ) ) except Exception : # pylint : disa...
def total_msgs ( xml ) : '''count total number of msgs'''
count = 0 for x in xml : count += len ( x . message ) return count
def destroyCluster ( self ) : """Try a few times to terminate all of the instances in the group ."""
logger . debug ( "Destroying cluster %s" % self . clusterName ) instancesToTerminate = self . _getNodesInCluster ( ) attempts = 0 while instancesToTerminate and attempts < 3 : self . _terminateInstances ( instances = instancesToTerminate ) instancesToTerminate = self . _getNodesInCluster ( ) attempts += 1 #...
def _compute_value ( power , wg ) : """Return the weight corresponding to single power ."""
if power not in wg : p1 , p2 = power # y power if p1 == 0 : yy = wg [ ( 0 , - 1 ) ] wg [ power ] = numpy . power ( yy , p2 / 2 ) . sum ( ) / len ( yy ) # x power else : xx = wg [ ( - 1 , 0 ) ] wg [ power ] = numpy . power ( xx , p1 / 2 ) . sum ( ) / len ( xx ) return ...
def encode_positions ( self , positions : mx . sym . Symbol , data : mx . sym . Symbol ) -> mx . sym . Symbol : """: param positions : ( batch _ size , ) : param data : ( batch _ size , num _ embed ) : return : ( batch _ size , num _ embed )"""
# ( batch _ size , source _ seq _ len , num _ embed ) pos_embedding = mx . sym . Embedding ( data = positions , input_dim = self . max_seq_len , weight = self . embed_weight , output_dim = self . num_embed , name = self . prefix + "pos_embed" ) return mx . sym . broadcast_add ( data , pos_embedding , name = "%s_add" % ...
def eval ( cls , exp , files = None ) : """: param str | unicode exp : Haskell expression to evaluate . : rtype : str | unicode"""
return cls . show ( cls . get ( exp , files = files ) )
def _add_hook ( self , socket , callback ) : """Generic hook . The passed socket has to be " receive only " ."""
self . _hooks . append ( socket ) self . _hooks_cb [ socket ] = callback if self . poller : self . poller . register ( socket , POLLIN )
def _get_cache_file_path ( self , cache_dir = None ) : """Get path for cache file : param str cache _ dir : base path for TLD cache , defaults to data dir : raises : CacheFileError when cached directory is not writable for user : return : Full path to cached file with TLDs : rtype : str"""
if cache_dir is None : # Tries to get writable cache dir with fallback to users data dir # and temp directory cache_dir = self . _get_writable_cache_dir ( ) else : if not os . access ( cache_dir , os . W_OK ) : raise CacheFileError ( "None of cache directories is writable." ) # get directory for cached ...
def _check_hyperedge_attributes_consistency ( self ) : """Consistency Check 1 : consider all hyperedge IDs listed in _ hyperedge _ attributes : raises : ValueError - - detected inconsistency among dictionaries"""
# required _ attrs are attributes that every hyperedge must have . required_attrs = [ 'weight' , 'tail' , 'head' , '__frozen_tail' , '__frozen_head' ] # Get list of hyperedge _ ids from the hyperedge attributes dict hyperedge_ids_from_attributes = set ( self . _hyperedge_attributes . keys ( ) ) # Perform consistency ch...
def execute ( self ) : """Start this action command in a subprocess . : raise : ActionError ' toomanyopenfiles ' if too many opened files on the system ' no _ process _ launched ' if arguments parsing failed ' process _ launch _ failed ' : if the process launch failed : return : reference to the started p...
self . status = ACT_STATUS_LAUNCHED self . check_time = time . time ( ) self . wait_time = 0.0001 self . last_poll = self . check_time # Get a local env variables with our additional values self . local_env = self . get_local_environnement ( ) # Initialize stdout and stderr . self . stdoutdata = '' self . stderrdata = ...
def delete_collection_runtime_class ( self , ** kwargs ) : """delete collection of RuntimeClass This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . delete _ collection _ runtime _ class ( async _ req = True ) > ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_collection_runtime_class_with_http_info ( ** kwargs ) else : ( data ) = self . delete_collection_runtime_class_with_http_info ( ** kwargs ) return data
def block_layer ( inputs , filters , bottleneck , block_fn , blocks , strides , training , name , data_format ) : """Creates one layer of blocks for the ResNet model . Args : inputs : A tensor of size [ batch , channels , height _ in , width _ in ] or [ batch , height _ in , width _ in , channels ] depending ...
# Bottleneck blocks end with 4x the number of filters as they start with filters_out = filters * 4 if bottleneck else filters def projection_shortcut ( inputs ) : return conv2d_fixed_padding ( inputs = inputs , filters = filters_out , kernel_size = 1 , strides = strides , data_format = data_format ) # Only the firs...
def standings ( self , league_table , league ) : """Prints the league standings in a pretty way"""
click . secho ( "%-6s %-30s %-10s %-10s %-10s" % ( "POS" , "CLUB" , "PLAYED" , "GOAL DIFF" , "POINTS" ) ) for team in league_table [ "standings" ] [ 0 ] [ "table" ] : if team [ "goalDifference" ] >= 0 : team [ "goalDifference" ] = ' ' + str ( team [ "goalDifference" ] ) # Define the upper and ...
def signup_or_login_with_mobile_phone ( cls , phone_number , sms_code ) : '''param phone _ nubmer : string _ types param sms _ code : string _ types 在调用此方法前请先使用 request _ sms _ code 请求 sms code'''
data = { 'mobilePhoneNumber' : phone_number , 'smsCode' : sms_code } response = client . post ( '/usersByMobilePhone' , data ) content = response . json ( ) user = cls ( ) user . _update_data ( content ) user . _handle_save_result ( True ) if 'smsCode' not in content : user . _attributes . pop ( 'smsCode' , None ) ...
def callback ( self , username , request ) : """Having : username : return user ' s identifiers or None ."""
credentials = self . _get_credentials ( request ) if credentials : username , api_key = credentials if self . check : return self . check ( username , api_key , request )
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : KeyContext for this KeyInstance : rtype : twilio . rest . preview . deployed _ devices . fleet . key . KeyContext"""
if self . _context is None : self . _context = KeyContext ( self . _version , fleet_sid = self . _solution [ 'fleet_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def _validate_param ( self , expected , param ) : """Validates a single param against its expected type . Raises RpcException if the param is invalid : Parameters : expected Type instance param Parameter value to validate"""
ok , msg = self . contract . validate ( expected , expected . is_array , param ) if not ok : vals = ( self . full_name , expected . name , msg ) msg = "Function '%s' invalid param '%s'. %s" % vals raise RpcException ( ERR_INVALID_PARAMS , msg )
def _fullqualname_builtin_py2 ( obj ) : """Fully qualified name for ' builtin _ function _ or _ method ' objects in Python 2."""
if obj . __self__ is None : # built - in functions module = obj . __module__ qualname = obj . __name__ else : # built - in methods if inspect . isclass ( obj . __self__ ) : cls = obj . __self__ else : cls = obj . __self__ . __class__ module = cls . __module__ qualname = cls . __n...
def colorize ( style , msg , resp ) : """Taken and modified from ` django . utils . log . ServerFormatter . format ` to mimic runserver ' s styling ."""
code = resp . status . split ( maxsplit = 1 ) [ 0 ] if code [ 0 ] == '2' : # Put 2XX first , since it should be the common case msg = style . HTTP_SUCCESS ( msg ) elif code [ 0 ] == '1' : msg = style . HTTP_INFO ( msg ) elif code == '304' : msg = style . HTTP_NOT_MODIFIED ( msg ) elif code [ 0 ] == '3' : ...
def full_url ( self ) : """Build the actual URL to use ."""
if not self . url : raise URLRequired ( ) # Support for unicode domain names and paths . scheme , netloc , path , params , query , fragment = urlparse ( self . url ) if not scheme : raise ValueError ( ) netloc = netloc . encode ( 'idna' ) if isinstance ( path , unicode ) : path = path . encode ( 'utf-8' ) p...
def firmware_autoupgrade_params_pass ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) firmware = ET . SubElement ( config , "firmware" , xmlns = "urn:brocade.com:mgmt:brocade-firmware" ) autoupgrade_params = ET . SubElement ( firmware , "autoupgrade-params" ) pass_el = ET . SubElement ( autoupgrade_params , "pass" ) pass_el . text = kwargs . pop ( 'pass' ) callback = k...
def start_timestamp ( self ) : """int : slice start timestamp or None ."""
if self . event_timestamp : return self . event_timestamp - ( self . duration * self . _MICRO_SECONDS_PER_MINUTE ) return None
def write_to_directory ( self , dataset_info_dir ) : """Write ` DatasetInfo ` as JSON to ` dataset _ info _ dir ` ."""
# Save the metadata from the features ( vocabulary , labels , . . . ) if self . features : self . features . save_metadata ( dataset_info_dir ) if self . redistribution_info . license : with tf . io . gfile . GFile ( self . _license_filename ( dataset_info_dir ) , "w" ) as f : f . write ( self . redistr...
def run ( self , in_batches ) : """Run shell operator synchronously to eat ` in _ batches ` : param in _ batches : ` tuple ` of batches to process"""
if len ( in_batches ) != len ( self . _batcmd . batch_to_file_s ) : BaseShellOperator . _rm_process_input_tmpfiles ( self . _batcmd . batch_to_file_s ) # [ todo ] - Removing tmpfiles can be easily forgot . Less lifetime for tmpfile . raise AttributeError ( 'len(in_batches) == %d, while %d IN_BATCH* are spec...
def _dict_to_tuple ( d ) : '''Convert a dictionary to a time tuple . Depends on key values in the regexp pattern !'''
# TODO : Adding a ms field to struct _ time tuples is problematic # since they don ' t have this field . Should use datetime # which has a microseconds field , else no ms . . When mapping struct _ time # to gDateTime the last 3 fields are irrelevant , here using dummy values to make # everything happy . retval = _nilti...
def isubset ( self , * keys ) : # type : ( * Hashable ) - > ww . g """Return key , self [ key ] as generator for key in keys . Raise KeyError if a key does not exist Args : keys : Iterable containing keys Example : > > > from ww import d > > > list ( d ( { 1 : 1 , 2 : 2 , 3 : 3 } ) . isubset ( 1 , 3 ) )...
return ww . g ( ( key , self [ key ] ) for key in keys )
def get_readonly_fields ( self , request , obj = None ) : """The model can ' t be changed once the export is created"""
if obj is None : return [ ] return super ( ExportAdmin , self ) . get_readonly_fields ( request , obj )
def append ( self , network ) : """Append a : class : ` caspo . core . logicalnetwork . LogicalNetwork ` to the list Parameters network : : class : ` caspo . core . logicalnetwork . LogicalNetwork ` The network to append"""
arr = network . to_array ( self . hg . mappings ) if len ( self . __matrix ) : self . __matrix = np . append ( self . __matrix , [ arr ] , axis = 0 ) self . __networks = np . append ( self . __networks , network . networks ) else : self . __matrix = np . array ( [ arr ] ) self . __networks = np . array ...
def as_euler_angles ( q ) : """Open Pandora ' s Box If somebody is trying to make you use Euler angles , tell them no , and walk away , and go and tell your mum . You don ' t want to use Euler angles . They are awful . Stay away . It ' s one thing to convert from Euler angles to quaternions ; at least you '...
alpha_beta_gamma = np . empty ( q . shape + ( 3 , ) , dtype = np . float ) n = np . norm ( q ) q = as_float_array ( q ) alpha_beta_gamma [ ... , 0 ] = np . arctan2 ( q [ ... , 3 ] , q [ ... , 0 ] ) + np . arctan2 ( - q [ ... , 1 ] , q [ ... , 2 ] ) alpha_beta_gamma [ ... , 1 ] = 2 * np . arccos ( np . sqrt ( ( q [ ... ...
def exec_rabbitmqctl ( self , command , args = [ ] , rabbitmqctl_opts = [ '-q' ] ) : """Execute a ` ` rabbitmqctl ` ` command inside a running container . : param command : the command to run : param args : a list of args for the command : param rabbitmqctl _ opts : a list of extra options to pass to ` ` ra...
cmd = [ 'rabbitmqctl' ] + rabbitmqctl_opts + [ command ] + args return self . inner ( ) . exec_run ( cmd )
def _parse_snapshot_share ( response , name ) : '''Extracts snapshot return header .'''
snapshot = response . headers . get ( 'x-ms-snapshot' ) return _parse_share ( response , name , snapshot )
def averageblocks ( blks , imgsz , stpsz = None ) : """Average blocks together from an ndarray to reconstruct ndarray signal . Parameters blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple , optional ( default None , corresponds to steps of 1) tuple of s...
blksz = blks . shape [ : - 1 ] if stpsz is None : stpsz = tuple ( 1 for _ in blksz ) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple ( int ( np . floor ( ( a - b ) / c ) + 1 ) for a , b , c in zip_longest ( imgsz , blksz , stpsz , fillvalue = 1 ) ) new_shape = blksz...
def leading_whitespace_in_current_line ( self ) : """The leading whitespace in the left margin of the current line ."""
current_line = self . current_line length = len ( current_line ) - len ( current_line . lstrip ( ) ) return current_line [ : length ]
def to_auto ( name , value , source = 'auto' , convert_to_human = True ) : '''Convert python value to zfs value'''
return _auto ( 'to' , name , value , source , convert_to_human )
def repl_init ( self , config ) : """create replica set by config return True if replica set created successfuly , else False"""
self . update_server_map ( config ) # init _ server - server which can init replica set init_server = [ member [ 'host' ] for member in config [ 'members' ] if not ( member . get ( 'arbiterOnly' , False ) or member . get ( 'priority' , 1 ) == 0 ) ] [ 0 ] servers = [ member [ 'host' ] for member in config [ 'members' ] ...
def dict_to_object ( d ) : """Recursively converts a dict to an object"""
top = type ( 'CreateSendModel' , ( object , ) , d ) seqs = tuple , list , set , frozenset for i , j in d . items ( ) : if isinstance ( j , dict ) : setattr ( top , i , dict_to_object ( j ) ) elif isinstance ( j , seqs ) : setattr ( top , i , type ( j ) ( dict_to_object ( sj ) if isinstance ( sj ...
def signable ( self , request , authheaders , bodyhash = None ) : """Creates the signable string for a request and returns it . Keyword arguments : request - - A request object which can be consumed by this API . authheaders - - A string - indexable object which contains the headers appropriate for this signa...
method = request . method . upper ( ) host = request . get_header ( "host" ) path = request . url . canonical_path ( ) query = request . url . encoded_query ( ) timestamp = request . get_header ( "x-authorization-timestamp" ) auth_headers = self . unroll_auth_headers ( authheaders , exclude_signature = True , sep = '&'...
def expire_record ( record ) : """Expire a record for a missing entry"""
load_message . cache_clear ( ) # This entry no longer exists so delete it , and anything that references it # SQLite doesn ' t support cascading deletes so let ' s just clean up # manually orm . delete ( pa for pa in model . PathAlias if pa . entry == record ) record . delete ( ) orm . commit ( )
def sfs_folded ( ac , n = None ) : """Compute the folded site frequency spectrum given reference and alternate allele counts at a set of biallelic variants . Parameters ac : array _ like , int , shape ( n _ variants , 2) Allele counts array . n : int , optional The total number of chromosomes called . ...
# check input ac , n = _check_ac_n ( ac , n ) # compute minor allele counts mac = np . amin ( ac , axis = 1 ) # need platform integer for bincount mac = mac . astype ( int , copy = False ) # compute folded site frequency spectrum x = n // 2 + 1 s = np . bincount ( mac , minlength = x ) return s
def show_text_glyphs ( self , text , glyphs , clusters , cluster_flags = 0 ) : """This operation has rendering effects similar to : meth : ` show _ glyphs ` but , if the target surface supports it ( see : meth : ` Surface . has _ show _ text _ glyphs ` ) , uses the provided text and cluster mapping to embed...
glyphs = ffi . new ( 'cairo_glyph_t[]' , glyphs ) clusters = ffi . new ( 'cairo_text_cluster_t[]' , clusters ) cairo . cairo_show_text_glyphs ( self . _pointer , _encode_string ( text ) , - 1 , glyphs , len ( glyphs ) , clusters , len ( clusters ) , cluster_flags ) self . _check_status ( )
def name_from_base ( base , max_length = 63 , short = False ) : """Append a timestamp to the provided string . This function assures that the total length of the resulting string is not longer than the specified max length , trimming the input parameter if necessary . Args : base ( str ) : String used as pr...
timestamp = sagemaker_short_timestamp ( ) if short else sagemaker_timestamp ( ) trimmed_base = base [ : max_length - len ( timestamp ) - 1 ] return '{}-{}' . format ( trimmed_base , timestamp )
def gopro_set_request_send ( self , target_system , target_component , cmd_id , value , force_mavlink1 = False ) : '''Request to set a GOPRO _ COMMAND with a desired target _ system : System ID ( uint8 _ t ) target _ component : Component ID ( uint8 _ t ) cmd _ id : Command ID ( uint8 _ t ) value : Value ( ...
return self . send ( self . gopro_set_request_encode ( target_system , target_component , cmd_id , value ) , force_mavlink1 = force_mavlink1 )
def doc_browse ( self , args , range = None ) : """Browse doc of whatever at cursor ."""
self . log . debug ( 'browse: in' ) self . call_options [ self . call_id ] = { "browse" : True } self . send_at_position ( "DocUri" , False , "point" )
def _events ( self ) : """Iterator over all catapult trace events , as python values ."""
for did , device in sorted ( six . iteritems ( self . _proto . devices ) ) : if device . name : yield dict ( ph = _TYPE_METADATA , pid = did , name = 'process_name' , args = dict ( name = device . name ) ) yield dict ( ph = _TYPE_METADATA , pid = did , name = 'process_sort_index' , args = dict ( sort_in...
def register ( self , patterns , obj = None , instances = None , ** reg_kwargs ) : """Register one object which can be matched / searched by regex . : param patterns : a list / tuple / set of regex - pattern . : param obj : return it while search / match success . : param instances : instance list will search...
assert obj , "bool(obj) should be True." patterns = patterns if isinstance ( patterns , ( list , tuple , set ) ) else [ patterns ] instances = instances or [ ] instances = ( instances if isinstance ( instances , ( list , tuple , set ) ) else [ instances ] ) for pattern in patterns : pattern_compiled = re . compile ...