signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def authenticate_glance_admin ( self , keystone , force_v1_client = False ) : """Authenticates admin user with glance ."""
self . log . debug ( 'Authenticating glance admin...' ) ep = keystone . service_catalog . url_for ( service_type = 'image' , interface = 'adminURL' ) if not force_v1_client and keystone . session : return glance_clientv2 . Client ( "2" , session = keystone . session ) else : return glance_client . Client ( ep ,...
def stats ( ) : '''Runs the quotastats command , and returns the parsed output CLI Example : . . code - block : : bash salt ' * ' quota . stats'''
ret = { } out = __salt__ [ 'cmd.run' ] ( 'quotastats' ) . splitlines ( ) for line in out : if not line : continue comps = line . split ( ': ' ) ret [ comps [ 0 ] ] = comps [ 1 ] return ret
def get_slugignores ( root , fname = '.slugignore' ) : """Given a root path , read any . slugignore file inside and return a list of patterns that should be removed prior to slug compilation . Return empty list if file does not exist ."""
try : with open ( os . path . join ( root , fname ) ) as f : return [ l . rstrip ( '\n' ) for l in f ] except IOError : return [ ]
def from_xy ( cls , x_array , y_array ) : """Create a dataset from two arrays of data . : note : infering the dimensions for the first elements of each array ."""
if len ( x_array ) == 0 : raise ValueError ( "data array is empty." ) dim_x , dim_y = len ( x_array [ 0 ] ) , len ( y_array [ 0 ] ) dataset = cls ( dim_x , dim_y ) for x , y in zip ( x_array , y_array ) : assert len ( x ) == dim_x and len ( y ) == dim_y dataset . add_xy ( x , y ) return dataset
def copy_texture_memory_args ( self , texmem_args ) : """adds texture memory arguments to the most recently compiled module , if using CUDA"""
if self . lang == "CUDA" : self . dev . copy_texture_memory_args ( texmem_args ) else : raise Exception ( "Error cannot copy texture memory arguments when language is not CUDA" )
def register_list_command ( self , list_func ) : """Add ' list ' command to get a list of projects or details about one project . : param list _ func : function : run when user choses this option ."""
description = "Show a list of project names or folders/files of a single project." list_parser = self . subparsers . add_parser ( 'list' , description = description ) project_name_or_auth_role = list_parser . add_mutually_exclusive_group ( required = False ) _add_project_filter_auth_role_arg ( project_name_or_auth_role...
def simplify ( self ) : """Reorganize the ranges in the set in order to ensure that each range is unique and that there is not overlap between to ranges ."""
# Sort the ranges self . __range . sort ( ) new_range = [ ] new_first = self . __range [ 0 ] . first new_count = self . __range [ 0 ] . count for r in self . __range : if r . first == new_first : # Longest range starting at new _ first new_count = r . count elif r . first <= new_first + new_count : # Ov...
def build_from_info ( cls , info ) : """build a TensorTerm instance from a dict Parameters cls : class info : dict contains all information needed to build the term Return TensorTerm instance"""
terms = [ ] for term_info in info [ 'terms' ] : terms . append ( SplineTerm . build_from_info ( term_info ) ) return cls ( * terms )
def register ( self , ModelClass , form_field = None , widget = None , title = None , prefix = None , has_id_value = True ) : """Register a custom model with the ` ` AnyUrlField ` ` ."""
if any ( urltype . model == ModelClass for urltype in self . _url_types ) : raise ValueError ( "Model is already registered: '{0}'" . format ( ModelClass ) ) opts = ModelClass . _meta opts = opts . concrete_model . _meta if not prefix : # Store something descriptive , easier to lookup from raw database content . ...
def _StubMethod ( self , stub , method_descriptor , rpc_controller , request , callback ) : """The body of all service methods in the generated stub class . Args : stub : Stub instance . method _ descriptor : Descriptor of the invoked method . rpc _ controller : Rpc controller to execute the method . requ...
return stub . rpc_channel . CallMethod ( method_descriptor , rpc_controller , request , method_descriptor . output_type . _concrete_class , callback )
def sealedbox_encrypt ( data , ** kwargs ) : '''Encrypt data using a public key generated from ` nacl . keygen ` . The encryptd data can be decrypted using ` nacl . sealedbox _ decrypt ` only with the secret key . CLI Examples : . . code - block : : bash salt - run nacl . sealedbox _ encrypt datatoenc sal...
kwargs [ 'opts' ] = __opts__ return salt . utils . nacl . sealedbox_encrypt ( data , ** kwargs )
def create_pool ( self ) : """Return a ConnectionPool instance of given host : param socket _ timeout : socket timeout for each connection in seconds"""
service = self . dao . service_name ( ) ca_certs = self . dao . get_setting ( "CA_BUNDLE" , "/etc/ssl/certs/ca-bundle.crt" ) cert_file = self . dao . get_service_setting ( "CERT_FILE" , None ) host = self . dao . get_service_setting ( "HOST" ) key_file = self . dao . get_service_setting ( "KEY_FILE" , None ) max_pool_s...
def open_any ( filename ) : """Helper to open also compressed files"""
if filename . endswith ( ".gz" ) : return gzip . open if filename . endswith ( ".bz2" ) : return bz2 . BZ2File return open
def validate ( self , schema = None ) : """Validate that we have a valid object . On error , this will raise a ` ScrapeValueError ` This also expects that the schemas assume that omitting required in the schema asserts the field is optional , not required . This is due to upstream schemas being in JSON Sche...
if schema is None : schema = self . _schema type_checker = Draft3Validator . TYPE_CHECKER . redefine ( "datetime" , lambda c , d : isinstance ( d , ( datetime . date , datetime . datetime ) ) ) ValidatorCls = jsonschema . validators . extend ( Draft3Validator , type_checker = type_checker ) validator = ValidatorCls...
def numerical_components ( self ) : """: return : lambda functions of each of the analytical components in model _ dict , to be used in numerical calculation ."""
Ans = variabletuple ( 'Ans' , self . keys ( ) ) # All components must feature the independent vars and params , that ' s # the API convention . But for those components which also contain # interdependence , we add those vars components = [ ] for var , expr in self . items ( ) : dependencies = self . connectivity_m...
def _preoptimize_model ( self ) : """Preoptimizes the model by estimating a Gaussian state space models Returns - Gaussian model latent variable object"""
gaussian_model = LLT ( self . data , integ = self . integ , target = self . target ) gaussian_model . fit ( ) self . latent_variables . z_list [ 0 ] . start = gaussian_model . latent_variables . get_z_values ( ) [ 1 ] self . latent_variables . z_list [ 1 ] . start = gaussian_model . latent_variables . get_z_values ( ) ...
def barplot ( bars , title = '' , upColor = 'blue' , downColor = 'red' ) : """Create candlestick plot for the given bars . The bars can be given as a DataFrame or as a list of bar objects ."""
import pandas as pd import matplotlib . pyplot as plt from matplotlib . lines import Line2D from matplotlib . patches import Rectangle if isinstance ( bars , pd . DataFrame ) : ohlcTups = [ tuple ( v ) for v in bars [ [ 'open' , 'high' , 'low' , 'close' ] ] . values ] elif bars and hasattr ( bars [ 0 ] , 'open_' ) ...
def do ( cmdline = None , runas = None ) : '''Execute a python command with pyenv ' s shims from the user or the system . CLI Example : . . code - block : : bash salt ' * ' pyenv . do ' gem list bundler ' salt ' * ' pyenv . do ' gem list bundler ' deploy'''
path = _pyenv_path ( runas ) cmd_split = cmdline . split ( ) quoted_line = '' for cmd in cmd_split : quoted_line = quoted_line + ' ' + _cmd_quote ( cmd ) result = __salt__ [ 'cmd.run_all' ] ( 'env PATH={0}/shims:$PATH {1}' . format ( _cmd_quote ( path ) , quoted_line ) , runas = runas , python_shell = True ) if res...
def device_key ( self , device_key ) : """Sets the device _ key of this DeviceData . The fingerprint of the device certificate . : param device _ key : The device _ key of this DeviceData . : type : str"""
if device_key is not None and len ( device_key ) > 512 : raise ValueError ( "Invalid value for `device_key`, length must be less than or equal to `512`" ) self . _device_key = device_key
def reject_outliers ( a , threshold = 3.5 ) : """Iglewicz and Hoaglin ' s robust test for multiple outliers ( two sided test ) . < http : / / www . itl . nist . gov / div898 / handbook / eda / section3 / eda35h . htm > See also : < http : / / contchart . com / outliers . aspx > > > > a = [ 0 , 1 , 2 , 4 , 1...
if len ( a ) < 3 : return np . zeros ( len ( a ) , dtype = bool ) A = np . array ( a , dtype = float ) lb , ub = outlier_cutoff ( A , threshold = threshold ) return np . logical_or ( A > ub , A < lb )
def _sanity_check_files ( item , files ) : """Ensure input files correspond with supported approaches . Handles BAM , fastqs , plus split fastqs ."""
msg = None file_types = set ( [ ( "bam" if x . endswith ( ".bam" ) else "fastq" ) for x in files if x ] ) if len ( file_types ) > 1 : msg = "Found multiple file types (BAM and fastq)" file_type = file_types . pop ( ) if file_type == "bam" : if len ( files ) != 1 : msg = "Expect a single BAM file input a...
def run ( self , host = None , port = None , debug = None , workers = None ) : """启动 : param host : 监听IP : param port : 监听端口 : param debug : 是否debug : param workers : workers数量 : return :"""
self . _validate_cmds ( ) if host is None : host = constants . SERVER_HOST if port is None : port = constants . SERVER_PORT if debug is not None : self . debug = debug workers = workers if workers is not None else 1 logger . info ( 'Running server on %s, debug: %s, workers: %s' , ( host , port ) , self . de...
def raise_check_result ( self ) : """Raise ACTIVE CHECK RESULT entry Example : " ACTIVE SERVICE CHECK : server ; DOWN ; HARD ; 1 ; I don ' t know what to say . . . " : return : None"""
if not self . __class__ . log_active_checks : return log_level = 'info' if self . state in [ u'WARNING' , u'UNREACHABLE' ] : log_level = 'warning' elif self . state == u'CRITICAL' : log_level = 'error' brok = make_monitoring_log ( log_level , 'ACTIVE SERVICE CHECK: %s;%s;%s;%d;%s' % ( self . host_name , sel...
def initialize ( self , runtime = None ) : """Initializes this manager . A manager is initialized once at the time of creation . arg : runtime ( osid . OsidRuntimeManager ) : the runtime environment raise : CONFIGURATION _ ERROR - an error with implementation configuration raise : ILLEGAL _ STATE - this...
if self . _runtime is not None : raise IllegalState ( ) self . _runtime = runtime config = runtime . get_configuration ( ) parameter_id = Id ( 'parameter:hostName@dlkit_service' ) host = config . get_value_by_parameter ( parameter_id ) . get_string_value ( ) if host is not None : self . _host = host parameter_i...
def parse ( readDataInstance ) : """Returns a new L { NetMetaDataStreamEntry } object . @ type readDataInstance : L { ReadData } @ param readDataInstance : A L { ReadData } object with data to be parsed as a L { NetMetaDataStreamEntry } . @ rtype : L { NetMetaDataStreamEntry } @ return : A new L { NetMetaDa...
n = NetMetaDataStreamEntry ( ) n . offset . value = readDataInstance . readDword ( ) n . size . value = readDataInstance . readDword ( ) n . name . value = readDataInstance . readAlignedString ( ) return n
def cache ( self , con ) : """Put a dedicated connection back into the idle cache ."""
if self . _maxusage and con . usage_count > self . _maxusage : self . _connections -= 1 logging . debug ( 'dropping connection %s uses past max usage %s' % ( con . usage_count , self . _maxusage ) ) con . _close ( ) return self . _condition . acquire ( ) if con in self . _idle_cache : # called via socke...
def _config2indy ( self , config : dict ) -> dict : """Given a configuration dict with indy and possibly more configuration values , return the corresponding indy wallet configuration dict from current default and input values . : param config : input configuration : return : configuration dict for indy walle...
assert { 'name' , 'id' } & { k for k in config } return { 'id' : config . get ( 'name' , config . get ( 'id' ) ) , 'storage_type' : config . get ( 'storage_type' , self . default_storage_type ) , 'freshness_time' : config . get ( 'freshness_time' , self . default_freshness_time ) }
def nacm_rule_list_rule_access_operations ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) nacm = ET . SubElement ( config , "nacm" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-acm" ) rule_list = ET . SubElement ( nacm , "rule-list" ) name_key = ET . SubElement ( rule_list , "name" ) name_key . text = kwargs . pop ( 'name' ) rule = ET . SubElement ( rule_list , "rule...
def string_relax ( start , end , V , n_images = 25 , dr = None , h = 3.0 , k = 0.17 , min_iter = 100 , max_iter = 10000 , max_tol = 5e-6 ) : """Implements path relaxation via the elastic band method . In general , the method is to define a path by a set of points ( images ) connected with bands with some elasti...
# This code is based on the MATLAB example provided by # Prof . Eric Vanden - Eijnden of NYU # ( http : / / www . cims . nyu . edu / ~ eve2 / main . htm ) # print ( " Getting path from { } to { } ( coords wrt V grid ) " . format ( start , end ) ) # Set parameters if not dr : dr = np . array ( [ 1.0 / V . shape [ 0 ...
def validate_headers ( self ) : """Check if CSV metadata files have the right format ."""
super ( ) . validate ( ) self . validate_header ( self . channeldir , self . channelinfo , CHANNEL_INFO_HEADER ) self . validate_header ( self . channeldir , self . contentinfo , CONTENT_INFO_HEADER ) if self . has_exercises ( ) : self . validate_header ( self . channeldir , self . exercisesinfo , EXERCISE_INFO_HEA...
def _qualified_key ( self , key ) : """Prepends the configured prefix to the key ( if applicable ) . : param key : The unprefixed key . : return : The key with any configured prefix prepended ."""
pfx = self . key_prefix if self . key_prefix is not None else '' return '{}{}' . format ( pfx , key )
def _is_junction ( arg ) : '''Return True , if arg is a junction statement .'''
return isinstance ( arg , dict ) and len ( arg ) == 1 and next ( six . iterkeys ( arg ) ) == 'junction'
def is_docstring ( tokens , previous_logical ) : """Return found docstring ' A docstring is a string literal that occurs as the first statement in a module , function , class , ' http : / / www . python . org / dev / peps / pep - 0257 / # what - is - a - docstring"""
for token_type , text , start , _ , _ in tokens : if token_type == tokenize . STRING : break elif token_type != tokenize . INDENT : return False else : return False line = text . lstrip ( ) start , start_triple = _find_first_of ( line , START_DOCSTRING_TRIPLE ) if ( previous_logical . starts...
def check_accesspoints ( sess ) : """check the status of all connected access points"""
ap_names = walk_data ( sess , name_ap_oid , helper ) [ 0 ] ap_operationals = walk_data ( sess , operational_ap_oid , helper ) [ 0 ] ap_availabilitys = walk_data ( sess , availability_ap_oid , helper ) [ 0 ] ap_alarms = walk_data ( sess , alarm_ap_oid , helper ) [ 0 ] # ap _ ip = walk _ data ( sess , ip _ ap _ oid , hel...
def gi ( ip , lo = None , iq = None , ico = None , pl = None ) : """This function is a wrapper for : meth : ` ~ pywbem . WBEMConnection . GetInstance ` . Retrieve an instance . Parameters : ip ( : class : ` ~ pywbem . CIMInstanceName ` ) : Instance path . If this object does not specify a namespace , th...
return CONN . GetInstance ( ip , LocalOnly = lo , IncludeQualifiers = iq , IncludeClassOrigin = ico , PropertyList = pl )
def load_and_run_pipeline ( pipeline_name , pipeline_context_input = None , working_dir = None , context = None , parse_input = True , loader = None ) : """Load and run the specified pypyr pipeline . This function runs the actual pipeline by name . If you are running another pipeline from within a pipeline , ca...
logger . debug ( f"you asked to run pipeline: {pipeline_name}" ) if loader : logger . debug ( f"you set the pype loader to: {loader}" ) else : loader = 'pypyr.pypeloaders.fileloader' logger . debug ( f"use default pype loader: {loader}" ) logger . debug ( f"you set the initial context to: {pipeline_context_...
def delete_data ( self , url , * args , ** kwargs ) : """Deletes data under provided url Returns status as boolean . Args : * * url * * : address of file to be deleted . . versionadded : : 0.3.2 * * additional _ headers * * : ( optional ) Additional headers to be used with request Returns : Boolean ...
res = self . _conn . delete ( url , headers = self . _prepare_headers ( ** kwargs ) ) if res . status_code == 200 or res . status_code == 202 : return True else : return False
def smartResizeColumnsToContents ( self ) : """Resizes the columns to the contents based on the user preferences ."""
self . blockSignals ( True ) self . setUpdatesEnabled ( False ) header = self . header ( ) header . blockSignals ( True ) columns = range ( self . columnCount ( ) ) sizes = [ self . columnWidth ( c ) for c in columns ] header . resizeSections ( header . ResizeToContents ) for col in columns : width = self . columnW...
def read_item ( self , from_date = None ) : """Read items and return them one by one . : param from _ date : start date for incremental reading . : return : next single item when any available . : raises ValueError : ` metadata _ _ timestamp ` field not found in index : raises NotFoundError : index not foun...
search_query = self . _build_search_query ( from_date ) for hit in helpers . scan ( self . _es_conn , search_query , scroll = '300m' , index = self . _es_index , preserve_order = True ) : yield hit
def omegac ( self , R ) : """NAME : omegac PURPOSE : calculate the circular angular speed at R in potential Pot INPUT : Pot - Potential instance or list of such instances R - Galactocentric radius ( can be Quantity ) OUTPUT : circular angular speed HISTORY : 2011-10-09 - Written - Bovy ( IAS )""...
return nu . sqrt ( - self . Rforce ( R , use_physical = False ) / R )
def get_current_observation_date ( self ) : """Get the date of the current observation by looking in the header of the observation for the DATE and EXPTIME keywords . The ' DATE AT MIDDLE OF OBSERVATION ' of the observation is returned @ return : Time"""
# All HDU elements have the same date and time so just use # last one , sometimes the first one is missing the header , in MEF header = self . get_current_cutout ( ) . hdulist [ - 1 ] . header mjd_obs = float ( header . get ( 'MJD-OBS' ) ) exptime = float ( header . get ( 'EXPTIME' ) ) mpc_date = Time ( mjd_obs , forma...
def has_unknown_attachment_error ( self , page_id ) : """Check has unknown attachment error on page : param page _ id : : return :"""
unknown_attachment_identifier = 'plugins/servlet/confluence/placeholder/unknown-attachment' result = self . get_page_by_id ( page_id , expand = 'body.view' ) if len ( result ) == 0 : return "" body = ( ( ( result . get ( 'body' ) or { } ) . get ( 'view' ) or { } ) . get ( 'value' ) or { } ) if unknown_attachment_id...
def solve ( guess_a , guess_b , power , solver = 'scipy' ) : """Constructs a pyneqsys . symbolic . SymbolicSys instance and returns from its ` ` solve ` ` method ."""
# The problem is 2 dimensional so we need 2 symbols x = sp . symbols ( 'x:2' , real = True ) # There is a user specified parameter ` ` p ` ` in this problem : p = sp . Symbol ( 'p' , real = True , negative = False , integer = True ) # Our system consists of 2 - non - linear equations : f = [ x [ 0 ] + ( x [ 0 ] - x [ 1...
def raw_cron ( user ) : '''Return the contents of the user ' s crontab CLI Example : . . code - block : : bash salt ' * ' cron . raw _ cron root'''
if _check_instance_uid_match ( user ) or __grains__ . get ( 'os_family' ) in ( 'Solaris' , 'AIX' ) : cmd = 'crontab -l' # Preserve line endings lines = salt . utils . data . decode ( __salt__ [ 'cmd.run_stdout' ] ( cmd , runas = user , ignore_retcode = True , rstrip = False , python_shell = False ) ) . spli...
def convenience_calc_probs ( self , params ) : """Calculates the probabilities of the chosen alternative , and the long format probabilities for this model and dataset ."""
shapes , intercepts , betas = self . convenience_split_params ( params ) prob_args = ( betas , self . design_3d , self . alt_id_vector , self . rows_to_obs , self . rows_to_alts , self . utility_transform ) prob_kwargs = { "chosen_row_to_obs" : self . chosen_row_to_obs , "return_long_probs" : True } probability_results...
def all ( cls , klass , db_session = None ) : """returns all objects of specific type - will work correctly with sqlalchemy inheritance models , you should normally use models base _ query ( ) instead of this function its for bw . compat purposes : param klass : : param db _ session : : return :"""
db_session = get_db_session ( db_session ) return db_session . query ( klass )
def ConfigureLogging ( debug_output = False , filename = None , mode = 'w' , quiet_mode = False ) : """Configures the logging root logger . Args : debug _ output ( Optional [ bool ] ) : True if the logging should include debug output . filename ( Optional [ str ] ) : log filename . mode ( Optional [ str ]...
# Remove all possible log handlers . The log handlers cannot be reconfigured # and therefore must be recreated . for handler in logging . root . handlers : logging . root . removeHandler ( handler ) logger = logging . getLogger ( ) if filename and filename . endswith ( '.gz' ) : handler = CompressedFileHandler ...
def to_list ( var ) : """Checks if given value is a list , tries to convert , if it is not ."""
if var is None : return [ ] if isinstance ( var , str ) : var = var . split ( '\n' ) elif not isinstance ( var , list ) : try : var = list ( var ) except TypeError : raise ValueError ( "{} cannot be converted to the list." . format ( var ) ) return var
def tokenize ( self , string ) : """Tokenize incoming string ."""
if self . language == 'akkadian' : tokens = tokenize_akkadian_words ( string ) elif self . language == 'arabic' : tokens = tokenize_arabic_words ( string ) elif self . language == 'french' : tokens = tokenize_french_words ( string ) elif self . language == 'greek' : tokens = tokenize_greek_words ( strin...
def main ( output_path = None ) : """Writes out new python build system This is needed because CircleCI does not support build matrices nor parameterisation of cache paths or other aspects of their config There ' s also the added bonus of validating the yaml as we go . Additionally , we template and write...
config_output_file = output_path or os . path . join ( PROJECT_ROOT , '.circleci' , 'config.yml' ) yaml_structure = generate_circle_output ( ) with open ( config_output_file , 'w' ) as fh : yaml_content = yaml . safe_dump ( data = yaml_structure , default_flow_style = False ) fh . write ( f'#\n' f'# This file i...
def observed_data_to_xarray ( self ) : """Convert observed data to xarray ."""
data = { } for idx , var_name in enumerate ( self . arg_names ) : # Use emcee3 syntax , else use emcee2 data [ var_name ] = ( self . sampler . log_prob_fn . args [ idx ] if hasattr ( self . sampler , "log_prob_fn" ) else self . sampler . args [ idx ] ) return dict_to_dataset ( data , library = self . emcee , coords...
def to_marker ( marker ) : """Serializes marker to string : param marker : object to serialize : return : string id"""
from sevenbridges . models . marker import Marker if not marker : raise SbgError ( 'Marker is required!' ) elif isinstance ( marker , Marker ) : return marker . id elif isinstance ( marker , six . string_types ) : return marker else : raise SbgError ( 'Invalid marker parameter!' )
def do_ams_auth ( endpoint , body ) : '''Acquire Media Services Authentication Token . Args : endpoint ( str ) : Azure Media Services Initial Endpoint . body ( str ) : A Content Body . Returns : HTTP response . JSON body .'''
headers = { "content-type" : "application/x-www-form-urlencoded" , "Accept" : json_acceptformat } return requests . post ( endpoint , data = body , headers = headers )
def resolvePublic ( self , pubID ) : """Try to lookup the catalog local reference associated to a public ID in that catalog"""
ret = libxml2mod . xmlACatalogResolvePublic ( self . _o , pubID ) return ret
def teardown_appcontext ( self , func : Callable ) -> Callable : """Add a teardown app ( context ) function . This is designed to be used as a decorator . An example usage , . . code - block : : python @ app . teardown _ appcontext def func ( ) : Arguments : func : The teardown function itself . name ...
handler = ensure_coroutine ( func ) self . teardown_appcontext_funcs . append ( handler ) return func
def request ( self , session_id ) : """Force the termination of a NETCONF session ( not the current one ! ) * session _ id * is the session identifier of the NETCONF session to be terminated as a string"""
node = new_ele ( "kill-session" ) sub_ele ( node , "session-id" ) . text = session_id return self . _request ( node )
def _interfaces_removed ( self , object_path , interfaces ) : """Internal method ."""
old_state = copy ( self . _objects [ object_path ] ) for interface in interfaces : del self . _objects [ object_path ] [ interface ] new_state = self . _objects [ object_path ] if Interface [ 'Drive' ] in interfaces : self . _detect_toggle ( 'has_media' , self . get ( object_path , old_state ) , self . get ( ob...
def checkIfHashIsCracked ( hash = None ) : """Method that checks if the given hash is stored in the md5db . net website . : param hash : hash to verify . : return : Resolved hash . If nothing was found , it will return an empty list ."""
apiURL = "http://md5db.net/api/" + str ( hash ) . lower ( ) try : # Getting the result of the query from MD5db . net data = urllib2 . urlopen ( apiURL ) . read ( ) return data except : # No information was found , then we return a null entity return [ ]
def detect_intent_stream ( project_id , session_id , audio_file_path , language_code ) : """Returns the result of detect intent with streaming audio as input . Using the same ` session _ id ` between requests allows continuation of the conversaion ."""
import dialogflow_v2 as dialogflow session_client = dialogflow . SessionsClient ( ) # Note : hard coding audio _ encoding and sample _ rate _ hertz for simplicity . audio_encoding = dialogflow . enums . AudioEncoding . AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 16000 session_path = session_client . session_path ( pro...
def decimals ( self ) : """Returns the number of decimal places for the values in the ` value < N > ` attributes of the current mode ."""
self . _decimals , value = self . get_attr_int ( self . _decimals , 'decimals' ) return value
def pictures ( self ) : """list [ Picture ] : List of embedded pictures"""
return [ b for b in self . metadata_blocks if b . code == Picture . code ]
def main ( argv = None ) : """psd - tools command line utility . Usage : psd - tools export < input _ file > < output _ file > [ options ] psd - tools show < input _ file > [ options ] psd - tools debug < input _ file > [ options ] psd - tools - h | - - help psd - tools - - version Options : - v - -...
args = docopt . docopt ( main . __doc__ , version = __version__ , argv = argv ) if args [ '--verbose' ] : logger . setLevel ( logging . DEBUG ) else : logger . setLevel ( logging . INFO ) if args [ 'export' ] : input_parts = args [ '<input_file>' ] . split ( '[' ) input_file = input_parts [ 0 ] if l...
def get_random_choice ( self ) : """returns a random name from the class"""
i = random . randint ( 0 , len ( self . dat ) - 1 ) return self . dat [ i ] [ 'name' ]
def getBindings ( varList , startLevel = 0 ) : """Given a list of identifiers as strings , construct the dictonary of the identifiers as keys and the evaluated values of the ientifiers as the values . Ie something like { id : full _ lookup ( id ) for id in identifiers } . full _ lookup here is looking up the va...
varsToFind = set ( varList ) bindings = { } # We start at the level of the caller of getBindings frame = inspect . currentframe ( ) try : for i in xrange ( startLevel + 1 ) : frame = frame . f_back except : raise Exception ( "bindings: startLevel {} is too high\n" . format ( startLevel ) ) # while we ha...
def top_priority_effect ( effects ) : """Given a collection of variant transcript effects , return the top priority object . ExonicSpliceSite variants require special treatment since they actually represent two effects - - the splicing modification and whatever else would happen to the exonic sequence if noth...
if len ( effects ) == 0 : raise ValueError ( "List of effects cannot be empty" ) effects = map ( select_between_exonic_splice_site_and_alternate_effect , effects ) effects_grouped_by_gene = apply_groupby ( effects , fn = gene_id_of_associated_transcript , skip_none = False ) if None in effects_grouped_by_gene : ...
def _compile_create_encoding ( self , sql , connection , blueprint ) : """Append the character set specifications to a command . : type sql : str : type connection : orator . connections . Connection : type blueprint : Blueprint : rtype : str"""
charset = blueprint . charset or connection . get_config ( "charset" ) if charset : sql += " DEFAULT CHARACTER SET %s" % charset collation = blueprint . collation or connection . get_config ( "collation" ) if collation : sql += " COLLATE %s" % collation return sql
def last_ehlo_response ( self , response : SMTPResponse ) -> None : """When setting the last EHLO response , parse the message for supported extensions and auth methods ."""
extensions , auth_methods = parse_esmtp_extensions ( response . message ) self . _last_ehlo_response = response self . esmtp_extensions = extensions self . server_auth_methods = auth_methods self . supports_esmtp = True
def DataClass ( name , columns , constraint = None ) : """Use the DataClass to define a class , but with some extra features : 1 . restrict the datatype of property 2 . restrict if ` required ` , or if ` nulls ` are allowed 3 . generic constraints on object properties It is expected that this class become a...
columns = wrap ( [ { "name" : c , "required" : True , "nulls" : False , "type" : object } if is_text ( c ) else c for c in columns ] ) slots = columns . name required = wrap ( filter ( lambda c : c . required and not c . nulls and not c . default , columns ) ) . name nulls = wrap ( filter ( lambda c : c . nulls , colum...
def get_random_word ( dictionary , starting_letter = None ) : """Takes the dictionary to read from and returns a random word optionally accepts a starting letter"""
if starting_letter is None : starting_letter = random . choice ( list ( dictionary . keys ( ) ) ) try : to_return = random . choice ( dictionary [ starting_letter ] ) except KeyError : msg = "Dictionary does not contain a word starting with '{}'" raise NoWordForLetter ( msg . format ( starting_letter ) ...
def check_map ( uri , url_root ) : """return a tuple of the rule and kw ."""
# TODO : Building the Map each time this is called seems like it could be more effiecent . result = [ ] try : result = db . execute ( text ( fetch_query_string ( 'select_route_where_dynamic.sql' ) ) ) . fetchall ( ) except OperationalError as err : current_app . logger . error ( "OperationalError: %s" , err ) ...
def _get_repr_list ( self ) : """Get some representation data common to all HDU types"""
spacing = ' ' * 2 text = [ '' ] text . append ( "%sfile: %s" % ( spacing , self . _filename ) ) text . append ( "%sextension: %d" % ( spacing , self . _info [ 'hdunum' ] - 1 ) ) text . append ( "%stype: %s" % ( spacing , _hdu_type_map [ self . _info [ 'hdutype' ] ] ) ) extname = self . get_extname ( ) if extname != "" ...
def import_wikipage ( self , slug , content , ** attrs ) : """Import a Wiki page and return a : class : ` WikiPage ` object . : param slug : slug of the : class : ` WikiPage ` : param content : content of the : class : ` WikiPage ` : param attrs : optional attributes for : class : ` Task `"""
return WikiPages ( self . requester ) . import_ ( self . id , slug , content , ** attrs )
def _get_synset_offsets ( synset_idxes ) : """Returs pointer offset in the WordNet file for every synset index . Notes Internal function . Do not call directly . Preserves order - - for [ x , y , z ] returns [ offset ( x ) , offset ( y ) , offset ( z ) ] . Parameters synset _ idxes : list of ints Lists ...
offsets = { } current_seeked_offset_idx = 0 ordered_synset_idxes = sorted ( synset_idxes ) with codecs . open ( _SOI , 'rb' , 'utf-8' ) as fin : for line in fin : split_line = line . split ( ':' ) while current_seeked_offset_idx < len ( ordered_synset_idxes ) and split_line [ 0 ] == str ( ordered_sy...
def do_eb ( self , arg ) : """[ ~ process ] eb < address > < data > - write the data to the specified address"""
# TODO # data parameter should be optional , use a child Cmd here pid = self . get_process_id_from_prefix ( ) token_list = self . split_tokens ( arg , 2 ) address = self . input_address ( token_list [ 0 ] , pid ) data = HexInput . hexadecimal ( ' ' . join ( token_list [ 1 : ] ) ) self . write_memory ( address , data , ...
def l3_tenant_id ( cls ) : """Returns id of tenant owning hosting device resources ."""
if cls . _l3_tenant_uuid is None : if hasattr ( cfg . CONF . keystone_authtoken , 'project_domain_id' ) : # TODO ( sridar ) : hack for now to determing if keystone v3 # API is to be used . cls . _l3_tenant_uuid = cls . _get_tenant_id_using_keystone_v3 ( ) else : cls . _l3_tenant_uuid = cls ....
def reqFundamentalData ( self , contract : Contract , reportType : str , fundamentalDataOptions : List [ TagValue ] = None ) -> str : """Get fundamental data of a contract in XML format . This method is blocking . https : / / interactivebrokers . github . io / tws - api / fundamentals . html Args : contract...
return self . _run ( self . reqFundamentalDataAsync ( contract , reportType , fundamentalDataOptions ) )
def get_program_status_brok ( self , brok_type = 'program_status' ) : """Create a program status brok Initially builds the running properties and then , if initial status brok , get the properties from the Config class where an entry exist for the brok ' full _ status ' : return : Brok with program status d...
# Get the running statistics data = { "is_running" : True , "instance_id" : self . instance_id , # " alignak _ name " : self . alignak _ name , "instance_name" : self . name , "last_alive" : time . time ( ) , "pid" : os . getpid ( ) , '_running' : self . get_scheduler_stats ( details = True ) , '_config' : { } , '_macr...
def png ( self , val , ng = 'ERR' ) : """Print val : ERR in red on STDOUT"""
self . pstd ( self . color . red ( '{}: {}' . format ( val , ng ) ) )
def log_env_info ( ) : """Prints information about execution environment ."""
logging . info ( 'Collecting environment information...' ) env_info = torch . utils . collect_env . get_pretty_env_info ( ) logging . info ( f'{env_info}' )
def _set_attribute ( self , name , value ) : """Make sure namespace gets updated when setting attributes ."""
setattr ( self , name , value ) self . namespace . update ( { name : getattr ( self , name ) } )
def read_moc_ascii ( moc , filename = None , file = None ) : """Read from an ASCII file into a MOC . Either a filename , or an open file object can be specified ."""
if file is not None : orders = _read_ascii ( file ) else : with open ( filename , 'r' ) as f : orders = _read_ascii ( f ) for text in orders : if not text : continue cells = [ ] ( order , ranges ) = text . split ( '/' ) for r in ranges . split ( ',' ) : try : ...
def main ( args ) : '''surface _ to _ rubbon . main ( args ) can be given a list of arguments , such as sys . argv [ 1 : ] ; these arguments may include any options and must include exactly one subject id and one output filename . Additionally one or two surface input filenames must be given . The surface files...
# Parse the arguments ( args , opts ) = _surface_to_ribbon_parser ( args ) # First , help ? if opts [ 'help' ] : print ( info , file = sys . stdout ) return 1 # and if we are verbose , lets setup a note function verbose = opts [ 'verbose' ] def note ( s ) : if verbose : print ( s , file = sys . stdo...
def feed_data ( self , data : bytes ) -> None : """代理 feed _ data"""
if self . _parser is not None : self . _parser . feed_data ( data )
def align ( expnums , ccd , version = 's' , dry_run = False ) : """Create a ' shifts ' file that transforms the space / flux / time scale of all images to the first image . This function relies on the . fwhm , . trans . jmp , . phot and . zeropoint . used files for inputs . The scaling we are computing here is ...
# Get the images and supporting files that we need from the VOSpace area # get _ image and get _ file check if the image / file is already on disk . # re - computed fluxes from the PSF stars and then recompute x / y / flux scaling . # some dictionaries to hold the various scale pos = { } apcor = { } mags = { } zmag = {...
def handle_other ( self , response ) : """Handles all responses with the exception of 401s . This is necessary so that we can authenticate responses if requested"""
log . debug ( "handle_other(): Handling: %d" % response . status_code ) if self . mutual_authentication in ( REQUIRED , OPTIONAL ) and not self . auth_done : is_http_error = response . status_code >= 400 if _negotiate_value ( response ) is not None : log . debug ( "handle_other(): Authenticating the ser...
def _calculate_num_queries ( self ) : """Calculate the total number of request and response queries . Used for count header and count table ."""
request_totals = self . _totals ( "request" ) response_totals = self . _totals ( "response" ) return request_totals [ 2 ] + response_totals [ 2 ]
def getItemDPList ( self ) : """Returns list of item , dp pairs corresponding to content of listview . Not - yet - saved items will have dp = None ."""
itemlist = [ ( item , item . _dp ) for item in self . iterator ( ) ] return itemlist
def init_account ( self ) : """Setup a new GitHub account ."""
ghuser = self . api . me ( ) # Setup local access tokens to be used by the webhooks hook_token = ProviderToken . create_personal ( 'github-webhook' , self . user_id , scopes = [ 'webhooks:event' ] , is_internal = True , ) # Initial structure of extra data self . account . extra_data = dict ( id = ghuser . id , login = ...
def digit ( nstr , schema ) : """! ~ ~ digit '0123456789 ' . isdigit ( ) or 123456789"""
if isinstance ( nstr , int ) : nstr = str ( nstr ) elif not isinstance ( nstr , basestring ) : return False return nstr . isdigit ( )
def _unwrap_obj ( self , fobj , fun ) : """Unwrap decorators ."""
try : prev_func_obj , next_func_obj = ( fobj . f_globals [ fun ] , getattr ( fobj . f_globals [ fun ] , "__wrapped__" , None ) , ) while next_func_obj : prev_func_obj , next_func_obj = ( next_func_obj , getattr ( next_func_obj , "__wrapped__" , None ) , ) return ( prev_func_obj , inspect . getfile (...
def is_contiguous ( self ) : '''Return whether entire collection is contiguous .'''
previous = None for index in self . indexes : if previous is None : previous = index continue if index != ( previous + 1 ) : return False previous = index return True
def inspect_current_object ( self ) : """Inspect current object in the Help plugin"""
editor = self . get_current_editor ( ) editor . sig_display_signature . connect ( self . display_signature_help ) line , col = editor . get_cursor_line_column ( ) editor . request_hover ( line , col )
def _parse_downloaded_items ( self , result , camera , path ) : """Parse downloaded videos ."""
for item in result : try : created_at = item [ 'created_at' ] camera_name = item [ 'camera_name' ] is_deleted = item [ 'deleted' ] address = item [ 'address' ] except KeyError : _LOGGER . info ( "Missing clip information, skipping..." ) continue if camera_name...
def conjugate_gradient ( op , x , rhs , niter , callback = None ) : """Optimized implementation of CG for self - adjoint operators . This method solves the inverse problem ( of the first kind ) : : A ( x ) = y for a linear and self - adjoint ` Operator ` ` ` A ` ` . It uses a minimum amount of memory copies...
# TODO : add a book reference # TODO : update doc if op . domain != op . range : raise ValueError ( 'operator needs to be self-adjoint' ) if x not in op . domain : raise TypeError ( '`x` {!r} is not in the domain of `op` {!r}' '' . format ( x , op . domain ) ) r = op ( x ) r . lincomb ( 1 , rhs , - 1 , r ) # r ...
def sasdata2dataframe ( self , table : str , libref : str = '' , dsopts : dict = None , method : str = 'MEMORY' , ** kwargs ) -> 'pd.DataFrame' : """This method exports the SAS Data Set to a Pandas Data Frame , returning the Data Frame object . SASdata object that refers to the Sas Data Set you want to export to ...
dsopts = dsopts if dsopts is not None else { } if self . exist ( table , libref ) == 0 : print ( 'The SAS Data Set ' + libref + '.' + table + ' does not exist' ) return None if self . nosub : print ( "too complicated to show the code, read the source :), sorry." ) return None else : return self . _i...
def dimension_values ( self , dimension , expanded = True , flat = True ) : """Return the values along the requested dimension . Args : dimension : The dimension to return values for expanded ( bool , optional ) : Whether to expand values Whether to return the expanded values , behavior depends on the typ...
dim = self . get_dimension ( dimension , strict = True ) return self . interface . values ( self , dim , expanded , flat )
def format_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : """Include Python object value , rendering it to text using str . Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages . Both are allowed to be empty . : param ...
if options is None : options = { } if content is None : content = [ ] name , _ , format_spec = tuple ( field . strip ( ) for field in text . partition ( "," ) ) try : prefixed_name , obj , parent , modname = import_by_name ( name ) except ImportError : msg = inliner . reporter . error ( "Could not locat...
def check_payment_v2 ( state_engine , state_op_type , nameop , fee_block_id , token_address , burn_address , name_fee , block_id ) : """Verify that for a version - 2 namespace ( burn - to - creator ) , the nameop paid the right amount of BTC or Stacks . It can pay either through a preorder ( for registers ) , or ...
# priced in BTC only if the namespace creator can receive name fees . # once the namespace switches over to burning , then the name creator can pay in Stacks as well . assert name_fee is not None assert isinstance ( name_fee , ( int , long ) ) epoch_features = get_epoch_features ( block_id ) name = nameop [ 'name' ] na...
def fix_related_item_tag ( dom ) : """Remove < mods : relatedItem > tag in case that there is only < mods : location > subtag ."""
location = dom . match ( "mods:mods" , "mods:relatedItem" , "mods:location" ) if not location : return location = first ( location ) location . replaceWith ( dhtmlparser . HTMLElement ( ) ) # remove whole < mods : relatedItem > tag , if there is nothing else left in it related_item = dom . match ( "mods:mods" , "mo...
def count_function ( func ) : """Decorator for functions that return a collection ( technically a dict of collections ) that should be counted up . Also automatically falls back to the Cohort - default filter _ fn and normalized _ per _ mb if not specified ."""
# Fall back to Cohort - level defaults . @ use_defaults @ wraps ( func ) def wrapper ( row , cohort , filter_fn = None , normalized_per_mb = None , ** kwargs ) : per_patient_data = func ( row = row , cohort = cohort , filter_fn = filter_fn , normalized_per_mb = normalized_per_mb , ** kwargs ) patient_id = row [...