signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _get_ssh_config_file ( opts ) : ''': return : Path to the . ssh / config file - usually < home > / . ssh / config'''
ssh_config_file = opts . get ( 'ssh_config_file' ) if not os . path . isfile ( ssh_config_file ) : raise IOError ( 'Cannot find SSH config file' ) if not os . access ( ssh_config_file , os . R_OK ) : raise IOError ( 'Cannot access SSH config file: {}' . format ( ssh_config_file ) ) return ssh_config_file
def refresh ( self , conditional = False ) : """Re - retrieve the information for this object and returns the refreshed instance . : param bool conditional : If True , then we will search for a stored header ( ' Last - Modified ' , or ' ETag ' ) on the object and send that as described in the ` Conditional ...
headers = { } if conditional : if self . last_modified : headers [ 'If-Modified-Since' ] = self . last_modified elif self . etag : headers [ 'If-None-Match' ] = self . etag headers = headers or None json = self . _json ( self . _get ( self . _api , headers = headers ) , 200 ) if json is not None...
def gps_bearing ( lat1 , lon1 , lat2 , lon2 ) : '''return bearing between two points in degrees , in range 0-360 thanks to http : / / www . movable - type . co . uk / scripts / latlong . html'''
lat1 = math . radians ( lat1 ) lat2 = math . radians ( lat2 ) lon1 = math . radians ( lon1 ) lon2 = math . radians ( lon2 ) dLat = lat2 - lat1 dLon = lon2 - lon1 y = math . sin ( dLon ) * math . cos ( lat2 ) x = math . cos ( lat1 ) * math . sin ( lat2 ) - math . sin ( lat1 ) * math . cos ( lat2 ) * math . cos ( dLon ) ...
def set ( self , key , value , ex = None , px = None , nx = False , xx = False ) : """Set the ` ` value ` ` for the ` ` key ` ` in the context of the provided kwargs . As per the behavior of the redis - py lib : If nx and xx are both set , the function does nothing and None is returned . If px and ex are both...
key = self . _encode ( key ) value = self . _encode ( value ) if nx and xx : return None mode = "nx" if nx else "xx" if xx else None if self . _should_set ( key , mode ) : expire = None if ex is not None : expire = ex if isinstance ( ex , timedelta ) else timedelta ( seconds = ex ) if px is not ...
def formula ( self ) : """Species formula"""
if self . _reader . _level == 3 : for ns in ( FBC_V2 , FBC_V1 ) : formula = self . _root . get ( _tag ( 'chemicalFormula' , ns ) ) if formula is not None : return formula return None
def _GetTimestamps ( self , olecf_item ) : """Retrieves the timestamps from an OLECF item . Args : olecf _ item ( pyolecf . item ) : OLECF item . Returns : tuple [ int , int ] : creation and modification FILETIME timestamp ."""
if not olecf_item : return None , None try : creation_time = olecf_item . get_creation_time_as_integer ( ) except OverflowError as exception : logger . warning ( 'Unable to read the creation time with error: {0!s}' . format ( exception ) ) creation_time = 0 try : modification_time = olecf_item . get...
def get_foreign_keys ( self , connection , table_name , schema = None , ** kw ) : """Return information about foreign keys in ` table _ name ` . Overrides interface : meth : ` ~ sqlalchemy . engine . interfaces . Dialect . get _ pk _ constraint ` ."""
constraints = self . _get_redshift_constraints ( connection , table_name , schema , ** kw ) fk_constraints = [ c for c in constraints if c . contype == 'f' ] uniques = defaultdict ( lambda : defaultdict ( dict ) ) for con in fk_constraints : uniques [ con . conname ] [ "key" ] = con . conkey uniques [ con . con...
def load_fits ( self ) : '''Load the FITS file from disk and populate the class instance with its data .'''
log . info ( "Loading FITS file for %d." % ( self . ID ) ) with pyfits . open ( self . fitsfile ) as f : # Params and long cadence data self . loaded = True self . is_parent = False try : self . X1N = f [ 2 ] . data [ 'X1N' ] except KeyError : self . X1N = None self . aperture = f [ ...
def create ( from_file = None , ** kwargs ) : '''Create a new vm from _ file : string json file to create the vm from - - if present , all other options will be ignored kwargs : string | int | . . . options to set for the vm CLI Example : . . code - block : : bash salt ' * ' vmadm . create from _ file...
ret = { } # prepare vmcfg vmcfg = { } kwargs = salt . utils . args . clean_kwargs ( ** kwargs ) for k , v in six . iteritems ( kwargs ) : vmcfg [ k ] = v if from_file : return _create_update_from_file ( 'create' , path = from_file ) else : return _create_update_from_cfg ( 'create' , vmcfg = vmcfg )
def resolve_attribute ( name , bases , default = None ) : """Find the first definition of an attribute according to MRO order ."""
for base in bases : if hasattr ( base , name ) : return getattr ( base , name ) return default
def get_function_diff ( self , function_addr_a , function_addr_b ) : """: param function _ addr _ a : The address of the first function ( in the first binary ) : param function _ addr _ b : The address of the second function ( in the second binary ) : returns : the FunctionDiff of the two functions"""
pair = ( function_addr_a , function_addr_b ) if pair not in self . _function_diffs : function_a = self . cfg_a . kb . functions . function ( function_addr_a ) function_b = self . cfg_b . kb . functions . function ( function_addr_b ) self . _function_diffs [ pair ] = FunctionDiff ( function_a , function_b , ...
def writeGlobalFile ( self , localFileName , cleanup = False ) : """Takes a file ( as a path ) and uploads it to the job store . Depending on the jobstore used , carry out the appropriate cache functions ."""
absLocalFileName = self . _resolveAbsoluteLocalPath ( localFileName ) # What does this do ? cleanupID = None if not cleanup else self . jobGraph . jobStoreID # If the file is from the scope of local temp dir if absLocalFileName . startswith ( self . localTempDir ) : # If the job store is of type FileJobStore and the jo...
def filename_from_path ( path ) : """Extract the file name from a given file path . : param str path : File path : return str : File name with extension"""
head , tail = ntpath . split ( path ) return head , tail or ntpath . basename ( head )
def add_group_email_grant ( self , permission , email_address , headers = None ) : """Convenience method that provides a quick way to add an email group grant to a key . This method retrieves the current ACL , creates a new grant based on the parameters passed in , adds that grant to the ACL and then PUT ' s ...
acl = self . get_acl ( headers = headers ) acl . add_group_email_grant ( permission , email_address ) self . set_acl ( acl , headers = headers )
def delete_connection ( self , name , reason = None ) : """Closes an individual connection . Give an optional reason : param name : The connection name : type name : str : param reason : An option reason why the connection was deleted : type reason : str"""
headers = { 'X-Reason' : reason } if reason else { } self . _api_delete ( '/api/connections/{0}' . format ( urllib . parse . quote_plus ( name ) ) , headers = headers , )
def repo_in_defined_envs ( repo , all_envs ) : """Raises exception if the repo references undefined environments"""
remaining_envs = set ( repo [ 'env' ] ) - set ( all_envs ) if set ( repo [ 'env' ] ) - set ( all_envs ) : raise JuicerRepoInUndefinedEnvs ( "Repo def %s references undefined environments: %s" % ( repo [ 'name' ] , ", " . join ( list ( remaining_envs ) ) ) ) else : return True
def init_queue ( ) : """Initialize indexing queue ."""
def action ( queue ) : queue . declare ( ) click . secho ( 'Indexing queue has been initialized.' , fg = 'green' ) return queue return action
def db_restore ( self , block_number = None ) : """Restore the database and clear the indexing lockfile . Restore to a given block if given ; otherwise use the most recent valid backup . Return True on success Return False if there is no state to restore Raise exception on error"""
restored = False if block_number is not None : # restore a specific backup try : self . backup_restore ( block_number , self . impl , self . working_dir ) restored = True except AssertionError : log . error ( "Failed to restore state from {}" . format ( block_number ) ) return Fa...
def retrieve ( cls , * args , ** kwargs ) : """Return parent method ."""
return super ( ApplicationFeeRefund , cls ) . retrieve ( * args , ** kwargs )
def _get_program ( self ) : """Fetch the module binary from the master if necessary ."""
return ansible_mitogen . target . get_small_file ( context = self . service_context , path = self . path , )
def jsd ( p , q ) : """Finds the per - column JSD between dataframes p and q Jensen - Shannon divergence of two probability distrubutions pandas dataframes , p and q . These distributions are usually created by running binify ( ) on the dataframe . Parameters p : pandas . DataFrame An nbins x features D...
try : _check_prob_dist ( p ) _check_prob_dist ( q ) except ValueError : return np . nan weight = 0.5 m = weight * ( p + q ) result = weight * kld ( p , m ) + ( 1 - weight ) * kld ( q , m ) return result
def to_source ( node , indent_with = ' ' * 4 , add_line_information = False , pretty_string = pretty_string , pretty_source = pretty_source ) : """This function can convert a node tree back into python sourcecode . This is useful for debugging purposes , especially if you ' re dealing with custom asts not gener...
generator = SourceGenerator ( indent_with , add_line_information , pretty_string ) generator . visit ( node ) generator . result . append ( '\n' ) if set ( generator . result [ 0 ] ) == set ( '\n' ) : generator . result [ 0 ] = '' return pretty_source ( generator . result )
def load_data_to_net ( net , inst_net ) : '''load data into nodes and mat , also convert mat to numpy array'''
net . dat [ 'nodes' ] = inst_net [ 'nodes' ] net . dat [ 'mat' ] = inst_net [ 'mat' ] data_formats . mat_to_numpy_arr ( net )
def sel_entries ( self ) : """Generator which returns all SEL entries ."""
ENTIRE_RECORD = 0xff rsp = self . send_message_with_name ( 'GetSelInfo' ) if rsp . entries == 0 : return reservation_id = self . get_sel_reservation_id ( ) next_record_id = 0 while True : req = create_request_by_name ( 'GetSelEntry' ) req . reservation_id = reservation_id req . record_id = next_record_i...
def nacm_exec_default ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) nacm = ET . SubElement ( config , "nacm" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-acm" ) exec_default = ET . SubElement ( nacm , "exec-default" ) exec_default . text = kwargs . pop ( 'exec_default' ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ...
def kde_gauss ( events_x , events_y , xout = None , yout = None ) : """Gaussian Kernel Density Estimation Parameters events _ x , events _ y : 1D ndarray The input points for kernel density estimation . Input is flattened automatically . xout , yout : ndarray The coordinates at which the KDE should be c...
valid_combi = ( ( xout is None and yout is None ) or ( xout is not None and yout is not None ) ) if not valid_combi : raise ValueError ( "Both `xout` and `yout` must be (un)set." ) if yout is None and yout is None : xout = events_x yout = events_y try : estimator = gaussian_kde ( [ events_x . flatten ( ...
def cast_to_seq ( obj , alphabet = IUPAC . extended_protein ) : """Return a Seq representation of a string or SeqRecord object . Args : obj ( str , Seq , SeqRecord ) : Sequence string or Biopython SeqRecord object alphabet : See Biopython SeqRecord docs Returns : Seq : Seq representation of the sequence""...
if isinstance ( obj , Seq ) : return obj if isinstance ( obj , SeqRecord ) : return obj . seq if isinstance ( obj , str ) : obj = obj . upper ( ) return Seq ( obj , alphabet ) else : raise ValueError ( 'Must provide a string, Seq, or SeqRecord object.' )
def AddSubkey ( self , registry_key ) : """Adds a subkey . Args : registry _ key ( WinRegistryKey ) : Windows Registry subkey . Raises : KeyError : if the subkey already exists ."""
name = registry_key . name . upper ( ) if name in self . _subkeys : raise KeyError ( 'Subkey: {0:s} already exists.' . format ( registry_key . name ) ) self . _subkeys [ name ] = registry_key key_path = self . _JoinKeyPath ( [ self . _key_path , registry_key . name ] ) registry_key . _key_path = key_path
async def get_next_match ( self ) : """Return the first open match found , or if none , the first pending match found | methcoro | Raises : APIException"""
if self . _final_rank is not None : return None matches = await self . get_matches ( MatchState . open_ ) if len ( matches ) == 0 : matches = await self . get_matches ( MatchState . pending ) if len ( matches ) > 0 : return matches [ 0 ] return None
def do_exit ( self , arg ) : '''Exit the shell .'''
if self . arm . is_connected ( ) : self . arm . disconnect ( ) print ( 'Bye!' ) return True
def add_alternate_formats ( self , filename ) : """Add phone number alternate format metadata retrieved from XML"""
with open ( filename , "r" ) as infile : xtree = etree . parse ( infile ) self . alt_territory = { } # country _ code to XAlternateTerritory xterritories = xtree . find ( TOP_XPATH ) for xterritory in xterritories : if xterritory . tag == TERRITORY_TAG : terrobj = XAlternateTerritory ( xterritory ) ...
def _update_object_map ( self , obj_map ) : """unclear if it ' s better to use this method or get _ object _ map My main consideration is that MultiLanguageQuestionRecord already overrides get _ object _ map"""
obj_map [ 'droppables' ] = self . get_droppables ( ) obj_map [ 'targets' ] = self . get_targets ( ) obj_map [ 'zones' ] = self . get_zones ( )
def _ComputeHash ( key , seed = 0x0 ) : """Computes the hash of the value passed using MurmurHash3 algorithm with the seed value ."""
def fmix ( h ) : h ^= h >> 16 h = ( h * 0x85ebca6b ) & 0xFFFFFFFF h ^= h >> 13 h = ( h * 0xc2b2ae35 ) & 0xFFFFFFFF h ^= h >> 16 return h length = len ( key ) nblocks = int ( length / 4 ) h1 = seed c1 = 0xcc9e2d51 c2 = 0x1b873593 # body for block_start in xrange ( 0 , nblocks * 4 , 4 ) : k1 =...
def _get_price ( self , package ) : """Returns valid price for ordering a dedicated host ."""
for price in package [ 'prices' ] : if not price . get ( 'locationGroupId' ) : return price [ 'id' ] raise SoftLayer . SoftLayerError ( "Could not find valid price" )
def progressbar ( iterable , length = 23 ) : """Print a simple progress bar while processing the given iterable . Function | progressbar | does print the progress bar when option ` printprogress ` is activted : > > > from hydpy import pub > > > pub . options . printprogress = True You can pass an iterable...
if hydpy . pub . options . printprogress and ( len ( iterable ) > 1 ) : temp_name = os . path . join ( tempfile . gettempdir ( ) , 'HydPy_progressbar_stdout' ) temp_stdout = open ( temp_name , 'w' ) real_stdout = sys . stdout try : sys . stdout = temp_stdout nmbstars = min ( len ( iterab...
def get ( self , po ) : """Lookup value for a PluginOption instance Args : po : PluginOption Returns : converted value"""
name = po . name typ = po . typ default = po . default handler = getattr ( self , '_get_{}' . format ( typ ) , None ) if handler is None : raise ValueError ( typ ) self . seen . add ( name ) # pylint : disable = not - callable if not self . parser . has_option ( self . section , name ) : if default is REQUIRED ...
def select ( self , return_models = False , nest = False , bypass_safe_limit = False , sql = None , sql_args = None ) : """Executes the SELECT statement and returns the rows as a list of dictionaries or a list of model instances : type return _ models : bool : param return _ models : Set to True to return a l...
# Check if we need to set a safe limit if bypass_safe_limit is False : if Query . enable_safe_limit : if self . count ( ) > Query . safe_limit : self . limit ( Query . safe_limit ) # determine which sql to use if sql is None : sql = self . get_sql ( ) # determine which sql args to use if sql...
def timed_cache ( ** timed_cache_kwargs ) : """LRU cache decorator with timeout . Parameters days : int seconds : int microseconds : int milliseconds : int minutes : int hours : int weeks : int maxsise : int [ default : 128] typed : bool [ default : False ]"""
def _wrapper ( f ) : maxsize = timed_cache_kwargs . pop ( 'maxsize' , 128 ) typed = timed_cache_kwargs . pop ( 'typed' , False ) update_delta = timedelta ( ** timed_cache_kwargs ) # nonlocal workaround to support Python 2 # https : / / technotroph . wordpress . com / 2012/10/01 / python - closures -...
def prep_parallel ( self , binary_args , other_args ) : """Prepare the parallel calculations Prepares the arguments to be run in parallel . It will divide up arrays according to num _ splits . Args : binary _ args ( list ) : List of binary arguments for input into the SNR function . other _ args ( tuple o...
if self . length < 100 : raise Exception ( "Run this across 1 processor by setting num_processors kwarg to None." ) if self . num_processors == - 1 : self . num_processors = mp . cpu_count ( ) split_val = int ( np . ceil ( self . length / self . num_splits ) ) split_inds = [ self . num_splits * i for i in np . ...
def is_multisig ( privkey_info , blockchain = 'bitcoin' , ** blockchain_opts ) : """Is the given private key bundle a multisig bundle ?"""
if blockchain == 'bitcoin' : return btc_is_multisig ( privkey_info , ** blockchain_opts ) else : raise ValueError ( 'Unknown blockchain "{}"' . format ( blockchain ) )
def lower ( self ) : """Returns a new query for this instance with Query . Function . Lower as a function option . : return < Query >"""
q = self . copy ( ) q . addFunction ( Query . Function . Lower ) return q
def columnwise_summary ( sf ) : """Plots a columnwise summary of the sframe provided as input , and returns the resulting Plot object . The function supports SFrames . Parameters sf : SFrame The data to get a columnwise summary for . Returns out : Plot A : class : Plot object that is the columnwise ...
if not isinstance ( sf , tc . data_structures . sframe . SFrame ) : raise ValueError ( "turicreate.visualization.columnwise_summary " + "supports SFrame" ) plt_ref = tc . extensions . plot_columnwise_summary ( sf ) return Plot ( plt_ref )
def node_pairing ( self ) : """if " node " then test current node and next one if " tag " , then create tests for every pair of the current tag ."""
value = self . attributes [ 'node_pairing' ] if value not in IMB . NODE_PAIRING : msg = 'Unexpected {0} value: got "{1}" but valid values are {2}' msg = msg . format ( 'node_pairing' , value , IMB . NODE_PAIRING ) raise ValueError ( msg ) return value
def progress ( self ) : """Get progress . Returns : namedtuple : : class : ` Progress ` ."""
return Progress ( done = len ( self . _get_all_set_properties ( ) ) , base = len ( worker_mapping ( ) ) , )
def queue_exc ( * arg , ** kw ) : """Queue undefined variable exception"""
_self = arg [ 0 ] if not isinstance ( _self , AnsibleUndefinedVariable ) : # Run for AnsibleUndefinedVariable instance return _rslt_q = None for stack_trace in inspect . stack ( ) : # Check if method to be skipped if stack_trace [ 3 ] in SKIP_METHODS : continue _frame = stack_trace [ 0 ] _locals...
def run_command ( self , config_file , sources ) : """: param str config _ file : The name of config file . : param list sources : The list with source files ."""
config = configparser . ConfigParser ( ) config . read ( config_file ) rdbms = config . get ( 'database' , 'rdbms' ) . lower ( ) loader = self . create_routine_loader ( rdbms ) status = loader . main ( config_file , sources ) return status
def set_set_point ( self , param ) : """Sets the target temperature . : param param : The new temperature in C . Must be positive . : return : Empty string ."""
if self . temperature_low_limit <= param <= self . temperature_high_limit : self . set_point_temperature = param return ""
def _drop_tip_during_transfer ( self , tips , i , total , ** kwargs ) : """Performs a : any : ` drop _ tip ` or : any : ` return _ tip ` when running a : any : ` transfer ` , : any : ` distribute ` , or : any : ` consolidate ` ."""
trash = kwargs . get ( 'trash' , True ) if tips > 1 or ( i + 1 == total and tips > 0 ) : if trash and self . trash_container : self . drop_tip ( ) else : self . return_tip ( ) tips -= 1 return tips
def get_commits ( self ) : """: calls : ` GET / repos / : owner / : repo / pulls / : number / commits < http : / / developer . github . com / v3 / pulls > ` _ : rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . Commit . Commit `"""
return github . PaginatedList . PaginatedList ( github . Commit . Commit , self . _requester , self . url + "/commits" , None )
def getRunningBatchJobIDs ( self ) : """Retrieve running job IDs from local and batch scheduler . Respects statePollingWait and will return cached results if not within time period to talk with the scheduler ."""
if ( self . _getRunningBatchJobIDsTimestamp and ( datetime . now ( ) - self . _getRunningBatchJobIDsTimestamp ) . total_seconds ( ) < self . config . statePollingWait ) : batchIds = self . _getRunningBatchJobIDsCache else : batchIds = with_retries ( self . worker . getRunningJobIDs ) self . _getRunningBatch...
def to_api_repr ( self ) : """Construct JSON API representation for the parameter . : rtype : dict : returns : JSON mapping"""
values = self . values if self . array_type == "RECORD" or self . array_type == "STRUCT" : reprs = [ value . to_api_repr ( ) for value in values ] a_type = reprs [ 0 ] [ "parameterType" ] a_values = [ repr_ [ "parameterValue" ] for repr_ in reprs ] else : a_type = { "type" : self . array_type } conv...
def construct ( name , exec_ , terminal = False , additional_opts = { } ) : '''Construct a . desktop file and return it as a string . Create a standards - compliant . desktop file , returning it as a string . Args : name ( str ) : The program ' s name . exec \ _ ( str ) : The command . terminal ( bool ) :...
desktop_file = '[Desktop Entry]\n' desktop_file_dict = { 'Name' : name , 'Exec' : exec_ , 'Terminal' : 'true' if terminal else 'false' , 'Comment' : additional_opts . get ( 'Comment' , name ) } desktop_file = ( '[Desktop Entry]\nName={name}\nExec={exec_}\n' 'Terminal={terminal}\nComment={comment}\n' ) desktop_file = de...
def set_mute ( mute_value ) : "Browse for mute usages and set value"
all_mutes = ( ( 0x8 , 0x9 ) , # LED page ( 0x1 , 0xA7 ) , # desktop page ( 0xb , 0x2f ) , ) all_target_usages = [ hid . get_full_usage_id ( u [ 0 ] , u [ 1 ] ) for u in all_mutes ] # usually you ' ll find and open the target device , here we ' ll browse for the # current connected devices all_devices = hid . find_all_h...
def tacacs_server_host_encryption_level ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) tacacs_server = ET . SubElement ( config , "tacacs-server" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" ) host = ET . SubElement ( tacacs_server , "host" ) hostname_key = ET . SubElement ( host , "hostname" ) hostname_key . text = kwargs . pop ( 'hostname' ) encryption_level = ET . Su...
def match_fields ( fields , searches , ignore_case = False , wholename = False , complement = False ) : """Return fields that match searches . Parameters fields : iterable searches : iterable ignore _ case , wholename , complement : boolean"""
if ignore_case : fields = [ f . lower ( ) for f in fields ] searches = [ s . lower ( ) for s in searches ] if wholename : match_found = _complete_match else : match_found = _partial_match fields = [ ( i , field ) for i , field in enumerate ( fields ) ] matched = [ ] for search , ( idx , field ) in itert...
def topics ( self ) : """Ordered dictionary with path : topic ordered by path"""
topics_sorted = sorted ( self . _topics . items ( ) , key = lambda t : t [ 0 ] ) return MappingProxyType ( OrderedDict ( topics_sorted ) )
def submit ( self , * items ) : """Return job ids assigned to the submitted items ."""
with self . lock : if self . closed : raise BrokenPipe ( 'Job submission has been closed.' ) id = self . jobcount self . _status += [ 'SUBMITTED' ] * len ( items ) self . jobcount += len ( items ) for item in items : self . waitqueue . put ( ( id , item ) ) id += 1 if len ( i...
def _onLeftButtonDClick ( self , evt ) : """Start measuring on an axis ."""
x = evt . GetX ( ) y = self . figure . bbox . height - evt . GetY ( ) evt . Skip ( ) self . CaptureMouse ( ) FigureCanvasBase . button_press_event ( self , x , y , 1 , dblclick = True , guiEvent = evt )
def tauV ( T ) : """gets the eigenvalues ( tau ) and eigenvectors ( V ) from matrix T"""
t , V , tr = [ ] , [ ] , 0. ind1 , ind2 , ind3 = 0 , 1 , 2 evalues , evectmps = numpy . linalg . eig ( T ) evectors = numpy . transpose ( evectmps ) # to make compatible with Numeric convention for tau in evalues : tr += tau # tr totals tau values if tr != 0 : for i in range ( 3 ) : evalues [ i ] = ...
def rm_anova2 ( dv = None , within = None , subject = None , data = None , export_filename = None ) : """Two - way repeated measures ANOVA . This is an internal function . The main call to this function should be done by the : py : func : ` pingouin . rm _ anova ` function . Parameters dv : string Name of...
a , b = within # Validate the dataframe _check_dataframe ( dv = dv , within = within , data = data , subject = subject , effects = 'within' ) # Remove NaN if data [ [ subject , a , b , dv ] ] . isnull ( ) . any ( ) . any ( ) : data = remove_rm_na ( dv = dv , subject = subject , within = [ a , b ] , data = data [ [ ...
def config_attributes ( self ) : """Helper method used by TorConfig when generating a torrc file ."""
rtn = [ ( 'HiddenServiceDir' , str ( self . dir ) ) ] if self . conf . _supports [ 'HiddenServiceDirGroupReadable' ] and self . group_readable : rtn . append ( ( 'HiddenServiceDirGroupReadable' , str ( 1 ) ) ) for port in self . ports : rtn . append ( ( 'HiddenServicePort' , str ( port ) ) ) if self . version :...
def create_asset ( self , asset_form ) : """Creates a new ` ` Asset ` ` . arg : asset _ form ( osid . repository . AssetForm ) : the form for this ` ` Asset ` ` return : ( osid . repository . Asset ) - the new ` ` Asset ` ` raise : IllegalState - ` ` asset _ form ` ` already used in a create transaction ...
# Implemented from template for # osid . resource . ResourceAdminSession . create _ resource _ template collection = JSONClientValidated ( 'repository' , collection = 'Asset' , runtime = self . _runtime ) if not isinstance ( asset_form , ABCAssetForm ) : raise errors . InvalidArgument ( 'argument type is not an Ass...
def to_s ( self ) : """this method is used to print the output of the executable in a readable / tokenized format . sample usage : > > > from boa . compiler import Compiler > > > module = Compiler . load ( ' . / boa / tests / src / LambdaTest . py ' ) . default > > > module . write ( ) > > > print ( modul...
# Initialize if needed if self . all_vm_tokens is None : self . link_methods ( ) lineno = 0 output = [ ] pstart = True for i , ( key , value ) in enumerate ( self . all_vm_tokens . items ( ) ) : if value . pytoken : pt = value . pytoken do_print_line_no = False to_label = None fr...
def all_issues ( issues ) : """Yields unique set of issues given a list of issues ."""
logging . info ( 'finding issues...' ) seen = set ( ) for issue in issues : if issue [ 'title' ] not in seen : seen . add ( issue [ 'title' ] ) yield issue
def in_edit_mode ( self , request , placeholder ) : """Returns True , if the plugin is in " edit mode " ."""
toolbar = getattr ( request , 'toolbar' , None ) edit_mode = getattr ( toolbar , 'edit_mode' , False ) and getattr ( placeholder , 'is_editable' , True ) if edit_mode : edit_mode = placeholder . has_change_permission ( request . user ) return edit_mode
def make_server ( host , port , app = None , threaded = False , processes = 1 , request_handler = None , passthrough_errors = False , ssl_context = None ) : """Create a new server instance that is either threaded , or forks or just processes one request after another ."""
if threaded and processes > 1 : raise ValueError ( "cannot have a multithreaded and " "multi process server." ) elif threaded : return ThreadedWSGIServer ( host , port , app , request_handler , passthrough_errors , ssl_context ) elif processes > 1 : return ForkingWSGIServer ( host , port , app , processes ,...
def main ( ) : """Main ShutIt function . Handles the configured actions : - skeleton - create skeleton module - list _ configs - output computed configuration - depgraph - output digraph of module dependencies"""
# Create base shutit object . shutit = shutit_global . shutit_global_object . shutit_objects [ 0 ] if sys . version_info [ 0 ] == 2 : if sys . version_info [ 1 ] < 7 : shutit . fail ( 'Python version must be 2.7+' ) # pragma : no cover try : shutit . setup_shutit_obj ( ) except KeyboardInterrupt...
def remove ( self , item ) : '''Remove ` ` item ` ` for the : class : ` zset ` it it exists . If found it returns the score of the item removed .'''
score = self . _dict . pop ( item , None ) if score is not None : index = self . _sl . rank ( score ) assert index >= 0 , 'could not find start range' for i , v in enumerate ( self . _sl . range ( index ) ) : if v == item : assert self . _sl . remove_range ( index + i , index + i + 1 ) =...
def output_capturing ( ) : """Temporarily captures / redirects stdout ."""
out = sys . stdout sys . stdout = StringIO ( ) try : yield finally : sys . stdout = out
def status ( ctx , client , revision , no_output , path ) : """Show a status of the repository ."""
graph = Graph ( client ) # TODO filter only paths = { graph . normalize _ path ( p ) for p in path } status = graph . build_status ( revision = revision , can_be_cwl = no_output ) click . echo ( 'On branch {0}' . format ( client . repo . active_branch ) ) if status [ 'outdated' ] : click . echo ( 'Files generated f...
def backup ( backup_filename = None ) : '''Backup a Cozy'''
timestamp = time . strftime ( "%Y-%m-%d-%H-%M-%S" , time . gmtime ( ) ) if not backup_filename : if not os . path . isdir ( BACKUPS_PATH ) : print 'Need to create {}' . format ( BACKUPS_PATH ) os . makedirs ( BACKUPS_PATH , 0700 ) backup_filename = '{backups_path}/cozy-{timestamp}.tgz' . format ...
def create_pointing ( self , event ) : """Plot the sky coverage of pointing at event . x , event . y on the canavas"""
import math ( ra , dec ) = self . c2p ( ( self . canvasx ( event . x ) , self . canvasy ( event . y ) ) ) this_camera = camera ( camera = self . camera . get ( ) ) ccds = this_camera . getGeometry ( ra , dec ) items = [ ] for ccd in ccds : ( x1 , y1 ) = self . p2c ( ( ccd [ 0 ] , ccd [ 1 ] ) ) ( x2 , y2 ) = sel...
def _get_container ( self , path ) : """Return single container ."""
path = path . strip ( SEP ) if SEP in path : raise errors . InvalidNameException ( "Path contains %s - %s" % ( SEP , path ) ) return self . cont_cls . from_path ( self , path )
def scan_full ( self , regex , return_string = True , advance_pointer = True ) : """Match from the current position . If ` return _ string ` is false and a match is found , returns the number of characters matched . > > > s = Scanner ( " test string " ) > > > s . scan _ full ( r ' ' ) > > > s . scan _ ful...
regex = get_regex ( regex ) self . match = regex . match ( self . string , self . pos ) if not self . match : return if advance_pointer : self . pos = self . match . end ( ) if return_string : return self . match . group ( 0 ) return len ( self . match . group ( 0 ) )
def _addSortParam ( self , field , order = '' ) : """Adds a sort parameter , order have to be in [ ' ascend ' , ' ascending ' , ' descend ' , ' descending ' , ' custom ' ]"""
if order != '' : validSortOrders = { 'ascend' : 'ascend' , 'ascending' : 'ascend' , '<' : 'ascend' , 'descend' : 'descend' , 'descending' : 'descend' , '>' : 'descend' } if not string . lower ( order ) in validSortOrders . keys ( ) : raise FMError , 'Invalid sort order for "' + field + '"' self . _sortP...
def slice_on_length ( self , data_len , * addSlices ) : '''Returns a slice representing the dimension range restrictions applied to a list of length data _ len . If addSlices contains additional slice requirements , they are processed in the order they are given .'''
if len ( self . ordered_ranges ) + len ( addSlices ) == 0 : return slice ( None , None , None ) ranges = self . ordered_ranges if len ( addSlices ) > 0 : ranges = ranges + DimensionRange ( * addSlices ) . ordered_ranges return self . _combine_lists_of_ranges_on_length ( data_len , * ranges )
def mag_cal_progress_encode ( self , compass_id , cal_mask , cal_status , attempt , completion_pct , completion_mask , direction_x , direction_y , direction_z ) : '''Reports progress of compass calibration . compass _ id : Compass being calibrated ( uint8 _ t ) cal _ mask : Bitmask of compasses being calibrated...
return MAVLink_mag_cal_progress_message ( compass_id , cal_mask , cal_status , attempt , completion_pct , completion_mask , direction_x , direction_y , direction_z )
def on_error_close ( logger ) : """Decorator for callback methods that implement ` IProtocol ` . Any uncaught exception is logged and the connection is closed forcefully . Usage : : import logger logger = logging . getLogger ( _ _ name _ _ ) class MyProtocol ( Protocol ) : @ on _ error _ close ( logge...
def make_wrapper ( func ) : @ functools . wraps ( func ) def wrapper ( self , * args , ** kwargs ) : d = defer . maybeDeferred ( func , self , * args , ** kwargs ) def on_error ( err ) : logger ( "Unhandled failure in %r:%s" % ( func , err . getTraceback ( ) ) ) if hasatt...
def pem ( self ) : """Returns PEM represntation of the certificate"""
bio = Membio ( ) if libcrypto . PEM_write_bio_X509 ( bio . bio , self . cert ) == 0 : raise X509Error ( "error serializing certificate" ) return str ( bio )
def url_path ( request , base_url = None , is_full = False , * args , ** kwargs ) : """join base _ url and some GET - parameters to one ; it could be absolute url optionally usage example : c [ ' current _ url ' ] = url _ path ( request , use _ urllib = True , is _ full = False ) < a href = " { { current _ ur...
if not base_url : base_url = request . path if is_full : protocol = 'https' if request . is_secure ( ) else 'http' base_url = '%s://%s%s' % ( protocol , request . get_host ( ) , base_url ) params = url_params ( request , * args , ** kwargs ) url = '%s%s' % ( base_url , params ) return url
def _fell_trees ( self ) : """Removes trees from the forest according to the specified fell method ."""
if callable ( self . fell_method ) : for tree in self . fell_method ( list ( self . trees ) ) : self . trees . remove ( tree )
def get_obs_route ( value ) : """obs - route = obs - domain - list " : " obs - domain - list = * ( CFWS / " , " ) " @ " domain * ( " , " [ CFWS ] [ " @ " domain ] ) Returns an obs - route token with the appropriate sub - tokens ( that is , there is no obs - domain - list in the parse tree ) ."""
obs_route = ObsRoute ( ) while value and ( value [ 0 ] == ',' or value [ 0 ] in CFWS_LEADER ) : if value [ 0 ] in CFWS_LEADER : token , value = get_cfws ( value ) obs_route . append ( token ) elif value [ 0 ] == ',' : obs_route . append ( ListSeparator ) value = value [ 1 : ] if ...
def find_candidate_splays ( splays , azm , inc , delta = LRUD_DELTA ) : """Given a list of splay shots , find candidate LEFT or RIGHT given target AZM and INC"""
return [ splay for splay in splays if angle_delta ( splay [ 'AZM' ] , azm ) <= delta / 2 and angle_delta ( splay [ 'INC' ] , inc ) <= delta / 2 ]
def redirect_stream ( system_stream , target_stream ) : """Redirect a system stream to a specified file . ` system _ stream ` is a standard system stream such as ` ` sys . stdout ` ` . ` target _ stream ` is an open file object that should replace the corresponding system stream object . If ` target _ strea...
if target_stream is None : target_fd = os . open ( os . devnull , os . O_RDWR ) else : target_fd = target_stream . fileno ( ) os . dup2 ( target_fd , system_stream . fileno ( ) )
def clipping_params ( ts , capacity = 100 ) : """Start and end index that clips the price / value of a time series the most Assumes that the integrated maximum includes the peak ( instantaneous maximum ) . Arguments : ts ( TimeSeries ) : Time series to attempt to clip to as low a max value as possible capac...
ts_sorted = ts . order ( ascending = False ) i , t0 , t1 , integral = 1 , None , None , 0 while integral <= capacity and i + 1 < len ( ts ) : i += 1 t0_within_capacity = t0 t1_within_capacity = t1 t0 = min ( ts_sorted . index [ : i ] ) t1 = max ( ts_sorted . index [ : i ] ) integral = integrated...
def iter_entries ( self ) : """Generate an | _ IfdEntry | instance corresponding to each entry in the directory ."""
for idx in range ( self . _entry_count ) : dir_entry_offset = self . _offset + 2 + ( idx * 12 ) ifd_entry = _IfdEntryFactory ( self . _stream_rdr , dir_entry_offset ) yield ifd_entry
def drawPolyline ( self , points ) : """Draw several connected line segments ."""
for i , p in enumerate ( points ) : if i == 0 : if not ( self . lastPoint == Point ( p ) ) : self . draw_cont += "%g %g m\n" % JM_TUPLE ( Point ( p ) * self . ipctm ) self . lastPoint = Point ( p ) else : self . draw_cont += "%g %g l\n" % JM_TUPLE ( Point ( p ) * self . i...
def getuserid ( username , copyright_str ) : """Get the ID of the user with ` username ` from write - math . com . If he doesn ' t exist by now , create it . Add ` copyright _ str ` as a description . Parameters username : string Name of a user . copyright _ str : string Description text of a user in Ma...
global username2id if username not in username2id : mysql = utils . get_mysql_cfg ( ) connection = pymysql . connect ( host = mysql [ 'host' ] , user = mysql [ 'user' ] , passwd = mysql [ 'passwd' ] , db = mysql [ 'db' ] , charset = 'utf8mb4' , cursorclass = pymysql . cursors . DictCursor ) cursor = connect...
def _calcsize ( fmt ) : '''struct . calcsize ( ) handling ' z ' for Py _ ssize _ t .'''
# sizeof ( long ) ! = sizeof ( ssize _ t ) on LLP64 if _sizeof_Clong < _sizeof_Cvoidp : # pragma : no coverage z = 'P' else : z = 'L' return calcsize ( fmt . replace ( 'z' , z ) )
def find_schema_yml ( cls , package_name , root_dir , relative_dirs ) : """This is common to both v1 and v2 - look through the relative _ dirs under root _ dir for . yml files yield pairs of filepath and loaded yaml contents ."""
extension = "[!.#~]*.yml" file_matches = dbt . clients . system . find_matching ( root_dir , relative_dirs , extension ) for file_match in file_matches : file_contents = dbt . clients . system . load_file_contents ( file_match . get ( 'absolute_path' ) , strip = False ) test_path = file_match . get ( 'relative_...
def send_audio ( self , left_channel , right_channel ) : """Add the audio samples to the stream . The left and the right channel should have the same shape . : param left _ channel : array containing the audio signal . : type left _ channel : numpy array with shape ( k , ) containing values between - 1.0 an...
self . lastaudioframe_left = left_channel self . lastaudioframe_right = right_channel
def pack_types ( types , args , major ) : """Pack arguments according the the types list . Parameters types : list of kattypes The types of the arguments ( in order ) . args : list of objects The arguments to format . major : integer Major version of KATCP to use when packing types"""
if len ( types ) > 0 : multiple = types [ - 1 ] . _multiple else : multiple = False if len ( types ) < len ( args ) and not multiple : raise ValueError ( "Too many arguments to pack." ) if len ( args ) < len ( types ) : # this passes in None for missing args retvals = map ( lambda ktype , arg : ktype . ...
def remove_capacity_from_diskgroup ( service_instance , host_ref , diskgroup , capacity_disks , data_evacuation = True , hostname = None , host_vsan_system = None ) : '''Removes capacity disk ( s ) from a disk group . service _ instance Service instance to the host or vCenter host _ vsan _ system ESXi host ...
if not hostname : hostname = salt . utils . vmware . get_managed_object_name ( host_ref ) cache_disk = diskgroup . ssd cache_disk_id = cache_disk . canonicalName log . debug ( 'Removing capacity from disk group with cache disk \'%s\' on host \'%s\'' , cache_disk_id , hostname ) log . trace ( 'capacity_disk_ids = %s...
def ctypes2buffer ( cptr , length ) : """Convert ctypes pointer to buffer type ."""
if not isinstance ( cptr , ctypes . POINTER ( ctypes . c_char ) ) : raise RuntimeError ( 'expected char pointer' ) res = bytearray ( length ) rptr = ( ctypes . c_char * length ) . from_buffer ( res ) if not ctypes . memmove ( rptr , cptr , length ) : raise RuntimeError ( 'memmove failed' ) return res
def fit_theil_sen ( x , y ) : """Compute a robust linear fit using the Theil - Sen method . See http : / / en . wikipedia . org / wiki / Theil % E2%80%93Sen _ estimator for details . This function " pairs up sample points by the rank of their x - coordinates ( the point with the smallest coordinate being pair...
xx = numpy . asarray ( x ) y1 = numpy . asarray ( y ) n = len ( xx ) if n < 5 : raise ValueError ( 'Number of points < 5' ) if xx . ndim != 1 : raise ValueError ( 'Input arrays have unexpected dimensions' ) if y1 . ndim == 1 : if len ( y1 ) != n : raise ValueError ( 'X and Y arrays have different si...
def should_rollover ( self , record : LogRecord ) -> bool : """Determine if rollover should occur . record is not used , as we are just comparing times , but it is needed so the method signatures are the same"""
t = int ( time . time ( ) ) if t >= self . rollover_at : return True return False
def write_acceptance_criteria_to_file ( self ) : """Writes current GUI acceptance criteria to criteria . txt or pmag _ criteria . txt depending on data model"""
crit_list = list ( self . acceptance_criteria . keys ( ) ) crit_list . sort ( ) rec = { } rec [ 'pmag_criteria_code' ] = "ACCEPT" # rec [ ' criteria _ definition ' ] = " " rec [ 'criteria_definition' ] = "acceptance criteria for study" rec [ 'er_citation_names' ] = "This study" for crit in crit_list : if type ( sel...
def create ( self , data ) : """Create a new SyncListItemInstance : param dict data : The data : returns : Newly created SyncListItemInstance : rtype : twilio . rest . preview . sync . service . sync _ list . sync _ list _ item . SyncListItemInstance"""
data = values . of ( { 'Data' : serialize . object ( data ) , } ) payload = self . _version . create ( 'POST' , self . _uri , data = data , ) return SyncListItemInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , list_sid = self . _solution [ 'list_sid' ] , )
def get_users ( self , omit_empty_organisms = False ) : """Get all users known to this Apollo instance : type omit _ empty _ organisms : bool : param omit _ empty _ organisms : Will omit users having no access to any organism : rtype : list of dicts : return : list of user info dictionaries"""
payload = { } if omit_empty_organisms : payload [ 'omitEmptyOrganisms' ] = omit_empty_organisms res = self . post ( 'loadUsers' , payload ) data = [ _fix_user ( user ) for user in res ] return data
def present ( name , retention_hours = None , enhanced_monitoring = None , num_shards = None , do_reshard = True , region = None , key = None , keyid = None , profile = None ) : '''Ensure the kinesis stream is properly configured and scaled . name ( string ) Stream name retention _ hours ( int ) Retain data...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } comments = [ ] changes_old = { } changes_new = { } # Ensure stream exists exists = __salt__ [ 'boto_kinesis.exists' ] ( name , region , key , keyid , profile ) if exists [ 'result' ] is False : if __opts__ [ 'test' ] : ret [ 'resul...