signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def getFailedItems ( self ) : """Return an iterable of two - tuples of listeners which raised an exception from C { processItem } and the item which was passed as the argument to that method ."""
for failed in self . store . query ( BatchProcessingError , BatchProcessingError . processor == self ) : yield ( failed . listener , failed . item )
def plotDutyCycles ( dutyCycle , filePath ) : """Create plot showing histogram of duty cycles : param dutyCycle : ( torch tensor ) the duty cycle of each unit : param filePath : ( str ) Full filename of image file"""
_ , entropy = binaryEntropy ( dutyCycle ) bins = np . linspace ( 0.0 , 0.3 , 200 ) plt . hist ( dutyCycle , bins , alpha = 0.5 , label = 'All cols' ) plt . title ( "Histogram of duty cycles, entropy=" + str ( float ( entropy ) ) ) plt . xlabel ( "Duty cycle" ) plt . ylabel ( "Number of units" ) plt . savefig ( filePath...
def save_data ( self , trigger_id , ** data ) : """let ' s save the data : param trigger _ id : trigger ID from which to save data : param data : the data to check to be used and save : type trigger _ id : int : type data : dict : return : the status of the save statement : rtype : boolean"""
from th_tumblr . models import Tumblr title , content = super ( ServiceTumblr , self ) . save_data ( trigger_id , ** data ) # get the data of this trigger trigger = Tumblr . objects . get ( trigger_id = trigger_id ) # we suppose we use a tag property for this service status = self . tumblr . create_text ( blogname = tr...
def idfdiffs ( idf1 , idf2 ) : """return the diffs between the two idfs"""
thediffs = { } keys = idf1 . model . dtls # undocumented variable for akey in keys : idfobjs1 = idf1 . idfobjects [ akey ] idfobjs2 = idf2 . idfobjects [ akey ] names = set ( [ getobjname ( i ) for i in idfobjs1 ] + [ getobjname ( i ) for i in idfobjs2 ] ) names = sorted ( names ) idfobjs1 = sorted ...
def getResultsRange ( self ) : """Returns the valid result ranges for the analyses this Analysis Request contains . By default uses the result ranges defined in the Analysis Specification set in " Specification " field if any . Values manually set through ` ResultsRange ` field for any given analysis keywor...
specs_range = [ ] specification = self . getSpecification ( ) if specification : specs_range = specification . getResultsRange ( ) specs_range = specs_range and specs_range or [ ] # Override with AR ' s custom ranges ar_range = self . Schema ( ) . getField ( "ResultsRange" ) . get ( self ) if not ar_range : ...
def _double_single_alleles ( df , chrom ) : """Double any single alleles in the specified chromosome . Parameters df : pandas . DataFrame SNPs chrom : str chromosome of alleles to double Returns df : pandas . DataFrame SNPs with specified chromosome ' s single alleles doubled"""
# find all single alleles of the specified chromosome single_alleles = np . where ( ( df [ "chrom" ] == chrom ) & ( df [ "genotype" ] . str . len ( ) == 1 ) ) [ 0 ] # double those alleles df . ix [ single_alleles , "genotype" ] = df . ix [ single_alleles , "genotype" ] * 2 return df
def process ( self , metric ) : """Queue a metric . Flushing queue if batch size reached"""
if self . _match_metric ( metric ) : self . metrics . append ( metric ) if self . should_flush ( ) : self . _send ( )
def getBitmapFromRect ( self , x , y , w , h ) : """Capture the specified area of the ( virtual ) screen ."""
min_x , min_y , screen_width , screen_height = self . _getVirtualScreenRect ( ) img = self . _getVirtualScreenBitmap ( ) # TODO # Limit the coordinates to the virtual screen # Then offset so 0,0 is the top left corner of the image # ( Top left of virtual screen could be negative ) x1 = min ( max ( min_x , x ) , min_x +...
def logfbank ( signal , samplerate = 16000 , winlen = 0.025 , winstep = 0.01 , nfilt = 26 , nfft = 512 , lowfreq = 0 , highfreq = None , preemph = 0.97 , winfunc = lambda x : numpy . ones ( ( x , ) ) ) : """Compute log Mel - filterbank energy features from an audio signal . : param signal : the audio signal from ...
feat , energy = fbank ( signal , samplerate , winlen , winstep , nfilt , nfft , lowfreq , highfreq , preemph , winfunc ) return numpy . log ( feat )
def load ( self , container_name , slot , label = None , share = False ) : """Load a piece of labware by specifying its name and position . This method calls : py : meth : ` . ProtocolContext . load _ labware _ by _ name ` ; see that documentation for more information on arguments and return values . Calls to...
if share : raise NotImplementedError ( "Sharing not supported" ) try : name = self . LW_TRANSLATION [ container_name ] except KeyError : if container_name in self . LW_NO_EQUIVALENT : raise NotImplementedError ( "Labware {} is not supported" . format ( container_name ) ) elif container_name in (...
def capture_insert_from_model ( cls , table_name , record_id , * , exclude_fields = ( ) ) : """Create a fresh insert record from the current model state in the database . For read - write connected models , this will lead to the attempted creation of a corresponding object in Salesforce . Args : table _ nam...
exclude_cols = ( ) if exclude_fields : model_cls = get_connected_model_for_table_name ( table_name ) exclude_cols = cls . _fieldnames_to_colnames ( model_cls , exclude_fields ) raw_query = sql . SQL ( """ SELECT {schema}.hc_capture_insert_from_row( hstore({schema}.{table_name}.*), ...
def fight ( self , moves , print_console ) : """runs a series of fights - TODO switch order of who attacks first , as this has an effect on win rate over 1000 fights"""
for _ in range ( 1 , moves ) : # if i = = 1 and random . randint ( 1,100 ) > 50 : # randomly choose who moves first # player 1 result , dmg = self . calc_move ( self . c1 ) self . show_message ( self . c1 , self . c2 , result , dmg , print_console ) self . take_damage ( self . c2 , dmg ) if self . is_ch...
def acf ( trajs , stride = 1 , max_lag = None , subtract_mean = True , normalize = True , mean = None ) : '''Computes the ( combined ) autocorrelation function of multiple trajectories . Parameters trajs : list of ( * , N ) ndarrays the observable trajectories , N is the number of observables stride : int (...
if not isinstance ( trajs , list ) : trajs = [ trajs ] mytrajs = [ None ] * len ( trajs ) for i in range ( len ( trajs ) ) : if trajs [ i ] . ndim == 1 : mytrajs [ i ] = trajs [ i ] . reshape ( ( trajs [ i ] . shape [ 0 ] , 1 ) ) elif trajs [ i ] . ndim == 2 : mytrajs [ i ] = trajs [ i ] ...
def list ( self , friendly_name = values . unset , evaluate_worker_attributes = values . unset , worker_sid = values . unset , limit = None , page_size = None ) : """Lists TaskQueueInstance records from the API as a list . Unlike stream ( ) , this operation is eager and will load ` limit ` records into memory b...
return list ( self . stream ( friendly_name = friendly_name , evaluate_worker_attributes = evaluate_worker_attributes , worker_sid = worker_sid , limit = limit , page_size = page_size , ) )
def ignore_exceptions ( f ) : """Decorator catches and ignores any exceptions raised by this function ."""
@ functools . wraps ( f ) def wrapped ( * args , ** kwargs ) : try : return f ( * args , ** kwargs ) except : logging . exception ( "Ignoring exception in %r" , f ) return wrapped
def composite_multiscale_entropy ( time_series , sample_length , scale , tolerance = None ) : """Calculate the Composite Multiscale Entropy of the given time series . Args : time _ series : Time series for analysis sample _ length : Number of sequential points of the time series scale : Scale factor toler...
cmse = np . zeros ( ( 1 , scale ) ) for i in range ( scale ) : for j in range ( i ) : tmp = util_granulate_time_series ( time_series [ j : ] , i + 1 ) cmse [ i ] += sample_entropy ( tmp , sample_length , tolerance ) / ( i + 1 ) return cmse
def get_desired ( ) : """Populate ` ` DESIRED _ TEMPLATE ` ` with public members . If there are no members , does nothing . Returns : str : The " desired " contents of ` ` bezier . rst ` ` ."""
public_members = get_public_members ( ) if public_members : members = "\n :members: {}" . format ( ", " . join ( public_members ) ) else : members = "" return DESIRED_TEMPLATE . format ( members = members )
def create ( self , identity , role_sid = values . unset ) : """Create a new InviteInstance : param unicode identity : The ` identity ` value that identifies the new resource ' s User : param unicode role _ sid : The Role assigned to the new member : returns : Newly created InviteInstance : rtype : twilio ....
data = values . of ( { 'Identity' : identity , 'RoleSid' : role_sid , } ) payload = self . _version . create ( 'POST' , self . _uri , data = data , ) return InviteInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , channel_sid = self . _solution [ 'channel_sid' ] , )
def getMetadata ( self , objectId = None , ** filters ) : """Request metadata about a text or a collection : param objectId : Object Identifier to filter on : type objectId : str : param filters : Kwargs parameters . : type filters : dict : return : Collection"""
return self . get_or ( _cache_key ( "Nautilus" , self . name , "GetMetadata" , objectId ) , super ( ProtoNautilusCtsResolver , self ) . getMetadata , objectId )
def watch ( self , * names ) : """Override the default watch method to allow the user to pass RedisField objects as names , which will be translated to their real keys and passed to the default watch method"""
watches = [ ] for watch in names : if isinstance ( watch , RedisField ) : watch = watch . key watches . append ( watch ) return super ( _Pipeline , self ) . watch ( * watches )
def walk ( cls , top = "." , ext = ".abo" ) : """Scan directory tree starting from top , look for files with extension ` ext ` and parse timing data . Return : ( parser , paths , okfiles ) where ` parser ` is the new object , ` paths ` is the list of files found and ` okfiles ` is the list of files that hav...
paths = [ ] for root , dirs , files in os . walk ( top ) : for f in files : if f . endswith ( ext ) : paths . append ( os . path . join ( root , f ) ) parser = cls ( ) okfiles = parser . parse ( paths ) return parser , paths , okfiles
def write ( structure , name = None ) : """Writes a Structure in PDB format through PDBIO . Simplifies life . ."""
from Bio . PDB import PDBIO io = PDBIO ( ) io . set_structure ( structure ) if not name : s_name = structure . id else : s_name = name name = "%s.pdb" % s_name seed = 0 while 1 : if os . path . exists ( name ) : name = "%s_%s.pdb" % ( s_name , seed ) seed += 1 else : break io . s...
def get_attachment_data ( cls , session , attachment_id ) : """Return a specific attachment ' s data . Args : session ( requests . sessions . Session ) : Authenticated session . attachment _ id ( int ) : The ID of the attachment from which to get data . Returns : helpscout . models . AttachmentData : An...
return cls ( '/attachments/%d/data.json' % attachment_id , singleton = True , session = session , out_type = AttachmentData , )
def Set ( self , key , value ) : """Sets the key - value pair and dumps to the preferences file ."""
if not value == None : self . prefs [ key ] = value else : self . prefs . pop ( key ) self . Dump ( )
def msvc14_get_vc_env ( plat_spec ) : """Patched " distutils . _ msvccompiler . _ get _ vc _ env " for support extra compilers . Set environment without use of " vcvarsall . bat " . Known supported compilers Microsoft Visual C + + 14.0: Microsoft Visual C + + Build Tools 2015 ( x86 , x64 , arm ) Microso...
# Try to get environment from vcvarsall . bat ( Classical way ) try : return get_unpatched ( msvc14_get_vc_env ) ( plat_spec ) except distutils . errors . DistutilsPlatformError : # Pass error Vcvarsall . bat is missing pass # If error , try to set environment directly try : return EnvironmentInfo ( plat_sp...
def Q_weir_rectangular_SIA ( h1 , h2 , b , b1 ) : r'''Calculates the flow rate across rectangular weir from the height of the liquid above the crest of the notch , the liquid depth beneath it , and the width of the notch . Model from [ 1 ] _ as reproduced in [2 ] _ . Flow rate is given by : . . math : : ...
h = h1 + h2 Q = 0.544 * ( 1 + 0.064 * ( b / b1 ) ** 2 + ( 0.00626 - 0.00519 * ( b / b1 ) ** 2 ) / ( h1 + 0.0016 ) ) * ( 1 + 0.5 * ( b / b1 ) ** 4 * ( h1 / ( h1 + h2 ) ) ** 2 ) * b * g ** 0.5 * h ** 1.5 return Q
def mdaOnes ( shap , dtype = numpy . float , mask = None ) : """One constructor for masked distributed array @ param shap the shape of the array @ param dtype the numpy data type @ param mask mask array ( or None if all data elements are valid )"""
res = MaskedDistArray ( shap , dtype ) res [ : ] = 1 res . mask = mask return res
def enum ( self , desc , func = None , args = None , krgs = None ) : """Add a menu entry whose name will be an auto indexed number ."""
name = str ( len ( self . entries ) + 1 ) self . entries . append ( MenuEntry ( name , desc , func , args or [ ] , krgs or { } ) )
def open ( self ) : """Open or re - open file ."""
if self . _fh : return # file is open if isinstance ( self . _file , pathlib . Path ) : self . _file = str ( self . _file ) if isinstance ( self . _file , basestring ) : # file name self . _file = os . path . realpath ( self . _file ) self . _dir , self . _name = os . path . split ( self . _file ) s...
def describe_properties ( self ) : """Returns several arrays describing the properties supported by this format . An element with the given index in each array describes one property . Thus , the number of elements in each returned array is the same and corresponds to the number of supported properties . ...
( names , descriptions , types , flags , defaults ) = self . _call ( "describeProperties" ) types = [ DataType ( a ) for a in types ] return ( names , descriptions , types , flags , defaults )
def string_to_tokentype ( s ) : """Convert a string into a token type : : > > > string _ to _ token ( ' String . Double ' ) Token . Literal . String . Double > > > string _ to _ token ( ' Token . Literal . Number ' ) Token . Literal . Number > > > string _ to _ token ( ' ' ) Token Tokens that are alre...
if isinstance ( s , _TokenType ) : return s if not s : return Token node = Token for item in s . split ( '.' ) : node = getattr ( node , item ) return node
def heapremove ( heap , item ) : """Removes item from heap . ( This function is missing from the standard heapq package . )"""
i = heap . index ( item ) lastelt = heap . pop ( ) if item == lastelt : return heap [ i ] = lastelt heapq . _siftup ( heap , i ) if i : heapq . _siftdown ( heap , 0 , i )
def per_delta ( start : datetime , end : datetime , delta : timedelta ) : """Iterates over time range in steps specified in delta . : param start : Start of time range ( inclusive ) : param end : End of time range ( exclusive ) : param delta : Step interval : return : Iterable collection of [ ( start + td *...
curr = start while curr < end : curr_end = curr + delta yield curr , curr_end curr = curr_end
def main ( param_path = 'parameters.txt' ) : """Entry point function for analysis based on parameter files . Parameters param _ path : str Path to user - generated parameter file"""
# Confirm parameters file is present if not os . path . isfile ( param_path ) : raise IOError , "Parameter file not found at %s" % param_path # Get raw params and base options ( non - run - dependent options ) params , base_options = _get_params_base_options ( param_path ) # Configure and start logging # Done here ...
def process_form ( self , instance , field , form , empty_marker = None , emptyReturnsMarker = False , validating = True ) : """Return UIDs of the selected services"""
service_uids = form . get ( "uids" , [ ] ) return service_uids , { }
def feed_interval_set ( feed_id , parameters , interval , interval_ts ) : 'Set adaptive interval between checks for a feed .'
cache . set ( getkey ( T_INTERVAL , key = feed_interval_key ( feed_id , parameters ) ) , ( interval , interval_ts ) )
def generate_message_signature ( self , query_string ) : """Returns a HMAC - SHA - 1 signature for the given query string . http : / / goo . gl / R4O0E"""
# split for sorting pairs = query_string . split ( '&' ) pairs = [ pair . split ( '=' , 1 ) for pair in pairs ] pairs_sorted = sorted ( pairs ) pairs_string = '&' . join ( [ '=' . join ( pair ) for pair in pairs_sorted ] ) digest = hmac . new ( self . key , b ( pairs_string ) , hashlib . sha1 ) . digest ( ) signature =...
def get_series ( self , * args , ** kwargs ) : """Fetches lists of events . get / v1 / public / events : returns : SeriesDataWrapper > > > # Find all the series that involved Wolverine > > > # wolverine ' s id : 1009718 > > > m = Marvel ( public _ key , private _ key ) > > > response = m . get _ series ...
response = json . loads ( self . _call ( Series . resource_url ( ) , self . _params ( kwargs ) ) . text ) return SeriesDataWrapper ( self , response )
def process_values ( self ) : """Takes a set of angles and converts them to the x , y , z coordinates in the internal prepresentation of the class , ready for plotting . : param vals : the values that are being modelled ."""
if self . padding > 0 : channels = np . zeros ( ( self . vals . shape [ 0 ] , self . vals . shape [ 1 ] + self . padding ) ) channels [ : , 0 : self . vals . shape [ 0 ] ] = self . vals else : channels = self . vals vals_mat = self . skel . to_xyz ( channels . flatten ( ) ) self . vals = np . zeros_like ( v...
def run ( self , config , data_store , signal_server , workflow_id ) : """Run all autostart dags in the workflow . Only the dags that are flagged as autostart are started . Args : config ( Config ) : Reference to the configuration object from which the settings for the workflow are retrieved . data _ stor...
self . _workflow_id = workflow_id self . _celery_app = create_app ( config ) # pre - fill the data store with supplied arguments args = self . _parameters . consolidate ( self . _provided_arguments ) for key , value in args . items ( ) : data_store . get ( self . _workflow_id ) . set ( key , value ) # start all dag...
def smartSummarize ( requestContext , seriesList , intervalString , func = 'sum' ) : """Smarter experimental version of summarize ."""
results = [ ] delta = parseTimeOffset ( intervalString ) interval = to_seconds ( delta ) # Adjust the start time to fit an entire day for intervals > = 1 day requestContext = requestContext . copy ( ) tzinfo = requestContext [ 'tzinfo' ] s = requestContext [ 'startTime' ] if interval >= DAY : requestContext [ 'star...
def __descendants ( self ) : """Implementation for descendants , hacky workaround for _ _ getattr _ _ issues ."""
return itertools . chain ( self . contents , * [ c . descendants for c in self . children ] )
def _operate ( self , other , operation , inplace = True ) : """Gives the CanonicalDistribution operation ( product or divide ) with the other factor . The product of two canonical factors over the same scope X is simply : C ( K1 , h1 , g1 ) * C ( K2 , h2 , g2 ) = C ( K1 + K2 , h1 + h2 , g1 + g2) The divi...
if not isinstance ( other , CanonicalDistribution ) : raise TypeError ( "CanonicalDistribution object can only be multiplied or divided " "with an another CanonicalDistribution object. Got {other_type}, " "expected CanonicalDistribution." . format ( other_type = type ( other ) ) ) phi = self if inplace else self . ...
def als ( X , rank , ** kwargs ) : """RESCAL - ALS algorithm to compute the RESCAL tensor factorization . Parameters X : list List of frontal slices X _ k of the tensor X . The shape of each X _ k is ( ' N ' , ' N ' ) . X _ k ' s are expected to be instances of scipy . sparse . csr _ matrix rank : int ...
# - - - - - init options - - - - - ainit = kwargs . pop ( 'init' , _DEF_INIT ) maxIter = kwargs . pop ( 'maxIter' , _DEF_MAXITER ) conv = kwargs . pop ( 'conv' , _DEF_CONV ) lmbdaA = kwargs . pop ( 'lambda_A' , _DEF_LMBDA ) lmbdaR = kwargs . pop ( 'lambda_R' , _DEF_LMBDA ) lmbdaV = kwargs . pop ( 'lambda_V' , _DEF_LMBD...
def query_str_2_dict ( query_str ) : """将查询字符串 , 转换成字典 a = 123 & b = 456 { ' a ' : ' 123 ' , ' b ' : ' 456 ' } : param query _ str : : return :"""
if query_str : query_list = query_str . split ( '&' ) query_dict = { } for t in query_list : x = t . split ( '=' ) query_dict [ x [ 0 ] ] = x [ 1 ] else : query_dict = { } return query_dict
def merge_tracks ( self , track_indices = None , mode = 'sum' , program = 0 , is_drum = False , name = 'merged' , remove_merged = False ) : """Merge pianorolls of the tracks specified by ` track _ indices ` . The merged track will have program number as given by ` program ` and drum indicator as given by ` is _...
if mode not in ( 'max' , 'sum' , 'any' ) : raise ValueError ( "`mode` must be one of {'max', 'sum', 'any'}." ) merged = self [ track_indices ] . get_merged_pianoroll ( mode ) merged_track = Track ( merged , program , is_drum , name ) self . append_track ( merged_track ) if remove_merged : self . remove_tracks (...
def obj_2_str ( obj , tg_type = None ) : """Converts a python object into a string according to the given tango type : param obj : the object to be converted : type obj : : py : obj : ` object ` : param tg _ type : tango type : type tg _ type : : class : ` tango . CmdArgType ` : return : a string represen...
if tg_type is None : return obj if tg_type in _scalar_types : # scalar cases if is_pure_str ( obj ) : return obj elif is_non_str_seq ( obj ) : if not len ( obj ) : return "" obj = obj [ 0 ] return str ( obj ) # sequence cases if obj is None : return '' return '\n'...
def _rjust ( expr , width , fillchar = ' ' ) : """Filling left side of strings in the sequence or scalar with an additional character . Equivalent to str . rjust ( ) . : param expr : : param width : Minimum width of resulting string ; additional characters will be filled with ` fillchar ` : param fillchar :...
return _string_op ( expr , Rjust , _width = width , _fillchar = fillchar )
def camel_to_snake_case ( name ) : """Takes a camelCased string and converts to snake _ case ."""
pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])' return '_' . join ( map ( str . lower , re . findall ( pattern , name ) ) )
def _find_new_forms ( self , forms , num , data , files , locale , tz ) : """Acknowledge new forms created client - side ."""
fullname = self . _get_fullname ( num ) while has_data ( data , fullname ) or has_data ( files , fullname ) : f = self . _form_class ( data , files = files , locale = locale , tz = tz , prefix = fullname , backref = self . _backref ) forms . append ( f ) num += 1 fullname = self . _get_fullname ( num ) ...
def _pyfftw_check_args ( arr_in , arr_out , axes , halfcomplex , direction ) : """Raise an error if anything is not ok with in and out ."""
if len ( set ( axes ) ) != len ( axes ) : raise ValueError ( 'duplicate axes are not allowed' ) if direction == 'forward' : out_shape = list ( arr_in . shape ) if halfcomplex : try : out_shape [ axes [ - 1 ] ] = arr_in . shape [ axes [ - 1 ] ] // 2 + 1 except IndexError : ...
def trigger_actions ( self , subsystem ) : """Refresh all modules which subscribed to the given subsystem ."""
for py3_module , trigger_action in self . udev_consumers [ subsystem ] : if trigger_action in ON_TRIGGER_ACTIONS : self . py3_wrapper . log ( "%s udev event, refresh consumer %s" % ( subsystem , py3_module . module_full_name ) ) py3_module . force_update ( )
def get_logs ( self ) : """print logs from pod : return : str or None"""
try : api_response = self . core_api . read_namespaced_pod_log ( self . name , self . namespace ) logger . debug ( "Logs from pod: %s in namespace: %s" , self . name , self . namespace ) for line in api_response . split ( '\n' ) : logger . debug ( line ) return api_response except ApiException a...
def is_handleable ( self , device ) : # TODO : handle pathes in first argument """Check whether this device should be handled by udiskie . : param device : device object , block device path or mount path : returns : handleability Currently this just means that the device is removable and holds a filesystem ...
ignored = self . _ignore_device ( device ) # propagate handleability of parent devices : if ignored is None and device is not None : return self . is_handleable ( _get_parent ( device ) ) return not ignored
def _expand_slice ( self , indices ) : """Expands slices containing steps into a list ."""
keys = list ( self . data . keys ( ) ) expanded = [ ] for idx , ind in enumerate ( indices ) : if isinstance ( ind , slice ) and ind . step is not None : dim_ind = slice ( ind . start , ind . stop ) if dim_ind == slice ( None ) : condition = self . _all_condition ( ) elif dim_ind...
def parse_complex_fault_geometry ( node ) : """Parses a complex fault geometry node returning both the attributes and parameters in a dictionary"""
assert "complexFaultGeometry" in node . tag # Get general attributes geometry = { "intermediateEdges" : [ ] } for subnode in node : crds = subnode . nodes [ 0 ] . nodes [ 0 ] . text if "faultTopEdge" in subnode . tag : geometry [ "faultTopEdge" ] = numpy . array ( [ [ crds [ i ] , crds [ i + 1 ] , crds ...
def find ( s ) : """Find an amino acid whose name or abbreviation is s . @ param s : A C { str } amino acid specifier . This may be a full name , a 3 - letter abbreviation or a 1 - letter abbreviation . Case is ignored . return : An L { AminoAcid } instance or C { None } if no matching amino acid can be loc...
abbrev1 = None origS = s if ' ' in s : # Convert first word to title case , others to lower . first , rest = s . split ( ' ' , 1 ) s = first . title ( ) + ' ' + rest . lower ( ) else : s = s . title ( ) if s in NAMES : abbrev1 = s elif s in ABBREV3_TO_ABBREV1 : abbrev1 = ABBREV3_TO_ABBREV1 [ s ] eli...
def next_day ( self ) : """Return the HDate for the next day ."""
return HDate ( self . gdate + datetime . timedelta ( 1 ) , self . diaspora , self . hebrew )
def remove_network_from_bgp_speaker ( self , speaker_id , body = None ) : """Removes a network from BGP speaker ."""
return self . put ( ( self . bgp_speaker_path % speaker_id ) + "/remove_gateway_network" , body = body )
def saveState ( self , stateObj ) : """Utility methos to save plugin state stored in stateObj to persistent storage to permit access to previous state in subsequent plugin runs . Any object that can be pickled and unpickled can be used to store the plugin state . @ param stateObj : Object that stores plugin...
try : fp = open ( self . _stateFile , 'w' ) pickle . dump ( stateObj , fp ) except : raise IOError ( "Failure in storing plugin state in file: %s" % self . _stateFile ) return True
def html_list ( data ) : """Convert dict into formatted HTML ."""
if data is None : return None as_li = lambda v : "<li>%s</li>" % v items = [ as_li ( v ) for v in data ] return mark_safe ( "<ul>%s</ul>" % '' . join ( items ) )
def get_id ( self , request_data , parameter_name = 'id' ) : """Extract an integer from request data ."""
if parameter_name not in request_data : raise ParseError ( "`{}` parameter is required" . format ( parameter_name ) ) id_parameter = request_data . get ( parameter_name , None ) if not isinstance ( id_parameter , int ) : raise ParseError ( "`{}` parameter not an integer" . format ( parameter_name ) ) return id_...
def reverse_set ( self , subid , ipaddr , entry , params = None ) : '''/ v1 / server / reverse _ set _ ipv4 POST - account Set a reverse DNS entry for an IPv4 address of a virtual machine . Upon success , DNS changes may take 6-12 hours to become active . Link : https : / / www . vultr . com / api / # serve...
params = update_params ( params , { 'SUBID' : subid , 'ip' : ipaddr , 'entry' : entry } ) return self . request ( '/v1/server/reverse_set_ipv4' , params , 'POST' )
def format_error ( error : "GraphQLError" ) -> dict : """Format a GraphQL error Given a GraphQLError , format it according to the rules described by the " Response Format , Errors " section of the GraphQL Specification ."""
if not error : raise ValueError ( "Received null or undefined error." ) formatted : Dict [ str , Any ] = dict ( # noqa : E701 ( pycqa / flake8#394) message = error . message or "An unknown error occurred." , locations = error . locations , path = error . path , ) if error . extensions : formatted . update ( ext...
def download ( url , path , verbose = None , blocksize = 128 * 1024 ) : """Download a file from a URL , possibly displaying a progress bar . Saves the output to the file named by ` path ` . If the URL cannot be downloaded or the file cannot be written , an IOError is raised . Normally , if the standard error ...
tempname = path + '.download' try : connection = urlopen ( url ) except Exception as e : raise IOError ( 'cannot get {0} because {1}' . format ( url , e ) ) if verbose is None : verbose = sys . stderr . isatty ( ) bar = None if verbose : if _running_IDLE : print ( 'Downloading {0} ...' . format ...
def has_dirty_state_machine ( self ) : """Checks if one of the registered sm has the marked _ dirty flag set to True ( i . e . the sm was recently modified , without being saved ) : return : True if contains state machine that is marked dirty , False otherwise ."""
for sm in self . state_machines . values ( ) : if sm . marked_dirty : return True return False
def add_updates ( self , messages : Iterable [ CachedMessage ] , expunged : Iterable [ int ] ) -> None : """Update the messages in the selected mailboxes . The ` ` messages ` ` should include non - expunged messages in the mailbox that should be checked for updates . The ` ` expunged ` ` argument is the set of ...
self . _messages . _update ( messages ) self . _messages . _remove ( expunged , self . _hide_expunged ) if not self . _hide_expunged : self . _session_flags . remove ( expunged )
def content_disposition ( self ) -> Optional [ ContentDispositionHeader ] : """The ` ` Content - Disposition ` ` header ."""
try : return cast ( ContentDispositionHeader , self [ b'content-disposition' ] [ 0 ] ) except ( KeyError , IndexError ) : return None
def add_row ( self , row_data , resize_x = True ) : """Adds a row at the end of the table"""
if not resize_x : self . _check_row_size ( row_data ) self . body ( Tr ( ) ( Td ( ) ( cell ) for cell in row_data ) ) return self
def create_attachment ( self , upload_stream , project , wiki_identifier , name , ** kwargs ) : """CreateAttachment . Creates an attachment in the wiki . : param object upload _ stream : Stream to upload : param str project : Project ID or project name : param str wiki _ identifier : Wiki Id or name . : p...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if wiki_identifier is not None : route_values [ 'wikiIdentifier' ] = self . _serialize . url ( 'wiki_identifier' , wiki_identifier , 'str' ) query_parameters = { } if name is not None...
def type_map_directive_reducer ( map_ : TypeMap , directive : GraphQLDirective = None ) -> TypeMap : """Reducer function for creating the type map from given directives ."""
# Directives are not validated until validate _ schema ( ) is called . if not is_directive ( directive ) : return map_ directive = cast ( GraphQLDirective , directive ) return reduce ( lambda prev_map , arg : type_map_reducer ( prev_map , arg . type ) , # type : ignore directive . args . values ( ) , map_ , )
def writeXMLFile ( filename , content ) : """Used only for debugging to write out intermediate files"""
xmlfile = open ( filename , 'w' ) # pretty print content = etree . tostring ( content , pretty_print = True ) xmlfile . write ( content ) xmlfile . close ( )
def hr ( color ) : """Colored horizontal rule printer / logger factory . The resulting function prints an entire terminal row with the given symbol repeated . It ' s a terminal version of the HTML ` ` < hr / > ` ` ."""
logger = log ( color ) return lambda symbol : logger ( symbol * terminal_size . usable_width )
def set_win_wallpaper ( img ) : """Set the wallpaper on Windows ."""
# There ' s a different command depending on the architecture # of Windows . We check the PROGRAMFILES envar since using # platform is unreliable . if "x86" in os . environ [ "PROGRAMFILES" ] : ctypes . windll . user32 . SystemParametersInfoW ( 20 , 0 , img , 3 ) else : ctypes . windll . user32 . SystemParamete...
def delete_applications ( self , applications ) : """Requires : account ID , application ID ( or name ) . Input should be a dictionary { ' app _ id ' : 1234 , ' app ' : ' My Application ' } Returns : list of failed deletions ( if any ) Endpoint : api . newrelic . com Errors : None Explicit , failed deletion...
endpoint = "https://api.newrelic.com" uri = "{endpoint}/api/v1/accounts/{account_id}/applications/delete.xml" . format ( endpoint = endpoint , account_id = self . account_id ) payload = applications response = self . _make_post_request ( uri , payload ) failed_deletions = { } for application in response . findall ( './...
def _run_task ( task , start_message , finished_message ) : """Tasks a task from tasks . py and runs through the commands on the server"""
# Get the hosts and record the start time env . hosts = fabconf [ 'EC2_INSTANCES' ] start = time . time ( ) # Check if any hosts exist if env . hosts == [ ] : print ( "There are EC2 instances defined in project_conf.py, please add some instances and try again" ) print ( "or run 'fab spawn_instance' to create an...
def annotate_indices ( self , sentence ) : """Add clause indexes to already annotated sentence ."""
max_index = 0 max_depth = 1 stack_of_indexes = [ max_index ] for token in sentence : if CLAUSE_ANNOT not in token : token [ CLAUSE_IDX ] = stack_of_indexes [ - 1 ] else : # Alustavad märgendused for annotation in token [ CLAUSE_ANNOT ] : if annotation == "KIILU_ALGUS" : # Liigume su...
def index_of ( self , child ) : """Returns the given child index . Usage : : > > > node _ a = AbstractCompositeNode ( " MyNodeA " ) > > > node _ b = AbstractCompositeNode ( " MyNodeB " , node _ a ) > > > node _ c = AbstractCompositeNode ( " MyNodeC " , node _ a ) > > > node _ a . index _ of ( node _ b ) ...
for i , item in enumerate ( self . __children ) : if child is item : return i
def team_absent ( name , profile = "github" , ** kwargs ) : '''Ensure a team is absent . Example : . . code - block : : yaml ensure team test is present in github : github . team _ absent : - name : ' test ' The following parameters are required : name This is the name of the team in the organizatio...
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } target = __salt__ [ 'github.get_team' ] ( name , profile = profile , ** kwargs ) if not target : ret [ 'comment' ] = 'Team {0} does not exist' . format ( name ) ret [ 'result' ] = True return ret else : if __opts__ [ 'test' ] :...
def _check_lal_pars ( p ) : """Create a laldict object from the dictionary of waveform parameters Parameters p : dictionary The dictionary of lalsimulation paramaters Returns laldict : LalDict The lal type dictionary to pass to the lalsimulation waveform functions ."""
lal_pars = lal . CreateDict ( ) # nonGRparams can be straightforwardly added if needed , however they have to # be invoked one by one if p [ 'phase_order' ] != - 1 : lalsimulation . SimInspiralWaveformParamsInsertPNPhaseOrder ( lal_pars , int ( p [ 'phase_order' ] ) ) if p [ 'amplitude_order' ] != - 1 : lalsimu...
def serialize ( self ) : """: returns : A dictionary representation of the statement object . : rtype : dict"""
data = { } for field_name in self . get_statement_field_names ( ) : format_method = getattr ( self , 'get_{}' . format ( field_name ) , None ) if format_method : data [ field_name ] = format_method ( ) else : data [ field_name ] = getattr ( self , field_name ) return data
def freeze ( self ) : """Freeze all settings so that they can ' t be altered"""
self . target . disable ( ) self . filter . configure ( state = 'disable' ) self . prog_ob . configure ( state = 'disable' ) self . pi . configure ( state = 'disable' ) self . observers . configure ( state = 'disable' ) self . comment . configure ( state = 'disable' )
def takes_arg ( obj , arg : str ) -> bool : """Checks whether the provided obj takes a certain arg . If it ' s a class , we ' re really checking whether its constructor does . If it ' s a function or method , we ' re checking the object itself . Otherwise , we raise an error ."""
if inspect . isclass ( obj ) : signature = inspect . signature ( obj . __init__ ) elif inspect . ismethod ( obj ) or inspect . isfunction ( obj ) : signature = inspect . signature ( obj ) else : raise ConfigurationError ( f"object {obj} is not callable" ) return arg in signature . parameters
def volume_attach ( name , server_name , device = '/dev/xvdb' , profile = None , timeout = 300 , ** kwargs ) : '''Attach a block storage volume name Name of the new volume to attach server _ name Name of the server to attach to device Name of the device on the server profile Profile to build on CL...
conn = _auth ( profile , ** kwargs ) return conn . volume_attach ( name , server_name , device , timeout )
def to_python ( self , value ) : """Returns a datetime . tzinfo instance for the value ."""
# pylint : disable = newstyle value = super ( TimeZoneField , self ) . to_python ( value ) if not value : return value try : return pytz . timezone ( str ( value ) ) except pytz . UnknownTimeZoneError : raise ValidationError ( message = self . error_messages [ 'invalid' ] , code = 'invalid' , params = { 'va...
def hdf5_col ( self , chain = - 1 ) : """Return a pytables column object . : Parameters : chain : integer The index of the chain . . . note : : This method is specific to the ` ` hdf5 ` ` backend ."""
return self . db . _tables [ chain ] . colinstances [ self . name ]
def get_relationship ( self , session , query , api_type , obj_id , rel_key ) : """Fetch a collection of related resource types and ids . : param session : SQLAlchemy session : param query : Dict of query args : param api _ type : Type of the resource : param obj _ id : ID of the resource : param rel _ ke...
resource = self . _fetch_resource ( session , api_type , obj_id , Permissions . VIEW ) if rel_key not in resource . __jsonapi_map_to_py__ . keys ( ) : raise RelationshipNotFoundError ( resource , resource , rel_key ) py_key = resource . __jsonapi_map_to_py__ [ rel_key ] relationship = self . _get_relationship ( res...
def _add_missing_routes ( route_spec , failed_ips , questionable_ips , chosen_routers , vpc_info , con , routes_in_rts ) : """Iterate over route spec and add all the routes we haven ' t set yet . This relies on being told what routes we HAVE already . This is passed in via the routes _ in _ rts dict . Further...
for dcidr , hosts in route_spec . items ( ) : new_router_ip = chosen_routers . get ( dcidr ) # Look at the routes we have seen in each of the route tables . for rt_id , dcidr_list in routes_in_rts . items ( ) : if dcidr not in dcidr_list : if not new_router_ip : # We haven ' t chosen a t...
def main ( ) : """NAME vgpmap _ magic . py DESCRIPTION makes a map of vgps and a95 / dp , dm for site means in a pmag _ results table SYNTAX vgpmap _ magic . py [ command line options ] OPTIONS - h prints help and quits - eye ELAT ELON [ specify eyeball location ] , default is 90 . , 0. - f FILE p...
dir_path = '.' res , ages = 'c' , 0 plot = 0 proj = 'ortho' results_file = 'pmag_results.txt' ell , flip = 0 , 0 lat_0 , lon_0 = 90. , 0. fmt = 'pdf' sym , size = 'ro' , 8 rsym , rsize = 'g^' , 8 anti = 0 fancy = 0 coord = "" if '-WD' in sys . argv : ind = sys . argv . index ( '-WD' ) dir_path = sys . argv [ in...
def _callback ( self , handle , event , channel , arg ) : """Is called if a working event occurred . : param int handle : USB - CAN - Handle returned by the function : meth : ` init _ hardware ` . : param int event : Event type . : param int channel : CAN channel ( : data : ` Channel . CHANNEL _ CH0 ` , : d...
log . debug ( "Handle: %s, Event: %s, Channel: %s" % ( handle , event , channel ) ) if event == CbEvent . EVENT_INITHW : self . init_hw_event ( ) elif event == CbEvent . EVENT_init_can : self . init_can_event ( channel ) elif event == CbEvent . EVENT_RECEIVE : self . can_msg_received_event ( channel ) elif ...
async def source ( dev : Device , scheme ) : """List available sources . If no ` scheme ` is given , will list sources for all sc hemes ."""
if scheme is None : schemes = await dev . get_schemes ( ) schemes = [ scheme . scheme for scheme in schemes ] # noqa : T484 else : schemes = [ scheme ] for schema in schemes : try : sources = await dev . get_source_list ( schema ) except SongpalException as ex : click . echo ( "U...
def repartitionAndSortWithinPartitions ( self , numPartitions = None , partitionFunc = portable_hash , ascending = True , keyfunc = lambda x : x ) : """Repartition the RDD according to the given partitioner and , within each resulting partition , sort records by their keys . > > > rdd = sc . parallelize ( [ ( 0...
if numPartitions is None : numPartitions = self . _defaultReducePartitions ( ) memory = _parse_memory ( self . ctx . _conf . get ( "spark.python.worker.memory" , "512m" ) ) serializer = self . _jrdd_deserializer def sortPartition ( iterator ) : sort = ExternalSorter ( memory * 0.9 , serializer ) . sorted re...
def add ( self , output , module , package = None ) : """Add output to"""
super ( Outputs , self ) . add ( output , module , package ) # only update layer info if it is missing ! if output not in self . layer : # copy output source parameters to : attr : ` Layer . layer ` self . layer [ output ] = { 'module' : module , 'package' : package } # instantiate the output object self . objects ...
def y_axis_transform ( compound , new_origin = None , point_on_y_axis = None , point_on_xy_plane = None ) : """Move a compound such that the y - axis lies on specified points . Parameters compound : mb . Compound The compound to move . new _ origin : mb . Compound or like - like of size 3 , optional , defau...
x_axis_transform ( compound , new_origin = new_origin , point_on_x_axis = point_on_y_axis , point_on_xy_plane = point_on_xy_plane ) rotate_around_z ( compound , np . pi / 2 )
def query_job_ids ( build_version , config , log ) : """Get one or more job IDs and their status associated with a build version . Filters jobs by name if - - job - name is specified . : raise HandledError : On invalid JSON data or bad job name . : param str build _ version : AppVeyor build version from query...
url = '/projects/{0}/{1}/build/{2}' . format ( config [ 'owner' ] , config [ 'repo' ] , build_version ) # Query version . log . debug ( 'Querying AppVeyor version API for %s/%s at %s...' , config [ 'owner' ] , config [ 'repo' ] , build_version ) json_data = query_api ( url ) if 'build' not in json_data : log . erro...
def get_transaction ( self , transaction_id ) : """Returns a Transaction object from the block store by its id . Params : transaction _ id ( str ) : The header _ signature of the desired txn Returns : Transaction : The specified transaction Raises : ValueError : The transaction is not in the block store...
payload = self . _get_data_by_id ( transaction_id , 'commit_store_get_transaction' ) txn = Transaction ( ) txn . ParseFromString ( payload ) return txn
def _send_view_change_done_message ( self ) : """Sends ViewChangeDone message to other protocol participants"""
new_primary_name = self . provider . next_primary_name ( ) ledger_summary = self . provider . ledger_summary ( ) message = ViewChangeDone ( self . view_no , new_primary_name , ledger_summary ) logger . info ( "{} is sending ViewChangeDone msg to all : {}" . format ( self , message ) ) self . send ( message ) self . _on...
async def set_pin_mode ( self , pin_number , pin_state , callback = None , callback_type = None ) : """This method sets the pin mode for the specified pin . For Servo , use servo _ config ( ) instead . : param pin _ number : Arduino Pin Number : param pin _ state : INPUT / OUTPUT / ANALOG / PWM / PULLUP - for...
# There is a potential start up race condition when running pymata3. # This is a workaround for that race condition if not len ( self . digital_pins ) : await asyncio . sleep ( 2 ) if callback : if pin_state == Constants . INPUT : self . digital_pins [ pin_number ] . cb = callback self . digital...
def abbreviate_paths ( pathspec , named_paths ) : """Given a dict of ( pathname , path ) pairs , removes any prefix shared by all pathnames . Helps keep menu items short yet unambiguous ."""
from os . path import commonprefix , dirname , sep prefix = commonprefix ( [ dirname ( name ) + sep for name in named_paths . keys ( ) ] + [ pathspec ] ) return OrderedDict ( [ ( name [ len ( prefix ) : ] , path ) for name , path in named_paths . items ( ) ] )
def aggregate ( self , pipeline , ** kwargs ) : """Execute an aggregation pipeline on this collection . The aggregation can be run on a secondary if the client is connected to a replica set and its ` ` read _ preference ` ` is not : attr : ` PRIMARY ` . : Parameters : - ` pipeline ` : a single command or li...
cursor_class = create_class_with_framework ( AgnosticLatentCommandCursor , self . _framework , self . __module__ ) # Latent cursor that will send initial command on first " async for " . return cursor_class ( self , self . _async_aggregate , pipeline , ** unwrap_kwargs_session ( kwargs ) )