signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def compute_index ( self , axis , data_object , compute_diff = True ) : """Computes the index after a number of rows have been removed . Note : In order for this to be used properly , the indexes must not be changed before you compute this . Args : axis : The axis to extract the index from . data _ object...
def pandas_index_extraction ( df , axis ) : if not axis : return df . index else : try : return df . columns except AttributeError : return pandas . Index ( [ ] ) index_obj = self . index if not axis else self . columns old_blocks = self . data if compute_diff els...
def nameop_put_collision ( cls , collisions , nameop ) : """Record a nameop as collided with another nameop in this block ."""
# these are supposed to have been put here by nameop _ set _ collided history_id_key = nameop . get ( '__collided_history_id_key__' , None ) history_id = nameop . get ( '__collided_history_id__' , None ) try : assert cls . nameop_is_collided ( nameop ) , "Nameop not collided" assert history_id_key is not None ,...
def rm_docs ( self ) : """Remove converted docs ."""
for filename in self . created : if os . path . exists ( filename ) : os . unlink ( filename )
def parse_args ( self , argv ) : """parse arguments / options : param argv : argument list to parse , usually ` ` sys . argv [ 1 : ] ` ` : type argv : list : returns : parsed arguments : rtype : : py : class : ` argparse . Namespace `"""
desc = 'Report on AWS service limits and usage via boto3, optionally ' 'warn about any services with usage nearing or exceeding their' ' limits. For further help, see ' '<http://awslimitchecker.readthedocs.org/>' # # # # # # IMPORTANT license notice # # # # # # Pursuant to Sections 5 ( b ) and 13 of the GNU Affero Gene...
def camel_case ( string ) : """Converts a string to camel case . For example : : camel _ case ( ' one _ two _ three ' ) - > ' oneTwoThree '"""
if not string : return string parts = snake_case ( string ) . split ( '_' ) rv = '' while parts : part = parts . pop ( 0 ) rv += part or '_' if part : break return rv + '' . join ( x . title ( ) for x in parts )
def over ( self , window ) : """Add a window clause to be applied to downstream analytic expressions"""
return GroupedTableExpr ( self . table , self . by , having = self . _having , order_by = self . _order_by , window = window , )
def add_empty_dataset ( self , value = 1 ) : """Create an empty data set . Empty means : all elements have the same value . Parameters value : float , optional which value to assign all element parameters . Default is one ."""
subdata = np . ones ( self . grid . nr_of_elements ) * value pid = self . add_data ( subdata ) return pid
def on_focusout ( self , event , a ) : """function that gets called whenever anywhere except entry is clicked"""
if event . widget . get ( ) == '' : event . widget . insert ( 0 , default_text [ a ] ) event . widget . config ( fg = 'grey' )
def _primary_input ( self , index ) : '''Primary input for the zkproof'''
primary_input = z . ZcashByteData ( ) primary_input += self . tx_joinsplits [ index ] . anchor primary_input += self . tx_joinsplits [ index ] . nullifiers primary_input += self . tx_joinsplits [ index ] . commitments primary_input += self . tx_joinsplits [ index ] . vpub_old primary_input += self . tx_joinsplits [ ind...
def choose_labels ( alternatives ) : """Prompt the user select several labels from the provided alternatives . At least one label must be selected . : param list alternatives : Sequence of options that are available to select from : return : Several selected labels"""
if not alternatives : raise ValueError if not isinstance ( alternatives , list ) : raise TypeError choice_map = OrderedDict ( ( '{}' . format ( i ) , value ) for i , value in enumerate ( alternatives , 1 ) ) # prepend a termination option input_terminator = '0' choice_map . update ( { input_terminator : '<done>...
def get_dedicated_package ( self , ha_enabled = False ) : """Retrieves the dedicated firewall package . : param bool ha _ enabled : True if HA is to be enabled on the firewall False for No HA : returns : A dictionary containing the dedicated virtual server firewall package"""
fwl_filter = 'Hardware Firewall (Dedicated)' ha_fwl_filter = 'Hardware Firewall (High Availability)' _filter = utils . NestedDict ( { } ) if ha_enabled : _filter [ 'items' ] [ 'description' ] = utils . query_filter ( ha_fwl_filter ) else : _filter [ 'items' ] [ 'description' ] = utils . query_filter ( fwl_filte...
def addAccount ( self , username , domain , password , avatars = None , protocol = u'email' , disabled = 0 , internal = False , verified = True ) : """Create a user account , add it to this LoginBase , and return it . This method must be called within a transaction in my store . @ param username : the user ' s ...
# unicode ( None ) = = u ' None ' , kids . if username is not None : username = unicode ( username ) if domain is not None : domain = unicode ( domain ) if password is not None : password = unicode ( password ) if self . accountByAddress ( username , domain ) is not None : raise DuplicateUser ( username...
def create_account_invitation ( self , account_id , body , ** kwargs ) : # noqa : E501 """Create a user invitation . # noqa : E501 An endpoint for inviting a new or an existing user to join the account . * * Example usage : * * ` curl - X POST https : / / api . us - east - 1 . mbedcloud . com / v3 / accouns / { a...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . create_account_invitation_with_http_info ( account_id , body , ** kwargs ) # noqa : E501 else : ( data ) = self . create_account_invitation_with_http_info ( account_id , body , ** kwargs ) # noqa : E501 ret...
def remove_credentials ( self , credIDs ) : """Removes a credential ID from the database"""
for credID in credIDs : cur = self . conn . cursor ( ) cur . execute ( "DELETE FROM users WHERE id=?" , [ credID ] ) cur . close ( )
def getfile ( self , project_id , file_path , ref ) : """Allows you to receive information about file in repository like name , size , content . Note that file content is Base64 encoded . : param project _ id : project _ id : param file _ path : Full path to file . Ex . lib / class . rb : param ref : The na...
data = { 'file_path' : file_path , 'ref' : ref } request = requests . get ( '{0}/{1}/repository/files' . format ( self . projects_url , project_id ) , headers = self . headers , data = data , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) if request . status_code == 200 : return reques...
def get_system_info ( self , x = 255 , y = 255 ) : """Discover the integrity and resource availability of a whole SpiNNaker system . This command performs : py : meth : ` . get _ chip _ info ` on all working chips in the system returning an enhanced : py : class : ` dict ` ( : py : class : ` . SystemInfo ` ...
# A quick way of getting a list of working chips p2p_tables = self . get_p2p_routing_table ( x , y ) # Calculate the extent of the system max_x = max ( x_ for ( x_ , y_ ) , r in iteritems ( p2p_tables ) if r != consts . P2PTableEntry . none ) max_y = max ( y_ for ( x_ , y_ ) , r in iteritems ( p2p_tables ) if r != cons...
def solar_azimuth ( self , dateandtime , latitude , longitude ) : """Calculate the azimuth angle of the sun . : param dateandtime : The date and time for which to calculate the angle . : type dateandtime : : class : ` ~ datetime . datetime ` : param latitude : Latitude - Northern latitudes should be positiv...
if latitude > 89.8 : latitude = 89.8 if latitude < - 89.8 : latitude = - 89.8 if dateandtime . tzinfo is None : zone = 0 utc_datetime = dateandtime else : zone = - dateandtime . utcoffset ( ) . total_seconds ( ) / 3600.0 utc_datetime = dateandtime . astimezone ( pytz . utc ) timenow = ( utc_date...
def ParseBookmarkRow ( self , parser_mediator , query , row , ** unused_kwargs ) : """Parses a bookmark row . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . query ( str ) : query that created the row . row ( sqlite3 . ...
query_hash = hash ( query ) rev_host = self . _GetRowValue ( query_hash , row , 'rev_host' ) bookmark_type = self . _GetRowValue ( query_hash , row , 'type' ) event_data = FirefoxPlacesBookmarkEventData ( ) event_data . host = rev_host or 'N/A' event_data . offset = self . _GetRowValue ( query_hash , row , 'id' ) event...
def pack_args_by_32 ( holder , maxlen , arg , typ , context , placeholder , dynamic_offset_counter = None , datamem_start = None , zero_pad_i = None , pos = None ) : """Copy necessary variables to pre - allocated memory section . : param holder : Complete holder for all args : param maxlen : Total length in byt...
if isinstance ( typ , BaseType ) : if isinstance ( arg , LLLnode ) : value = unwrap_location ( arg ) else : value = parse_expr ( arg , context ) value = base_type_conversion ( value , value . typ , typ , pos ) holder . append ( LLLnode . from_list ( [ 'mstore' , placeholder , value ]...
def escape_attr ( s ) : '''escape the given string such that it can be placed in an XML attribute , like : < foo bar = ' $ value ' > Args : s ( str ) : the string to escape . Returns : str : the escaped string .'''
esc = xml . sax . saxutils . quoteattr ( s ) esc = esc . encode ( 'ascii' , 'xmlcharrefreplace' ) . decode ( 'ascii' ) esc = RESTRICTED_CHARS . sub ( '' , esc ) return esc
def create ( self , typ , data , return_response = False ) : """Create new type Valid arguments : skip : number of records to skip limit : number of records to limit request to"""
res = self . _request ( typ , method = 'POST' , data = data ) if res . status_code != 201 : try : data = res . json ( ) self . _throw ( res , data ) except ValueError as e : if not isinstance ( e , InvalidRequestException ) : self . _throw ( res , { } ) else : ...
def add_output_arg ( self , out ) : """Add an output as an argument"""
self . add_arg ( out . _dax_repr ( ) ) self . _add_output ( out )
def firstPass ( ASTs , verbose ) : '''Return a dictionary of function definition nodes , a dictionary of imported object names and a dictionary of imported module names . All three dictionaries use source file paths as keys .'''
fdefs = dict ( ) cdefs = dict ( ) imp_obj_strs = dict ( ) imp_mods = dict ( ) for ( root , path ) in ASTs : fdefs [ path ] = [ ] fdefs [ path ] . append ( formatBodyNode ( root , path ) ) imp_obj_strs [ path ] = [ ] imp_mods [ path ] = [ ] cdefs [ path ] = [ ] for ( node , stack ) in traversal (...
def _build_prior ( self , unconstrained_tensor , constrained_tensor ) : """Build a tensorflow representation of the prior density . The log Jacobian is included ."""
if not misc . is_tensor ( unconstrained_tensor ) : raise GPflowError ( "Unconstrained input must be a tensor." ) if not misc . is_tensor ( constrained_tensor ) : raise GPflowError ( "Constrained input must be a tensor." ) prior_name = 'prior' if self . prior is None : return tf . constant ( 0.0 , settings ....
def update_file ( self , path ) : '''Updates the file watcher and calls the appropriate method for results @ return : False if we need to keep trying the connection'''
try : # grab the file result , stat = self . zoo_client . get ( path , watch = self . watch_file ) except ZookeeperError : self . set_valid ( False ) self . call_error ( self . INVALID_GET ) return False if self . pointer : if result is not None and len ( result ) > 0 : self . pointed_at_exp...
def is_valid ( self , instance ) : '''Perform validation for * instance * and stores serialized data , indexes and errors into local cache . Return ` ` True ` ` if the instance is ready to be saved to database .'''
dbdata = instance . dbdata data = dbdata [ 'cleaned_data' ] = { } errors = dbdata [ 'errors' ] = { } # Loop over scalar fields first for field , value in instance . fieldvalue_pairs ( ) : name = field . attname try : svalue = field . set_get_value ( instance , value ) except Exception as e : ...
def modpath_last ( module , entry_point ) : """Provides the raw _ _ path _ _ . Incompatible with PEP 302 - based import hooks and incompatible with zip _ safe packages . Deprecated . Will be removed by calmjs - 4.0."""
module_paths = modpath_all ( module , entry_point ) if len ( module_paths ) > 1 : logger . info ( "module '%s' has multiple paths, default selecting '%s' as base." , module . __name__ , module_paths [ - 1 ] , ) return module_paths [ - 1 : ]
def read ( self , length = None ) : """Fill bytes and read some number of bytes ( up to length if specified ) < = length bytes may be read if reached the end of input if at buffer boundary , will attempt to read again until specified length is read"""
all_buffs = [ ] while length is None or length > 0 : self . _fillbuff ( ) if self . empty ( ) : break buff = self . buff . read ( length ) all_buffs . append ( buff ) if length : length -= len ( buff ) return b'' . join ( all_buffs )
def from_dict ( data , ctx ) : """Instantiate a new AccountChangesState from a dict ( generally from loading a JSON response ) . The data used to instantiate the AccountChangesState is a shallow copy of the dict passed in , with any complex child types instantiated appropriately ."""
data = data . copy ( ) if data . get ( 'unrealizedPL' ) is not None : data [ 'unrealizedPL' ] = ctx . convert_decimal_number ( data . get ( 'unrealizedPL' ) ) if data . get ( 'NAV' ) is not None : data [ 'NAV' ] = ctx . convert_decimal_number ( data . get ( 'NAV' ) ) if data . get ( 'marginUsed' ) is not None :...
def main ( ) : """Entrypoint for compare _ layers"""
parser = argparse . ArgumentParser ( description = 'Tool for testing caffe to mxnet conversion layer by layer' ) parser . add_argument ( '--image_url' , type = str , default = 'https://github.com/dmlc/web-data/raw/master/mxnet/doc/' 'tutorials/python/predict_image/cat.jpg' , help = 'input image to test inference, can b...
def is_superset_of ( self , other , soft_combinator = False ) : """Return True iff this selector matches the same elements as ` other ` , and perhaps others . That is , ` ` . foo ` ` is a superset of ` ` . foo . bar ` ` , because the latter is more specific . Set ` soft _ combinator ` true to ignore the spe...
# Combinators must match , OR be compatible - - space is a superset of > , # ~ is a superset of + if soft_combinator and self . combinator == ' ' : combinator_superset = True else : combinator_superset = ( self . combinator == other . combinator or ( self . combinator == ' ' and other . combinator == '>' ) or (...
def delete_max ( self ) : """Delete the right - most value from a tree ."""
# Attempt to rotate left - leaning reds to the right . if self . left . red : self = self . rotate_right ( ) # Base case : If there are no selfs greater than this self , then this is # the self to delete . if self . right is NULL : return NULL , self . value # Acquire more reds if necessary to continue the trav...
def RedirectDemo ( handler , t ) : """Demonstration of redirecting to another number ."""
# t . say ( " One moment please . " ) t . redirect ( SIP_PHONE ) json = t . RenderJson ( ) logging . info ( "RedirectDemo json: %s" % json ) handler . response . out . write ( json )
def predict_log_partial_hazard ( self , X ) : r"""This is equivalent to R ' s linear . predictors . Returns the log of the partial hazard for the individuals , partial since the baseline hazard is not included . Equal to : math : ` ( x - \ bar { x } ) ' \ beta ` Parameters X : numpy array or DataFrame a (...
if isinstance ( X , pd . DataFrame ) : order = self . hazards_ . index X = X [ order ] check_for_numeric_dtypes_or_raise ( X ) X = X . astype ( float ) index = _get_index ( X ) X = normalize ( X , self . _norm_mean . values , 1 ) return pd . DataFrame ( np . dot ( X , self . hazards_ ) , index = index )
def chunk_by ( fn : Callable [ [ T ] , object ] ) : """> > > from Redy . Collections import Traversal , Flow > > > lst : Iterable [ int ] = [ 0 , 1 , 2 , 3 , 4 , 5 , 6] > > > x = Flow ( lst ) [ Traversal . chunk _ by ( lambda x : x / / 3 ) ] > > > assert list ( x . unbox ) = = [ [ 0 , 1 , 2 ] , [ 3 , 4 , 5 ] ...
def inner ( seq : ActualIterable [ T ] ) -> ActualIterable [ ActualIterable [ T ] ] : seq = iter ( seq ) try : head = next ( seq ) except StopIteration : return iter ( seq ) current_status = fn ( head ) group = [ head ] for each in seq : status = fn ( each ) if st...
def on ( self , event , handler = None , namespace = None ) : """Register an event handler . : param event : The event name . It can be any string . The event names ` ` ' connect ' ` ` , ` ` ' message ' ` ` and ` ` ' disconnect ' ` ` are reserved and should not be used . : param handler : The function that ...
namespace = namespace or '/' def set_handler ( handler ) : if namespace not in self . handlers : self . handlers [ namespace ] = { } self . handlers [ namespace ] [ event ] = handler return handler if handler is None : return set_handler set_handler ( handler )
def _validate_inputs ( self , inputdict ) : """Validate input links ."""
# Check inputdict try : parameters = inputdict . pop ( self . get_linkname ( 'parameters' ) ) except KeyError : raise InputValidationError ( "No parameters specified for this " "calculation" ) if not isinstance ( parameters , RipsDistanceMatrixParameters ) : raise InputValidationError ( "parameters not of t...
def on_close ( self , stats , previous_stats ) : """Print the extended JSON report to reporter ' s output . : param dict stats : Metrics for the current pylint run : param dict previous _ stats : Metrics for the previous pylint run"""
reports = { 'messages' : self . _messages , 'stats' : stats , 'previous' : previous_stats , } print ( json . dumps ( reports , cls = JSONSetEncoder , indent = 4 ) , file = self . out )
def present ( name , clients = None , hosts = None , options = None , exports = '/etc/exports' ) : '''Ensure that the named export is present with the given options name The export path to configure clients A list of hosts and the options applied to them . This option may not be used in combination with ...
path = name ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } if not clients : if not hosts : ret [ 'result' ] = False ret [ 'comment' ] = 'Either \'clients\' or \'hosts\' must be defined' return ret # options being None is handled by add _ export ( ) clien...
def destroy ( name , call = None ) : '''Destroy a node . CLI Example : . . code - block : : bash salt - cloud - - destroy mymachine'''
if call == 'function' : raise SaltCloudSystemExit ( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__ [ 'cloud.fire_event' ] ( 'event' , 'destroying instance' , 'salt/cloud/{0}/destroying' . format ( name ) , args = { 'name' : name } , sock_dir = __opts__ [ 'sock_dir' ] , transp...
def plot_predict ( self , h = 5 , past_values = 20 , intervals = True , ** kwargs ) : """Makes forecast with the estimated model Parameters h : int ( default : 5) How many steps ahead would you like to forecast ? past _ values : int ( default : 20) How many past observations to show on the forecast graph ...
import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) nsims = kwargs . get ( 'nsims' , 200 ) if self . latent_variables . estimated is False : raise Exception ( "No latent variables estimated!" ) else : # Retrieve data , dates and ( transformed ) latent variables ...
def read ( self , len = 1024 , buffer = None ) : """Read data from connection Read up to len bytes and return them . Arguments : len - - maximum number of bytes to read Return value : string containing read bytes"""
try : return self . _wrap_socket_library_call ( lambda : SSL_read ( self . _ssl . value , len , buffer ) , ERR_READ_TIMEOUT ) except openssl_error ( ) as err : if err . ssl_error == SSL_ERROR_SYSCALL and err . result == - 1 : raise_ssl_error ( ERR_PORT_UNREACHABLE , err ) raise
def get_frame_list ( ) : """Create the list of frames"""
# TODO : use this function in IPS below ( less code duplication ) frame_info_list = [ ] frame_list = [ ] frame = inspect . currentframe ( ) while frame is not None : frame_list . append ( frame ) info = inspect . getframeinfo ( frame ) frame_info_list . append ( info ) frame = frame . f_back frame_info_...
def getQueryEngineDescriptionResponse ( self , queryEngine , vendorSpecific = None , ** kwargs ) : """CNRead . getQueryEngineDescription ( session , queryEngine ) → QueryEngineDescription https : / / releases . dataone . org / online / api - documentation - v2.0.1 / apis / CN _ APIs . html # CNRead . getQueryEn...
return self . GET ( [ 'query' , queryEngine ] , query = kwargs , headers = vendorSpecific )
def Validate ( self , win ) : """Returns True if Value in digits , False otherwise"""
val = self . GetWindow ( ) . GetValue ( ) for x in val : if x not in string . digits : return False return True
def send_notification ( self , method , params ) : """Send a notification"""
msg = self . _encoder . create_notification ( method , params ) self . _send_message ( msg )
def cut_edges ( image , numPix ) : """cuts out the edges of a 2d image and returns re - sized image to numPix center is well defined for odd pixel sizes . : param image : 2d numpy array : param numPix : square size of cut out image : return : cutout image with size numPix"""
nx , ny = image . shape if nx < numPix or ny < numPix : print ( 'WARNING: image can not be resized, in routine cut_edges.' ) return image if nx % 2 == 0 or ny % 2 == 0 or numPix % 2 == 0 : # pass print ( "WARNING: image or cutout side are even number. This routine only works for odd numbers %s %s %s" % ( nx...
def save_var ( self , key , value , ** kwargs ) : 'Save one variable to the database .'
# Check whether Highwall ' s variables table exists self . __check_or_create_vars_table ( ) column_type = get_column_type ( value ) tmp = quote ( self . __vars_table_tmp ) self . execute ( u'DROP TABLE IF EXISTS %s' % tmp , commit = False ) # This is vulnerable to injection self . execute ( u'CREATE TABLE %s (`value` %...
def _iter_channels ( framefile ) : """Yields the name and type of each channel in a GWF file TOC * * Requires : * * | LDAStools . frameCPP | _ Parameters framefile : ` str ` , ` LDAStools . frameCPP . IFrameFStream ` path of GWF file , or open file stream , to read"""
from LDAStools import frameCPP if not isinstance ( framefile , frameCPP . IFrameFStream ) : framefile = open_gwf ( framefile , 'r' ) toc = framefile . GetTOC ( ) for typename in ( 'Sim' , 'Proc' , 'ADC' ) : typen = typename . lower ( ) for name in getattr ( toc , 'Get{0}' . format ( typename ) ) ( ) : ...
def plot_places ( self ) : '''Plot places ( in the parameter space ) of all the generated artifacts and the artifacts accepted to the domain .'''
from matplotlib import pyplot as plt fig , ax = plt . subplots ( ) title = "Agent places, artifacts and env artifacts ({} env artifacts)" . format ( len ( self . artifacts ) ) x = [ ] y = [ ] for a in self . get_agents ( ) : args = a . arg_history x = x + [ e [ 0 ] for e in args ] y = y + [ e [ 1 ] for e in...
def moving_average_smooth ( t , y , dy , span = None , cv = True , t_out = None , span_out = None , period = None ) : """Perform a moving - average smooth of the data Parameters t , y , dy : array _ like time , value , and error in value of the input data span : array _ like the integer spans of the data ...
prep = _prep_smooth ( t , y , dy , span , t_out , span_out , period ) t , y , dy , span , t_out , span_out , indices = prep w = 1. / ( dy ** 2 ) w , yw = windowed_sum ( [ w , y * w ] , t = t , span = span , subtract_mid = cv , indices = indices , period = period ) if t_out is None or span_out is not None : return y...
def base64_bytes ( x ) : """Turn base64 into bytes"""
if six . PY2 : return base64 . decodestring ( x ) return base64 . decodebytes ( bytes_encode ( x ) )
def get_all_attributes ( klass_or_instance ) : """Get all attribute members ( attribute , property style method ) ."""
pairs = list ( ) for attr , value in inspect . getmembers ( klass_or_instance , lambda x : not inspect . isroutine ( x ) ) : if not ( attr . startswith ( "__" ) or attr . endswith ( "__" ) ) : pairs . append ( ( attr , value ) ) return pairs
def score ( self , eval_instances , verbosity = 0 ) : '''Return scores ( negative log likelihoods ) assigned to each testing instance in ` eval _ instances ` . : param eval _ instances : The data to use to evaluate the model . Instances should have at least the ` input ` and ` output ` fields populated . ` ...
if hasattr ( self , '_using_default_combined' ) and self . _using_default_combined : raise NotImplementedError self . _using_default_separate = True return self . predict_and_score ( eval_instances , verbosity = verbosity ) [ 1 ]
def get_name ( model_id ) : """Get the name for a model . : returns str : The model ' s name . If the id has no associated name , then " id = { ID } ( no name ) " is returned ."""
name = _names . get ( model_id ) if name is None : name = 'id = %s (no name)' % str ( model_id ) return name
def getReadNoise ( self , exten ) : """Method for returning the readnoise of a detector ( in counts ) . Returns readnoise : float The readnoise of the detector in * * units of counts / electrons * * ."""
rn = self . _image [ exten ] . _rdnoise if self . proc_unit == 'native' : rn = self . _rdnoise / self . getGain ( exten ) return rn
def to_array ( self ) : """Serializes this PhotoSize to a dictionary . : return : dictionary representation of this object . : rtype : dict"""
array = super ( PhotoSize , self ) . to_array ( ) array [ 'file_id' ] = u ( self . file_id ) # py2 : type unicode , py3 : type str array [ 'width' ] = int ( self . width ) # type int array [ 'height' ] = int ( self . height ) # type int if self . file_size is not None : array [ 'file_size' ] = int ( self . file_siz...
def update_selection_sm_prior ( self ) : """State machine prior update of tree selection"""
if self . _do_selection_update : return self . _do_selection_update = True tree_selection , selected_model_list , sm_selection , sm_selected_model_list = self . get_selections ( ) if tree_selection is not None : # self . _ logger . info ( " SM SELECTION IS : { 2 } \ n { 0 } , \ n { 1 } " . format ( selected _ model...
def add_latlonalt ( self , lat , lon , altitude , terrain_alt = False ) : '''add a point via latitude / longitude / altitude'''
if terrain_alt : frame = mavutil . mavlink . MAV_FRAME_GLOBAL_TERRAIN_ALT else : frame = mavutil . mavlink . MAV_FRAME_GLOBAL_RELATIVE_ALT p = mavutil . mavlink . MAVLink_mission_item_message ( self . target_system , self . target_component , 0 , frame , mavutil . mavlink . MAV_CMD_NAV_WAYPOINT , 0 , 0 , 0 , 0 ...
async def unmount ( self , device ) : """Unmount a Device if mounted . : param device : device object , block device path or mount path : returns : whether the device is unmounted"""
device = self . _find_device ( device ) if not self . is_handleable ( device ) or not device . is_filesystem : self . _log . warn ( _ ( 'not unmounting {0}: unhandled device' , device ) ) return False if not device . is_mounted : self . _log . info ( _ ( 'not unmounting {0}: not mounted' , device ) ) re...
def set_exception ( self , exc_info ) : """This method allows you to set an exception in the future without requring that exception to be raised from the futures worker . This method can be called on an unbound future . : param exc _ info : Either an exception info tuple or an exception value . In the latte...
if not isinstance ( exc_info , tuple ) : if not isinstance ( exc_info , BaseException ) : raise TypeError ( 'expected BaseException instance' ) try : # TODO : Filld the traceback so it appears as if the exception # was actually raised by the caller ? ( Not sure if possible ) raise exc_info ...
def make_output_layers ( self ) : """Extract the ordering of output layers ."""
self . output_layers = [ ] # import pytest ; pytest . set _ trace ( ) if hasattr ( self . model , 'output_layers' ) : # find corresponding output layers in CoreML model # assume output layers are not shared # Helper function to recursively extract output layers # even if the model has a layer which is a nested model ...
def reset_permission_factories ( self ) : """Remove cached permission factories ."""
for key in ( 'read' , 'create' , 'update' , 'delete' ) : full_key = '{0}_permission_factory' . format ( key ) if full_key in self . __dict__ : del self . __dict__ [ full_key ]
def obo ( self ) : """str : the ` Relationship ` serialized in an ` ` [ Typedef ] ` ` stanza . Note : The following guide was used : ftp : / / ftp . geneontology . org / pub / go / www / GO . format . obo - 1_4 . shtml"""
lines = [ "[Typedef]" , "id: {}" . format ( self . obo_name ) , "name: {}" . format ( self . obo_name ) ] if self . complementary is not None : lines . append ( "inverse_of: {}" . format ( self . complementary ) ) if self . symmetry is not None : lines . append ( "is_symmetric: {}" . format ( self . symmetry ) ...
def do_visualize ( self , line ) : """Visualize an ontology - ie wrapper for export command"""
if not self . current : self . _help_noontology ( ) return line = line . split ( ) try : # from . . viz . builder import action _ visualize from . . ontodocs . builder import action_visualize except : self . _print ( "This command requires the ontodocs package: `pip install ontodocs`" ) return impor...
def print_probabilities ( state : State , ndigits : int = 4 , file : TextIO = None ) -> None : """Pretty print state probabilities . Args : state : ndigits : Number of digits of accuracy file : Output stream ( Defaults to stdout )"""
prob = bk . evaluate ( state . probabilities ( ) ) for index , prob in np . ndenumerate ( prob ) : prob = round ( prob , ndigits ) if prob == 0.0 : continue ket = "" . join ( [ str ( n ) for n in index ] ) print ( ket , ":" , prob , file = file )
def make_event ( event : Callable ) -> Callable : """Create an event from a method signature ."""
@ property # type : ignore @ wraps ( event ) def actualevent ( self ) : # pylint : disable = missing - docstring name = event . __name__ [ 3 : ] try : # the getter post processing function # is preserved with an underscore getter = event ( self ) . __name__ except AttributeError : getter...
def iter ( self ) : """Extract DIAMOND records and yield C { ReadAlignments } instances . @ return : A generator that yields C { ReadAlignments } instances ."""
# Note that self . _ reader is already initialized ( in _ _ init _ _ ) for # the first input file . This is less clean than it could be , but it # makes testing easier , since open ( ) is then only called once for # each input file . reads = iter ( self . reads ) first = True for filename in self . filenames : if f...
def _compile_signature ( self , iexec , call_name ) : """Compiles the signature for the specified executable and returns as a dictionary ."""
if iexec is not None : summary = iexec . summary if isinstance ( iexec , Function ) : summary = iexec . returns + "| " + iexec . summary elif isinstance ( iexec , Subroutine ) and len ( iexec . modifiers ) > 0 : summary = ", " . join ( iexec . modifiers ) + " | " + iexec . summary elif i...
def get_filters ( self ) : """Returns the result filters : rtype : str or None"""
if self . _filters : filters_list = self . _filters if isinstance ( filters_list [ - 1 ] , Enum ) : filters_list = filters_list [ : - 1 ] return ' ' . join ( [ fs . value if isinstance ( fs , Enum ) else fs [ 1 ] for fs in filters_list ] ) . strip ( ) else : return None
def get_crystal_field_spin ( self , coordination : str = "oct" , spin_config : str = "high" ) : """Calculate the crystal field spin based on coordination and spin configuration . Only works for transition metal species . Args : coordination ( str ) : Only oct and tet are supported at the moment . spin _ con...
if coordination not in ( "oct" , "tet" ) or spin_config not in ( "high" , "low" ) : raise ValueError ( "Invalid coordination or spin config." ) elec = self . full_electronic_structure if len ( elec ) < 4 or elec [ - 1 ] [ 1 ] != "s" or elec [ - 2 ] [ 1 ] != "d" : raise AttributeError ( "Invalid element {} for c...
def _init_vocab ( self , token_generator , add_reserved_tokens = True ) : """Initialize vocabulary with tokens from token _ generator ."""
self . _id_to_token = { } non_reserved_start_index = 0 if add_reserved_tokens : self . _id_to_token . update ( enumerate ( RESERVED_TOKENS ) ) non_reserved_start_index = len ( RESERVED_TOKENS ) self . _id_to_token . update ( enumerate ( token_generator , start = non_reserved_start_index ) ) # _ token _ to _ id ...
def stmts_from_path ( path , model , stmts ) : """Return source Statements corresponding to a path in a model . Parameters path : list [ tuple [ str , int ] ] A list of tuples where the first element of the tuple is the name of a rule , and the second is the associated polarity along a path . model : py...
path_stmts = [ ] for path_rule , sign in path : for rule in model . rules : if rule . name == path_rule : stmt = stmt_from_rule ( path_rule , model , stmts ) assert stmt is not None path_stmts . append ( stmt ) return path_stmts
def add_key ( pub ) : """Adds a new public key to be used when encrypting new data is needed"""
global _server_keys key = rsa . PublicKey . load_pkcs1 ( pub ) _server_keys [ _compute_fingerprint ( key ) ] = key
def graphql_mutation_from_summary ( summary ) : """This function returns a graphql mutation corresponding to the provided summary ."""
# get the name of the mutation from the summary mutation_name = summary [ 'name' ] # print ( summary ) # the treat the " type " string as a gra input_name = mutation_name + "Input" input_fields = build_native_type_dictionary ( summary [ 'inputs' ] , name = input_name , respect_required = True ) # the inputs for the mut...
def set_mrt ( self , s , mrt : str ) : """accepts a statement and adds a qualifer setting the mrt modifies s in place : param s : a WDBaseDataType statement : param mrt : one of { ' close ' , ' broad ' , ' exact ' , ' related ' , ' narrow ' } : return : s"""
valid_mrts_abv = self . ABV_MRT . keys ( ) valid_mrts_uri = self . ABV_MRT . values ( ) if mrt in valid_mrts_abv : mrt_uri = self . ABV_MRT [ mrt ] elif mrt in valid_mrts_uri : mrt_uri = mrt else : raise ValueError ( "mrt must be one of {}, found {}" . format ( valid_mrts_abv , mrt ) ) mrt_qid = self . mrt_...
def terminate ( name , call = None ) : '''To do an immediate power off of a VM using its name . A ` ` SIGKILL ` ` is issued to the vmx process of the VM CLI Example : . . code - block : : bash salt - cloud - a terminate vmname'''
if call != 'action' : raise SaltCloudSystemExit ( 'The terminate action must be called with ' '-a or --action.' ) vm_properties = [ "name" , "summary.runtime.powerState" ] vm_list = salt . utils . vmware . get_mors_with_properties ( _get_si ( ) , vim . VirtualMachine , vm_properties ) for vm in vm_list : if vm ...
def insert_child ( self , child_pid , index = - 1 ) : """Insert a new child into a PID concept . Argument ' index ' can take the following values : 0,1,2 , . . . - insert child PID at the specified position -1 - insert the child PID at the last position None - insert child without order ( no re - ordering i...
self . _check_child_limits ( child_pid ) if index is None : index = - 1 try : with db . session . begin_nested ( ) : if not isinstance ( child_pid , PersistentIdentifier ) : child_pid = resolve_pid ( child_pid ) child_relations = self . _resolved_pid . child_relations . filter ( PIDR...
def plotAAClusters ( sequence , propertyNames , showLines = True , showFigure = True ) : """Plot amino acid property cluster numbers for a sequence . @ param sequence : An C { AARead } ( or a subclass ) instance . @ param propertyNames : An iterable of C { str } property names ( each of which must be a key of...
MISSING_AA_VALUE = 0 propertyClusters = clustersForSequence ( sequence , propertyNames , missingAAValue = MISSING_AA_VALUE ) if showFigure : minCluster = 1 maxCluster = - 1 legend = [ ] x = np . arange ( 0 , len ( sequence ) ) plot = plt . plot if showLines else plt . scatter for index , propert...
def opacity ( self , value ) : """Setter for * * self . _ _ opacity * * attribute . : param value : Attribute value . : type value : float"""
if value is not None : assert type ( value ) in ( int , float ) , "'{0}' attribute: '{1}' type is not 'int' or 'float'!" . format ( "opacity" , value ) if value > 1 : value = 1 elif value < 0 : value = 0 self . __opacity = float ( value ) self . __set_style_sheet ( )
def take_percentile ( arr , percent ) : """take the top ` percent ` items in a list rounding up"""
size = len ( arr ) stop = min ( int ( size * percent ) , len ( arr ) ) return arr [ 0 : stop ]
def num_listeners ( self , event = None ) : """Return the number of listeners for ` ` event ` ` . Return the total number of listeners for all events on this object if ` ` event ` ` is : class : ` None ` ."""
if event is not None : return len ( self . _listeners [ event ] ) else : return sum ( len ( l ) for l in self . _listeners . values ( ) )
def create_poi_gdf ( polygon = None , amenities = None , north = None , south = None , east = None , west = None ) : """Parse GeoDataFrames from POI json that was returned by Overpass API . Parameters polygon : shapely Polygon or MultiPolygon geographic shape to fetch the POIs within amenities : list List...
responses = osm_poi_download ( polygon = polygon , amenities = amenities , north = north , south = south , east = east , west = west ) # Parse coordinates from all the nodes in the response coords = parse_nodes_coords ( responses ) # POI nodes poi_nodes = { } # POI ways poi_ways = { } # A list of POI relations relation...
def get_targets ( self , raw_string ) : # type : ( Optional [ Text ] ) - > Dict [ Text , Text ] """Extract targets from a string in ' key : value ' format ."""
targets = { } if raw_string is not None : for line in raw_string . splitlines ( ) : if line : target , directory = line . split ( ':' , 1 ) targets [ target . strip ( ) ] = directory . strip ( ) return targets
def parse_digest_challenge ( authentication_header ) : '''Parses the value of a ' WWW - Authenticate ' header . Returns an object with properties corresponding to each of the recognized parameters in the header .'''
if not is_digest_challenge ( authentication_header ) : return None parts = parse_parts ( authentication_header [ 7 : ] , defaults = { 'algorithm' : 'MD5' , 'stale' : 'false' } ) if not _check_required_parts ( parts , _REQUIRED_DIGEST_CHALLENGE_PARTS ) : return None parts [ 'stale' ] = parts [ 'stale' ] . lower ...
def send_request ( ** kwargs ) : """Return a data frame from a web service request to cBio portal . Sends a web service requrest to the cBio portal with arguments given in the dictionary data and returns a Pandas data frame on success . More information about the service here : http : / / www . cbioportal ....
skiprows = kwargs . pop ( 'skiprows' , None ) res = requests . get ( cbio_url , params = kwargs ) if res . status_code == 200 : # Adaptively skip rows based on number of comment lines if skiprows == - 1 : lines = res . text . split ( '\n' ) skiprows = 0 for line in lines : if lin...
def set_json ( self , config_json ) : """Permanently set the JSON configuration Unable to call twice ."""
if self . configuration_dict is not None : raise RuntimeError ( "Can only set configuration once" , self . configuration_dict ) schema = fetch_config ( 'ConfigurationSchema.json' ) validictory . validate ( config_json , schema ) config_json [ 'name' ] = self . name config_json [ 'run_number' ] = self . run config_j...
def build_tree_from_alignment ( aln , moltype = DNA , best_tree = False , params = None ) : """Returns a tree from alignment Will check MolType of aln object"""
if params is None : params = { } if moltype == DNA or moltype == RNA : params [ '-nt' ] = True elif moltype == PROTEIN : params [ '-nt' ] = False else : raise ValueError , "FastTree does not support moltype: %s" % moltype . label if best_tree : params [ '-slow' ] = True # Create mapping between abbr...
def to_xml ( self ) : '''Returns an XMLi representation of the shipping details . @ return : Element'''
for n , v in { "recipient" : self . recipient } . items ( ) : if is_empty_or_none ( v ) : raise ValueError ( "'%s' attribute cannot be empty or None." % n ) doc = Document ( ) root = doc . createElement ( "shipping" ) root . appendChild ( self . recipient . to_xml ( "recipient" ) ) return root
def fetch_internal ( item , request ) : """Fetches the given request by using the local Flask context ."""
# Break client dependence on Flask if internal fetches aren ' t being used . from flask import make_response from werkzeug . test import EnvironBuilder # Break circular dependencies . from dpxdt . server import app # Attempt to create a Flask environment from a urllib2 . Request object . environ_base = { 'REMOTE_ADDR' ...
def from_values_indices ( cls , values , indices , populate = False , structure = None , voigt_rank = None , vsym = True , verbose = False ) : """Creates a tensor from values and indices , with options for populating the remainder of the tensor . Args : values ( floats ) : numbers to place at indices indice...
# auto - detect voigt notation # TODO : refactor rank inheritance to make this easier indices = np . array ( indices ) if voigt_rank : shape = ( [ 3 ] * ( voigt_rank % 2 ) + [ 6 ] * ( voigt_rank // 2 ) ) else : shape = np . ceil ( np . max ( indices + 1 , axis = 0 ) / 3. ) * 3 base = np . zeros ( shape . astype...
def _temporary_filenames ( total ) : """Context manager to create temporary files and remove them after use ."""
temp_files = [ _get_temporary_filename ( 'optimage-' ) for i in range ( total ) ] yield temp_files for temp_file in temp_files : try : os . remove ( temp_file ) except OSError : # Continue in case we could not remove the file . One reason is that # the fail was never created . pass
def decode ( value , strip = False ) : """Python 2/3 friendly decoding of output . Args : value ( str | unicode | bytes | None ) : The value to decode . strip ( bool ) : If True , ` strip ( ) ` the returned string . ( Default value = False ) Returns : str : Decoded value , if applicable ."""
if value is None : return None if isinstance ( value , bytes ) and not isinstance ( value , unicode ) : value = value . decode ( "utf-8" ) if strip : return unicode ( value ) . strip ( ) return unicode ( value )
def unregister_project ( self , project_node , raise_exception = False ) : """Unregisters given : class : ` umbra . components . factory . scriptProject . nodes . ProjectNode ` class Node from the Model . : param project _ node : ProjectNode to unregister . : type project _ node : ProjectNode : param raise _ ...
if raise_exception : if not project_node in self . list_project_nodes ( ) : raise foundations . exceptions . ProgrammingError ( "{0} | '{1}' project 'ProjectNode' isn't registered!" . format ( self . __class__ . __name__ , project_node ) ) LOGGER . debug ( "> Unregistering '{0}' project 'ProjectNode'." . fo...
def get_snapshot_closest_to_state_change ( self , state_change_identifier : int , ) -> Tuple [ int , Any ] : """Get snapshots earlier than state _ change with provided ID ."""
row = super ( ) . get_snapshot_closest_to_state_change ( state_change_identifier ) if row [ 1 ] : last_applied_state_change_id = row [ 0 ] snapshot_state = self . serializer . deserialize ( row [ 1 ] ) result = ( last_applied_state_change_id , snapshot_state ) else : result = ( 0 , None ) return result
def _is_mwtab ( string ) : """Test if input string is in ` mwtab ` format . : param string : Input string . : type string : : py : class : ` str ` or : py : class : ` bytes ` : return : Input string if in mwTab format or False otherwise . : rtype : : py : class : ` str ` or : py : obj : ` False `"""
if isinstance ( string , str ) : lines = string . split ( "\n" ) elif isinstance ( string , bytes ) : lines = string . decode ( "utf-8" ) . split ( "\n" ) else : raise TypeError ( "Expecting <class 'str'> or <class 'bytes'>, but {} was passed" . format ( type ( string ) ) ) lines = [ line for line in lines ...
def relation_get ( attribute = None , unit = None , rid = None ) : """Get relation information"""
_args = [ 'relation-get' , '--format=json' ] if rid : _args . append ( '-r' ) _args . append ( rid ) _args . append ( attribute or '-' ) if unit : _args . append ( unit ) try : return json . loads ( subprocess . check_output ( _args ) . decode ( 'UTF-8' ) ) except ValueError : return None except Cal...
def _rd_segment ( file_name , dir_name , pb_dir , fmt , n_sig , sig_len , byte_offset , samps_per_frame , skew , sampfrom , sampto , channels , smooth_frames , ignore_skew ) : """Read the digital samples from a single segment record ' s associated dat file ( s ) . Parameters file _ name : list The names of ...
# Avoid changing outer variables byte_offset = byte_offset [ : ] samps_per_frame = samps_per_frame [ : ] skew = skew [ : ] # Set defaults for empty fields for i in range ( n_sig ) : if byte_offset [ i ] == None : byte_offset [ i ] = 0 if samps_per_frame [ i ] == None : samps_per_frame [ i ] = 1 ...
def _buckets_nearly_equal ( a_dist , b_dist ) : """Determines whether two ` Distributions ` are nearly equal . Args : a _ dist ( : class : ` Distribution ` ) : an instance b _ dist ( : class : ` Distribution ` ) : another instance Return : boolean : ` True ` if the two instances are approximately equal , ...
a_type , a_buckets = _detect_bucket_option ( a_dist ) b_type , b_buckets = _detect_bucket_option ( b_dist ) if a_type != b_type : return False elif a_type == u'linearBuckets' : return _linear_buckets_nearly_equal ( a_buckets , b_buckets ) elif a_type == u'exponentialBuckets' : return _exponential_buckets_ne...
def SplitV ( a , splits , axis ) : """Split op with multiple split sizes ."""
return tuple ( np . split ( np . copy ( a ) , np . cumsum ( splits ) , axis = axis ) )