signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def pop ( self , key , timeout = 1 , is_async = False , only_read = False ) : """Test : > > > cache = Cache ( log _ level = logging . WARNING ) > > > cache . put ( ' a ' , 0) > > > cache . pop ( ' a ' ) > > > cache . pop ( ' b ' ) = = None True"""
if key not in self . cache_items : return None return self . cache_items . pop ( key ) [ key ]
def parse ( text ) : """Parse the given text into metadata and strip it for a Markdown parser . : param text : text to be parsed"""
rv = { } m = META . match ( text ) while m : key = m . group ( 1 ) value = m . group ( 2 ) value = INDENTATION . sub ( '\n' , value . strip ( ) ) rv [ key ] = value text = text [ len ( m . group ( 0 ) ) : ] m = META . match ( text ) return rv , text
def process_source ( self ) : """Return source with transformations , if any"""
if isinstance ( self . source , str ) : # Replace single and double quotes with escaped single - quote self . source = self . source . replace ( "'" , "\'" ) . replace ( '"' , "\'" ) return "\"{source}\"" . format ( source = self . source ) return self . source
def accept ( self ) : """Saves the data to the profile before closing ."""
if ( not self . uiNameTXT . text ( ) ) : QMessageBox . information ( self , 'Invalid Name' , 'You need to supply a name for your layout.' ) return prof = self . profile ( ) if ( not prof ) : prof = XViewProfile ( ) prof . setName ( nativestring ( self . uiNameTXT . text ( ) ) ) prof . setVersion ( self . ui...
def batch ( iterable , length ) : """Returns a series of iterators across the inputted iterable method , broken into chunks based on the inputted length . : param iterable | < iterable > | ( list , tuple , set , etc . ) length | < int > : credit http : / / en . sharejs . com / python / 14362 : return < ge...
source_iter = iter ( iterable ) while True : batch_iter = itertools . islice ( source_iter , length ) yield itertools . chain ( [ batch_iter . next ( ) ] , batch_iter )
def _mpl_cmap2pgf_cmap ( cmap , data ) : """Converts a color map as given in matplotlib to a color map as represented in PGFPlots ."""
if isinstance ( cmap , mpl . colors . LinearSegmentedColormap ) : return _handle_linear_segmented_color_map ( cmap , data ) assert isinstance ( cmap , mpl . colors . ListedColormap ) , "Only LinearSegmentedColormap and ListedColormap are supported" return _handle_listed_color_map ( cmap , data )
def calibration_lines ( freqs , data , tref = None ) : """Extract the calibration lines from strain data . Parameters freqs : list List containing the frequencies of the calibration lines . data : pycbc . types . TimeSeries Strain data to extract the calibration lines from . tref : { None , float } , op...
if tref is None : tref = float ( data . start_time ) for freq in freqs : measured_line = matching_line ( freq , data , tref , bin_size = data . duration ) data -= measured_line . data . real return data
def resource_filename_mod_entry_point ( module_name , entry_point ) : """If a given package declares a namespace and also provide submodules nested at that namespace level , and for whatever reason that module is needed , Python ' s import mechanism will not have a path associated with that module . However ,...
if entry_point . dist is None : # distribution missing is typically caused by mocked entry # points from tests ; silently falling back to basic lookup result = pkg_resources . resource_filename ( module_name , '' ) else : result = resource_filename_mod_dist ( module_name , entry_point . dist ) if not result : ...
def switch_to ( self , newstate ) : """Switch to a new state newstate : int or string Can be either the value of the state , or the label of the state"""
if type ( newstate ) is int : if newstate in self . _states : self . _curcode = newstate else : raise Exception ( "The state value " + str ( newstate ) + " does not exist." ) else : if newstate in self . _scodes : self . _curcode = self . _scodes [ newstate ] else : raise...
def remove ( self , item , count = 0 ) : """Removes @ item from the list for @ count number of occurences"""
self . _client . lrem ( self . key_prefix , count , self . _dumps ( item ) )
def initdb ( ) : """Initialize the database"""
from plnt . database import Blog , session make_app ( ) . init_database ( ) # and now fill in some python blogs everybody should read ( shamelessly # added my own blog too ) blogs = [ Blog ( "Armin Ronacher" , "http://lucumr.pocoo.org/" , "http://lucumr.pocoo.org/cogitations/feed/" , ) , Blog ( "Georg Brandl" , "http:/...
def __audiorender_thread ( self ) : """Thread that takes care of the audio rendering . Do not call directly , but only as the target of a thread ."""
new_audioframe = None logger . debug ( "Started audio rendering thread." ) while self . status in [ PLAYING , PAUSED ] : # Retrieve audiochunk if self . status == PLAYING : if new_audioframe is None : # Get a new frame from the audiostream , skip to the next one # if the current one gives a problem ...
async def probe_message ( self , _message , context ) : """Handle a probe message . See : meth : ` AbstractDeviceAdapter . probe ` ."""
client_id = context . user_data await self . probe ( client_id )
def cell ( filename = None , mass = None , instrument = None , logging_mode = "INFO" , cycle_mode = None , auto_summary = True ) : """Create a CellpyData object"""
from cellpy import log log . setup_logging ( default_level = logging_mode ) cellpy_instance = setup_cellpy_instance ( ) if instrument is not None : cellpy_instance . set_instrument ( instrument = instrument ) if cycle_mode is not None : cellpy_instance . cycle_mode = cycle_mode if filename is not None : fil...
def get_user_events ( self , id , ** data ) : """GET / users / : id / events / Returns a : ref : ` paginated < pagination > ` response of : format : ` events < event > ` , under the key ` ` events ` ` , of all events the user has access to"""
return self . get ( "/users/{0}/events/" . format ( id ) , data = data )
def disable ( gandi , resource , backend , port , probe ) : """Disable a backend or a probe on a webaccelerator"""
result = [ ] if backend : backends = backend for backend in backends : if 'port' not in backend : if not port : backend [ 'port' ] = click . prompt ( 'Please set a port for ' 'backends. If you want to ' ' different port for ' 'each backend, use `-b ' 'ip:port`' , type = int )...
def has_map ( self ) : """Return the has map attribute of the BFD file being processed ."""
if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . get_bfd_attribute ( self . _ptr , BfdAttributes . HAS_MAP )
def check_calendar_dates ( feed : "Feed" , * , as_df : bool = False , include_warnings : bool = False ) -> List : """Analog of : func : ` check _ agency ` for ` ` feed . calendar _ dates ` ` ."""
table = "calendar_dates" problems = [ ] # Preliminary checks if feed . calendar_dates is None : return problems f = feed . calendar_dates . copy ( ) problems = check_for_required_columns ( problems , table , f ) if problems : return format_problems ( problems , as_df = as_df ) if include_warnings : problems...
def fit ( self , X = None , u = None ) : """Fit X into an embedded space . Inputs X : array , shape ( n _ samples , n _ features ) u , s , v : svd decomposition of X ( optional ) Assigns embedding : array - like , shape ( n _ samples , n _ components ) Stores the embedding vectors . u , sv , v : singu...
X = X . copy ( ) if self . mode is 'parallel' : Xall = X . copy ( ) X = np . reshape ( Xall . copy ( ) , ( - 1 , Xall . shape [ - 1 ] ) ) # X - = X . mean ( axis = - 1 ) [ : , np . newaxis ] if ( ( u is None ) ) : nmin = min ( [ X . shape [ 0 ] , X . shape [ 1 ] ] ) nmin = np . minimum ( nmin - 1 , self...
def read_file ( cls , path ) : """Reads file at path and returns dict with separated frontmatter . See read ( ) for more info on dict return value ."""
with open ( path , encoding = "utf-8" ) as file : file_contents = file . read ( ) return cls . read ( file_contents )
def _build_model ( self , x ) : """Build the core model within the graph ."""
with tf . variable_scope ( 'init' ) : x = self . _conv ( 'init_conv' , x , 3 , x . shape [ 3 ] , 16 , self . _stride_arr ( 1 ) ) strides = [ 1 , 2 , 2 ] activate_before_residual = [ True , False , False ] if self . hps . use_bottleneck : res_func = self . _bottleneck_residual filters = [ 16 , 64 , 128 , 256...
def RqueryBM ( query_filter , query_items , query_attributes , dataset , database , host = rbiomart_host ) : """Queries BioMart . : param query _ filtery : one BioMart filter associated with the items being queried : param query _ items : list of items to be queried ( must assoiate with given filter ) : param...
biomaRt = importr ( "biomaRt" ) ensemblMart = biomaRt . useMart ( database , host = rbiomart_host ) ensembl = biomaRt . useDataset ( dataset , mart = ensemblMart ) df = biomaRt . getBM ( attributes = query_attributes , filters = query_filter , values = query_items , mart = ensembl ) output = [ tuple ( [ df [ j ] [ i ] ...
def GetFormatsWithSignatures ( cls , parser_filter_expression = None ) : """Retrieves the format specifications that have signatures . This method will create a specification store for parsers that define a format specification with signatures and a list of parser names for those that do not . Args : pars...
specification_store = specification . FormatSpecificationStore ( ) remainder_list = [ ] for parser_name , parser_class in cls . GetParsers ( parser_filter_expression = parser_filter_expression ) : format_specification = parser_class . GetFormatSpecification ( ) if format_specification and format_specification ....
def get_doctypes ( self , default_doctypes = None ) : """Returns the doctypes ( or mapping type names ) to use ."""
doctypes = self . type . get_mapping_type_name ( ) if isinstance ( doctypes , six . string_types ) : doctypes = [ doctypes ] return super ( S , self ) . get_doctypes ( default_doctypes = doctypes )
def running_as_string ( self , add_colour = True ) : '''Get the state of this context as an optionally coloured string . @ param add _ colour If True , ANSI colour codes will be added . @ return A string describing this context ' s running state .'''
with self . _mutex : if self . running : result = 'Running' , [ 'bold' , 'green' ] else : result = 'Stopped' , [ 'reset' ] if add_colour : return utils . build_attr_string ( result [ 1 ] , supported = add_colour ) + result [ 0 ] + utils . build_attr_string ( 'reset' , supported = add_colour ...
def list ( self , request , * args , ** kwargs ) : """Modified list view to driving listing from ES"""
search_kwargs = { "published" : False } for field_name in ( "before" , "after" , "status" , "published" ) : if field_name in get_query_params ( self . request ) : search_kwargs [ field_name ] = get_query_params ( self . request ) . get ( field_name ) for field_name in ( "tags" , "types" , "feature_types" ) ...
def ensure_col_dep_constraints ( self , M_c , M_r , T , X_L , X_D , dep_constraints , seed , max_rejections = 100 ) : """Ensures dependencey or indepdendency between columns . ` dep _ constraints ` is a list of where each entry is an ( int , int , bool ) tuple where the first two entries are column indices and ...
X_L_list , X_D_list , was_multistate = su . ensure_multistate ( X_L , X_D ) if was_multistate : num_states = len ( X_L_list ) else : num_states = 1 dependencies = [ ( c [ 0 ] , c [ 1 ] ) for c in dep_constraints if c [ 2 ] ] independencies = [ ( c [ 0 ] , c [ 1 ] ) for c in dep_constraints if not c [ 2 ] ] col_...
def linexand ( listoflists , columnlist , valuelist ) : """Returns the rows of a list of lists where col ( from columnlist ) = val ( from valuelist ) for EVERY pair of values ( columnlist [ i ] , valuelists [ i ] ) . len ( columnlist ) must equal len ( valuelist ) . Usage : linexand ( listoflists , columnlist...
if type ( columnlist ) not in [ ListType , TupleType ] : columnlist = [ columnlist ] if type ( valuelist ) not in [ ListType , TupleType ] : valuelist = [ valuelist ] criterion = '' for i in range ( len ( columnlist ) ) : if type ( valuelist [ i ] ) == StringType : critval = '\'' + valuelist [ i ] +...
def getOldestRequestTime ( self ) : """Returns the submitted _ at of the oldest unclaimed build request for this builder , or None if there are no build requests . @ returns : datetime instance or None , via Deferred"""
bldrid = yield self . getBuilderId ( ) unclaimed = yield self . master . data . get ( ( 'builders' , bldrid , 'buildrequests' ) , [ resultspec . Filter ( 'claimed' , 'eq' , [ False ] ) ] , order = [ 'submitted_at' ] , limit = 1 ) if unclaimed : return unclaimed [ 0 ] [ 'submitted_at' ]
def top_proportions ( mtx , n ) : """Calculates cumulative proportions of top expressed genes Parameters mtx : ` Union [ np . array , sparse . spmatrix ] ` Matrix , where each row is a sample , each column a feature . n : ` int ` Rank to calculate proportions up to . Value is treated as 1 - indexed , ` ...
if issparse ( mtx ) : if not isspmatrix_csr ( mtx ) : mtx = csr_matrix ( mtx ) # Allowing numba to do more return top_proportions_sparse_csr ( mtx . data , mtx . indptr , np . array ( n ) ) else : return top_proportions_dense ( mtx , n )
def method_returns_something ( self ) : '''Check if the docstrings method can return something . Bare returns , returns valued None and returns from nested functions are disconsidered . Returns bool Whether the docstrings method can return something .'''
def get_returns_not_on_nested_functions ( node ) : returns = [ node ] if isinstance ( node , ast . Return ) else [ ] for child in ast . iter_child_nodes ( node ) : # Ignore nested functions and its subtrees . if not isinstance ( child , ast . FunctionDef ) : child_returns = get_returns_not_o...
def get ( self , url , content_type = JSON_CONTENT_TYPE , ** kwargs ) : """Send GET request and check response . : param str method : The HTTP method to use . : param str url : The URL to make the request to . : raises txacme . client . ServerError : If server response body carries HTTP Problem ( draft - ie...
with LOG_JWS_GET ( ) . context ( ) : return ( DeferredContext ( self . _send_request ( u'GET' , url , ** kwargs ) ) . addCallback ( self . _check_response , content_type = content_type ) . addActionFinish ( ) )
def init ( spark_home = None , python_path = None , edit_rc = False , edit_profile = False ) : """Make pyspark importable . Sets environment variables and adds dependencies to sys . path . If no Spark location is provided , will try to find an installation . Parameters spark _ home : str , optional , defaul...
if not spark_home : spark_home = find ( ) if not python_path : python_path = os . environ . get ( 'PYSPARK_PYTHON' , sys . executable ) # ensure SPARK _ HOME is defined os . environ [ 'SPARK_HOME' ] = spark_home # ensure PYSPARK _ PYTHON is defined os . environ [ 'PYSPARK_PYTHON' ] = python_path if not os . env...
def retrieve_commands ( self , module ) : """Function smartly imports Command type classes given module Args module ( module ) : The module which Command classes will be extracted from Returns commands ( list ) : A list of Command instances Note : This function will not register any command class ...
commands = [ ] for name , obj in inspect . getmembers ( module ) : if name != 'Command' and 'Command' in name : if name != 'GlimCommand' : cobject = getattr ( module , name ) commands . append ( cobject ) return commands
def get_cell_shift ( flow_model ) : """Get flow direction induced cell shift dict . Args : flow _ model : Currently , " TauDEM " , " ArcGIS " , and " Whitebox " are supported ."""
assert flow_model . lower ( ) in FlowModelConst . d8_deltas return FlowModelConst . d8_deltas . get ( flow_model . lower ( ) )
def send_response ( self , msgid , error = None , result = None ) : """Send a response"""
msg = self . _encoder . create_response ( msgid , error , result ) self . _send_message ( msg )
def maximum_impact_estimation ( membership_matrix , max_iters = 1000 ) : """An expectation maximization technique that produces pathway definitions devoid of crosstalk . That is , each gene is mapped to the pathway in which it has the greatest predicted impact ; this removes any overlap between pathway defini...
# Initialize the probability vector as the sum of each column in the # membership matrix normalized by the sum of the entire membership matrix . # The probability at some index j in the vector represents the likelihood # that a pathway ( column ) j is defined by the current set of genes ( rows ) # in the membership mat...
def _condition_entries ( self ) : """Extracts any ARNs , Account Numbers , UserIDs , Usernames , CIDRs , VPCs , and VPC Endpoints from a condition block . Ignores any negated condition operators like StringNotLike . Ignores weak condition keys like referer , date , etc . Reason : A condition is meant to limit...
conditions = list ( ) condition = self . statement . get ( 'Condition' ) if not condition : return conditions key_mapping = { 'aws:sourcearn' : 'arn' , 'aws:sourceowner' : 'account' , 'aws:sourceaccount' : 'account' , 'aws:principalorgid' : 'org-id' , 'kms:calleraccount' : 'account' , 'aws:userid' : 'userid' , 'aws...
def parse_args ( self ) : """Parse our arguments ."""
# compile the parser self . _compile ( ) # clear the args self . args = None self . _self_event ( 'before_parse' , 'parse' , * sys . argv [ 1 : ] , ** { } ) # list commands / subcommands in argv cmds = [ cmd for cmd in sys . argv [ 1 : ] if not cmd . startswith ( "-" ) ] if ( len ( cmds ) > 0 and not utils . check_help...
def add_header ( self , key , value , ** params ) : """Add a header to the collection , including potential parameters . Args : key ( str ) : The name of the header value ( str ) : The value to store under that key params : Option parameters to be appended to the value , automatically formatting them in a...
key = self . escape ( key ) ci_key = key . casefold ( ) def quoted_params ( items ) : for p in items : param_name = self . escape ( p [ 0 ] ) param_val = self . de_quote ( self . escape ( p [ 1 ] ) ) yield param_name , param_val sorted_items = sorted ( params . items ( ) ) quoted_iter = ( '%...
def node ( key , default = None , edit = True ) : """Simple node tag : { % node ' page / title ' default = ' Lorem ipsum ' edit = True % }"""
node = cio . get ( key , default = default or u'' ) return lambda _ : render_node ( node , edit = edit )
def main ( ) : """Ideally we shouldn ' t lose the first second of events"""
time . sleep ( 1 ) with Input ( ) as input_generator : for e in input_generator : print ( repr ( e ) )
def _find_usage_vpc_links ( self ) : """Find usage on VPC Links . Update ` self . limits ` ."""
logger . debug ( 'Finding usage for VPC Links' ) link_count = 0 paginator = self . conn . get_paginator ( 'get_vpc_links' ) for resp in paginator . paginate ( ) : link_count += len ( resp [ 'items' ] ) self . limits [ 'VPC Links per account' ] . _add_current_usage ( link_count , aws_type = 'AWS::ApiGateway::VpcLink...
def get_stp_mst_detail_output_msti_msti_bridge_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_stp_mst_detail = ET . Element ( "get_stp_mst_detail" ) config = get_stp_mst_detail output = ET . SubElement ( get_stp_mst_detail , "output" ) msti = ET . SubElement ( output , "msti" ) instance_id_key = ET . SubElement ( msti , "instance-id" ) instance_id_key . text = kwargs . pop...
def bunchify ( x ) : """Recursively transforms a dictionary into a Bunch via copy . > > > b = bunchify ( { ' urmom ' : { ' sez ' : { ' what ' : ' what ' } } } ) > > > b . urmom . sez . what ' what ' bunchify can handle intermediary dicts , lists and tuples ( as well as their subclasses ) , but ymmv on cus...
if isinstance ( x , dict ) : return Bunch ( ( k , bunchify ( v ) ) for k , v in iteritems ( x ) ) elif isinstance ( x , ( list , tuple ) ) : return type ( x ) ( bunchify ( v ) for v in x ) else : return x
def connect ( self , mac : str ) : """Connect to a device ."""
from bluepy . btle import Peripheral match_result = re . search ( r'hci([\d]+)' , self . adapter ) if match_result is None : raise BluetoothBackendException ( 'Invalid pattern "{}" for BLuetooth adpater. ' 'Expetected something like "hci0".' . format ( self . adapter ) ) iface = int ( match_result . group ( 1 ) ) s...
def process ( self , sourcewords , debug = False ) : """Process a list of words , passing it to the server and realigning the output with the original words"""
if isinstance ( sourcewords , list ) or isinstance ( sourcewords , tuple ) : sourcewords_s = " " . join ( sourcewords ) else : sourcewords_s = sourcewords sourcewords = sourcewords . split ( ' ' ) self . socket . sendall ( sourcewords_s . encode ( self . encoding ) + '\n\0' ) if debug : print ( "Sent:" ...
def split_input ( self , input_filepath ) : """Splits the input file into the ' merge file ' ( which contains the EDUs ) and the ' parsetree file ' ."""
with open ( input_filepath , 'r' ) as input_file : input_file_str = input_file . read ( ) merge_file_str , parsetree_str = input_file_str . split ( 'ParentedTree' , 1 ) return merge_file_str , 'ParentedTree' + parsetree_str
def get_interpolated_value ( self , x ) : """Returns an interpolated y value for a particular x value . Args : x : x value to return the y value for Returns : Value of y at x"""
if len ( self . ydim ) == 1 : return get_linear_interpolated_value ( self . x , self . y , x ) else : return [ get_linear_interpolated_value ( self . x , self . y [ : , k ] , x ) for k in range ( self . ydim [ 1 ] ) ]
def initialize_concept_scheme ( rdf , cs , label , language , set_modified ) : """Initialize a concept scheme : Optionally add a label if the concept scheme doesn ' t have a label , and optionally add a dct : modified timestamp ."""
# check whether the concept scheme is unlabeled , and label it if possible labels = list ( rdf . objects ( cs , RDFS . label ) ) + list ( rdf . objects ( cs , SKOS . prefLabel ) ) if len ( labels ) == 0 : if not label : logging . warning ( "Concept scheme has no label(s). " "Use --label option to set the co...
def _filterDictToStr ( self , filterDict ) : """Converts friend filters to a string representation for transport ."""
values = [ ] for key , vals in filterDict . items ( ) : if key not in ( 'contentRating' , 'label' ) : raise BadRequest ( 'Unknown filter key: %s' , key ) values . append ( '%s=%s' % ( key , '%2C' . join ( vals ) ) ) return '|' . join ( values )
def factory ( coords , dependent_variables , helper_functions ) : """Fields factory generating specialized container build around a triflow Model and xarray . Parameters coords : iterable of str : coordinates name . First coordinate have to be shared with all variables dependent _ variables : iterable t...
Field = type ( 'Field' , BaseFields . __bases__ , dict ( BaseFields . __dict__ ) ) Field . _coords = coords Field . dependent_variables_info = dependent_variables Field . helper_functions_info = helper_functions Field . _var_info = [ * list ( Field . dependent_variables_info ) , * list ( Field . helper_functions_info )...
def get ( self , days ) : """* download a cache of ATLAS nights data * * * Key Arguments : * * - ` ` days ` ` - - the number of days data to cache locally * * Return : * * - None * * Usage : * * See class docstring"""
self . log . info ( 'starting the ``get`` method' ) self . _remove_processed_data ( ) archivePath = self . settings [ "atlas archive path" ] self . _update_day_tracker_table ( ) mjds = self . _determine_mjds_to_download ( days = days ) if len ( mjds ) == 0 : return dbConn = self . atlasMoversDBConn # DOWNLOAD THE D...
def suggest_type ( full_text , text_before_cursor ) : """Takes the full _ text that is typed so far and also the text before the cursor to suggest completion type and scope . Returns a tuple with a type of entity ( ' table ' , ' column ' etc ) and a scope . A scope for a column category will be a list of tabl...
word_before_cursor = last_word ( text_before_cursor , include = 'many_punctuations' ) identifier = None # here should be removed once sqlparse has been fixed try : # If we ' ve partially typed a word then word _ before _ cursor won ' t be an empty # string . In that case we want to remove the partially typed string bef...
def items ( self ) : """Returns a list of the items that are linked to this layer . : return [ < XNode > | | < XNodeConnection > , . . ]"""
from projexui . widgets . xnodewidget import XNode , XNodeConnection output = [ ] for item in self . scene ( ) . items ( ) : if not ( isinstance ( item , XNode ) or isinstance ( item , XNodeConnection ) ) : continue if item . layer ( ) == self : output . append ( item ) return output
def swap ( self , c2 ) : '''put the order of currencies as market standard'''
inv = False c1 = self if c1 . order > c2 . order : ct = c1 c1 = c2 c2 = ct inv = True return inv , c1 , c2
def split ( pipe , splitter , skip_empty = False ) : '''this function works a lot like groupby but splits on given patterns , the same behavior as str . split provides . if skip _ empty is True , split only yields pieces that have contents Example : splitting 1011101010101 by 10 returns , 11 , , , , 1 ...
splitter = tuple ( splitter ) len_splitter = len ( splitter ) pipe = iter ( pipe ) current = deque ( ) tmp = [ ] windowed = window ( pipe , len ( splitter ) ) for i in windowed : if i == splitter : skip ( windowed , len ( splitter ) - 1 ) yield list ( current ) current . clear ( ) tm...
def load_module ( self , path , changed_time , parser = None ) : """Attempts to load the specified module from a serialized , cached version . If that fails , the method returns none ."""
if settings . use_filesystem_cache == False : return None try : pickle_changed_time = self . _index [ path ] except KeyError : return None if ( changed_time is not None and pickle_changed_time < changed_time ) : # the pickle file is outdated return None target_path = self . _get_hashed_path ( path ) wit...
def getSoundFileDuration ( fn ) : '''Returns the duration of a wav file ( in seconds )'''
audiofile = wave . open ( fn , "r" ) params = audiofile . getparams ( ) framerate = params [ 2 ] nframes = params [ 3 ] duration = float ( nframes ) / framerate return duration
def file_hash ( load , fnd ) : '''Return a file hash , the hash type is set in the master config file'''
if 'env' in load : # " env " is not supported ; Use " saltenv " . load . pop ( 'env' ) if not all ( x in load for x in ( 'path' , 'saltenv' ) ) : return '' ret = { 'hash_type' : __opts__ [ 'hash_type' ] } relpath = fnd [ 'rel' ] path = fnd [ 'path' ] hashdest = os . path . join ( __opts__ [ 'cachedir' ] , 'hgfs...
def createPregeneratedGraphs ( ) : """Creates graphs based on previous runs of the scripts . Useful for editing graph format for writeups ."""
# Graph for computeMatchProbabilities ( kw = 32 , nTrials = 3000) listofNValues = [ 250 , 500 , 1000 , 1500 , 2000 , 2500 ] kw = 32 errors = np . array ( [ [ 3.65083333e-03 , 3.06166667e-04 , 1.89166667e-05 , 4.16666667e-06 , 1.50000000e-06 , 9.16666667e-07 ] , [ 2.44633333e-02 , 3.64491667e-03 , 3.16083333e-04 , 6.933...
def overall_rating ( object , category = "" ) : """Usage : { % overall _ rating obj [ category ] as var % }"""
try : ct = ContentType . objects . get_for_model ( object ) if category : rating = OverallRating . objects . get ( object_id = object . pk , content_type = ct , category = category_value ( object , category ) ) . rating or 0 else : rating = OverallRating . objects . filter ( object_id = obje...
def dist ( x1 , x2 = None , metric = 'sqeuclidean' , to_numpy = True ) : """Compute distance between samples in x1 and x2 on gpu Parameters x1 : np . array ( n1 , d ) matrix with n1 samples of size d x2 : np . array ( n2 , d ) , optional matrix with n2 samples of size d ( if None then x2 = x1) metric : ...
if x2 is None : x2 = x1 if metric == "sqeuclidean" : return euclidean_distances ( x1 , x2 , squared = True , to_numpy = to_numpy ) elif metric == "euclidean" : return euclidean_distances ( x1 , x2 , squared = False , to_numpy = to_numpy ) else : raise NotImplementedError
def _visit_te_shape ( self , shape : ShExJ . shapeExpr , visit_center : _VisitorCenter ) -> None : """Visit a shape expression that was reached through a triple expression . This , in turn , is used to visit additional triple expressions that are referenced by the Shape : param shape : Shape reached through tri...
if isinstance ( shape , ShExJ . Shape ) and shape . expression is not None : visit_center . f ( visit_center . arg_cntxt , shape . expression , self )
def _parse_sparkml_pipeline ( spark , scope , model , global_inputs , output_dict ) : '''The basic ideas of spark - ml parsing : 1 . Sequentially go though all stages defined in the considered spark - ml pipeline 2 . The output variables of one stage will be fed into its next stage as the inputs . : param sco...
for stage in model . stages : _parse_sparkml ( spark , scope , stage , global_inputs , output_dict )
def insert_many ( self , doc_or_docs , ** kwargs ) : """Insert method"""
check = kwargs . pop ( 'check' , True ) if check is True : for i in doc_or_docs : i = self . _valid_record ( i ) return self . __collect . insert_many ( doc_or_docs , ** kwargs )
def generate ( self ) : """Generate a list of strings representing the table in RST format ."""
header = ' ' . join ( '=' * self . width [ i ] for i in range ( self . w ) ) lines = [ ' ' . join ( row [ i ] . ljust ( self . width [ i ] ) for i in range ( self . w ) ) for row in self . rows ] return [ header ] + lines + [ header ]
def _get_width ( maxwidth ) : """Return the width of a single bar , when width of the page is given ."""
width = maxwidth / 3 if maxwidth <= 60 : width = maxwidth elif 60 < maxwidth <= 120 : width = maxwidth / 2 return width
def get_container_or_none ( self , type_ ) : """Returns reference to the class declaration or None ."""
type_ = type_traits . remove_alias ( type_ ) type_ = type_traits . remove_cv ( type_ ) utils . loggers . queries_engine . debug ( "Container traits: cleaned up search %s" , type_ ) if isinstance ( type_ , cpptypes . declarated_t ) : cls_declaration = type_traits . remove_alias ( type_ . declaration ) elif isinstanc...
def merge_in_place ( self , others ) : """Add the models present other predictors into the current predictor . Parameters others : list of Class1AffinityPredictor Other predictors to merge into the current predictor . Returns list of string : names of newly added models"""
new_model_names = [ ] for predictor in others : for model in predictor . class1_pan_allele_models : model_name = self . model_name ( "pan-class1" , len ( self . class1_pan_allele_models ) ) self . class1_pan_allele_models . append ( model ) row = pandas . Series ( collections . OrderedDict (...
def add_subnet ( self , subnet_type , quantity = None , vlan_id = None , version = 4 , test_order = False ) : """Orders a new subnet : param str subnet _ type : Type of subnet to add : private , public , global : param int quantity : Number of IPs in the subnet : param int vlan _ id : VLAN id for the subnet t...
package = self . client [ 'Product_Package' ] category = 'sov_sec_ip_addresses_priv' desc = '' if version == 4 : if subnet_type == 'global' : quantity = 0 category = 'global_ipv4' elif subnet_type == 'public' : category = 'sov_sec_ip_addresses_pub' else : category = 'static_ipv6_addr...
def random_possible_hands ( self ) : '''Returns random possible hands for all players , given the information known by the player whose turn it is . This information includes the current player ' s hand , the sizes of the other players ' hands , and the moves played by every player , including the passes . ...
# compute values that must be missing from # each hand , to rule out impossible hands missing = self . missing_values ( ) # get the dominoes that are in all of the other hands . note that , even # though we are ' looking ' at the other hands to get these dominoes , we # are not ' cheating ' because these dominoes could...
def package_filter ( config , message , package = None , * args , ** kw ) : """A particular package Use this rule to include messages that relate to a certain package ( * i . e . , nethack * ) ."""
package = kw . get ( 'package' , package ) if package : return package in fmn . rules . utils . msg2packages ( message , ** config )
def commit_confirmed ( name ) : '''. . versionadded : : 2019.2.0 Confirm a commit scheduled to be reverted via the ` ` revert _ in ` ` and ` ` revert _ at ` ` arguments from the : mod : ` net . load _ template < salt . modules . napalm _ network . load _ template > ` or : mod : ` net . load _ config < salt ...
confirmed = { 'name' : name , 'result' : None , 'changes' : { } , 'comment' : '' } if __opts__ [ 'test' ] : confirmed [ 'comment' ] = 'It would confirm commit #{}' . format ( name ) return confirmed ret = __salt__ [ 'net.confirm_commit' ] ( name ) confirmed . update ( ret ) return confirmed
def drift ( stack , region , profile ) : """Produce a CloudFormation drift report for the given stack ."""
logging . debug ( 'finding drift - stack: {}' . format ( stack ) ) logging . debug ( 'region: {}' . format ( region ) ) logging . debug ( 'profile: {}' . format ( profile ) ) tool = DriftTool ( Stack = stack , Region = region , Profile = profile , Verbose = True ) if tool . determine_drift ( ) : sys . exit ( 0 ) el...
def get_origin ( tp ) : """Get the unsubscripted version of a type . Supports generic types , Union , Callable , and Tuple . Returns None for unsupported types . Examples : : get _ origin ( int ) = = None get _ origin ( ClassVar [ int ] ) = = None get _ origin ( Generic ) = = Generic get _ origin ( Generi...
if NEW_TYPING : if isinstance ( tp , _GenericAlias ) : return tp . __origin__ if tp . __origin__ is not ClassVar else None if tp is Generic : return Generic return None if isinstance ( tp , GenericMeta ) : return _gorg ( tp ) if is_union_type ( tp ) : return Union return None
def get_squeeze_dims ( xarray_obj , dim : Union [ Hashable , Iterable [ Hashable ] , None ] = None , axis : Union [ int , Iterable [ int ] , None ] = None ) -> List [ Hashable ] : """Get a list of dimensions to squeeze out ."""
if dim is not None and axis is not None : raise ValueError ( 'cannot use both parameters `axis` and `dim`' ) if dim is None and axis is None : return [ d for d , s in xarray_obj . sizes . items ( ) if s == 1 ] if isinstance ( dim , Iterable ) and not isinstance ( dim , str ) : dim = list ( dim ) elif dim is...
def delete ( self , uri ) : """Method deletes a Fedora Object in the repository Args : uri ( str ) : URI of Fedora Object"""
try : self . connect ( uri , method = 'DELETE' ) return True except urllib . error . HTTPError : return False
def connect ( self , uuid_value , wait = None ) : """Connect to a specific device by its uuid Attempt to connect to a device that we have previously scanned using its UUID . If wait is not None , then it is used in the same was a scan ( wait ) to override default wait times with an explicit value . Args : ...
if self . connected : raise HardwareError ( "Cannot connect when we are already connected" ) if uuid_value not in self . _scanned_devices : self . scan ( wait = wait ) with self . _scan_lock : if uuid_value not in self . _scanned_devices : raise HardwareError ( "Could not find device to connect to b...
def write ( self , w , val ) : """Writes remaining part of TVP _ TYPE _ INFO structure , resuming from TVP _ COLMETADATA specs : https : / / msdn . microsoft . com / en - us / library / dd302994 . aspx https : / / msdn . microsoft . com / en - us / library / dd305261 . aspx https : / / msdn . microsoft . co...
if val . is_null ( ) : w . put_usmallint ( tds_base . TVP_NULL_TOKEN ) else : columns = self . _table_type . columns w . put_usmallint ( len ( columns ) ) for i , column in enumerate ( columns ) : w . put_uint ( column . column_usertype ) w . put_usmallint ( column . flags ) # TY...
def read_templates ( folder = None ) : """Load yaml templates from template folder . Return list of dicts . Use built - in templates if no folder is set . Parameters folder : str user defined folder where they stores their files , if None uses built - in templates Returns output : Instance of ` InvoiceT...
output = [ ] if folder is None : folder = pkg_resources . resource_filename ( __name__ , 'templates' ) for path , subdirs , files in os . walk ( folder ) : for name in sorted ( files ) : if name . endswith ( '.yml' ) : with open ( os . path . join ( path , name ) , 'rb' ) as f : ...
def buckingham_input ( self , structure , keywords , library = None , uc = True , valence_dict = None ) : """Gets a GULP input for an oxide structure and buckingham potential from library . Args : structure : pymatgen . core . structure . Structure keywords : GULP first line keywords . library ( Default =...
gin = self . keyword_line ( * keywords ) gin += self . structure_lines ( structure , symm_flg = not uc ) if not library : gin += self . buckingham_potential ( structure , valence_dict ) else : gin += self . library_line ( library ) return gin
def validate_nla ( nla , maxtype , policy ) : """https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / attr . c # L188. Positional arguments : nla - - nlattr class instance . maxtype - - integer . policy - - dictionary of nla _ policy class instances as values , with nla types as keys . ...
minlen = 0 type_ = nla_type ( nla ) if type_ < 0 or type_ > maxtype : return 0 pt = policy [ type_ ] if pt . type_ > NLA_TYPE_MAX : raise BUG if pt . minlen : minlen = pt . minlen elif pt . type_ != NLA_UNSPEC : minlen = nla_attr_minlen [ pt . type_ ] if nla_len ( nla ) < minlen : return - NLE_RANGE...
def GetParsersInformation ( cls ) : """Retrieves the parsers information . Returns : list [ tuple [ str , str ] ] : parser names and descriptions ."""
parsers_information = [ ] for _ , parser_class in cls . GetParsers ( ) : description = getattr ( parser_class , 'DESCRIPTION' , '' ) parsers_information . append ( ( parser_class . NAME , description ) ) return parsers_information
def delMatch ( self , rule_id ) : """Removes a message matching rule previously registered with addMatch"""
rule = self . match_rules [ rule_id ] d = self . callRemote ( '/org/freedesktop/DBus' , 'RemoveMatch' , interface = 'org.freedesktop.DBus' , destination = 'org.freedesktop.DBus' , body = [ rule ] , signature = 's' , ) def ok ( _ ) : del self . match_rules [ rule_id ] self . router . delMatch ( rule_id ) d . add...
def osculating_elements_of ( position , reference_frame = None ) : """Produce the osculating orbital elements for a position . The ` ` position ` ` should be an : class : ` ~ skyfield . positionlib . ICRF ` instance like that returned by the ` ` at ( ) ` ` method of any Solar System body , specifying a positi...
mu = GM_dict . get ( position . center , 0 ) + GM_dict . get ( position . target , 0 ) if reference_frame is not None : position_vec = Distance ( reference_frame . dot ( position . position . au ) ) velocity_vec = Velocity ( reference_frame . dot ( position . velocity . au_per_d ) ) else : position_vec = po...
def cause_repertoire ( self , mechanism , purview ) : """Return the cause repertoire ."""
return self . repertoire ( Direction . CAUSE , mechanism , purview )
def ParseFileObject ( self , parser_mediator , file_object ) : """Parses a text file - like object using a pyparsing definition . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . file _ object ( dfvfs . FileIO ) : file - l...
# TODO : self . _ line _ structures is a work - around and this needs # a structural fix . if not self . _line_structures : raise errors . UnableToParseFile ( 'Line structure undeclared, unable to proceed.' ) encoding = self . _ENCODING or parser_mediator . codepage text_file_object = text_file . TextFile ( file_ob...
def sign_digest_deterministic ( self , digest , hashfunc = None , sigencode = sigencode_string ) : """Calculates ' k ' from data itself , removing the need for strong random generator and producing deterministic ( reproducible ) signatures . See RFC 6979 for more details ."""
secexp = self . privkey . secret_multiplier k = rfc6979 . generate_k ( self . curve . generator . order ( ) , secexp , hashfunc , digest ) return self . sign_digest ( digest , sigencode = sigencode , k = k )
def generate ( self , data , width , height , padding = ( 0 , 0 , 0 , 0 ) , output_format = "png" , inverted = False ) : """Generates an identicon image with requested width , height , padding , and output format , optionally inverting the colours in the indeticon ( swapping background and foreground colours ) ...
# Calculate the digest , and get byte list . digest_byte_list = self . _data_to_digest_byte_list ( data ) # Create the matrix describing which block should be filled - in . matrix = self . _generate_matrix ( digest_byte_list ) # Determine the background and foreground colours . if output_format == "ascii" : foregro...
def get_distribution_names ( self ) : """Return all the distribution names known to this locator ."""
result = set ( ) for root , dirs , files in os . walk ( self . base_dir ) : for fn in files : if self . should_include ( fn , root ) : fn = os . path . join ( root , fn ) url = urlunparse ( ( 'file' , '' , pathname2url ( os . path . abspath ( fn ) ) , '' , '' , '' ) ) inf...
def reorg_crawl_tasks ( tasks , concurrency , logger = None ) : """Extract content returned by the crawler ` iter _ crawl _ tasks ` member method . : return : tuple made of the sub - tasks to executed , the epilogue task to execute or ` None ` is none was specified by the crawler , and the proper tasks co...
futures = tasks [ 'tasks' ] epilogue = tasks . get ( 'epilogue' ) custom_concurrency = tasks . get ( 'max_concurrent_tasks' , concurrency ) check_custom_concurrency ( concurrency , custom_concurrency , logger ) futures = list ( futures ) return futures , epilogue , concurrency
def Execute ( cmd , args , time_limit = - 1 , bypass_whitelist = False , daemon = False , use_client_context = False , cwd = None ) : """Executes commands on the client . This function is the only place where commands will be executed by the GRR client . This makes sure that all issued commands are compared to ...
if not bypass_whitelist and not IsExecutionWhitelisted ( cmd , args ) : # Whitelist doesn ' t contain this cmd / arg pair logging . info ( "Execution disallowed by whitelist: %s %s." , cmd , " " . join ( args ) ) return ( b"" , b"Execution disallowed by whitelist." , - 1 , - 1 ) if daemon : pid = os . fork ...
def _collect_result ( self ) : """Collect test result . Generate PDF , excel and pcap file"""
# generate pdf self . _browser . find_element_by_class_name ( 'save-pdf' ) . click ( ) time . sleep ( 1 ) try : dialog = self . _browser . find_element_by_id ( 'Testinfo' ) except : logger . exception ( 'Failed to get test info dialog.' ) else : if dialog . get_attribute ( 'aria-hidden' ) != 'false' : ...
def determine_when_discovered_sne_disappear ( log , redshiftArray , limitingMags , observedFrameLightCurveInfo , ripeDayList , plot = True ) : """* Given the observed frame lightcurve , determine when the discovered SNe become too faint to be detected . * * * Key Arguments : * * - ` ` log ` ` - - logger - ` `...
# # # # # # > IMPORTS # # # # # # # STANDARD LIB # # import math # # THIRD PARTY # # # # LOCAL APPLICATION # # # # # # # # > ACTION ( S ) # # # # # filters = [ 'g' , 'r' , 'i' , 'z' ] models = [ 'he80' , 'he100' , 'he130' ] disappearDayList = [ ] for item in range ( len ( redshiftArray ) ) : # log . info ( " I AM HERE ...
def gen_zonal_stats ( vectors , raster , layer = 0 , band = 1 , nodata = None , affine = None , stats = None , all_touched = False , categorical = False , category_map = None , add_stats = None , zone_func = None , raster_out = False , prefix = None , geojson_out = False , ** kwargs ) : """Zonal statistics of raste...
stats , run_count = check_stats ( stats , categorical ) # Handle 1.0 deprecations transform = kwargs . get ( 'transform' ) if transform : warnings . warn ( "GDAL-style transforms will disappear in 1.0. " "Use affine=Affine.from_gdal(*transform) instead" , DeprecationWarning ) if not affine : affine = Af...
def _get_wanted_channels ( wanted_sig_names , record_sig_names , pad = False ) : """Given some wanted signal names , and the signal names contained in a record , return the indices of the record channels that intersect . Parameters wanted _ sig _ names : list List of desired signal name strings record _ s...
if pad : return [ record_sig_names . index ( s ) if s in record_sig_names else None for s in wanted_sig_names ] else : return [ record_sig_names . index ( s ) for s in wanted_sig_names if s in record_sig_names ]
def _build_udf ( name , code , return_type , params , language , imports ) : """Creates the UDF part of a BigQuery query using its pieces Args : name : the name of the javascript function code : function body implementing the logic . return _ type : BigQuery data type of the function return . See supported ...
params = ',' . join ( [ '%s %s' % named_param for named_param in params ] ) imports = ',' . join ( [ 'library="%s"' % i for i in imports ] ) if language . lower ( ) == 'sql' : udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\n' + 'RETURNS {return_type}\n' + 'AS (\n' + '{code}\n' + ');' else : udf = 'CREATE TE...
def setGamepadFocusOverlay ( self , ulNewFocusOverlay ) : """Sets the current Gamepad focus overlay"""
fn = self . function_table . setGamepadFocusOverlay result = fn ( ulNewFocusOverlay ) return result
def update_dscp_marking_rule ( self , rule , policy , body = None ) : """Updates a DSCP marking rule ."""
return self . put ( self . qos_dscp_marking_rule_path % ( policy , rule ) , body = body )