signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def to_lower ( cls ) : # NOQA """Return a list of all the fields that should be lowercased This is done on fields with ` lower = True ` ."""
email = cls . get_fields_by_class ( EmailType ) lower = cls . get_fields_by_prop ( 'lower' , True ) + email return list ( set ( email + lower ) )
def describe ( self , bucket , descriptor = None ) : """https : / / github . com / frictionlessdata / tableschema - pandas - py # storage"""
# Set descriptor if descriptor is not None : self . __descriptors [ bucket ] = descriptor # Get descriptor else : descriptor = self . __descriptors . get ( bucket ) if descriptor is None : dataframe = self . __dataframes [ bucket ] descriptor = self . __mapper . restore_descriptor ( datafram...
def addTask ( self , task ) : """Add a task to the task set ."""
with self . regcond : self . taskset . append ( task ) task . add_callback ( 'resolved' , self . child_done , self . numtasks ) self . numtasks += 1 self . count += 1 task . initialize ( self ) task . start ( )
def get_realtime_alarm ( username , auth , url ) : """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API : param username OpeatorName , String type . Required . Default Value " admin " . Checks the operator has the privileges to view the Real - Time Alarms . : param auth : requests au...
f_url = url + "/imcrs/fault/faultRealTime?operatorName=" + username response = requests . get ( f_url , auth = auth , headers = HEADERS ) try : realtime_alarm_list = ( json . loads ( response . text ) ) return realtime_alarm_list [ 'faultRealTime' ] [ 'faultRealTimeList' ] except requests . exceptions . Request...
def from_array ( array ) : """Deserialize a new ShippingOption from a given dictionary . : return : new ShippingOption instance . : rtype : ShippingOption"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) data = { } data [ 'id' ] = u ( array . get ( 'id' ) ) data [ 'title' ] = u ( array . get ( 'title' ) ) data [ 'prices' ] = LabeledPrice . from_array_list ( array . get ( 'prices' ) , list_level = 1 ...
def print_functions ( self , d ) : """Export all the functions to dot files"""
for c in self . contracts : for f in c . functions : f . cfg_to_dot ( os . path . join ( d , '{}.{}.dot' . format ( c . name , f . name ) ) )
def _read_state_variables ( self ) : """Reads the stateVariable information from the xml - file . The information we like to extract are name and dataType so we can assign them later on to FritzActionArgument - instances . Returns a dictionary : key : value = name : dataType"""
nodes = self . root . iterfind ( './/ns:stateVariable' , namespaces = { 'ns' : self . namespace } ) for node in nodes : key = node . find ( self . nodename ( 'name' ) ) . text value = node . find ( self . nodename ( 'dataType' ) ) . text self . state_variables [ key ] = value
def update_policy_configuration ( self , configuration , project , configuration_id ) : """UpdatePolicyConfiguration . Update a policy configuration by its ID . : param : class : ` < PolicyConfiguration > < azure . devops . v5_0 . policy . models . PolicyConfiguration > ` configuration : The policy configuratio...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if configuration_id is not None : route_values [ 'configurationId' ] = self . _serialize . url ( 'configuration_id' , configuration_id , 'int' ) content = self . _serialize . body ( c...
def checked_open ( filename , log = None , quiet = False ) : """Open and validate the given metafile . Optionally provide diagnostics on the passed logger , for invalid metafiles , which then just cause a warning but no exception . " quiet " can supress that warning ."""
with open ( filename , "rb" ) as handle : raw_data = handle . read ( ) data = bencode . bdecode ( raw_data ) try : check_meta ( data ) if raw_data != bencode . bencode ( data ) : raise ValueError ( "Bad bencoded data - dict keys out of order?" ) except ValueError as exc : if log : # Warn about i...
def sign_up ( self ) : """Signs up a participant for the experiment . This is done using a POST request to the / participant / endpoint ."""
self . log ( "Bot player signing up." ) self . subscribe_to_quorum_channel ( ) while True : url = ( "{host}/participant/{self.worker_id}/" "{self.hit_id}/{self.assignment_id}/" "debug?fingerprint_hash={hash}&recruiter=bots:{bot_name}" . format ( host = self . host , self = self , hash = uuid . uuid4 ( ) . hex , bot...
def compose_all ( stream , Loader = Loader ) : """Parse all YAML documents in a stream and produce corresponding representation trees ."""
loader = Loader ( stream ) try : while loader . check_node ( ) : yield loader . get_node ( ) finally : loader . dispose ( )
def write ( self , obj , ** kwargs ) : """we are going to write this as a frame table"""
name = obj . name or 'values' obj , self . levels = self . validate_multiindex ( obj ) cols = list ( self . levels ) cols . append ( name ) obj . columns = cols return super ( ) . write ( obj = obj , ** kwargs )
def _calc_F_guess ( self , alpha , predictions , probabilities ) : """Calculate an estimate of the F - measure based on the scores"""
num = np . sum ( predictions . T * probabilities , axis = 1 ) den = np . sum ( ( 1 - alpha ) * probabilities + alpha * predictions . T , axis = 1 ) F_guess = num / den # Ensure guess is not undefined F_guess [ den == 0 ] = 0.5 return F_guess
def advisory_lock ( dax , key , lock_mode = LockMode . wait , xact = False ) : """A context manager for obtaining a lock , executing code , and then releasing the lock . A boolean value is passed to the block indicating whether or not the lock was obtained . : dax : a DataAccess instance : key : either a ...
if lock_mode == LockMode . wait : obtain_lock ( dax , key , lock_mode , xact ) else : got_lock = obtain_lock ( dax , key , lock_mode , xact ) if not got_lock : if lock_mode == LockMode . error : raise Exception ( "Unable to obtain advisory lock {}" . format ( key ) ) else : # loc...
def add_tags_to_bookmark ( self , bookmark_id , tags ) : """Add tags to to a bookmark . The identified bookmark must belong to the current user . : param bookmark _ id : ID of the bookmark to delete . : param tags : Comma separated tags to be applied ."""
url = self . _generate_url ( 'bookmarks/{0}/tags' . format ( bookmark_id ) ) params = dict ( tags = tags ) return self . post ( url , params )
def reconnect ( self , exc = None ) : """Schedule reconnect after connection has been unexpectedly lost ."""
# Reset protocol binding before starting reconnect self . protocol = None if not self . closing : log . warning ( 'disconnected from Rflink, reconnecting' ) self . loop . create_task ( self . connect ( ) )
def sphere ( target , pore_diameter = 'pore.diameter' , throat_area = 'throat.area' ) : r"""Calculates internal surface area of pore bodies assuming they are spherical then subtracts the area of the neighboring throats in a crude way , by simply considering the throat cross - sectional area , thus not accountin...
network = target . project . network R = target [ pore_diameter ] / 2 Asurf = 4 * _np . pi * R ** 2 Tn = network . find_neighbor_throats ( pores = target . Ps , flatten = False ) Tsurf = _np . array ( [ _np . sum ( network [ throat_area ] [ Ts ] ) for Ts in Tn ] ) value = Asurf - Tsurf return value
def create_http_method ( logic : Callable , http_method : str , handle_http : Callable , before : Callable = None , after : Callable = None ) -> Callable : """Create a handler method to be used in a handler class . : param callable logic : The underlying function to execute with the parsed and validated paramet...
@ functools . wraps ( logic ) def fn ( handler , * args , ** kwargs ) : if before is not None and callable ( before ) : before ( ) result = handle_http ( handler , args , kwargs , logic ) if after is not None and callable ( after ) : after ( result ) return result return fn
def protect ( self , password = None , read_protect = False , protect_from = 0 ) : """Protect a FeliCa Lite Tag . A FeliCa Lite Tag can be provisioned with a custom password ( or the default manufacturer key if the password is an empty string or bytearray ) to ensure that data retrieved by future read opera...
return super ( FelicaLite , self ) . protect ( password , read_protect , protect_from )
def list_numbers ( self , ** kwargs ) : # noqa : E501 """Get your numbers # noqa : E501 List all your purchased numbers # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ numbers ( async = True )...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return self . list_numbers_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . list_numbers_with_http_info ( ** kwargs ) # noqa : E501 return data
def extract ( src_vector : str , burn_attribute : str , src_raster : list , dst_names : list , dst_dir : str , src_raster_template : str = None , gdal_dtype : int = 4 , n_jobs : int = 1 ) : """Extract values from list of single band raster for pixels overlapping with a vector data . The extracted data will be sto...
if src_raster_template is None : src_raster_template = src_raster [ 0 ] path_rasterized = os . path . join ( dst_dir , f"burn_attribute_rasterized_{burn_attribute}.tif" ) paths_extracted_aux = { ele : os . path . join ( dst_dir , f"{ele}.npy" ) for ele in [ f"aux_vector_{burn_attribute}" , "aux_coord_x" , "aux_coor...
def add_next_tick_callback ( self , callback ) : '''Add callback to be invoked once on the next tick of the event loop . Args : callback ( callable ) : A callback function to execute on the next tick . Returns : NextTickCallback : can be used with ` ` remove _ next _ tick _ callback ` ` . . note : : N...
from . . server . callbacks import NextTickCallback cb = NextTickCallback ( self , None ) return self . _add_session_callback ( cb , callback , one_shot = True , originator = self . add_next_tick_callback )
def get_best_experiment_sets ( nets , expvars , num ) : '''given the network and the experimental variables , and the bound on the size of an experiment set returns the experiments as a ` ` TermSet ` ` object [ instance ] .'''
netsf = nets . to_file ( ) expvarsf = expvars . to_file ( ) best = - 1 best_solutions = [ ] best_found = False i = 0 while i < num and not best_found : i += 1 num_exp = String2TermSet ( 'pexperiment(' + str ( i ) + ')' ) num_expf = num_exp . to_file ( ) prg = [ netsf , expvarsf , num_expf , find_best_ex...
def symbols_to_prob ( symbols ) : '''Return a dict mapping symbols to probability . input : symbols : iterable of hashable items works well if symbols is a zip of iterables'''
myCounter = Counter ( symbols ) N = float ( len ( list ( symbols ) ) ) # symbols might be a zip object in python 3 for k in myCounter : myCounter [ k ] /= N return myCounter
def get_utc_date ( entry ) : """Return datestamp converted to UTC"""
if entry [ 'numeric_date_stamp' ] == '0' : entry [ 'numeric_date_stamp_utc' ] = '0' return entry else : if '.' in entry [ 'numeric_date_stamp' ] : t = datetime . strptime ( entry [ 'numeric_date_stamp' ] , '%Y%m%d%H%M%S.%f' ) else : t = datetime . strptime ( entry [ 'numeric_date_stamp' ...
def dict ( self ) : """Return this ` ` SoSOptions ` ` option values as a dictionary of argument name to value mappings . : returns : a name : value dictionary of option values ."""
odict = { } for arg in _arg_names : value = getattr ( self , arg ) # Do not attempt to store preset option values in presets if arg in ( 'add_preset' , 'del_preset' , 'desc' , 'note' ) : value = None odict [ arg ] = value return odict
def _partition_operation_sql ( self , operation , settings = None , from_part = None ) : """Performs some operation over partition : param db : Database object to execute operation on : param operation : Operation to execute from SystemPart . OPERATIONS set : param settings : Settings for executing request to...
operation = operation . upper ( ) assert operation in self . OPERATIONS , "operation must be in [%s]" % comma_join ( self . OPERATIONS ) sql = "ALTER TABLE `%s`.`%s` %s PARTITION %s" % ( self . _database . db_name , self . table , operation , self . partition ) if from_part is not None : sql += " FROM %s" % from_pa...
def _run_smoove ( full_bams , sr_bams , disc_bams , work_dir , items ) : """Run lumpy - sv using smoove ."""
batch = sshared . get_cur_batch ( items ) ext = "-%s-svs" % batch if batch else "-svs" name = "%s%s" % ( dd . get_sample_name ( items [ 0 ] ) , ext ) out_file = os . path . join ( work_dir , "%s-smoove.genotyped.vcf.gz" % name ) sv_exclude_bed = sshared . prepare_exclude_file ( items , out_file ) old_out_file = os . pa...
def post ( self , url , data ) : """Send a HTTP POST request to a URL and return the result ."""
headers = { "Content-type" : "application/x-www-form-urlencoded" , "Accept" : "text/json" } self . conn . request ( "POST" , url , data , headers ) return self . _process_response ( )
def get_modifications ( self ) : """Extract INDRA Modification Statements from the BioPAX model . To extract Modifications , this method reuses the structure of BioPAX Pattern ' s org . biopax . paxtools . pattern . PatternBox . constrolsStateChange pattern with additional constraints to specify the type of...
for modtype , modclass in modtype_to_modclass . items ( ) : # TODO : we could possibly try to also extract generic # modifications here if modtype == 'modification' : continue stmts = self . _get_generic_modification ( modclass ) self . statements += stmts
def _get_files ( self , folderId ) : """Retrieve the list of files contained in a folder"""
uri = '/' . join ( [ self . base_url , self . name , folderId , 'Files' ] ) return uri , { } , 'get' , None , None , False , None
def get_fixture ( self , fixture_id , head2head = None ) : """Loads a single fixture . Args : * fixture _ id ( str ) : the id of the fixture * head2head ( int , optional ) : load the previous n fixture of the two teams Returns : * : obj : json : the fixture - json"""
filters = [ ] if head2head is not None and int ( head2head ) > 0 : self . logger . debug ( f'Getting fixture {fixture_id}. head2head is {head2head}.' ) filters . append ( self . __createFilter ( 'head2head' , head2head ) ) else : self . logger . debug ( f'Getting fixture {fixture_id}.' ) return self . _requ...
def count_genes ( model ) : """Count the number of distinct genes in model reactions ."""
genes = set ( ) for reaction in model . reactions : if reaction . genes is None : continue if isinstance ( reaction . genes , boolean . Expression ) : genes . update ( v . symbol for v in reaction . genes . variables ) else : genes . update ( reaction . genes ) return len ( genes )
def add_spaces ( self , spaces , ret = False ) : """Add ` ` pyny . Spaces ` ` to the current space . In other words , it merges multiple ` ` pyny . Spaces ` ` in this instance . : param places : ` ` pyny . Spaces ` ` to add . : type places : list of pyny . Spaces : param ret : If True , returns the whole up...
if type ( spaces ) != list : spaces = [ spaces ] Space . add_places ( self , sum ( [ space . places for space in spaces ] , [ ] ) ) if ret : return self
def generate_dc_xml ( dc_dict ) : """Generate a DC XML string ."""
# Define the root namespace . root_namespace = '{%s}' % DC_NAMESPACES [ 'oai_dc' ] # Set the elements namespace URL . elements_namespace = '{%s}' % DC_NAMESPACES [ 'dc' ] schema_location = ( 'http://www.openarchives.org/OAI/2.0/oai_dc/ ' 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd' ) root_attributes = { '{%s}schema...
def clustering_fields ( self ) : """Union [ List [ str ] , None ] : Fields defining clustering for the table ( Defaults to : data : ` None ` ) . Clustering fields are immutable after table creation . . . note : : As of 2018-06-29 , clustering fields cannot be set on a table which does not also have time p...
prop = self . _properties . get ( "clustering" ) if prop is not None : return list ( prop . get ( "fields" , ( ) ) )
def process_pulls ( self , testpulls = None , testarchive = None , expected = None ) : """Runs self . find _ pulls ( ) * and * processes the pull requests unit tests , status updates and wiki page creations . : arg expected : for unit testing the output results that would be returned from running the tests in...
from datetime import datetime pulls = self . find_pulls ( None if testpulls is None else testpulls . values ( ) ) for reponame in pulls : for pull in pulls [ reponame ] : try : archive = self . archive [ pull . repokey ] if pull . snumber in archive : # We pass the archive in so that...
def coarse_tag_str ( pos_seq ) : """Convert POS sequence to our coarse system , formatted as a string ."""
global tag2coarse tags = [ tag2coarse . get ( tag , 'O' ) for tag in pos_seq ] return '' . join ( tags )
def get_all_network_interfaces ( self , filters = None ) : """Retrieve all of the Elastic Network Interfaces ( ENI ' s ) associated with your account . : type filters : dict : param filters : Optional filters that can be used to limit the results returned . Filters are provided in the form of a dictionary...
params = { } if filters : self . build_filter_params ( params , filters ) return self . get_list ( 'DescribeNetworkInterfaces' , params , [ ( 'item' , NetworkInterface ) ] , verb = 'POST' )
def parse_args ( args , default_server_definitions_path , default_profile_definitions_path ) : """Parse the command line arguments and return the args dictionary"""
prog = os . path . basename ( sys . argv [ 0 ] ) usage = '%(prog)s [options] server' desc = """ Test script for testing get_central_instances method. This script executes a number of tests and displays against a set of servers defined in the test file """ epilog = """ Examples: %s Fujitsu -v 3 %s -v 1` """ % ( pr...
def clear_samples ( self ) : """Clears the chain and blobs from memory ."""
# store the iteration that the clear is occuring on self . _lastclear = self . niterations self . _itercounter = 0 # now clear the chain self . _sampler . reset ( )
def search_group_by_id ( self , groupID ) -> Group : """searches a group by given id Args : groupID ( str ) : groupID the group to search for Returns the group object or None if it couldn ' t find a group"""
for g in self . groups : if g . id == groupID : return g return None
def getUserAgent ( ) : '''Generate a randomized user agent by permuting a large set of possible values . The returned user agent should look like a valid , in - use brower , with a specified preferred language of english . Return value is a list of tuples , where each tuple is one of the user - agent headers . ...
coding = random . choice ( ENCODINGS ) random . shuffle ( coding ) coding = random . choice ( ( ", " , "," ) ) . join ( coding ) accept_list = [ tmp for tmp in random . choice ( ACCEPT ) ] accept_list . append ( random . choice ( ACCEPT_POSTFIX ) ) accept_str = random . choice ( ( ", " , "," ) ) . join ( accept_list ) ...
def auto_change_docstring ( app , what , name , obj , options , lines ) : r"""Make some automatic changes to docstrings . Things this function does are : - Add a title to module docstrings - Merge lines that end with a ' \ ' with the next line ."""
if what == 'module' and name . startswith ( 'pylatex' ) : lines . insert ( 0 , len ( name ) * '=' ) lines . insert ( 0 , name ) hits = 0 for i , line in enumerate ( lines . copy ( ) ) : if line . endswith ( '\\' ) : lines [ i - hits ] += lines . pop ( i + 1 - hits ) hits += 1
def run ( self ) : """Run the plugin ."""
# Only run if the build was successful if self . workflow . build_process_failed : self . log . info ( "Not promoting failed build to koji" ) return self . koji_session = get_koji_session ( self . workflow , self . koji_fallback ) koji_metadata , output_files = self . get_metadata ( ) try : server_dir = sel...
def calcSMA ( self ) : """Calculates the semi - major axis from Keplers Third Law"""
try : return eq . KeplersThirdLaw ( None , self . star . M , self . P ) . a except HierarchyError : return np . nan
def create_secgroup ( self , name , desc ) : """Creates a new server security group . : param str name : The name of the security group to create . : param str desc : A short description of the group ."""
self . nova . security_groups . create ( name , desc )
def _add_argument_register ( self , reg_offset ) : """Registers a register offset as being used as an argument to the function . : param reg _ offset : The offset of the register to register ."""
if reg_offset in self . _function_manager . _arg_registers and reg_offset not in self . _argument_registers : self . _argument_registers . append ( reg_offset )
def update_image ( self , container_name , image_name ) : """update a container ' s image , : param container _ name : ` class ` : ` str ` , container name : param image _ name : ` class ` : ` str ` , the full image name , like alpine : 3.3 : return : ` class ` : ` bool ` , True if success , otherwise False ....
code , container = self . get_container ( container_name ) if code != httplib . OK : self . logger . error ( "Container %s is not exists. error code %s, error message %s" , container_name , code , container ) return False _ , old_image_name , _ = utils . parse_image_name ( container . image ) repository , name ...
def reachableFrom ( self , id , hint = None , relationships = None , lbls = None , callback = None , output = 'application/json' ) : """Get all the nodes reachable from a starting point , traversing the provided edges . from : / graph / reachablefrom / { id } Arguments : id : The type of the edge hint : A lab...
if id and id . startswith ( 'http:' ) : id = parse . quote ( id , safe = '' ) kwargs = { 'id' : id , 'hint' : hint , 'relationships' : relationships , 'lbls' : lbls , 'callback' : callback } kwargs = { k : dumps ( v ) if builtins . type ( v ) is dict else v for k , v in kwargs . items ( ) } param_rest = self . _mak...
def frequencies_plot ( self , xmin = 0 , xmax = 200 ) : """Generate the qualities plot"""
helptext = ''' A possible way to assess the complexity of a library even in absence of a reference sequence is to look at the kmer profile of the reads. The idea is to count all the kmers (_i.e._, sequence of length `k`) that occur in the reads. In this way it is possible...
def get_config ( cls , key , default = None ) : """Shortcut to access the application ' s config in your class : param key : The key to access : param default : The default value when None : returns mixed :"""
return cls . _app . config . get ( key , default )
def _pull_query_results ( resultset ) : '''Parses a ResultSet returned from InfluxDB into a dictionary of results , grouped by series names and optional JSON - encoded grouping tags .'''
_results = collections . defaultdict ( lambda : { } ) for _header , _values in resultset . items ( ) : _header , _group_tags = _header if _group_tags : _results [ _header ] [ salt . utils . json . dumps ( _group_tags ) ] = [ _value for _value in _values ] else : _results [ _header ] = [ _val...
def repeat_last_axis ( array , count ) : """Restride ` array ` to repeat ` count ` times along the last axis . Parameters array : np . array The array to restride . count : int Number of times to repeat ` array ` . Returns result : array Array of shape array . shape + ( count , ) composed of ` array...
return as_strided ( array , array . shape + ( count , ) , array . strides + ( 0 , ) )
def get_syllable_count ( self , syllables : List [ str ] ) -> int : """Counts the number of syllable groups that would occur after ellision . Often we will want preserve the position and separation of syllables so that they can be used to reconstitute a line , and apply stresses to the original word positions ....
tmp_syllables = copy . deepcopy ( syllables ) return len ( string_utils . remove_blank_spaces ( string_utils . move_consonant_right ( tmp_syllables , self . _find_solo_consonant ( tmp_syllables ) ) ) )
def get_modules ( modulename = None ) : """Return a list of modules and packages under modulename . If modulename is not given , return a list of all top level modules and packages ."""
modulename = compat . ensure_not_unicode ( modulename ) if not modulename : try : return ( [ modname for ( importer , modname , ispkg ) in iter_modules ( ) if not modname . startswith ( "_" ) ] + list ( sys . builtin_module_names ) ) except OSError : # Bug in Python 2.6 , see # 275 return list (...
def get_sections ( self , s , base , sections = [ 'Parameters' , 'Other Parameters' ] ) : """Method that extracts the specified sections out of the given string if ( and only if ) the docstring follows the numpy documentation guidelines [1 ] _ . Note that the section either must appear in the : attr : ` param...
params = self . params # Remove the summary and dedent the rest s = self . _remove_summary ( s ) for section in sections : key = '%s.%s' % ( base , section . lower ( ) . replace ( ' ' , '_' ) ) params [ key ] = self . _get_section ( s , section ) return s
def _GetStatus ( self , two_factor = False ) : """Check whether OS Login is installed . Args : two _ factor : bool , True if two factor should be enabled . Returns : bool , True if OS Login is installed ."""
params = [ 'status' ] if two_factor : params += [ '--twofactor' ] retcode = self . _RunOsLoginControl ( params ) if retcode is None : if self . oslogin_installed : self . logger . warning ( 'OS Login not installed.' ) self . oslogin_installed = False return None # Prevent log spam when OS Lo...
def initialize ( app : Flask , app_config ) : """Initialize the module . : param app : The Flask application . : param app _ config : Application configuration dictionary . If ` http . serve _ on _ endpoint ` attribute is specified ( e . g . / sacredboard / ) , the application will be hosted on that endpoint ...
sub_url = app_config [ "http.serve_on_endpoint" ] if sub_url != "/" : app . wsgi_app = ReverseProxied ( app . wsgi_app , script_name = sub_url )
def _validate_config ( self ) : """Ensure at least one switch is configured"""
if len ( cfg . CONF . ml2_arista . get ( 'switch_info' ) ) < 1 : msg = _ ( 'Required option - when "sec_group_support" is enabled, ' 'at least one switch must be specified ' ) LOG . exception ( msg ) raise arista_exc . AristaConfigError ( msg = msg )
def fetch ( args ) : """% prog fetch " query " OR % prog fetch queries . txt Please provide a UniProt compatible ` query ` to retrieve data . If ` query ` contains spaces , please remember to " quote " it . You can also specify a ` filename ` which contains queries , one per line . Follow this syntax < ...
import re import csv p = OptionParser ( fetch . __doc__ ) p . add_option ( "--format" , default = "tab" , choices = valid_formats , help = "download format [default: %default]" ) p . add_option ( "--columns" , default = "entry name, protein names, genes,organism" , help = "columns to download, if --format is `tab` or `...
def get_addition_score ( source_counts , prediction_counts , target_counts ) : """Compute the addition score ( Equation 4 in the paper ) ."""
added_to_prediction_counts = prediction_counts - source_counts true_positives = sum ( ( added_to_prediction_counts & target_counts ) . values ( ) ) selected = sum ( added_to_prediction_counts . values ( ) ) # Note that in the paper the summation is done over all the ngrams in the # output rather than the ngrams in the ...
def DataRefreshRequired ( self , path = None , last = None ) : """True if we need to update this path from the client . Args : path : The path relative to the root to check freshness of . last : An aff4 : last attribute to check freshness of . At least one of path or last must be supplied . Returns : Tr...
# If we didn ' t get given a last attribute , use the path to get one from the # object . if last is None : if path is None : # If we didn ' t get a path either , we can ' t do anything . raise type_info . TypeValueError ( "Either 'path' or 'last' must" " be supplied as an argument." ) fd = aff4 . FACTO...
def radial_density ( im , bins = 10 , voxel_size = 1 ) : r"""Computes radial density function by analyzing the histogram of voxel values in the distance transform . This function is defined by Torquato [ 1 ] as : . . math : : \ int _ 0 ^ \ infty P ( r ) dr = 1.0 where * P ( r ) dr * is the probability of ...
if im . dtype == bool : im = spim . distance_transform_edt ( im ) mask = find_dt_artifacts ( im ) == 0 im [ mask ] = 0 x = im [ im > 0 ] . flatten ( ) h = sp . histogram ( x , bins = bins , density = True ) h = _parse_histogram ( h = h , voxel_size = voxel_size ) rdf = namedtuple ( 'radial_density_function' , ( 'R'...
def interface_by_macaddr ( self , macaddr ) : '''Given a MAC address , return the interface that ' owns ' this address'''
macaddr = EthAddr ( macaddr ) for devname , iface in self . _devinfo . items ( ) : if iface . ethaddr == macaddr : return iface raise KeyError ( "No device has MAC address {}" . format ( macaddr ) )
def name ( self ) : """The name for this window as it should be displayed in the status bar ."""
# Name , explicitely set for the window . if self . chosen_name : return self . chosen_name else : pane = self . active_pane if pane : return pane . name return ''
def all ( self ) : """Return all registered users http : / / www . keycloak . org / docs - api / 3.4 / rest - api / index . html # _ users _ resource"""
return self . _client . get ( url = self . _client . get_full_url ( self . get_path ( 'collection' , realm = self . _realm_name ) ) )
def description ( self ) : """This read - only attribute is a sequence of 7 - item sequences ."""
if self . _closed : return description = [ ] for col in self . _result [ "cols" ] : description . append ( ( col , None , None , None , None , None , None ) ) return tuple ( description )
def advanced_search ( pattern ) : """Parse the grammar of a pattern and build a queryset with it ."""
query_parsed = QUERY . parseString ( pattern ) return Entry . published . filter ( query_parsed [ 0 ] ) . distinct ( )
def get ( self ) : """Get a task from the queue ."""
tasks = self . _get_avaliable_tasks ( ) if not tasks : return None name , data = tasks [ 0 ] self . _client . kv . delete ( name ) return data
def listext ( self , ext , stream = sys . stdout ) : """Print to the given ` stream ` a table with the list of the output files with the given ` ext ` produced by the flow ."""
nodes_files = [ ] for node in self . iflat_nodes ( ) : filepath = node . outdir . has_abiext ( ext ) if filepath : nodes_files . append ( ( node , File ( filepath ) ) ) if nodes_files : print ( "Found %s files with extension `%s` produced by the flow" % ( len ( nodes_files ) , ext ) , file = stream ...
def save_config ( config , logdir = None ) : """Save a new configuration by name . If a logging directory is specified , is will be created and the configuration will be stored there . Otherwise , a log message will be printed . Args : config : Configuration object . logdir : Location for writing summarie...
if logdir : with config . unlocked : config . logdir = logdir message = 'Start a new run and write summaries and checkpoints to {}.' tf . logging . info ( message . format ( config . logdir ) ) tf . gfile . MakeDirs ( config . logdir ) config_path = os . path . join ( config . logdir , 'conf...
def closed ( self , reason ) : '''异步爬取本地化处理完成后 , 使用结果数据 , 进行输出文件的渲染 , 渲染完毕 , 调用 : meth : ` . MobiSpider . generate _ mobi _ file ` 方法 , 生成目标 ` ` mobi ` ` 文件'''
# 拷贝封面 & 报头图片文件 utils . mkdirp ( os . path . join ( self . build_source_dir , 'images' ) ) self . _logger . info ( self . options ) shutil . copy ( self . options . get ( 'img_cover' ) , os . path . join ( self . build_source_dir , 'images' , 'cover.jpg' ) ) shutil . copy ( self . options . get ( 'img_masthead' ) , os ...
def move_in_32 ( library , session , space , offset , length , extended = False ) : """Moves an 32 - bit block of data from the specified address space and offset to local memory . Corresponds to viMoveIn32 * functions of the VISA library . : param library : the visa library wrapped by ctypes . : param sessio...
buffer_32 = ( ViUInt32 * length ) ( ) if extended : ret = library . viMoveIn32Ex ( session , space , offset , length , buffer_32 ) else : ret = library . viMoveIn32 ( session , space , offset , length , buffer_32 ) return list ( buffer_32 ) , ret
def original_unescape ( self , s ) : """Since we need to use this sometimes"""
if isinstance ( s , basestring ) : return unicode ( HTMLParser . unescape ( self , s ) ) elif isinstance ( s , list ) : return [ unicode ( HTMLParser . unescape ( self , item ) ) for item in s ] else : return s
def redim ( cls , dataset , dimensions ) : """Rename coords on the Cube ."""
new_dataset = dataset . data . copy ( ) for name , new_dim in dimensions . items ( ) : if name == new_dataset . name ( ) : new_dataset . rename ( new_dim . name ) for coord in new_dataset . dim_coords : if name == coord . name ( ) : coord . rename ( new_dim . name ) return new_datase...
def sleep ( self , ms = 1 ) : """Pauses the current green thread for * ms * milliseconds : : p = h . pipe ( ) @ h . spawn def _ ( ) : p . send ( ' 1 ' ) h . sleep ( 50) p . send ( ' 2 ' ) p . recv ( ) # returns ' 1' p . recv ( ) # returns ' 2 ' after 50 ms"""
self . scheduled . add ( ms , getcurrent ( ) ) self . loop . switch ( )
def envelop ( self , begin , end = None ) : """Returns the set of all intervals fully contained in the range [ begin , end ) . Completes in O ( m + k * log n ) time , where : * n = size of the tree * m = number of matches * k = size of the search range : rtype : set of Interval"""
root = self . top_node if not root : return set ( ) if end is None : iv = begin return self . envelop ( iv . begin , iv . end ) elif begin >= end : return set ( ) result = root . search_point ( begin , set ( ) ) # bound _ begin might be greater boundary_table = self . boundary_table bound_begin = bounda...
def build ( self , title , text , img_url ) : """: param title : Title of the card : param text : Description of the card : param img _ url : Image of the card"""
super ( ImageCard , self ) . build ( ) self . title = Title ( id = self . id + "-title" , text = title , classname = "card-title" , size = 3 , parent = self ) self . block = Panel ( id = self . id + "-block" , classname = "card-block" , parent = self ) self . image = Image ( id = self . id + "-image" , img_url = img_ur...
def detect_member ( row , key ) : '''properly detects if a an attribute exists'''
( target , tkey , tvalue ) = dict_crawl ( row , key ) if target : return True return False
def compute ( self ) : """This is the main method of the : class : ` MUSX ` class . It computes a set of soft clauses belonging to an MUS of the input formula . First , the method checks whether the formula is satisfiable . If it is , nothing else is done . Otherwise , an * unsatisfiable core * of the formu...
# cheking whether or not the formula is unsatisfiable if not self . oracle . solve ( assumptions = self . sels ) : # get an overapproximation of an MUS approx = sorted ( self . oracle . get_core ( ) ) if self . verbose : print ( 'c MUS approx:' , ' ' . join ( [ str ( self . vmap [ sel ] + 1 ) for sel in...
def dim_dtau ( self , pars ) : r""": math : Add formula"""
self . _set_parameters ( pars ) # term 1 num1 = - self . m * ( self . w ** self . c ) * self . c * ( self . tau ** ( self . c - 1 ) ) * np . sin ( self . ang ) term1 = self . sigmai * num1 / self . denom # term 2 num2a = - self . m * self . otc * np . sin ( self . ang ) num2b = 2 * ( self . w ** 2.0 ) * self . c * ( se...
def do_down ( self , arg ) : """d ( own ) [ count ] Move the current frame count ( default one ) levels down in the stack trace ( to a newer frame ) ."""
if self . curindex + 1 == len ( self . stack ) : self . error ( 'Newest frame' ) return try : count = int ( arg or 1 ) except ValueError : self . error ( 'Invalid frame count (%s)' % arg ) return if count < 0 : newframe = len ( self . stack ) - 1 else : newframe = min ( len ( self . stack ) ...
def print_mhc_peptide ( neoepitope_info , peptides , pepmap , outfile , netmhc = False ) : """Accept data about one neoepitope from merge _ mhc _ peptide _ calls and print it to outfile . This is a generic module to reduce code redundancy . : param pandas . core . frame neoepitope _ info : object containing wit...
if netmhc : peptide_names = [ neoepitope_info . peptide_name ] else : peptide_names = [ x for x , y in peptides . items ( ) if neoepitope_info . pept in y ] # Convert named tuple to dict so it can be modified neoepitope_info = neoepitope_info . _asdict ( ) # Handle fusion peptides ( They are characterized by ha...
def env ( self , current_scope ) : """Return an environment that will look up in current _ scope for keys in this tuple , and the parent env otherwise ."""
return self . __env_cache . get ( current_scope . ident , framework . Environment , current_scope , names = self . keys ( ) , parent = framework . Environment ( { 'self' : current_scope } , parent = self . __parent_env ) )
def evdev_device ( self ) : """Return our corresponding evdev device object"""
devices = [ evdev . InputDevice ( fn ) for fn in evdev . list_devices ( ) ] for device in devices : if device . name == self . evdev_device_name : return device raise Exception ( "%s: could not find evdev device '%s'" % ( self , self . evdev_device_name ) )
def validate_config_must_have ( config , required_keys ) : """Validate a config dictionary to make sure it has all of the specified keys Args : config : the config to validate . required _ keys : the list of possible keys that config must include . Raises : Exception if the config does not have any of the...
missing_keys = set ( required_keys ) - set ( config ) if len ( missing_keys ) > 0 : raise Exception ( 'Invalid config with missing keys "%s"' % ', ' . join ( missing_keys ) )
def register_success ( self , upgrade ) : """Register a successful upgrade ."""
u = Upgrade ( upgrade = upgrade . name , applied = datetime . now ( ) ) db . session . add ( u ) db . session . commit ( )
def DOMDebugger_setXHRBreakpoint ( self , url ) : """Function path : DOMDebugger . setXHRBreakpoint Domain : DOMDebugger Method name : setXHRBreakpoint Parameters : Required arguments : ' url ' ( type : string ) - > Resource URL substring . All XHRs having this substring in the URL will get stopped upon ....
assert isinstance ( url , ( str , ) ) , "Argument 'url' must be of type '['str']'. Received type: '%s'" % type ( url ) subdom_funcs = self . synchronous_command ( 'DOMDebugger.setXHRBreakpoint' , url = url ) return subdom_funcs
def support_autoupload_enable ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) support = ET . SubElement ( config , "support" , xmlns = "urn:brocade.com:mgmt:brocade-ras" ) autoupload = ET . SubElement ( support , "autoupload" ) enable = ET . SubElement ( autoupload , "enable" ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config )
def get_dict ( self , obj , state = None , base_name = 'View' ) : """The style dict for a view instance ."""
return self . get_dict_for_class ( class_name = obj . __class__ , state = obj . state , base_name = base_name )
def devices ( self ) : """Manages users enrolled u2f devices"""
self . verify_integrity ( ) if session . get ( 'u2f_device_management_authorized' , False ) : if request . method == 'GET' : return jsonify ( self . get_devices ( ) ) , 200 elif request . method == 'DELETE' : response = self . remove_device ( request . json ) if response [ 'status' ] == ...
def do_speak ( self , args : argparse . Namespace ) : """Repeats what you tell me to ."""
words = [ ] for word in args . words : if args . piglatin : word = '%s%say' % ( word [ 1 : ] , word [ 0 ] ) if args . shout : word = word . upper ( ) words . append ( word ) repetitions = args . repeat or 1 for i in range ( min ( repetitions , self . maxrepeats ) ) : self . poutput ( ' '...
def independentlinear60__ffnn ( ) : """4 - Layer Neural Network"""
from keras . models import Sequential from keras . layers import Dense model = Sequential ( ) model . add ( Dense ( 32 , activation = 'relu' , input_dim = 60 ) ) model . add ( Dense ( 20 , activation = 'relu' ) ) model . add ( Dense ( 20 , activation = 'relu' ) ) model . add ( Dense ( 1 ) ) model . compile ( optimizer ...
def apply_empty_result ( self ) : """we have an empty result ; at least 1 axis is 0 we will try to apply the function to an empty series in order to see if this is a reduction function"""
# we are not asked to reduce or infer reduction # so just return a copy of the existing object if self . result_type not in [ 'reduce' , None ] : return self . obj . copy ( ) # we may need to infer reduce = self . result_type == 'reduce' from pandas import Series if not reduce : EMPTY_SERIES = Series ( [ ] ) ...
def _fail_early ( message , ** kwds ) : """The module arguments are dynamically generated based on the Opsview version . This means that fail _ json isn ' t available until after the module has been properly initialized and the schemas have been loaded ."""
import json output = dict ( kwds ) output . update ( { 'msg' : message , 'failed' : True , } ) print ( json . dumps ( output ) ) sys . exit ( 1 )
def get_scopes_information ( self ) : """Return a list with the description of all the scopes requested ."""
scopes = StandardScopeClaims . get_scopes_info ( self . params [ 'scope' ] ) if settings . get ( 'OIDC_EXTRA_SCOPE_CLAIMS' ) : scopes_extra = settings . get ( 'OIDC_EXTRA_SCOPE_CLAIMS' , import_str = True ) . get_scopes_info ( self . params [ 'scope' ] ) for index_extra , scope_extra in enumerate ( scopes_extra...
def accept ( self ) : """Method invoked when OK button is clicked ."""
output_path = self . output_path_line_edit . text ( ) if not output_path : display_warning_message_box ( self , tr ( 'Empty Output Path' ) , tr ( 'Output path can not be empty' ) ) return try : self . convert_metadata ( ) except MetadataConversionError as e : display_warning_message_box ( self , tr ( 'M...
def get_cursor ( cls ) : """Return a message list cursor that returns sqlite3 . Row objects"""
db = SqliteConnection . get ( ) db . row_factory = sqlite3 . Row return db . cursor ( )
def explain_linear_regressor_weights ( reg , vec = None , top = _TOP , target_names = None , targets = None , feature_names = None , coef_scale = None , feature_re = None , feature_filter = None , ) : """Return an explanation of a linear regressor weights . See : func : ` eli5 . explain _ weights ` for descriptio...
if isinstance ( reg , ( SVR , NuSVR ) ) and reg . kernel != 'linear' : return explain_weights_sklearn_not_supported ( reg ) feature_names , coef_scale = handle_hashing_vec ( vec , feature_names , coef_scale ) feature_names , flt_indices = get_feature_names_filtered ( reg , vec , feature_names = feature_names , feat...