signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _process_cmap ( cmap ) : '''Returns a kwarg dict suitable for a ColorScale'''
option = { } if isinstance ( cmap , str ) : option [ 'scheme' ] = cmap elif isinstance ( cmap , list ) : option [ 'colors' ] = cmap else : raise ValueError ( '''`cmap` must be a string (name of a color scheme) or a list of colors, but a value of {} was given ...
def thread_local_property ( name ) : '''Creates a thread local ` ` property ` ` .'''
name = '_thread_local_' + name def fget ( self ) : try : return getattr ( self , name ) . value except AttributeError : return None def fset ( self , value ) : getattr ( self , name ) . value = value return property ( fget = fget , fset = fset )
def latlon_round ( latlon , spacing = 1000 ) : '''round to nearest grid corner'''
g = latlon_to_grid ( latlon ) g . easting = ( g . easting // spacing ) * spacing g . northing = ( g . northing // spacing ) * spacing return g . latlon ( )
def duplicates ( base , items ) : """Get an iterator of items similar but not equal to the base . @ param base : base item to perform comparison against @ param items : list of items to compare to the base @ return : generator of items sorted by similarity to the base"""
for item in items : if item . similarity ( base ) and not item . equality ( base ) : yield item
def deprecated ( msg ) : """Marks a function / method as deprecated . Takes one argument , a message to be logged with information on future usage of the function or alternative methods to call . Args : msg ( str ) : Deprecation message to be logged Returns : ` callable `"""
def decorator ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : logging . getLogger ( __name__ ) . warning ( msg ) return func ( * args , ** kwargs ) return wrapper return decorator
def alter_function ( self , dbName , funcName , newFunc ) : """Parameters : - dbName - funcName - newFunc"""
self . send_alter_function ( dbName , funcName , newFunc ) self . recv_alter_function ( )
def restrict_to ( self , restriction ) : """Restrict list operations to the hosts given in restriction . This is used to exclude failed hosts in main playbook code , don ' t use this for other reasons ."""
if type ( restriction ) != list : restriction = [ restriction ] self . _restriction = restriction
def processPreKeyBundle ( self , preKey ) : """: type preKey : PreKeyBundle"""
if not self . identityKeyStore . isTrustedIdentity ( self . recipientId , preKey . getIdentityKey ( ) ) : raise UntrustedIdentityException ( self . recipientId , preKey . getIdentityKey ( ) ) if preKey . getSignedPreKey ( ) is not None and not Curve . verifySignature ( preKey . getIdentityKey ( ) . getPublicKey ( )...
def get_params ( img , output_size ) : """Get parameters for ` ` crop ` ` for a random crop . Args : img ( PIL Image ) : Image to be cropped . output _ size ( tuple ) : Expected output size of the crop . Returns : tuple : params ( i , j , h , w ) to be passed to ` ` crop ` ` for random crop ."""
w , h , * _ = img . shape th , tw = output_size if w == tw and h == th : return 0 , 0 , h , w i = random . randint ( 0 , h - th ) j = random . randint ( 0 , w - tw ) return i , j , th , tw
def get_protocol_version ( protocol = None , target = None ) : """Return a suitable pickle protocol version for a given target . Arguments : target : The internals description of the targeted python version . If this is ` ` None ` ` the specification of the currently running python version will be used . ...
target = get_py_internals ( target ) if protocol is None : protocol = target [ 'pickle_default_protocol' ] if protocol > cPickle . HIGHEST_PROTOCOL : warnings . warn ( 'Downgrading pickle protocol, running python supports up to %d.' % cPickle . HIGHEST_PROTOCOL ) protocol = cPickle . HIGHEST_PROTOCOL target...
def run_sparser ( fname , output_fmt , outbuf = None , timeout = 600 ) : """Return the path to reading output after running Sparser reading . Parameters fname : str The path to an input file to be processed . Due to the Spaser executable ' s assumptions , the file name needs to start with PMC and should b...
if not sparser_path or not os . path . exists ( sparser_path ) : logger . error ( 'Sparser executable not set in %s' % sparser_path_var ) return None if output_fmt == 'xml' : format_flag = '-x' suffix = '.xml' elif output_fmt == 'json' : format_flag = '-j' suffix = '.json' else : logger . er...
def _get_ess ( sample_array ) : """Compute the effective sample size for a 2D array ."""
shape = sample_array . shape if len ( shape ) != 2 : raise TypeError ( "Effective sample size calculation requires 2 dimensional arrays." ) n_chain , n_draws = shape if n_chain <= 1 : raise TypeError ( "Effective sample size calculation requires multiple chains." ) acov = np . asarray ( [ _autocov ( sample_arra...
def whois_list ( request , format = None ) : """Retrieve basic whois information related to a layer2 or layer3 network address ."""
results = [ ] # layer3 results for ip in Ip . objects . select_related ( ) . all ( ) : interface = ip . interface user = interface . device . node . user device = interface . device results . append ( { 'address' : str ( ip . address ) , 'user' : user . username , 'name' : user . get_full_name ( ) , 'de...
def _inputLoop ( self ) : """Loop and copy console - > serial until EXIT _ CHARCTER character is found ."""
# Switch statement for handling " special " characters actionChars = { self . EXIT_CHARACTER : self . _exit , self . EXIT_CHARACTER_2 : self . _exit , console . CURSOR_LEFT : self . _cursorLeft , console . CURSOR_RIGHT : self . _cursorRight , console . CURSOR_UP : self . _cursorUp , console . CURSOR_DOWN : self . _curs...
def may_be_null_is_nullable ( ) : """If may _ be _ null returns nullable or if NULL can be passed in . This can still be wrong if the specific typelib is older than the linked libgirepository . https : / / bugzilla . gnome . org / show _ bug . cgi ? id = 660879 # c47"""
repo = GIRepository ( ) repo . require ( "GLib" , "2.0" , 0 ) info = repo . find_by_name ( "GLib" , "spawn_sync" ) # this argument is ( allow - none ) and can never be ( nullable ) return not info . get_arg ( 8 ) . may_be_null
def __merge_json_values ( current , previous ) : """Merges the values between the current and previous run of the script ."""
for value in current : name = value [ 'name' ] # Find the previous value previous_value = __find_and_remove_value ( previous , value ) if previous_value is not None : flags = value [ 'flags' ] previous_flags = previous_value [ 'flags' ] if flags != previous_flags : lo...
def new_term ( self , term , value , ** kwargs ) : """Create a new root - level term in this section"""
tc = self . doc . get_term_class ( term . lower ( ) ) t = tc ( term , value , doc = self . doc , parent = None , section = self ) . new_children ( ** kwargs ) self . doc . add_term ( t ) return t
def removeClass ( self , cn ) : '''Remove classes'''
if cn : ks = self . _classes if ks : for cn in cn . split ( ) : if cn in ks : ks . remove ( cn ) return self
def onLeftDown ( self , event = None ) : """left button down : report x , y coords , start zooming mode"""
if event is None : return self . cursor_mode_action ( 'leftdown' , event = event ) self . ForwardEvent ( event = event . guiEvent )
def metadata ( self ) : """Retrieves the remote server metadata dictionary . : returns : Dictionary containing server metadata details"""
resp = self . r_session . get ( self . server_url ) resp . raise_for_status ( ) return response_to_json_dict ( resp )
def extend ( self , ** kwargs ) : """Returns a new instance with this instance ' s data overlayed by the key - value args ."""
props = self . copy ( ) props . update ( kwargs ) return TemplateData ( ** props )
def _load ( self , event ) : """Processes a load event by setting the properties of this record to the data restored from the database . : param event : < orb . events . LoadEvent >"""
if not event . data : return context = self . context ( ) schema = self . schema ( ) dbname = schema . dbname ( ) clean = { } for col , value in event . data . items ( ) : try : model_dbname , col_name = col . split ( '.' ) except ValueError : col_name = col model_dbname = dbname ...
def parallelize ( mapfunc , workers = None ) : '''Parallelize the mapfunc with multithreading . mapfunc calls will be partitioned by the provided list of arguments . Each item in the list will represent one call ' s arguments . They can be tuples if the function takes multiple arguments , but one - tupling is...
workers = workers if workers else _get_default_workers ( ) def wrapper ( args_list ) : result = { } with concurrent . futures . ThreadPoolExecutor ( max_workers = workers ) as executor : tasks = { } for args in args_list : if isinstance ( args , tuple ) : task = execu...
def to_threepoint ( center , radius , angles = None ) : """For 2D arcs , given a center and radius convert them to three points on the arc . Parameters center : ( 2 , ) float Center point on the plane radius : float Radius of arc angles : ( 2 , ) float Angles in radians for start and end angle if ...
# if no angles provided assume we want a half circle if angles is None : angles = [ 0.0 , np . pi ] # force angles to float64 angles = np . asanyarray ( angles , dtype = np . float64 ) if angles . shape != ( 2 , ) : raise ValueError ( 'angles must be (2,)!' ) # provide the wrap around if angles [ 1 ] < angles [...
def replace_suffix ( name , new_suffix ) : """Replaces the suffix of name by new _ suffix . If no suffix exists , the new one is added ."""
assert isinstance ( name , basestring ) assert isinstance ( new_suffix , basestring ) split = os . path . splitext ( name ) return split [ 0 ] + new_suffix
def until_connected ( self , timeout = None ) : """Return future that resolves when the client is connected ."""
t0 = self . ioloop . time ( ) yield self . until_running ( timeout = timeout ) t1 = self . ioloop . time ( ) if timeout : timedelta = timeout - ( t1 - t0 ) else : timedelta = None assert get_thread_ident ( ) == self . ioloop_thread_id yield self . _connected . until_set ( timeout = timedelta )
def addevensubodd ( operator , operand ) : """Add even numbers , subtract odd ones . See http : / / 1w6 . org / w6"""
try : for i , x in enumerate ( operand ) : if x % 2 : operand [ i ] = - x return operand except TypeError : if operand % 2 : return - operand return operand
def delete ( self , key ) : '''Removes the object named by ` key ` . Removes the object from the collection corresponding to ` ` key . path ` ` . Args : key : Key naming the object to remove .'''
try : del self . _collection ( key ) [ key ] if len ( self . _collection ( key ) ) == 0 : del self . _items [ str ( key . path ) ] except KeyError , e : pass
def find_initial_offset ( self , pyramids = 6 ) : """Estimate time offset This sets and returns the initial time offset estimation . Parameters pyramids : int Number of pyramids to use for ZNCC calculations . If initial estimation of time offset fails , try lowering this value . Returns float Estima...
flow = self . video . flow gyro_rate = self . parameter [ 'gyro_rate' ] frame_times = np . arange ( len ( flow ) ) / self . video . frame_rate gyro_times = np . arange ( self . gyro . num_samples ) / gyro_rate time_offset = timesync . sync_camera_gyro ( flow , frame_times , self . gyro . data . T , gyro_times , levels ...
def wx_menu ( self ) : '''return a wx . Menu ( ) for this menu'''
from MAVProxy . modules . lib . wx_loader import wx menu = wx . Menu ( ) for i in range ( len ( self . items ) ) : m = self . items [ i ] m . _append ( menu ) return menu
def create_string ( self , key , value ) : """Create method of CRUD operation for string data . Args : key ( string ) : The variable to write to the DB . value ( any ) : The data to write to the DB . Returns : ( string ) : Result of DB write ."""
data = None if key is not None and value is not None : if isinstance ( value , ( bool , list , int , dict ) ) : # value = str ( value ) value = u'{}' . format ( value ) # data = self . db . create ( key . strip ( ) , str ( json . dumps ( value ) ) ) data = self . db . create ( key . strip ( ) , u'{}...
def set_job ( user , path , mask , cmd ) : '''Sets an incron job up for a specified user . CLI Example : . . code - block : : bash salt ' * ' incron . set _ job root ' / root ' ' IN _ MODIFY ' ' echo " $ $ $ @ $ # $ % $ & " ' '''
# Scrub the types mask = six . text_type ( mask ) . upper ( ) # Check for valid mask types for item in mask . split ( ',' ) : if item not in _MASK_TYPES : return 'Invalid mask type: {0}' . format ( item ) updated = False arg_mask = mask . split ( ',' ) arg_mask . sort ( ) lst = list_tab ( user ) updated_cro...
def create_asset ( json ) : """Create : class : ` . resources . Asset ` from JSON . : param json : JSON dict . : return : Asset instance ."""
result = Asset ( json [ 'sys' ] ) file_dict = json [ 'fields' ] [ 'file' ] result . fields = json [ 'fields' ] result . url = file_dict [ 'url' ] result . mimeType = file_dict [ 'contentType' ] return result
def _get_running_parameters ( self , scale , f , loop = 3 ) : """Get the running parameters ( e . g . quark masses and the strong coupling at a given scale ."""
p = { } p [ 'alpha_s' ] = qcd . alpha_s ( scale , self . f , self . parameters [ 'alpha_s' ] , loop = loop ) p [ 'm_b' ] = qcd . m_b ( self . parameters [ 'm_b' ] , scale , self . f , self . parameters [ 'alpha_s' ] , loop = loop ) p [ 'm_c' ] = qcd . m_c ( self . parameters [ 'm_c' ] , scale , self . f , self . parame...
def reproject_on_template_raster ( src_file , dst_file , template_file , resampling = "near" , compress = None , overwrite = False ) : """Reproject a one - band raster to fit the projection , extend , pixel size etc . of a template raster . Function based on https : / / stackoverflow . com / questions / 10454316 ...
if not overwrite and Path ( dst_file ) . exists ( ) : print ( "Processing skipped. Destination file exists." ) return 0 GDAL_RESAMPLING_ALGORITHMS = { "bilinear" : "GRA_Bilinear" , "cubic" : "GRA_Cubic" , "cubicspline" : "GRA_CubicSpline" , "lanczos" : "GRA_Lanczos" , "average" : "GRA_Average" , "mode" : "GRA_M...
def Images ( self , run , tag ) : """Retrieve the image events associated with a run and tag . Args : run : A string name of the run for which values are retrieved . tag : A string name of the tag for which values are retrieved . Raises : KeyError : If the run is not found , or the tag is not available fo...
accumulator = self . GetAccumulator ( run ) return accumulator . Images ( tag )
def build_path ( levels ) : """make a linear directory structure from a list of path levels names levels = [ " chefdir " , " trees " , " test " ] builds . / chefdir / trees / test /"""
path = os . path . join ( * levels ) if not dir_exists ( path ) : os . makedirs ( path ) return path
def zrevrange ( self , key , start , stop , withscores = False , encoding = _NOTSET ) : """Return a range of members in a sorted set , by index , with scores ordered from high to low . : raises TypeError : if start or stop is not int"""
if not isinstance ( start , int ) : raise TypeError ( "start argument must be int" ) if not isinstance ( stop , int ) : raise TypeError ( "stop argument must be int" ) if withscores : args = [ b'WITHSCORES' ] else : args = [ ] fut = self . execute ( b'ZREVRANGE' , key , start , stop , * args , encoding ...
def register_options ( cls , register ) : """Register an option to make capturing snapshots optional . This class is intended to be extended by Jvm resolvers ( coursier and ivy ) , and the option name should reflect that ."""
super ( JvmResolverBase , cls ) . register_options ( register ) # TODO This flag should be defaulted to True when we are doing hermetic execution , # and should probably go away as we move forward into that direction . register ( '--capture-snapshots' , type = bool , default = False , help = 'Enable capturing snapshots...
def _url_search_builder ( term , country = 'US' , media = 'all' , entity = None , attribute = None , limit = 50 ) : """Builds the URL to perform the search based on the provided data : param term : String . The URL - encoded text string you want to search for . Example : Steven Wilson . The method will take car...
built_url = base_search_url + _parse_query ( term ) built_url += ampersand + parameters [ 1 ] + country built_url += ampersand + parameters [ 2 ] + media if entity is not None : built_url += ampersand + parameters [ 3 ] + entity if attribute is not None : built_url += ampersand + parameters [ 4 ] + attribute bu...
def ConsultarCTGActivosPorPatente ( self , patente = "ZZZ999" ) : "Consulta de CTGs activos por patente"
ret = self . client . consultarCTGActivosPorPatente ( request = dict ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuitRepresentado' : self . Cuit , } , patente = patente , ) ) [ 'response' ] self . __analizar_errores ( ret ) datos = ret . get ( 'arrayConsultarCTGActivosPorPatenteResponse' ) if datos : ...
def getIndicesFromInstId ( self , instId ) : """Return index values for instance identification"""
if instId in self . _idToIdxCache : return self . _idToIdxCache [ instId ] indices = [ ] for impliedFlag , modName , symName in self . _indexNames : mibObj , = mibBuilder . importSymbols ( modName , symName ) try : syntax , instId = self . oidToValue ( mibObj . syntax , instId , impliedFlag , indice...
def x ( self ) : """Block the main thead until future finish , return the future . result ( ) ."""
with self . _condition : result = None if not self . done ( ) : self . _condition . wait ( self . _timeout ) if not self . done ( ) : # timeout self . set_exception ( TimeoutError ( ) ) if self . _state in [ CANCELLED , CANCELLED_AND_NOTIFIED ] : # cancelled result = CancelledErr...
def toLily ( self ) : '''Method which converts the object instance and its attributes to a string of lilypond code : return : str of lilypond code'''
lilystring = "" if hasattr ( self , "size" ) : try : size = float ( self . size ) lilystring += "\\abs-fontsize #" + str ( self . size ) + " " except : lilystring += "\\" + str ( self . size ) + " " if hasattr ( self , "font" ) : fonts_available = [ "sans" , "typewriter" , "roman" ] ...
def move_object ( self , container , obj , new_container , new_obj_name = None , new_reference = False , content_type = None ) : """Works just like copy _ object , except that the source object is deleted after a successful copy . You can optionally change the content _ type of the object by supplying that in...
new_obj_etag = self . copy_object ( container , obj , new_container , new_obj_name = new_obj_name , content_type = content_type ) if not new_obj_etag : return # Copy succeeded ; delete the original . self . delete_object ( container , obj ) if new_reference : nm = new_obj_name or utils . get_name ( obj ) re...
def _sign_block ( self , block ) : """The block should be complete and the final signature from the publishing validator ( this validator ) needs to be added ."""
block_header = block . block_header header_bytes = block_header . SerializeToString ( ) signature = self . _identity_signer . sign ( header_bytes ) block . set_signature ( signature ) return block
def help_center_section_subscriptions ( self , section_id , locale = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / subscriptions # list - section - subscriptions"
api_path = "/api/v2/help_center/sections/{section_id}/subscriptions.json" api_path = api_path . format ( section_id = section_id ) if locale : api_opt_path = "/api/v2/help_center/{locale}/sections/{section_id}/subscriptions.json" api_path = api_opt_path . format ( section_id = section_id , locale = locale ) ret...
def product ( * arrays ) : """Generate a cartesian product of input arrays . Parameters arrays : list of array - like 1 - D arrays to form the cartesian product of . Returns out : ndarray 2 - D array of shape ( M , len ( arrays ) ) containing cartesian products formed of input arrays ."""
arrays = [ np . asarray ( x ) for x in arrays ] shape = ( len ( x ) for x in arrays ) dtype = arrays [ 0 ] . dtype ix = np . indices ( shape ) ix = ix . reshape ( len ( arrays ) , - 1 ) . T out = np . empty_like ( ix , dtype = dtype ) for n , _ in enumerate ( arrays ) : out [ : , n ] = arrays [ n ] [ ix [ : , n ] ]...
def build ( context , provider , ** kwargs ) : # pylint : disable = unused - argument """Build static site ."""
session = get_session ( provider . region ) options = kwargs . get ( 'options' , { } ) context_dict = { } context_dict [ 'artifact_key_prefix' ] = "%s-%s-" % ( options [ 'namespace' ] , options [ 'name' ] ) # noqa default_param_name = "%shash" % context_dict [ 'artifact_key_prefix' ] if options . get ( 'build_output' )...
def compute_ ( self ) : """Main core - guided loop , which iteratively calls a SAT oracle , extracts a new unsatisfiable core and processes it . The loop finishes as soon as a satisfiable formula is obtained . If specified in the command line , the method additionally calls : meth : ` adapt _ am1 ` to detec...
# trying to adapt ( simplify ) the formula # by detecting and using atmost1 constraints if self . adapt : self . adapt_am1 ( ) # main solving loop while not self . oracle . solve ( assumptions = self . sels + self . sums ) : self . get_core ( ) if not self . core : # core is empty , i . e . hard part is uns...
def fit ( model , params , X_train , y_train , X_test , y_test , additional_calls , fit_params = None , scorer = None , random_state = None , ) : """Find a good model and search among a space of hyper - parameters This does a hyper - parameter search by creating many models and then fitting them incrementally o...
return default_client ( ) . sync ( _fit , model , params , X_train , y_train , X_test , y_test , additional_calls , fit_params = fit_params , scorer = scorer , random_state = random_state , )
def start ( st_reg_number ) : """Checks the number valiaty for the Amazonas state"""
weights = range ( 2 , 10 ) digits = st_reg_number [ 0 : len ( st_reg_number ) - 1 ] control_digit = 11 check_digit = st_reg_number [ - 1 : ] if len ( st_reg_number ) != 9 : return False sum_total = 0 for i in weights : sum_total = sum_total + i * int ( digits [ i - 2 ] ) if sum_total < control_digit : contr...
def check_model ( self ) : """Checks the model for various errors . This method checks for the following error - * Checks if the CPDs associated with nodes are consistent with their parents . Returns check : boolean True if all the checks pass ."""
for node in self . nodes ( ) : cpd = self . get_cpds ( node = node ) if isinstance ( cpd , LinearGaussianCPD ) : if set ( cpd . evidence ) != set ( self . get_parents ( node ) ) : raise ValueError ( "CPD associated with %s doesn't have " "proper parents associated with it." % node ) return T...
def profile ( ctx , filepath , calltree = False ) : """Run and profile a given Python script . : param str filepath : The filepath of the script to profile"""
filepath = pathlib . Path ( filepath ) if not filepath . is_file ( ) : log ( "profile" , f"no such script {filepath!s}" , LogLevel . ERROR ) else : if calltree : log ( "profile" , f"profiling script {filepath!s} calltree" ) ctx . run ( ( f"python -m cProfile -o .profile.cprof {filepath!s}" " && ...
def scaled_pressure3_encode ( self , time_boot_ms , press_abs , press_diff , temperature ) : '''Barometer readings for 3rd barometer time _ boot _ ms : Timestamp ( milliseconds since system boot ) ( uint32 _ t ) press _ abs : Absolute pressure ( hectopascal ) ( float ) press _ diff : Differential pressure 1 (...
return MAVLink_scaled_pressure3_message ( time_boot_ms , press_abs , press_diff , temperature )
def deleteRole ( self , * args , ** kwargs ) : """Delete Role Delete a role . This operation will succeed regardless of whether or not the role exists . This method is ` ` stable ` `"""
return self . _makeApiCall ( self . funcinfo [ "deleteRole" ] , * args , ** kwargs )
def qemu_rebase ( target , backing_file , safe = True , fail_on_error = True ) : """changes the backing file of ' source ' to ' backing _ file ' If backing _ file is specified as " " ( the empty string ) , then the image is rebased onto no backing file ( i . e . it will exist independently of any backing file...
cmd = [ 'qemu-img' , 'rebase' , '-b' , backing_file , target ] if not safe : cmd . insert ( 2 , '-u' ) return run_command_with_validation ( cmd , fail_on_error , msg = 'Failed to rebase {target} onto {backing_file}' . format ( target = target , backing_file = backing_file ) )
def distant_total_damped_rated_level ( octave_frequencies , distance , temp , relhum , reference_distance = 1.0 ) : """Calculates the damped , A - rated total sound pressure level in a given distance , temperature and relative humidity from octave frequency sound pressure levels in a reference distance"""
damping_distance = distance - reference_distance sums = 0.0 for band in OCTAVE_BANDS . keys ( ) : if band not in octave_frequencies : continue if octave_frequencies [ band ] is None : continue # distance - adjusted level per band distant_val = distant_level ( reference_level = float ( oc...
def on_connect ( self , connection ) : "Called when the socket connects"
self . _sock = connection . _sock self . _buffer = SocketBuffer ( self . _sock , self . socket_read_size ) self . encoder = connection . encoder
def validate_to_schema ( nanopub , schema ) -> Tuple [ bool , List [ Tuple [ str , str ] ] ] : """Validate nanopub against jsonschema for nanopub Args : nanopub ( Mapping [ str , Any ] ) : nanopub dict schema ( Mapping [ str , Any ] ) : nanopub schema Returns : Tuple [ bool , List [ str ] ] : bool : Is ...
v = jsonschema . Draft4Validator ( schema ) messages = [ ] errors = sorted ( v . iter_errors ( nanopub ) , key = lambda e : e . path ) for error in errors : for suberror in sorted ( error . context , key = lambda e : e . schema_path ) : print ( list ( suberror . schema_path ) , suberror . message , sep = ",...
def add_zfs_apt_repository ( ) : """adds the ZFS repository"""
with settings ( hide ( 'warnings' , 'running' , 'stdout' ) , warn_only = False , capture = True ) : sudo ( 'DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get update' ) install_ubuntu_development_tools ( ) apt_install ( packages = [ 'software-properties-common' , 'dkms' , 'linux-headers-generic' , 'build-essen...
def add_activation_summary ( x , types = None , name = None , collections = None ) : """Call : func : ` add _ tensor _ summary ` under a reused ' activation - summary ' name scope . This function is a no - op if not calling from main training tower . Args : x ( tf . Tensor ) : the tensor to summary . types ...
ndim = x . get_shape ( ) . ndims if ndim < 2 : logger . warn ( "Cannot summarize scalar activation {}" . format ( x . name ) ) return if types is None : types = [ 'sparsity' , 'rms' , 'histogram' ] with cached_name_scope ( 'activation-summary' ) : add_tensor_summary ( x , types , name = name , collectio...
def create_gzip ( archive , compression , cmd , verbosity , interactive , filenames ) : """Create a GZIP archive with the gzip Python module ."""
if len ( filenames ) > 1 : raise util . PatoolError ( 'multi-file compression not supported in Python gzip' ) try : with gzip . GzipFile ( archive , 'wb' ) as gzipfile : filename = filenames [ 0 ] with open ( filename , 'rb' ) as srcfile : data = srcfile . read ( READ_SIZE_BYTES ) ...
def to_fasta ( self ) : """Returns a string with the sequence in fasta format Returns str The FASTA representation of the sequence"""
prefix , suffix = re . split ( '(?<=size=)\w+' , self . label , maxsplit = 1 ) new_count = int ( round ( self . frequency ) ) new_label = "%s%d%s" % ( prefix , new_count , suffix ) return ">%s\n%s\n" % ( new_label , self . sequence )
def connect ( self , hostname , port = SSH_PORT , username = None , password = None , pkey = None , key_filename = None , timeout = None , allow_agent = True , look_for_keys = True , compress = False , sock = None ) : """Connect to an SSH server and authenticate to it . The server ' s host key is checked against ...
if not sock : for ( family , socktype , proto , canonname , sockaddr ) in socket . getaddrinfo ( hostname , port , socket . AF_UNSPEC , socket . SOCK_STREAM ) : if socktype == socket . SOCK_STREAM : af = family addr = sockaddr break else : # some OS like AIX don ' t i...
def _mmc_loop ( self , rounds , temp = 298.15 , verbose = True ) : """The main MMC loop . Parameters rounds : int The number of rounds of optimisation to perform . temp : float , optional The temperature ( in K ) used during the optimisation . verbose : bool , optional If true , prints information abo...
# TODO add weighted randomisation of altered variable current_round = 0 while current_round < rounds : modifiable = list ( filter ( lambda p : p . parameter_type is not MMCParameterType . STATIC_VALUE , self . current_parameters ) ) chosen_parameter = random . choice ( modifiable ) if chosen_parameter . par...
def _write_json ( self , message , extra ) : '''The JSON logger doesn ' t obey log levels @ param message : The message to write @ param extra : The object to write'''
self . logger . info ( message , extra = extra )
def undobutton_action ( self ) : """when undo is clicked , revert the thematic map to the previous state"""
if len ( self . history ) > 1 : old = self . history . pop ( - 1 ) self . selection_array = old self . mask . set_data ( old ) self . fig . canvas . draw_idle ( )
def xpointerNewLocationSetNodes ( self , end ) : """Create a new xmlXPathObjectPtr of type LocationSet and initialize it with the single range made of the two nodes @ start and @ end"""
if end is None : end__o = None else : end__o = end . _o ret = libxml2mod . xmlXPtrNewLocationSetNodes ( self . _o , end__o ) if ret is None : raise treeError ( 'xmlXPtrNewLocationSetNodes() failed' ) return xpathObjectRet ( ret )
def load_page_buffer ( self , buffer_number , address , bytes ) : """@ brief Load data to a numbered page buffer . This method is used in conjunction with start _ program _ page _ with _ buffer ( ) to implement double buffered programming ."""
assert buffer_number < len ( self . page_buffers ) , "Invalid buffer number" # prevent security settings from locking the device bytes = self . override_security_bits ( address , bytes ) # transfer the buffer to device RAM self . target . write_memory_block8 ( self . page_buffers [ buffer_number ] , bytes )
def _elidable_begin ( self , word ) : """Check word beginning to see if it is elidable . Elidable beginnings include : 1 ) A word begins with ' h ' 2 ) A word begins with a vowel 3 ) A word begins with a diphthong : param word : syllabified / ' qu ' fixed word : return : True if the beginning of a word is...
if str ( word [ 0 ] ) . startswith ( 'h' ) : return True elif str ( word [ 0 ] [ 0 ] ) in self . long_vowels : return True elif str ( word [ 0 ] [ 0 ] + word [ 0 ] [ - 1 ] ) in self . diphthongs : return True elif str ( word [ 0 ] [ 0 ] ) in self . vowels : return True else : return False
def create_set ( self , project , json_data = None , ** options ) : """Create a new article set . Provide the needed arguments using post _ data or with key - value pairs"""
url = URL . articlesets . format ( ** locals ( ) ) if json_data is None : # form encoded request return self . request ( url , method = "post" , data = options ) else : if not isinstance ( json_data , ( string_types ) ) : json_data = json . dumps ( json_data , default = serialize ) headers = { 'cont...
def _ParseAbstractInteger ( text , is_long = False ) : """Parses an integer without checking size / signedness . Args : text : The text to parse . is _ long : True if the value should be returned as a long integer . Returns : The integer value . Raises : ValueError : Thrown Iff the text is not a valid...
# Do the actual parsing . Exception handling is propagated to caller . try : # We force 32 - bit values to int and 64 - bit values to long to make # alternate implementations where the distinction is more significant # ( e . g . the C + + implementation ) simpler . if is_long : return long ( text , 0 ) ...
def sample_batch ( self , nlive_new = 500 , update_interval = None , logl_bounds = None , maxiter = None , maxcall = None , save_bounds = True ) : """Generate an additional series of nested samples that will be combined with the previous set of dead points . Works by hacking the internal ` sampler ` object . ...
# Initialize default values . if maxcall is None : maxcall = sys . maxsize if maxiter is None : maxiter = sys . maxsize if nlive_new <= 2 * self . npdim : warnings . warn ( "Beware: `nlive_batch <= 2 * ndim`!" ) self . sampler . save_bounds = save_bounds # Initialize starting values . h = 0.0 # Information ...
def genenare_callmap_sif ( self , filepath ) : """Generate a sif file from the call map"""
graph = self . call_map if graph is None : raise AngrGirlScoutError ( 'Please generate the call graph first.' ) f = open ( filepath , "wb" ) for src , dst in graph . edges ( ) : f . write ( "0x%x\tDirectEdge\t0x%x\n" % ( src , dst ) ) f . close ( )
def _determine_datatype ( fields ) : """Determine the numpy dtype of the data ."""
# Convert the NRRD type string identifier into a NumPy string identifier using a map np_typestring = _TYPEMAP_NRRD2NUMPY [ fields [ 'type' ] ] # This is only added if the datatype has more than one byte and is not using ASCII encoding # Note : Endian is not required for ASCII encoding if np . dtype ( np_typestring ) . ...
def set ( self , level = None ) : """Set the default log level If the level is not specified environment variable DEBUG is used with the following meaning : : DEBUG = 0 . . . LOG _ WARN ( default ) DEBUG = 1 . . . LOG _ INFO DEBUG = 2 . . . LOG _ DEBUG DEBUG = 3 . . . LOG _ DETAILS DEBUG = 4 . . . LOG...
# If level specified , use given if level is not None : Logging . _level = level # Otherwise attempt to detect from the environment else : try : Logging . _level = Logging . MAPPING [ int ( os . environ [ "DEBUG" ] ) ] except StandardError : Logging . _level = logging . WARN self . logger . ...
def copytree_atomic ( source_path , dest_path , make_parents = False , backup_suffix = None , symlinks = False ) : """Copy a file or directory recursively , and atomically , reanaming file or top - level dir when done . Unlike shutil . copytree , this will not fail on a file ."""
if os . path . isdir ( source_path ) : with atomic_output_file ( dest_path , make_parents = make_parents , backup_suffix = backup_suffix ) as tmp_path : shutil . copytree ( source_path , tmp_path , symlinks = symlinks ) else : copyfile_atomic ( source_path , dest_path , make_parents = make_parents , bac...
def deploy ( project , version , promote , quiet ) : """Deploy the app to the target environment . The target environments can be configured using the ENVIRONMENTS conf variable . This will also collect all static files and compile translation messages"""
from . import logic logic . deploy ( project , version , promote , quiet )
def Start ( self , file_size = 0 , maximum_pending_files = 1000 , use_external_stores = False ) : """Initialize our state ."""
super ( MultiGetFileLogic , self ) . Start ( ) self . state . files_hashed = 0 self . state . use_external_stores = use_external_stores self . state . file_size = file_size self . state . files_to_fetch = 0 self . state . files_fetched = 0 self . state . files_skipped = 0 # Counter to batch up hash checking in the file...
def cast_to_unstructured_grid ( self ) : """Get a new representation of this object as an : class : ` vtki . UnstructuredGrid `"""
alg = vtk . vtkAppendFilter ( ) alg . AddInputData ( self ) alg . Update ( ) return vtki . filters . _get_output ( alg )
def connect_head_namespaced_pod_proxy ( self , name , namespace , ** kwargs ) : """connect HEAD requests to proxy of Pod This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . connect _ head _ namespaced _ pod _ prox...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . connect_head_namespaced_pod_proxy_with_http_info ( name , namespace , ** kwargs ) else : ( data ) = self . connect_head_namespaced_pod_proxy_with_http_info ( name , namespace , ** kwargs ) return data
def show ( self , ** kwargs ) : """Shows the menu . Any ` kwargs ` supplied will be passed to ` show _ menu ( ) ` ."""
show_kwargs = copy . deepcopy ( self . _show_kwargs ) show_kwargs . update ( kwargs ) return show_menu ( self . entries , ** show_kwargs )
def RegisterCustomFieldCodec ( encoder , decoder ) : """Register a custom encoder / decoder for this field ."""
def Register ( field ) : _CUSTOM_FIELD_CODECS [ field ] = _Codec ( encoder = encoder , decoder = decoder ) return field return Register
def _read_msg_header ( session ) : """Perform a read on input socket to consume headers and then return a tuple of message type , message length . : param session : Push Session to read data for . Returns response type ( i . e . PUBLISH _ MESSAGE ) if header was completely read , otherwise None if header wa...
try : data = session . socket . recv ( 6 - len ( session . data ) ) if len ( data ) == 0 : # No Data on Socket . Likely closed . return NO_DATA session . data += data # Data still not completely read . if len ( session . data ) < 6 : return INCOMPLETE except ssl . SSLError : # This c...
def remove ( self , value , count = 1 ) : """Remove occurences of ` ` value ` ` from the list . : keyword count : Number of matching values to remove . Default is to remove a single value ."""
count = self . client . lrem ( self . name , value , num = count ) if not count : raise ValueError ( "%s not in list" % value ) return count
def decorate ( self , func , target , * anoop , ** kwnoop ) : """decorate the passed in func calling target when func is called : param func : the function being decorated : param target : the target that will be run when func is called : returns : the decorated func"""
if target : self . target = target def decorated ( decorated_self , * args , ** kwargs ) : self . handle_target ( request = decorated_self . request , controller_args = args , controller_kwargs = kwargs ) return func ( decorated_self , * args , ** kwargs ) return decorated
def _parse_wenner_file ( filename , settings ) : """Parse a Geotom . wen ( Wenner configuration ) file Parsing problems Due to column overflows it is necessary to make sure that spaces are present around the ; character . Example : 8.000 14.000 10835948.70 ; 0.001 - 123.1853 - 1.0 23.10.2014"""
# read data with open ( filename , 'r' ) as fid2 : geotom_data_orig = fid2 . read ( ) # replace all ' ; ' by ' ; ' geotom_data = geotom_data_orig . replace ( ';' , ' ; ' ) fid = StringIO ( ) fid . write ( geotom_data ) fid . seek ( 0 ) header = [ fid . readline ( ) for i in range ( 0 , 16 ) ] header df = pd . read_...
def countries ( self ) : """Access the countries : returns : twilio . rest . voice . v1 . dialing _ permissions . country . CountryList : rtype : twilio . rest . voice . v1 . dialing _ permissions . country . CountryList"""
if self . _countries is None : self . _countries = CountryList ( self . _version , ) return self . _countries
def content ( self , value ) : """Setter for * * self . _ _ content * * attribute . : param value : Attribute value . : type value : list"""
if value is not None : assert type ( value ) is list , "'{0}' attribute: '{1}' type is not 'list'!" . format ( "content" , value ) self . __content = value
def file_find ( self , load ) : '''Convenience function for calls made using the LocalClient'''
path = load . get ( 'path' ) if not path : return { 'path' : '' , 'rel' : '' } tgt_env = load . get ( 'saltenv' , 'base' ) return self . find_file ( path , tgt_env )
def getApplicationSupportedMimeTypes ( self , pchAppKey , pchMimeTypesBuffer , unMimeTypesBuffer ) : """Get the list of supported mime types for this application , comma - delimited"""
fn = self . function_table . getApplicationSupportedMimeTypes result = fn ( pchAppKey , pchMimeTypesBuffer , unMimeTypesBuffer ) return result
def as_bin ( self , as_spendable = False ) : """Return the txo as binary ."""
f = io . BytesIO ( ) self . stream ( f , as_spendable = as_spendable ) return f . getvalue ( )
def get_ip_by_equip_and_vip ( self , equip_name , id_evip ) : """Get a available IP in the Equipment related Environment VIP : param equip _ name : Equipment Name . : param id _ evip : Vip environment identifier . Integer value and greater than zero . : return : Dictionary with the following structure : { '...
if not is_valid_int_param ( id_evip ) : raise InvalidParameterError ( u'Vip environment is invalid or was not informed.' ) ip_map = dict ( ) ip_map [ 'equip_name' ] = equip_name ip_map [ 'id_evip' ] = id_evip url = "ip/getbyequipandevip/" code , xml = self . submit ( { 'ip_map' : ip_map } , 'POST' , url ) return se...
def parse_point_source_node ( node , mfd_spacing = 0.1 ) : """Returns an " areaSource " node into an instance of the : class : openquake . hmtk . sources . area . mtkAreaSource"""
assert "pointSource" in node . tag pnt_taglist = get_taglist ( node ) # Get metadata point_id , name , trt = ( node . attrib [ "id" ] , node . attrib [ "name" ] , node . attrib [ "tectonicRegion" ] ) assert point_id # Defensive validation ! # Process geometry location , upper_depth , lower_depth = node_to_point_geometr...
def _init_metadata ( self , ** kwargs ) : """Initialize form metadata"""
osid_objects . OsidObjectForm . _init_metadata ( self , ** kwargs ) self . _grade_system_default = self . _mdata [ 'grade_system' ] [ 'default_id_values' ] [ 0 ]
def get_aws_secrets_from_file ( credentials_file ) : # type : ( str ) - > Set [ str ] """Extract AWS secrets from configuration files . Read an ini - style configuration file and return a set with all found AWS secret access keys ."""
aws_credentials_file_path = os . path . expanduser ( credentials_file ) if not os . path . exists ( aws_credentials_file_path ) : return set ( ) parser = configparser . ConfigParser ( ) try : parser . read ( aws_credentials_file_path ) except configparser . MissingSectionHeaderError : return set ( ) keys = ...
def create_rule ( self , txtrule = None , regex = None , extension = None , cmd = None , codes = [ 0 , None ] , recurse = True ) : '''Adds a set of rules to the extraction rule list . @ txtrule - Rule string , or list of rule strings , in the format < regular expression > : < file extension > [ : < command to run...
rules = [ ] created_rules = [ ] match = False r = { 'extension' : '' , 'cmd' : '' , 'regex' : None , 'codes' : codes , 'recurse' : recurse , } # Process single explicitly specified rule if not txtrule and regex and extension : r [ 'extension' ] = extension r [ 'regex' ] = re . compile ( regex ) if cmd : ...
def create_jsonable_registry ( self ) : """Creates a JSON - able representation of this object . Returns : A dictionary mapping ( device , tensor name ) to JSON - able object representations of NumericsAlertHistory ."""
# JSON does not support tuples as keys . Only strings . Therefore , we store # the device name , tensor name , and dictionary data within a 3 - item list . return [ HistoryTriplet ( pair [ 0 ] , pair [ 1 ] , history . create_jsonable_history ( ) ) for ( pair , history ) in self . _data . items ( ) ]
def calculate_oobatake_dG ( seq , temp ) : """Get free energy of unfolding ( dG ) using Oobatake method in units cal / mol . Args : seq ( str , Seq , SeqRecord ) : Amino acid sequence temp ( float ) : Temperature in degrees C Returns : float : Free energy of unfolding dG ( J / mol )"""
dH = calculate_oobatake_dH ( seq , temp ) dS = calculate_oobatake_dS ( seq , temp ) dG = dH - ( temp + 273.15 ) * dS # 563.552 - a correction for N - and C - terminal group ( approximated from 7 examples in the paper ) return dG - 563.552