signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def eventFilter ( self , widget , event ) : """A filter that is used to send a signal when the figure canvas is clicked ."""
if event . type ( ) == QEvent . MouseButtonPress : if event . button ( ) == Qt . LeftButton : self . sig_canvas_clicked . emit ( self ) return super ( FigureThumbnail , self ) . eventFilter ( widget , event )
def bytesize ( arr ) : """Returns the memory byte size of a Numpy array as an integer ."""
byte_size = np . prod ( arr . shape ) * np . dtype ( arr . dtype ) . itemsize return byte_size
def apply_weight_drop ( block , local_param_regex , rate , axes = ( ) , weight_dropout_mode = 'training' ) : """Apply weight drop to the parameter of a block . Parameters block : Block or HybridBlock The block whose parameter is to be applied weight - drop . local _ param _ regex : str The regex for param...
if not rate : return existing_params = _find_params ( block , local_param_regex ) for ( local_param_name , param ) , ( ref_params_list , ref_reg_params_list ) in existing_params . items ( ) : dropped_param = WeightDropParameter ( param , rate , weight_dropout_mode , axes ) for ref_params in ref_params_list ...
def reduce ( self , sum1 , sum2 , * args ) : """The internal reduce function that sums the results from various processors"""
self . sum1g [ ... ] += sum1 if not self . pts_only : self . sum2g [ ... ] += sum2 if self . compute_mean_coords : N , centers_sum = args self . N [ ... ] += N for i in range ( self . bins . Ndim ) : self . centers [ i ] [ ... ] += centers_sum [ i ]
def query ( self , query_criteria , valid_record = None ) : '''a core method for querying model valid data with criteria * * NOTE : input is only returned if all fields & qualifiers are valid for model : param query _ criteria : dictionary with model field names and query qualifiers : param valid _ record : d...
__name__ = '%s.query' % self . __class__ . __name__ _query_arg = '%s(query_criteria={...})' % __name__ _record_arg = '%s(valid_record={...})' % __name__ # validate input if not isinstance ( query_criteria , dict ) : raise ModelValidationError ( '%s must be a dictionary.' % _query_arg ) # convert javascript dot _ pa...
def setHintColor ( self , color ) : """Sets the hint color for this combo box provided its line edit is an XLineEdit instance . : param color | < QColor >"""
lineEdit = self . lineEdit ( ) if isinstance ( lineEdit , XLineEdit ) : lineEdit . setHintColor ( color )
def isPlantOrigin ( taxid ) : """Given a taxid , this gets the expanded tree which can then be checked to see if the organism is a plant or not > > > isPlantOrigin ( 29760) True"""
assert isinstance ( taxid , int ) t = TaxIDTree ( taxid ) try : return "Viridiplantae" in str ( t ) except AttributeError : raise ValueError ( "{0} is not a valid ID" . format ( taxid ) )
def master_config ( opts , vm_ ) : '''Return a master ' s configuration for the provided options and VM'''
# Let ' s get a copy of the salt master default options master = copy . deepcopy ( salt . config . DEFAULT_MASTER_OPTS ) # Some default options are Null , let ' s set a reasonable default master . update ( log_level = 'info' , log_level_logfile = 'info' , hash_type = 'sha256' ) # Get ANY defined master setting , mergin...
def annot_boxplot ( ax , dmetrics , xoffwithin = 0.85 , xoff = 1.6 , yoff = 0 , annotby = 'xs' , test = False ) : """: param dmetrics : hue in index , x in columns # todos # x | y off in % xmin , xmax = ax . get _ xlim ( ) ( xmax - xmin ) + ( xmax - xmin ) * 0.35 + xmin"""
xlabel = ax . get_xlabel ( ) ylabel = ax . get_ylabel ( ) if test : dmetrics . index . name = 'index' dmetrics . columns . name = 'columns' dm = dmetrics . melt ( ) dm [ 'value' ] = 1 ax = sns . boxplot ( data = dm , x = 'columns' , y = 'value' ) for huei , hue in enumerate ( dmetrics . index ) : ...
def Bankoff ( m , x , rhol , rhog , mul , mug , D , roughness = 0 , L = 1 ) : r'''Calculates two - phase pressure drop with the Bankoff ( 1960 ) correlation , as shown in [ 2 ] _ , [ 3 ] _ , and [ 4 ] _ . . . math : : \ Delta P _ { tp } = \ phi _ { l } ^ { 7/4 } \ Delta P _ { l } . . math : : \ phi _ l = ...
# Liquid - only properties , for calculation of dP _ lo v_lo = m / rhol / ( pi / 4 * D ** 2 ) Re_lo = Reynolds ( V = v_lo , rho = rhol , mu = mul , D = D ) fd_lo = friction_factor ( Re = Re_lo , eD = roughness / D ) dP_lo = fd_lo * L / D * ( 0.5 * rhol * v_lo ** 2 ) gamma = ( 0.71 + 2.35 * rhog / rhol ) / ( 1. + ( 1. -...
def directions ( self , features , profile = 'mapbox/driving' , alternatives = None , geometries = None , overview = None , steps = None , continue_straight = None , waypoint_snapping = None , annotations = None , language = None , ** kwargs ) : """Request directions for waypoints encoded as GeoJSON features . Pa...
# backwards compatible , deprecated if 'geometry' in kwargs and geometries is None : geometries = kwargs [ 'geometry' ] warnings . warn ( 'Use `geometries` instead of `geometry`' , errors . MapboxDeprecationWarning ) annotations = self . _validate_annotations ( annotations ) coordinates = encode_coordinates ( f...
def power_status_update ( self , POWER_STATUS ) : '''update POWER _ STATUS warnings level'''
now = time . time ( ) Vservo = POWER_STATUS . Vservo * 0.001 Vcc = POWER_STATUS . Vcc * 0.001 self . high_servo_voltage = max ( self . high_servo_voltage , Vservo ) if self . high_servo_voltage > 1 and Vservo < self . settings . servowarn : if now - self . last_servo_warn_time > 30 : self . last_servo_warn_...
def log_progress ( lbl = 'Progress: ' , length = 0 , flushfreq = 4 , startafter = - 1 , start = True , repl = False , approx = False , disable = False , writefreq = 1 , with_time = False , backspace = True , pad_stdout = False , wfreq = None , ffreq = None , freq = None , total = None , num = None , with_totaltime = No...
global AGGROFLUSH # Alias kwargs with simpler names if num is not None : length = num if total is not None : length = total if wfreq is not None : writefreq = wfreq if ffreq is not None : flushfreq = ffreq if freq is not None : writefreq = flushfreq = freq if with_totaltime is not None : with_ti...
def recoSurface ( points , bins = 256 ) : """Surface reconstruction from a scattered cloud of points . : param int bins : number of voxels in x , y and z . . . hint : : | recosurface | | recosurface . py | _"""
if isinstance ( points , vtk . vtkActor ) : points = points . coordinates ( ) N = len ( points ) if N < 50 : print ( "recoSurface: Use at least 50 points." ) return None points = np . array ( points ) ptsSource = vtk . vtkPointSource ( ) ptsSource . SetNumberOfPoints ( N ) ptsSource . Update ( ) vpts = ptsS...
def validate_words ( word_list ) : '''Checks for each edited word in word _ list if that word is a valid english word . abs Returns all validated words as a set instance .'''
if word_list is None : return { } elif isinstance ( word_list , list ) : if not word_list : return { } else : return set ( word for word in word_list if word in WORD_DISTRIBUTION ) else : raise InputError ( "list variable not passed as argument to validate_words" )
def write ( self , oprot ) : '''Write this object to the given output protocol and return self . : type oprot : thryft . protocol . _ output _ protocol . _ OutputProtocol : rtype : pastpy . gen . database . impl . online . online _ database _ objects _ list _ item . OnlineDatabaseObjectsListItem'''
oprot . write_struct_begin ( 'OnlineDatabaseObjectsListItem' ) oprot . write_field_begin ( name = 'detail_href' , type = 11 , id = None ) oprot . write_string ( self . detail_href ) oprot . write_field_end ( ) oprot . write_field_begin ( name = 'record_type' , type = 11 , id = None ) oprot . write_string ( self . recor...
def _create_bvals_bvecs ( multiframe_dicom , bval_file , bvec_file , nifti , nifti_file ) : """Write the bvals from the sorted dicom files to a bval file Inspired by https : / / github . com / IBIC / ibicUtils / blob / master / ibicBvalsBvecs . py"""
# create the empty arrays number_of_stack_slices = common . get_ss_value ( multiframe_dicom [ Tag ( 0x2001 , 0x105f ) ] [ 0 ] [ Tag ( 0x2001 , 0x102d ) ] ) number_of_stacks = int ( int ( multiframe_dicom . NumberOfFrames ) / number_of_stack_slices ) bvals = numpy . zeros ( [ number_of_stacks ] , dtype = numpy . int32 )...
def get_file ( self , fp , headers = None , cb = None , num_cb = 10 , torrent = False , version_id = None , override_num_retries = None , response_headers = None , callback = None ) : """Retrieves a file from an S3 Key : type fp : file : param fp : File pointer to put the data into : type headers : string :...
if cb : if num_cb > 2 : cb_count = self . size / self . BufferSize / ( num_cb - 2 ) elif num_cb < 0 : cb_count = - 1 else : cb_count = 0 i = total_bytes = 0 cb ( total_bytes , self . size ) save_debug = self . bucket . connection . debug if self . bucket . connection . debug ...
def format_private_ip_address ( result ) : '''Formats the PrivateIPAddress object removing arguments that are empty'''
from collections import OrderedDict # Only display parameters that have content order_dict = OrderedDict ( ) if result . ip_address is not None : order_dict [ 'ipAddress' ] = result . ip_address if result . subnet_resource_id is not None : order_dict [ 'subnetResourceId' ] = result . subnet_resource_id return o...
def add_row_range_from_keys ( self , start_key = None , end_key = None , start_inclusive = True , end_inclusive = False ) : """Add row range to row _ ranges list from the row keys For example : . . literalinclude : : snippets _ table . py : start - after : [ START bigtable _ row _ range _ from _ keys ] : en...
row_range = RowRange ( start_key , end_key , start_inclusive , end_inclusive ) self . row_ranges . append ( row_range )
def set_mode ( self , mode ) : """: param mode : a str , one of [ home , away , night ] : return : nothing"""
values = { "desired_state" : { "mode" : mode } } response = self . api_interface . set_device_state ( self , values ) self . _update_state_from_response ( response )
def _request_get ( self , path , params = None , json = True , url = BASE_URL ) : """Perform a HTTP GET request ."""
url = urljoin ( url , path ) headers = self . _get_request_headers ( ) response = requests . get ( url , params = params , headers = headers ) if response . status_code >= 500 : backoff = self . _initial_backoff for _ in range ( self . _max_retries ) : time . sleep ( backoff ) backoff_response =...
def get_nonparametric_sources ( self ) : """: returns : list of non parametric sources in the composite source model"""
return [ src for sm in self . source_models for src_group in sm . src_groups for src in src_group if hasattr ( src , 'data' ) ]
def get ( self , sid ) : """Constructs a RoleContext : param sid : The unique string that identifies the resource : returns : twilio . rest . chat . v2 . service . role . RoleContext : rtype : twilio . rest . chat . v2 . service . role . RoleContext"""
return RoleContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = sid , )
def discard ( self , element ) : """Removes an element from the set . . . note : You may remove elements from the set that are not present , but a context from the server is required . : param element : the element to remove : type element : str"""
_check_element ( element ) self . _require_context ( ) self . _removes . add ( element )
def count_generator ( generator , memory_efficient = True ) : """Count number of item in generator . memory _ efficient = True , 3 times slower , but memory _ efficient . memory _ efficient = False , faster , but cost more memory ."""
if memory_efficient : counter = 0 for _ in generator : counter += 1 return counter else : return len ( list ( generator ) )
def pause ( self ) : """Pauses a running pipeline . This will stop retrieving results from the pipeline . Parallel parts of the pipeline will stop after the ` ` NuMap ` ` buffer is has been filled . A paused pipeline can be run or stopped ."""
# 1 . stop the plumbing thread by raising a StopIteration on a stride # boundary if self . _started . isSet ( ) and self . _running . isSet ( ) and not self . _pausing . isSet ( ) : self . _pausing . set ( ) self . _plunger . join ( ) del self . _plunger self . _pausing . clear ( ) self . _running ....
def vertex_enumeration_gen ( g , qhull_options = None ) : """Generator version of ` vertex _ enumeration ` . Parameters g : NormalFormGame NormalFormGame instance with 2 players . qhull _ options : str , optional ( default = None ) Options to pass to ` scipy . spatial . ConvexHull ` . See the ` Qhull ma...
try : N = g . N except AttributeError : raise TypeError ( 'input must be a 2-player NormalFormGame' ) if N != 2 : raise NotImplementedError ( 'Implemented only for 2-player games' ) brps = [ _BestResponsePolytope ( g . players [ 1 - i ] , idx = i , qhull_options = qhull_options ) for i in range ( N ) ] labe...
def send_query ( query_dict ) : """Query ChEMBL API Parameters query _ dict : dict ' query ' : string of the endpoint to query ' params ' : dict of params for the query Returns js : dict dict parsed from json that is unique to the submitted query"""
query = query_dict [ 'query' ] params = query_dict [ 'params' ] url = 'https://www.ebi.ac.uk/chembl/api/data/' + query + '.json' r = requests . get ( url , params = params ) r . raise_for_status ( ) js = r . json ( ) return js
def _escape_arg ( self , arg ) : '''Properly escape argument to protect special characters from shell interpretation . This avoids having to do tricky argument quoting . Effectively just escape all characters in the argument that are not alphanumeric !'''
if self . winrm : return arg return '' . join ( [ '\\' + char if re . match ( r'\W' , char ) else char for char in arg ] )
def loop_write ( self , max_packets = 1 ) : """Process read network events . Use in place of calling loop ( ) if you wish to handle your client reads as part of your own application . Use socket ( ) to obtain the client socket to call select ( ) or equivalent on . Use want _ write ( ) to determine if there ...
if self . _sock is None and self . _ssl is None : return MQTT_ERR_NO_CONN max_packets = len ( self . _out_packet ) + 1 if max_packets < 1 : max_packets = 1 for i in range ( 0 , max_packets ) : rc = self . _packet_write ( ) if rc > 0 : return self . _loop_rc_handle ( rc ) elif rc == MQTT_ERR_...
def constantrotating_to_static ( frame_r , frame_i , w , t = None ) : """Transform from a constantly rotating frame to a static , inertial frame . Parameters frame _ i : ` ~ gala . potential . StaticFrame ` frame _ r : ` ~ gala . potential . ConstantRotatingFrame ` w : ` ~ gala . dynamics . PhaseSpacePositi...
return _constantrotating_static_helper ( frame_r = frame_r , frame_i = frame_i , w = w , t = t , sign = - 1. )
def _realpath ( self , relpath ) : """Follow symlinks to find the real path to a file or directory in the repo . : returns : if the expanded path points to a file , the relative path to that file ; if a directory , the relative path + ' / ' ; if a symlink outside the repo , a path starting with / or . . / .""...
obj , path_so_far = self . _read_object ( relpath , MAX_SYMLINKS_IN_REALPATH ) if isinstance ( obj , self . Symlink ) : raise self . SymlinkLoopException ( self . rev , relpath ) return path_so_far
def remember ( self , user_name ) : '''Remember the authenticated identity . This method simply delegates to another IIdentifier plugin if configured .'''
log . debug ( 'Repoze OAuth remember' ) environ = toolkit . request . environ rememberer = self . _get_rememberer ( environ ) identity = { 'repoze.who.userid' : user_name } headers = rememberer . remember ( environ , identity ) for header , value in headers : toolkit . response . headers . add ( header , value )
def put ( self , resource , obj , operation_timeout = None , max_envelope_size = None , locale = None ) : """resource can be a URL or a ResourceLocator"""
headers = None return self . service . invoke ( headers , obj )
def create_api_v4_virtual_interface ( self ) : """Get an instance of Api Virtual Interface services facade ."""
return ApiV4VirtualInterface ( self . networkapi_url , self . user , self . password , self . user_ldap )
def make3d ( self , forcefield = "mmff94" , steps = 50 ) : """A wrapper to pybel ' s make3D method generate a 3D structure from a 2D or 0D structure . The 3D structure is made very quickly using a combination of rules ( e . g . sp3 atoms should have four bonds arranged in a tetrahedron ) and ring templates ...
pbmol = pb . Molecule ( self . _obmol ) pbmol . make3D ( forcefield = forcefield , steps = steps ) self . _obmol = pbmol . OBMol
def get_mesh ( self , var , coords = None ) : """Get the mesh variable for the given ` var ` Parameters var : xarray . Variable The data source whith the ` ` ' mesh ' ` ` attribute coords : dict The coordinates to use . If None , the coordinates of the dataset of this decoder is used Returns xarray ...
mesh = var . attrs . get ( 'mesh' ) if mesh is None : return None if coords is None : coords = self . ds . coords return coords . get ( mesh , self . ds . coords . get ( mesh ) )
def serialize ( self ) : """serialize ."""
if self . request is None : request = None else : request = json . loads ( self . request ) if self . response is None : response = None else : response = json . loads ( self . response ) return { 'id' : self . id , 'name' : self . name , 'request' : request , 'response' : response }
def query_other_gene_name ( ) : """Returns list of alternative short name by query query parameters tags : - Query functions parameters : - name : type _ in : query type : string required : false description : Alternative short name default : CVAP - name : name in : query type : string req...
args = get_args ( request_args = request . args , allowed_str_args = [ 'name' , 'entry_name' ] , allowed_int_args = [ 'limit' ] ) return jsonify ( query . other_gene_name ( ** args ) )
def get_trips ( feed : "Feed" , date : Optional [ str ] = None , time : Optional [ str ] = None ) -> DataFrame : """Return a subset of ` ` feed . trips ` ` . Parameters feed : Feed date : string YYYYMMDD date string time : string HH : MM : SS time string , possibly with HH > 23 Returns DataFrame T...
if feed . trips is None or date is None : return feed . trips f = feed . trips . copy ( ) f [ "is_active" ] = f [ "trip_id" ] . map ( lambda trip_id : feed . is_active_trip ( trip_id , date ) ) f = f [ f [ "is_active" ] ] . copy ( ) del f [ "is_active" ] if time is not None : # Get trips active during given time ...
def add ( self , value , session = None , ** kwargs ) : '''Add ` ` value ` ` , an instance of : attr : ` formodel ` to the : attr : ` through ` model . This method can only be accessed by an instance of the model for which this related manager is an attribute .'''
s , instance = self . session_instance ( 'add' , value , session , ** kwargs ) return s . add ( instance )
def class_name_to_resource_name ( class_name : str ) -> str : """Converts a camel case class name to a resource name with spaces . > > > class _ name _ to _ resource _ name ( ' FooBarObject ' ) ' Foo Bar Object ' : param class _ name : The name to convert . : returns : The resource name ."""
s = re . sub ( '(.)([A-Z][a-z]+)' , r'\1 \2' , class_name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1 \2' , s )
def progress_color ( current , total , name , style = 'normal' , when = 'auto' ) : """Display a simple , colored progress report ."""
update_color ( '[%d/%d] ' % ( current , total ) , name , style , when )
def login ( self , role , jwt , use_token = True , mount_point = DEFAULT_MOUNT_POINT ) : """Login to retrieve a Vault token via the GCP auth method . This endpoint takes a signed JSON Web Token ( JWT ) and a role name for some entity . It verifies the JWT signature with Google Cloud to authenticate that entity ...
params = { 'role' : role , 'jwt' : jwt , } api_path = '/v1/auth/{mount_point}/login' . format ( mount_point = mount_point ) response = self . _adapter . login ( url = api_path , use_token = use_token , json = params , ) return response
def parse ( fp ) : """Parse the contents of the ` ~ io . IOBase . readline ` - supporting file - like object ` ` fp ` ` as a simple line - oriented ` ` . properties ` ` file and return a generator of ` ` ( key , value , original _ lines ) ` ` triples for every entry in ` ` fp ` ` ( including duplicate keys ) ...
def lineiter ( ) : while True : ln = fp . readline ( ) if isinstance ( ln , binary_type ) : ln = ln . decode ( 'iso-8859-1' ) if ln == '' : return for l in ascii_splitlines ( ln ) : yield l liter = lineiter ( ) for source in liter : line = sour...
def filename ( self , appendix = None , create_if_not_existing = False ) : """creates a filename based Args : appendix : appendix for file Returns : filename"""
# if provided path is a relative path and self . data _ path exists , build path if os . path . isabs ( self . settings [ 'path' ] ) == False and self . data_path is not None : path = os . path . join ( self . data_path , self . settings [ 'path' ] ) else : path = self . settings [ 'path' ] tag = self . setting...
def cipher ( self ) : """Applies the Caesar shift cipher . Based on the attributes of the object , applies the Caesar shift cipher to the message attribute . Accepts positive and negative integers as offsets . Required attributes : message offset Returns : String with cipher applied ."""
# If no offset is selected , pick random one with sufficient distance # from original . if self . offset is False : self . offset = randrange ( 5 , 25 ) logging . info ( "Random offset selected: {0}" . format ( self . offset ) ) logging . debug ( "Offset set: {0}" . format ( self . offset ) ) # Cipher ciphered_...
def _get_order_clause ( archive_table ) : """Returns an ascending order clause on the versioned unique constraint as well as the version column ."""
order_clause = [ sa . asc ( getattr ( archive_table , col_name ) ) for col_name in archive_table . _version_col_names ] order_clause . append ( sa . asc ( archive_table . version_id ) ) return order_clause
def step ( self , action ) : """Run one timestep of the environment ' s dynamics . When end of episode is reached , you are responsible for calling ` reset ( ) ` to reset this environment ' s state . Accepts an action and returns a tuple ( observation , reward , done , info ) . In the case of multi - agent ...
# Use random actions for all other agents in environment . if self . _multiagent : if not isinstance ( action , list ) : raise UnityGymException ( "The environment was expecting `action` to be a list." ) if len ( action ) != self . _n_agents : raise UnityGymException ( "The environment was expec...
def list_repo ( self ) : """Returns info about all Repos ."""
req = proto . ListRepoRequest ( ) res = self . stub . ListRepo ( req , metadata = self . metadata ) if hasattr ( res , 'repo_info' ) : return res . repo_info return [ ]
def _lowerAsn ( asnfile ) : """Create a copy of the original asn file and change the case of all members to lower - case ."""
# Start by creating a new name for the ASN table _indx = asnfile . find ( '_asn.fits' ) _new_asn = asnfile [ : _indx ] + '_pipeline' + asnfile [ _indx : ] if os . path . exists ( _new_asn ) : os . remove ( _new_asn ) # copy original ASN table to new table shutil . copy ( asnfile , _new_asn ) # Open up the new copy ...
def obj_from_file ( filename = 'annotation.yaml' , filetype = 'auto' ) : '''Read object from file'''
if filetype == 'auto' : _ , ext = os . path . splitext ( filename ) filetype = ext [ 1 : ] if filetype in ( 'yaml' , 'yml' ) : from ruamel . yaml import YAML yaml = YAML ( typ = "unsafe" ) with open ( filename , encoding = "utf-8" ) as f : obj = yaml . load ( f ) if obj is None : ...
def get_resources_nodes ( call = None , resFilter = None ) : '''Retrieve all hypervisors ( nodes ) available on this environment CLI Example : . . code - block : : bash salt - cloud - f get _ resources _ nodes my - proxmox - config'''
log . debug ( 'Getting resource: nodes.. (filter: %s)' , resFilter ) resources = query ( 'get' , 'cluster/resources' ) ret = { } for resource in resources : if 'type' in resource and resource [ 'type' ] == 'node' : name = resource [ 'node' ] ret [ name ] = resource if resFilter is not None : log...
def reconfigure ( working_dir ) : """Reconfigure blockstackd ."""
configure ( working_dir , force = True , interactive = True ) print "Blockstack successfully reconfigured." sys . exit ( 0 )
def disconnect_child ( self , sprite , * handlers ) : """disconnects from child event . if handler is not specified , will disconnect from all the child sprite events"""
handlers = handlers or self . _child_handlers . get ( sprite , [ ] ) for handler in list ( handlers ) : if sprite . handler_is_connected ( handler ) : sprite . disconnect ( handler ) if handler in self . _child_handlers . get ( sprite , [ ] ) : self . _child_handlers [ sprite ] . remove ( handle...
def show_instance ( name = None , instance_id = None , call = None , kwargs = None ) : '''Show the details from EC2 concerning an AMI . Can be called as an action ( which requires a name ) : . . code - block : : bash salt - cloud - a show _ instance myinstance . . . or as a function ( which requires either ...
if not name and call == 'action' : raise SaltCloudSystemExit ( 'The show_instance action requires a name.' ) if call == 'function' : name = kwargs . get ( 'name' , None ) instance_id = kwargs . get ( 'instance_id' , None ) if not name and not instance_id : raise SaltCloudSystemExit ( 'The show_instance ...
def display_start ( self ) : """Set up status display if option selected . NB : this method assumes that the first entry is the iteration count and the last is the rho value ."""
if self . opt [ 'Verbose' ] : # If AutoRho option enabled rho is included in iteration status if self . opt [ 'AutoRho' , 'Enabled' ] : hdrtxt = type ( self ) . hdrtxt ( ) else : hdrtxt = type ( self ) . hdrtxt ( ) [ 0 : - 1 ] # Call utility function to construct status display formatting ...
def metadata ( request , config_loader_path = None , valid_for = None ) : """Returns an XML with the SAML 2.0 metadata for this SP as configured in the settings . py file ."""
conf = get_config ( config_loader_path , request ) metadata = entity_descriptor ( conf ) return HttpResponse ( content = text_type ( metadata ) . encode ( 'utf-8' ) , content_type = "text/xml; charset=utf8" )
def opt_func ( options , check_mandatory = True ) : """Restore argument checks for functions that takes options dicts as arguments Functions that take the option dictionary produced by : meth : ` Options . parse ` as ` kwargs ` loose the argument checking usually performed by the python interpretor . They als...
# A function ` my _ function ` decorated with ` opt _ func ` is replaced by # ` opt _ func ( options ) ( my _ function ) ` . This is equivalent to # ` validate _ arguments ( my _ function ) ` using the ` options ` argument provided # to the decorator . A call to ` my _ function ` results in a call to # ` opt _ func ( o...
def ntp_authentication_key_md5 ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ntp = ET . SubElement ( config , "ntp" , xmlns = "urn:brocade.com:mgmt:brocade-ntp" ) authentication_key = ET . SubElement ( ntp , "authentication-key" ) keyid_key = ET . SubElement ( authentication_key , "keyid" ) keyid_key . text = kwargs . pop ( 'keyid' ) md5 = ET . SubElement ( au...
def highlightBlock ( self , text ) : """Apply syntax highlighting to the given block of text ."""
# Do other syntax formatting for expression , nth , format in self . rules : index = expression . indexIn ( text , 0 ) while index >= 0 : # We actually want the index of the nth match index = expression . pos ( nth ) length = len ( expression . cap ( nth ) ) self . setFormat ( index , le...
def __hammingDistance ( s1 , s2 ) : '''Finds the Hamming distance between two strings . @ param s1 : string @ param s2 : string @ return : the distance @ raise ValueError : if the lenght of the strings differ'''
l1 = len ( s1 ) l2 = len ( s2 ) if l1 != l2 : raise ValueError ( "Hamming distance requires strings of same size." ) return sum ( ch1 != ch2 for ch1 , ch2 in zip ( s1 , s2 ) )
def simxCreateDummy ( clientID , size , color , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
handle = ct . c_int ( ) if color != None : c_color = ( ct . c_ubyte * 12 ) ( * color ) else : c_color = None return c_CreateDummy ( clientID , size , c_color , ct . byref ( handle ) , operationMode ) , handle . value
def salt_spm ( ) : '''The main function for spm , the Salt Package Manager . . versionadded : : 2015.8.0'''
import salt . cli . spm spm = salt . cli . spm . SPM ( ) # pylint : disable = E1120 spm . run ( )
def execute ( st , ** kwargs ) : """Work around for Python3 exec function which doesn ' t allow changes to the local namespace because of scope . This breaks a lot of the old functionality in the code which was origionally in Python2 . So this function runs just like exec except that it returns the output of th...
namespace = kwargs exec ( "b = {}" . format ( st ) , namespace ) return namespace [ 'b' ]
def write_batch ( self , batch ) : """Buffer a batch of items to be written and update internal counters . Calling this method doesn ' t guarantee that all items have been written . To ensure everything has been written you need to call flush ( ) ."""
for item in batch : self . write_buffer . buffer ( item ) key = self . write_buffer . get_key_from_item ( item ) if self . write_buffer . should_write_buffer ( key ) : self . _write_current_buffer_for_group_key ( key ) self . increment_written_items ( ) self . _check_items_limit ( )
def python_value ( self , value ) : """Return the value in the database as an Pendulum object . Returns : pendulum . Pendulum : An instance of Pendulum with the field filled in ."""
value = super ( PendulumDateTimeField , self ) . python_value ( value ) if isinstance ( value , datetime . datetime ) : value = pendulum . instance ( value ) elif isinstance ( value , datetime . date ) : value = pendulum . instance ( datetime . datetime . combine ( value , datetime . datetime . min . time ( ) )...
def count_by_tag ( stack , descriptor ) : """Returns the count of currently running or pending instances that match the given stack and deployer combo"""
ec2_conn = boto . ec2 . connection . EC2Connection ( ) resses = ec2_conn . get_all_instances ( filters = { 'tag:stack' : stack , 'tag:descriptor' : descriptor } ) instance_list_raw = list ( ) [ [ instance_list_raw . append ( x ) for x in res . instances ] for res in resses ] instance_list = [ x for x in instance_list_r...
def setup ( app ) : """Called by Sphinx during phase 0 ( initialization ) . : param sphinx . application . Sphinx app : Sphinx application object . : returns : Extension version . : rtype : dict"""
# Used internally . For rebuilding all pages when one or versions fail . app . add_config_value ( 'sphinxcontrib_versioning_versions' , SC_VERSIONING_VERSIONS , 'html' ) # Needed for banner . app . config . html_static_path . append ( STATIC_DIR ) app . add_stylesheet ( 'banner.css' ) # Tell Sphinx which config values ...
def get_google_drive_folder_location ( ) : """Try to locate the Google Drive folder . Returns : ( str ) Full path to the current Google Drive folder"""
gdrive_db_path = 'Library/Application Support/Google/Drive/sync_config.db' yosemite_gdrive_db_path = ( 'Library/Application Support/Google/Drive/' 'user_default/sync_config.db' ) yosemite_gdrive_db = os . path . join ( os . environ [ 'HOME' ] , yosemite_gdrive_db_path ) if os . path . isfile ( yosemite_gdrive_db ) : ...
def get_dict ( self ) : """Returns a dict containing the host ' s attributes . The following keys are contained : - hostname - address - protocol - port : rtype : dict : return : The resulting dictionary ."""
return { 'hostname' : self . get_name ( ) , 'address' : self . get_address ( ) , 'protocol' : self . get_protocol ( ) , 'port' : self . get_tcp_port ( ) }
def apply_transforms ( self , data , rot_deg ) : """Apply transformations to the given data . These include flip / swap X / Y , invert Y , and rotation . Parameters data : ndarray Data to be transformed . rot _ deg : float Rotate the data by the given degrees . Returns data : ndarray Transformed d...
start_time = time . time ( ) wd , ht = self . get_dims ( data ) xoff , yoff = self . _org_xoff , self . _org_yoff # Do transforms as necessary flip_x , flip_y = self . t_ [ 'flip_x' ] , self . t_ [ 'flip_y' ] swap_xy = self . t_ [ 'swap_xy' ] data = trcalc . transform ( data , flip_x = flip_x , flip_y = flip_y , swap_x...
def create_shape ( self ) : """Create the toolkit shape for the proxy object . This method is called during the top - down pass , just before the ' init _ shape ( ) ' method is called . This method should create the toolkit widget and assign it to the ' widget ' attribute ."""
d = self . declaration if d . shape1 and d . shape2 : self . shape = self . _do_operation ( d . shape1 , d . shape2 ) else : self . shape = None
def convert ( model , feature_names , target ) : """Convert a Support Vector Classtion ( SVC ) model to the protobuf spec . Parameters model : SVC A trained SVC encoder model . feature _ names : [ str ] , optional ( default = None ) Name of the input columns . target : str , optional ( default = None ) ...
if not ( _HAS_SKLEARN ) : raise RuntimeError ( 'scikit-learn not found. scikit-learn conversion API is disabled.' ) spec = _generate_base_svm_classifier_spec ( model ) spec = set_classifier_interface_params ( spec , feature_names , model . classes_ , 'supportVectorClassifier' , output_features = target ) svm = spec...
def _add_point_scalar ( self , scalars , name , set_active = False , deep = True ) : """Adds point scalars to the mesh Parameters scalars : numpy . ndarray Numpy array of scalars . Must match number of points . name : str Name of point scalars to add . set _ active : bool , optional Sets the scalars t...
if not isinstance ( scalars , np . ndarray ) : raise TypeError ( 'Input must be a numpy.ndarray' ) if scalars . shape [ 0 ] != self . n_points : raise Exception ( 'Number of scalars must match the number of ' + 'points' ) # need to track which arrays are boolean as all boolean arrays # must be stored as uint8 i...
def moveEvent ( self , event ) : """Reimplement Qt method"""
if not self . isMaximized ( ) and not self . fullscreen_flag : self . window_position = self . pos ( ) QMainWindow . moveEvent ( self , event ) # To be used by the tour to be able to move self . sig_moved . emit ( event )
def editPerson ( self , person , nickname , edits ) : """Change the name and contact information associated with the given L { Person } . @ type person : L { Person } @ param person : The person which will be modified . @ type nickname : C { unicode } @ param nickname : The new value for L { Person . name...
for existing in self . store . query ( Person , Person . name == nickname ) : if existing is person : continue raise ValueError ( "A person with the name %r exists already." % ( nickname , ) ) oldname = person . name person . name = nickname self . _callOnOrganizerPlugins ( 'personNameChanged' , person ...
def font_width ( self ) : """Return the badge font width ."""
return self . get_font_width ( font_name = self . font_name , font_size = self . font_size )
def cudnnDestroy ( handle ) : """Release cuDNN resources . Release hardware resources used by cuDNN . Parameters handle : cudnnHandle cuDNN context ."""
status = _libcudnn . cudnnDestroy ( ctypes . c_void_p ( handle ) ) cudnnCheckStatus ( status )
def get_collection ( self , collection , filter = None , fields = None , page_size = None ) : """Returns a specific collection from the asset service with the given collection endpoint . Supports passing through parameters such as . . . - filters such as " name = Vesuvius " following GEL spec - fields such ...
params = { } if filter : params [ 'filter' ] = filter if fields : params [ 'fields' ] = fields if page_size : params [ 'pageSize' ] = page_size uri = self . uri + '/v1' + collection return self . service . _get ( uri , params = params )
def group_members ( self , group_id , include_orphans = False ) : """Find all group member trigger definitions : param group _ id : group trigger id : param include _ orphans : If True , include orphan members : return : list of asociated group members as trigger objects"""
params = { 'includeOrphans' : str ( include_orphans ) . lower ( ) } url = self . _service_url ( [ 'triggers' , 'groups' , group_id , 'members' ] , params = params ) return Trigger . list_to_object_list ( self . _get ( url ) )
def roc_curve ( df , col_true = None , col_pred = None , col_scores = None , pos_label = 1 ) : r"""Compute true positive rate ( TPR ) , false positive rate ( FPR ) and threshold from predicted DataFrame . Note that this method will trigger the defined flow to execute . : param df : predicted data frame : type...
if not col_pred : col_pred = get_field_name_by_role ( df , FieldRole . PREDICTED_CLASS ) if not col_scores : col_scores = get_field_name_by_role ( df , FieldRole . PREDICTED_SCORE ) thresh , tp , fn , tn , fp = _run_roc_node ( df , pos_label , col_true , col_pred , col_scores ) if np is not None : tpr = tp ...
def read_stream_stats ( self ) : """: return : dictionary { stream index { stat name : value } } . Sea XenaStream . stats _ captions ."""
stream_stats = OrderedDict ( ) for stream in self . streams . values ( ) : stream_stats [ stream ] = stream . read_stats ( ) return stream_stats
def collect_variables ( self , g_scope = 'gen' , d_scope = 'discrim' ) : """Assign ` self . g _ vars ` to the parameters under scope ` g _ scope ` , and same with ` self . d _ vars ` ."""
self . g_vars = tf . get_collection ( tf . GraphKeys . TRAINABLE_VARIABLES , g_scope ) assert self . g_vars self . d_vars = tf . get_collection ( tf . GraphKeys . TRAINABLE_VARIABLES , d_scope ) assert self . d_vars
def _check_metrics ( cls , schema , metrics ) : """Ensure that returned metrics are properly exposed"""
for name , value in metrics . items ( ) : metric = schema . get ( name ) if not metric : message = "Unexpected metric '{}' returned" . format ( name ) raise Exception ( message ) cls . _check_metric ( schema , metric , name , value )
def check_with_pyflakes ( source_code , filename = None ) : """Check source code with pyflakes Returns an empty list if pyflakes is not installed"""
try : if filename is None : filename = '<string>' try : source_code += '\n' except TypeError : # Python 3 source_code += to_binary_string ( '\n' ) import _ast from pyflakes . checker import Checker # First , compile into an AST and handle syntax errors . try : ...
def save_dir_list ( key , * dirs_refs ) : """Convert the given parameters to a special JSON object . Each parameter is a dir - refs specification of the form : < dir - path > : < reference1 > , < reference2 > , . . . , where the colon ' : ' and the list of references are optional . JSON object is of the for...
dir_list = [ ] for dir_refs in dirs_refs : if ':' in dir_refs : try : dir_path , refs = dir_refs . split ( ':' ) except ValueError as e : return error ( "Only one colon ':' allowed in dir-refs specification." ) else : dir_path , refs = dir_refs , None if not o...
def recycle_view ( self , position ) : """Tell the view to render the item at the given position"""
d = self . declaration if position < len ( d . parent . items ) : d . index = position d . item = d . parent . items [ position ] else : d . index = - 1 d . item = None
def mkpart ( self , disk , start , end , part_type = 'primary' ) : """Make partition on disk : param disk : device path ( / dev / sda , / dev / sdb , etc . . . ) : param start : partition start as accepted by parted mkpart : param end : partition end as accepted by parted mkpart : param part _ type : partit...
args = { 'disk' : disk , 'start' : start , 'end' : end , 'part_type' : part_type , } self . _mkpart_chk . check ( args ) response = self . _client . raw ( 'disk.mkpart' , args ) result = response . get ( ) if result . state != 'SUCCESS' : raise RuntimeError ( 'failed to create partition: %s' % result . stderr )
def linkCustomerToVerifiedUser ( sender , ** kwargs ) : """If a Registration is processed in which the associated Customer does not yet have a User , then check to see if the Customer ' s email address has been verified as belonging to a specific User , and if that User has an associated Customer . If such a ...
registration = kwargs . get ( 'registration' , None ) if not registration or ( hasattr ( registration . customer , 'user' ) and registration . customer . user ) : return logger . debug ( 'Checking for User for Customer with no associated registration.' ) customer = registration . customer try : verified_email =...
def check_process ( pidfile ) : """Read pid file and check process status . Return ( running , pid ) ."""
# Check pid file try : handle = open ( pidfile , 'r' ) except IOError as exc : if exc . errno == errno . ENOENT : # pid file disappeared return False , 0 raise try : pid = int ( handle . read ( ) . strip ( ) , 10 ) except ( TypeError , ValueError ) as exc : raise EnvironmentError ( "Invalid ...
async def redis ( self ) -> aioredis . RedisConnection : """Get Redis connection This property is awaitable ."""
# Use thread - safe asyncio Lock because this method without that is not safe async with self . _connection_lock : if self . _redis is None : self . _redis = await aioredis . create_connection ( ( self . _host , self . _port ) , db = self . _db , password = self . _password , ssl = self . _ssl , loop = self...
def get_package_version ( self , feed_id , package_id , package_version_id , project = None , include_urls = None , is_listed = None , is_deleted = None ) : """GetPackageVersion . [ Preview API ] Get details about a specific package version . : param str feed _ id : Name or Id of the feed . : param str packag...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if feed_id is not None : route_values [ 'feedId' ] = self . _serialize . url ( 'feed_id' , feed_id , 'str' ) if package_id is not None : route_values [ 'packageId' ] = self . _ser...
def auth_creds ( cls , username , password ) : """Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization mechanizm does not need it . : return : string token"""
store = goldman . sess . store login = store . find ( cls . RTYPE , 'username' , username ) if not login : msg = 'No login found by that username. Spelling error?' raise AuthRejected ( ** { 'detail' : msg } ) elif login . locked : msg = 'The login account is currently locked out.' raise AuthRejected ( *...
def get_img_tag ( self , title = '' , alt_text = '' , ** kwargs ) : """Build a < img > tag for the image with the specified options . Returns : an HTML fragment ."""
try : style = [ ] for key in ( 'img_style' , 'style' ) : if key in kwargs : if isinstance ( kwargs [ key ] , ( list , tuple , set ) ) : style += list ( kwargs [ key ] ) else : style . append ( kwargs [ key ] ) if 'shape' in kwargs : sha...
def routing_area_2_json ( self ) : """transform ariane _ clip3 routing area object to Ariane server JSON obj : return : Ariane JSON obj"""
LOGGER . debug ( "RoutingArea.routing_area_2_json" ) json_obj = { 'routingAreaID' : self . id , 'routingAreaName' : self . name , 'routingAreaDescription' : self . description , 'routingAreaType' : self . type , 'routingAreaMulticast' : self . multicast , 'routingAreaLocationsID' : self . loc_ids , 'routingAreaSubnetsI...
def expand_dependencies_section ( section , kwargs ) : """Expands dependency section , e . g . substitues " use : foo " for its contents , but doesn ' t evaluate conditions nor substitue variables ."""
deps = [ ] for dep in section : for dep_type , dep_list in dep . items ( ) : if dep_type in [ 'call' , 'use' ] : deps . extend ( Command ( dep_type , dep_list , kwargs ) . run ( ) ) elif dep_type . startswith ( 'if ' ) or dep_type == 'else' : deps . append ( { dep_type : expa...
def append_to_history ( self , filename , command , go_to_eof ) : """Append an entry to history filename . Args : filename ( str ) : file to be updated in a new tab . command ( str ) : line to be added . go _ to _ eof ( bool ) : scroll to the end of file ."""
if not is_text_string ( filename ) : # filename is a QString filename = to_text_string ( filename . toUtf8 ( ) , 'utf-8' ) command = to_text_string ( command ) index = self . filenames . index ( filename ) self . editors [ index ] . append ( command ) if go_to_eof : self . editors [ index ] . set_cursor_positio...
def _handle_is_dag_stopped ( self , request ) : """The handler for the dag _ stopped request . The dag _ stopped request checks whether a dag is flagged to be terminated . Args : request ( Request ) : Reference to a request object containing the incoming request . The payload has to contain the following ...
return Response ( success = True , uid = request . uid , payload = { 'is_stopped' : request . payload [ 'dag_name' ] in self . _stop_dags } )