signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def collect ( self ) : """Do pre - flight checks , get list of db names , collect metrics , publish"""
if psycopg2 is None : self . log . error ( 'Unable to import module psycopg2' ) return { } # Get list of databases dbs = self . _get_db_names ( ) if len ( dbs ) == 0 : self . log . error ( "I have 0 databases!" ) return { } if self . config [ 'metrics' ] : metrics = self . config [ 'metrics' ] elif ...
def automain ( self , function ) : """Decorator that defines * and runs * the main function of the experiment . The decorated function is marked as the default command for this experiment , and the command - line interface is automatically run when the file is executed . The method decorated by this should ...
captured = self . main ( function ) if function . __module__ == '__main__' : # Ensure that automain is not used in interactive mode . import inspect main_filename = inspect . getfile ( function ) if ( main_filename == '<stdin>' or ( main_filename . startswith ( '<ipython-input-' ) and main_filename . endswi...
def premis_to_data ( premis_lxml_el ) : """Transform a PREMIS ` ` lxml . _ Element ` ` instance to a Python tuple ."""
premis_version = premis_lxml_el . get ( "version" , utils . PREMIS_VERSION ) nsmap = utils . PREMIS_VERSIONS_MAP [ premis_version ] [ "namespaces" ] return _lxml_el_to_data ( premis_lxml_el , "premis" , nsmap )
def map_t ( func ) : """Transformation for Sequence . map : param func : map function : return : transformation"""
return Transformation ( 'map({0})' . format ( name ( func ) ) , partial ( map , func ) , { ExecutionStrategies . PARALLEL } )
def add ( self , callback = None , name = None , shortcut = None , alias = None , docstring = None , menu = None , verbose = True ) : """Add an action with a keyboard shortcut ."""
if callback is None : # Allow to use either add ( func ) or @ add or @ add ( . . . ) . return partial ( self . add , name = name , shortcut = shortcut , alias = alias , menu = menu ) assert callback # Get the name from the callback function if needed . name = name or callback . __name__ alias = alias or _alias ( na...
def generate_ngrams ( args , parser ) : """Adds n - grams data to the data store ."""
store = utils . get_data_store ( args ) corpus = utils . get_corpus ( args ) if args . catalogue : catalogue = utils . get_catalogue ( args ) else : catalogue = None store . add_ngrams ( corpus , args . min_size , args . max_size , catalogue )
def find_module ( self , modname , folder = None ) : """Returns a resource corresponding to the given module returns None if it can not be found"""
for src in self . get_source_folders ( ) : module = _find_module_in_folder ( src , modname ) if module is not None : return module for src in self . get_python_path_folders ( ) : module = _find_module_in_folder ( src , modname ) if module is not None : return module if folder is not None...
def availableDurations ( self ) : '''A lesson can always be booked for the length of a single slot , but this method checks if multiple slots are available . This method requires that slots are non - overlapping , which needs to be enforced on slot save .'''
potential_slots = InstructorAvailabilitySlot . objects . filter ( instructor = self . instructor , location = self . location , room = self . room , pricingTier = self . pricingTier , startTime__gte = self . startTime , startTime__lte = self . startTime + timedelta ( minutes = getConstant ( 'privateLessons__maximumLess...
def ucamel_method ( func ) : """Decorator to ensure the given snake _ case method is also written in UpperCamelCase in the given namespace . That was mainly written to avoid confusion when using wxPython and its UpperCamelCaseMethods ."""
frame_locals = inspect . currentframe ( ) . f_back . f_locals frame_locals [ snake2ucamel ( func . __name__ ) ] = func return func
def temporal_split ( X , y , test_size = 0.25 ) : '''Split time series or sequence data along the time axis . Test data is drawn from the end of each series / sequence Parameters X : array - like , shape [ n _ series , . . . ] Time series data and ( optionally ) contextual data y : array - like shape [ n ...
if test_size <= 0. or test_size >= 1. : raise ValueError ( "temporal_split: test_size must be >= 0.0 and <= 1.0" " (was %.1f)" % test_size ) Ns = len ( y ) # number of series check_ts_data ( X , y ) Xt , Xc = get_ts_data_parts ( X ) train_size = 1. - test_size train_ind = [ np . arange ( 0 , int ( train_size * len ...
def request ( url , args = None , data = None , headers = None , method = None , credentials = None , raw_response = False , stats = None ) : """Issues HTTP requests . Args : url : the URL to request . args : optional query string arguments . data : optional data to be sent within the request . headers : ...
if headers is None : headers = { } headers [ 'user-agent' ] = 'GoogleCloudDataLab/1.0' # Add querystring to the URL if there are any arguments . if args is not None : qs = urllib . parse . urlencode ( args ) url = url + '?' + qs # Setup method to POST if unspecified , and appropriate request headers # if th...
def get_object ( self , queryset = None ) : '''Get the guest list from the URL'''
return get_object_or_404 ( GuestList . objects . filter ( id = self . kwargs . get ( 'guestlist_id' ) ) )
def _compute_forearc_backarc_term ( self , C , sites , dists ) : """Computes the forearc / backarc scaling term given by equation ( 4 ) ."""
f_faba = np . zeros_like ( dists . rhypo ) # Term only applies to backarc sites ( F _ FABA = 0 . for forearc ) max_dist = dists . rhypo [ sites . backarc ] max_dist [ max_dist < 85.0 ] = 85.0 f_faba [ sites . backarc ] = C [ 'theta7' ] + ( C [ 'theta8' ] * np . log ( max_dist / 40.0 ) ) return f_faba
def intersect ( self , other ) : """Calculate the intersection of this rectangle and another rectangle . Args : other ( Rect ) : The other rectangle . Returns : Rect : The intersection of this rectangle and the given other rectangle , or None if there is no such intersection ."""
intersection = Rect ( ) if lib . SDL_IntersectRect ( self . _ptr , self . _ptr , intersection . _ptr ) : return intersection else : return None
def get_account_details ( self , account ) : """Get the account details ."""
result = { } try : luser = self . _get_account ( account . username ) luser = preload ( luser , database = self . _database ) except ObjectDoesNotExist : return result for i , j in luser . items ( ) : if i != 'userPassword' and j is not None : result [ i ] = j return result
def _check ( self ) : """Check that entry attributes are legal ."""
# Run the super method super ( Photometry , self ) . _check ( ) err_str = None has_flux = self . _KEYS . FLUX in self has_flux_dens = self . _KEYS . FLUX_DENSITY in self has_u_flux = self . _KEYS . U_FLUX in self has_u_flux_dens = self . _KEYS . U_FLUX_DENSITY in self has_freq = self . _KEYS . FREQUENCY in self has_ban...
def get ( self , key ) : """Return set of descendants of node named ` key ` in ` target _ graph ` . Returns from cached dict if exists , otherwise compute over the graph and cache results in the dict ."""
if key not in self : self [ key ] = set ( get_descendants ( self . _target_graph , key ) ) return self [ key ]
def get_datetime ( strings : Sequence [ str ] , prefix : str , datetime_format_string : str , ignoreleadingcolon : bool = False , precedingline : str = "" ) -> Optional [ datetime . datetime ] : """Fetches a ` ` datetime . datetime ` ` parameter via : func : ` get _ string ` ."""
x = get_string ( strings , prefix , ignoreleadingcolon = ignoreleadingcolon , precedingline = precedingline ) if len ( x ) == 0 : return None # For the format strings you can pass to datetime . datetime . strptime , see # http : / / docs . python . org / library / datetime . html # A typical one is " % d - % b - % ...
def parse_port ( port_obj , owner ) : '''Create a port object of the correct type . The correct port object type is chosen based on the port . port _ type property of port _ obj . @ param port _ obj The CORBA PortService object to wrap . @ param owner The owner of this port . Should be a Component object or...
profile = port_obj . get_port_profile ( ) props = utils . nvlist_to_dict ( profile . properties ) if props [ 'port.port_type' ] == 'DataInPort' : return DataInPort ( port_obj , owner ) elif props [ 'port.port_type' ] == 'DataOutPort' : return DataOutPort ( port_obj , owner ) elif props [ 'port.port_type' ] == '...
def orbit_gen ( self ) : """Generator for iterating over each orbit ."""
if self . norbits == 1 : yield self else : for i in range ( self . norbits ) : yield self [ : , i ]
def rehash ( self , password ) : """Recreates the internal hash ."""
self . hash = self . _new ( password , self . desired_rounds ) self . rounds = self . desired_rounds
def get_hcurves_and_means ( dstore ) : """Extract hcurves from the datastore and compute their means . : returns : curves _ by _ rlz , mean _ curves"""
rlzs_assoc = dstore [ 'csm_info' ] . get_rlzs_assoc ( ) getter = getters . PmapGetter ( dstore , rlzs_assoc ) pmaps = getter . get_pmaps ( ) return dict ( zip ( getter . rlzs , pmaps ) ) , dstore [ 'hcurves/mean' ]
def concatenate ( arrs , axis = 0 ) : r"""Concatenate multiple values into a new unitized object . This is essentially a unit - aware version of ` numpy . concatenate ` . All items must be able to be converted to the same units . If an item has no units , it will be given those of the rest of the collection ,...
dest = 'dimensionless' for a in arrs : if hasattr ( a , 'units' ) : dest = a . units break data = [ ] for a in arrs : if hasattr ( a , 'to' ) : a = a . to ( dest ) . magnitude data . append ( np . atleast_1d ( a ) ) # Use masked array concatenate to ensure masks are preserved , but c...
def _pdf_value ( pdf , population , fitnesses , fitness_threshold ) : """Give the value of a pdf . This represents the likelihood of a pdf generating solutions that exceed the threshold ."""
# Add the chance of obtaining a solution from the pdf # when the fitness for that solution exceeds a threshold value = 0.0 for solution , fitness in zip ( population , fitnesses ) : if fitness >= fitness_threshold : # 1.0 + chance to avoid issues with chance of 0 value += math . log ( 1.0 + _chance ( soluti...
def intersectingIntervalIterator ( self , start , end ) : """Get an iterator which will iterate over those objects in the tree which intersect the given interval - sorted in order of start index : param start : find intervals in the tree that intersect an interval with with this start index ( inclusive ) : ...
items = self . intersectingInterval ( start , end ) items . sort ( key = lambda x : x . start ) for item in items : yield item
def ssh_key_info_from_key_data ( key_id , priv_key = None ) : """Get / load SSH key info necessary for signing . @ param key _ id { str } Either a private ssh key fingerprint , e . g . ' b3 : f0 : a1:6c : 18:3b : 42:63 : fd : 6e : 57:42:74:17 : d4 : bc ' , or the path to an ssh private key file ( like ssh ' s...
if FINGERPRINT_RE . match ( key_id ) and priv_key : key_info = { "fingerprint" : key_id , "priv_key" : priv_key } else : # Otherwise , we attempt to load necessary details from ~ / . ssh . key_info = load_ssh_key ( key_id ) # Load a key signer . key = None try : key = serialization . load_pem_private_key ( ...
def _epoch ( self , X , epoch_idx , batch_size , updates_epoch , constants , show_progressbar ) : """Run a single epoch . This function shuffles the data internally , as this improves performance . Parameters X : numpy array The training data . epoch _ idx : int The current epoch batch _ size : int ...
# Create batches X_ = self . _create_batches ( X , batch_size ) X_len = np . prod ( X . shape [ : - 1 ] ) # Initialize the previous activation prev = self . _init_prev ( X_ ) prev = self . distance_function ( X_ [ 0 ] , self . weights ) [ 0 ] influences = self . _update_params ( prev ) # Iterate over the training data ...
async def RemoveBlocks ( self , all_ ) : '''all _ : bool Returns - > None'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'Controller' , request = 'RemoveBlocks' , version = 5 , params = _params ) _params [ 'all' ] = all_ reply = await self . rpc ( msg ) return reply
def common_cli_output_options ( f ) : """Add common CLI output options to commands ."""
@ click . option ( "-d" , "--debug" , default = False , is_flag = True , help = "Produce debug output during processing." , ) @ click . option ( "-F" , "--output-format" , default = "pretty" , type = click . Choice ( [ "pretty" , "json" , "pretty_json" ] ) , help = "Determines how output is formatted. This is only supp...
def _build_relations_config ( self , yamlconfig ) : """Builds a dictionary from relations configuration while maintaining compatibility"""
config = { } for element in yamlconfig : if isinstance ( element , str ) : config [ element ] = { 'relation_name' : element , 'schemas' : [ ] } elif isinstance ( element , dict ) : if 'relation_name' not in element or 'schemas' not in element : self . log . warning ( "Unknown element...
def getTextualNode ( self , textId , subreference = None , prevnext = False , metadata = False ) : """Retrieve a text node from the API : param textId : CtsTextMetadata Identifier : type textId : str : param subreference : CapitainsCtsPassage Reference : type subreference : str : param prevnext : Retrieve...
text = CtsText ( urn = textId , retriever = self . endpoint ) if metadata or prevnext : return text . getPassagePlus ( reference = subreference ) else : return text . getTextualNode ( subreference = subreference )
def negociate_content ( default = 'json-ld' ) : '''Perform a content negociation on the format given the Accept header'''
mimetype = request . accept_mimetypes . best_match ( ACCEPTED_MIME_TYPES . keys ( ) ) return ACCEPTED_MIME_TYPES . get ( mimetype , default )
def final_mass_from_f0_tau ( f0 , tau , l = 2 , m = 2 ) : """Returns the final mass ( in solar masses ) based on the given frequency and damping time . . . note : : Currently , only l = m = 2 is supported . Any other indices will raise a ` ` KeyError ` ` . Parameters f0 : float or array Frequency of t...
# from Berti et al . 2006 spin = final_spin_from_f0_tau ( f0 , tau , l = l , m = m ) a , b , c = _berti_mass_constants [ l , m ] return ( a + b * ( 1 - spin ) ** c ) / ( 2 * numpy . pi * f0 * lal . MTSUN_SI )
def expose_endpoint ( self ) : """Expose / metrics endpoint on the same Sanic server . This may be useful if Sanic is launched from a container and you do not want to expose more than one port for some reason ."""
@ self . _app . route ( '/metrics' , methods = [ 'GET' ] ) async def expose_metrics ( request ) : return raw ( self . _get_metrics_data ( ) , content_type = CONTENT_TYPE_LATEST )
def use_setuptools ( version = DEFAULT_VERSION , download_base = DEFAULT_URL , to_dir = os . curdir , download_delay = 15 ) : """Automatically find / download setuptools and make it available on sys . path ` version ` should be a valid setuptools version number that is available as an egg for download under the...
try : import setuptools if setuptools . __version__ == '0.0.1' : print >> sys . stderr , ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys . exit ( 2 ) except ImportError : egg = download_setuptools (...
def delete ( self , uri , default_response = None ) : """Call DELETE on the Gitlab server > > > gitlab = Gitlab ( host = ' http : / / localhost : 10080 ' , verify _ ssl = False ) > > > gitlab . login ( user = ' root ' , password = ' 5iveL ! fe ' ) > > > gitlab . delete ( ' / users / 5 ' ) : param uri : Stri...
url = self . api_url + uri response = requests . delete ( url , headers = self . headers , verify = self . verify_ssl , auth = self . auth , timeout = self . timeout ) return self . success_or_raise ( response , default_response = default_response )
def DbDeleteServer ( self , argin ) : """Delete server from the database but dont delete device properties : param argin : Device server name : type : tango . DevString : return : : rtype : tango . DevVoid"""
self . _log . debug ( "In DbDeleteServer()" ) if '*' in argin or '%' in argin or not '/' in argin : self . warn_stream ( "DataBase::db_delete_server(): server name " + argin + " incorrect " ) th_exc ( DB_IncorrectServerName , "failed to delete server, server name incorrect" , "DataBase::DeleteServer()" ) self ....
def install ( cls , handler , fmt = None , use_chroot = True , style = DEFAULT_FORMAT_STYLE ) : """Install the : class : ` HostNameFilter ` on a log handler ( only if needed ) . : param fmt : The log format string to check for ` ` % ( hostname ) ` ` . : param style : One of the characters ` ` % ` ` , ` ` { ` ` ...
if fmt : parser = FormatStringParser ( style = style ) if not parser . contains_field ( fmt , 'hostname' ) : return handler . addFilter ( cls ( use_chroot ) )
def POST_AUTH ( self , courseid , classroomid ) : # pylint : disable = arguments - differ """Edit a classroom"""
course , __ = self . get_course_and_check_rights ( courseid , allow_all_staff = True ) if course . is_lti ( ) : raise web . notfound ( ) error = False data = web . input ( tutors = [ ] , groups = [ ] , classroomfile = { } ) if "delete" in data : # Get the classroom classroom = self . database . classrooms . fin...
def swipe_down ( self , width : int = 1080 , length : int = 1920 ) -> None : '''Swipe down .'''
self . swipe ( 0.5 * width , 0.2 * length , 0.5 * width , 0.8 * length )
def sb_vgp_calc ( dataframe , site_correction = 'yes' , dec_tc = 'dec_tc' , inc_tc = 'inc_tc' ) : """This function calculates the angular dispersion of VGPs and corrects for within site dispersion ( unless site _ correction = ' no ' ) to return a value S _ b . The input data needs to be within a pandas Datafram...
# calculate the mean from the directional data dataframe_dirs = [ ] for n in range ( 0 , len ( dataframe ) ) : dataframe_dirs . append ( [ dataframe [ dec_tc ] [ n ] , dataframe [ inc_tc ] [ n ] , 1. ] ) dataframe_dir_mean = pmag . fisher_mean ( dataframe_dirs ) # calculate the mean from the vgp data dataframe_pole...
def present ( name , keys = None , user = None , keyserver = None , gnupghome = None , trust = None , ** kwargs ) : '''Ensure GPG public key is present in keychain name The unique name or keyid for the GPG public key . keys The keyId or keyIds to add to the GPG keychain . user Add GPG keys to the specif...
ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : [ ] } _current_keys = __salt__ [ 'gpg.list_keys' ] ( user = user , gnupghome = gnupghome ) current_keys = { } for key in _current_keys : keyid = key [ 'keyid' ] current_keys [ keyid ] = { } current_keys [ keyid ] [ 'trust' ] = key [ 'tr...
def set ( self , x ) : """Set variable values via a dictionary mapping name to value ."""
for name , value in iter ( x . items ( ) ) : if hasattr ( value , "ndim" ) : if self [ name ] . value . ndim < value . ndim : self [ name ] . value . itemset ( value . squeeze ( ) ) else : self [ name ] . value = value else : self [ name ] . value . itemset ( valu...
def load_configuration_from_file ( directory , args ) : """Return new ` ` args ` ` with configuration loaded from file ."""
args = copy . copy ( args ) directory_or_file = directory if args . config is not None : directory_or_file = args . config options = _get_options ( directory_or_file , debug = args . debug ) args . report = options . get ( 'report' , args . report ) threshold_dictionary = docutils . frontend . OptionParser . thresh...
def run_migrations_online ( ) : """Run migrations in ' online ' mode . In this scenario we need to create an Engine and associate a connection with the context ."""
engine = engine_from_config ( config . get_section ( config . config_ini_section ) , prefix = 'sqlalchemy.' , poolclass = pool . NullPool ) connection = engine . connect ( ) context . configure ( connection = connection , target_metadata = target_metadata , compare_type = True ) try : with context . begin_transacti...
def do_pickle_ontology ( filename , g = None ) : """from a valid filename , generate the graph instance and pickle it too note : option to pass a pre - generated graph instance too 2015-09-17 : added code to increase recursion limit if cPickle fails see http : / / stackoverflow . com / questions / 2134706 / h...
ONTOSPY_LOCAL_MODELS = get_home_location ( ) get_or_create_home_repo ( ) # ensure all the right folders are there pickledpath = os . path . join ( ONTOSPY_LOCAL_CACHE , filename + ".pickle" ) # pickledpath = ONTOSPY _ LOCAL _ CACHE + " / " + filename + " . pickle " if not g : g = Ontospy ( os . path . join ( ONTOSP...
def get_flair_list ( self , subreddit , * args , ** kwargs ) : """Return a get _ content generator of flair mappings . : param subreddit : Either a Subreddit object or the name of the subreddit to return the flair list for . The additional parameters are passed directly into : meth : ` . get _ content ` . N...
url = self . config [ 'flairlist' ] . format ( subreddit = six . text_type ( subreddit ) ) return self . get_content ( url , * args , root_field = None , thing_field = 'users' , after_field = 'next' , ** kwargs )
def set_format ( self , format ) : """Pick the correct default format ."""
if self . options . format : self . format = self . options . format else : self . format = self . config [ "default_format_" + format ]
def _gather_from_files ( self , config ) : """gathers from the files in a way that is convienent to use"""
command_file = config . get_help_files ( ) cache_path = os . path . join ( config . get_config_dir ( ) , 'cache' ) cols = _get_window_columns ( ) with open ( os . path . join ( cache_path , command_file ) , 'r' ) as help_file : data = json . load ( help_file ) self . add_exit ( ) commands = data . keys ( ) for comm...
def likelihood ( self , outcomes , modelparams , expparams ) : """Calculates the likelihood function at the states specified by modelparams and measurement specified by expparams . This is given by the Born rule and is the probability of outcomes given the state and measurement operator . Parameters outco...
# By calling the superclass implementation , we can consolidate # call counting there . super ( QubitStatePauliModel , self ) . likelihood ( outcomes , modelparams , expparams ) # Note that expparams [ ' axis ' ] has shape ( n _ exp , 3 ) . pr0 = 0.5 * ( 1 + np . sum ( modelparams * expparams [ 'axis' ] , 1 ) ) # Note ...
def print_user ( self , user ) : '''print a relational database user'''
status = "active" token = user . token if token in [ 'finished' , 'revoked' ] : status = token if token is None : token = '' subid = "%s\t%s[%s]" % ( user . id , token , status ) print ( subid ) return subid
def get_vhost ( self , vname ) : """Returns the attributes of a single named vhost in a dict . : param string vname : Name of the vhost to get . : returns dict vhost : Attribute dict for the named vhost"""
vname = quote ( vname , '' ) path = Client . urls [ 'vhosts_by_name' ] % vname vhost = self . _call ( path , 'GET' , headers = Client . json_headers ) return vhost
def set_outlet ( self , latitude , longitude , outslope ) : """Adds outlet point to project"""
self . project_manager . setOutlet ( latitude = latitude , longitude = longitude , outslope = outslope )
def get_blobstore ( layout ) : """Return Blobstore instance for a given storage layout Args : layout ( StorageLayout ) : Target storage layout ."""
if layout . is_s3 : from wal_e . blobstore import s3 blobstore = s3 elif layout . is_wabs : from wal_e . blobstore import wabs blobstore = wabs elif layout . is_swift : from wal_e . blobstore import swift blobstore = swift elif layout . is_gs : from wal_e . blobstore import gs blobstore ...
def tohdf5 ( input_files , output_file , n_events , conv_times_to_jte , ** kwargs ) : """Convert Any file to HDF5 file"""
if len ( input_files ) > 1 : cprint ( "Preparing to convert {} files to HDF5." . format ( len ( input_files ) ) ) from km3pipe import Pipeline # noqa from km3pipe . io import GenericPump , HDF5Sink , HDF5MetaData # noqa for input_file in input_files : cprint ( "Converting '{}'..." . format ( input_file ) ) ...
def _GetPqlService ( self ) : """Lazily initializes a PQL service client ."""
if not self . _pql_service : self . _pql_service = self . _ad_manager_client . GetService ( 'PublisherQueryLanguageService' , self . _version , self . _server ) return self . _pql_service
def _delete_org ( self , org_name ) : """Send organization delete request to DCNM . : param org _ name : name of organization to be deleted"""
url = self . _del_org_url % ( org_name ) return self . _send_request ( 'DELETE' , url , '' , 'organization' )
def get_cmor_fname_meta ( fname ) : """Processes a CMOR style file name . Section 3.3 of the ` Data Reference Syntax ` _ details : filename = < variable name > _ < mip _ table > _ < model > _ < experiment > _ < ensemble _ member > [ _ < temporal _ subset > ] [ _ < geographical _ info > ] . nc Temporal subse...
if '/' in fname : fname = os . path . split ( fname ) [ 1 ] fname = os . path . splitext ( fname ) [ 0 ] meta = fname . split ( '_' ) res = { } try : for key in CMIP5_FNAME_REQUIRED_ATTS : res [ key ] = meta . pop ( 0 ) except IndexError : raise PathError ( fname ) # Determine presence and order of ...
def get_ctype ( rtype , cfunc , * args ) : """Call a C function that takes a pointer as its last argument and return the C object that it contains after the function has finished . : param rtype : C data type is filled by the function : param cfunc : C function to call : param args : Arguments to call funct...
val_p = backend . ffi . new ( rtype ) args = args + ( val_p , ) cfunc ( * args ) return val_p [ 0 ]
def add_auth ( self , user = None , password = None , pattern = None ) : """Add given authentication data ."""
if not user or not pattern : log . warn ( LOG_CHECK , _ ( "missing user or URL pattern in authentication data." ) ) return entry = dict ( user = user , password = password , pattern = re . compile ( pattern ) , ) self [ "authentication" ] . append ( entry )
def post ( self , request , * args , ** kwargs ) : """Accepts POST requests , and substitute the data in for the page ' s attributes ."""
self . object = self . get_object ( ) self . object . content = request . POST [ 'content' ] self . object . title = request . POST [ 'title' ] self . object = self . _mark_html_fields_as_safe ( self . object ) context = self . get_context_data ( object = self . object ) return self . render_to_response ( context , con...
def _get_args_for_reloading ( ) : """Returns the executable . This contains a workaround for windows if the executable is incorrectly reported to not have the . exe extension which can cause bugs on reloading ."""
rv = [ sys . executable ] py_script = sys . argv [ 0 ] if os . name == 'nt' and not os . path . exists ( py_script ) and os . path . exists ( py_script + '.exe' ) : py_script += '.exe' rv . append ( py_script ) rv . extend ( sys . argv [ 1 : ] ) return rv
def is_searchable ( self ) : """A bool value that indicates whether the person has enough data and can be sent as a query to the API ."""
filter_func = lambda field : field . is_searchable return bool ( filter ( filter_func , self . names ) or filter ( filter_func , self . emails ) or filter ( filter_func , self . phones ) or filter ( filter_func , self . usernames ) )
def _ref_check ( self , case ) : """Checks that there is only one reference bus ."""
refs = [ bus . _i for bus in case . buses if bus . type == REFERENCE ] if len ( refs ) == 1 : return True , refs else : logger . error ( "OPF requires a single reference bus." ) return False , refs
def unfederate ( self , serverId ) : """This operation unfederates an ArcGIS Server from Portal for ArcGIS"""
url = self . _url + "/servers/{serverid}/unfederate" . format ( serverid = serverId ) params = { "f" : "json" } return self . _get ( url = url , param_dict = params , proxy_port = self . _proxy_port , proxy_url = self . _proxy_ur )
def _rescanSizes ( self , force = True ) : """Zero and recalculate quota sizes to subvolume sizes will be correct ."""
status = self . QUOTA_CTL ( cmd = BTRFS_QUOTA_CTL_ENABLE ) . status logger . debug ( "CTL Status: %s" , hex ( status ) ) status = self . QUOTA_RESCAN_STATUS ( ) logger . debug ( "RESCAN Status: %s" , status ) if not status . flags : if not force : return self . QUOTA_RESCAN ( ) logger . warn ( "Waiting ...
def remove_collisions ( self , min_dist = 0.5 ) : """Remove vnodes that are too close to existing atoms in the structure Args : min _ dist ( float ) : The minimum distance that a vertex needs to be from existing atoms ."""
vfcoords = [ v . frac_coords for v in self . vnodes ] sfcoords = self . structure . frac_coords dist_matrix = self . structure . lattice . get_all_distances ( vfcoords , sfcoords ) all_dist = np . min ( dist_matrix , axis = 1 ) new_vnodes = [ ] for i , v in enumerate ( self . vnodes ) : if all_dist [ i ] > min_dist...
def dot ( a , b ) : """Dot product of two TT - matrices or two TT - vectors"""
if hasattr ( a , '__dot__' ) : return a . __dot__ ( b ) if a is None : return b else : raise ValueError ( 'Dot is waiting for two TT-vectors or two TT- matrices' )
def list_exports ( exports = '/etc/exports' ) : '''List configured exports CLI Example : . . code - block : : bash salt ' * ' nfs . list _ exports'''
ret = { } with salt . utils . files . fopen ( exports , 'r' ) as efl : for line in salt . utils . stringutils . to_unicode ( efl . read ( ) ) . splitlines ( ) : if not line : continue if line . startswith ( '#' ) : continue comps = line . split ( ) # Handle th...
def get_file_to_stream ( self , share_name , directory_name , file_name , stream , start_range = None , end_range = None , validate_content = False , progress_callback = None , max_connections = 2 , timeout = None ) : '''Downloads a file to a stream , with automatic chunking and progress notifications . Returns a...
_validate_not_none ( 'share_name' , share_name ) _validate_not_none ( 'file_name' , file_name ) _validate_not_none ( 'stream' , stream ) # If the user explicitly sets max _ connections to 1 , do a single shot download if max_connections == 1 : file = self . _get_file ( share_name , directory_name , file_name , star...
def _init_loaders ( self ) -> None : """This creates the loaders instances and subscribes to their updates ."""
for loader in settings . I18N_TRANSLATION_LOADERS : loader_class = import_class ( loader [ 'loader' ] ) instance = loader_class ( ) instance . on_update ( self . update ) run ( instance . load ( ** loader [ 'params' ] ) )
def get_diskinfo ( opts , show_all = False , local_only = False ) : '''Returns a list holding the current disk info , stats divided by the ouptut unit .'''
disks = [ ] outunit = opts . outunit for drive in get_drives ( ) : drive += ':\\' disk = DiskInfo ( dev = drive ) try : usage = get_fs_usage ( drive ) except WindowsError : # disk not ready , request aborted , etc . if show_all : usage = _diskusage ( 0 , 0 , 0 ) else ...
def get_files_from_dir ( path , recursive = True , depth = 0 , file_ext = '.py' ) : """Retrieve the list of files from a folder . @ param path : file or directory where to search files @ param recursive : if True will search also sub - directories @ param depth : if explore recursively , the depth of sub dire...
file_list = [ ] if os . path . isfile ( path ) or path == '-' : return [ path ] if path [ - 1 ] != os . sep : path = path + os . sep for f in glob . glob ( path + "*" ) : if os . path . isdir ( f ) : if depth < MAX_DEPTH_RECUR : # avoid infinite recursive loop file_list . extend ( get_fi...
def rfind ( self , bs , start = None , end = None , bytealigned = None ) : """Find final occurrence of substring bs . Returns a single item tuple with the bit position if found , or an empty tuple if not found . The bit position ( pos property ) will also be set to the start of the substring if it is found . ...
bs = Bits ( bs ) start , end = self . _validate_slice ( start , end ) if bytealigned is None : bytealigned = globals ( ) [ 'bytealigned' ] if not bs . len : raise ValueError ( "Cannot find an empty bitstring." ) # Search chunks starting near the end and then moving back # until we find bs . increment = max ( 81...
def insert_node ( self , i , species , coords , validate_proximity = False , site_properties = None , edges = None ) : """A wrapper around Molecule . insert ( ) , which also incorporates the new site into the MoleculeGraph . : param i : Index at which to insert the new site : param species : Species for the n...
self . molecule . insert ( i , species , coords , validate_proximity = validate_proximity , properties = site_properties ) mapping = { } for j in range ( len ( self . molecule ) - 1 ) : if j < i : mapping [ j ] = j else : mapping [ j ] = j + 1 nx . relabel_nodes ( self . graph , mapping , copy =...
def Register ( ) : """Adds all known parsers to the registry ."""
# pyformat : disable # Command parsers . parsers . SINGLE_RESPONSE_PARSER_FACTORY . Register ( "Dpkg" , linux_cmd_parser . DpkgCmdParser ) parsers . SINGLE_RESPONSE_PARSER_FACTORY . Register ( "Dmidecode" , linux_cmd_parser . DmidecodeCmdParser ) parsers . SINGLE_RESPONSE_PARSER_FACTORY . Register ( "Mount" , config_fi...
def filter_pypi ( self , entry ) : """Show only usefull packages"""
for package in self . packages : if entry . title . lower ( ) . startswith ( package ) : return entry
def check_if_needs_modeling ( tomodir ) : """check of we need to run CRMod in a given tomodir"""
print ( 'check for modeling' , tomodir ) required_files = ( 'config' + os . sep + 'config.dat' , 'rho' + os . sep + 'rho.dat' , 'grid' + os . sep + 'elem.dat' , 'grid' + os . sep + 'elec.dat' , 'exe' + os . sep + 'crmod.cfg' , ) not_allowed = ( 'mod' + os . sep + 'volt.dat' , ) needs_modeling = True for filename in not...
def minmax_candidates ( self ) : '''Get points where derivative is zero . Useful for computing the extrema of the polynomial over an interval if the polynomial has real roots . In this case , the maximum is attained for one of the interval endpoints or a point from the result of this function that is contai...
from numpy . polynomial import Polynomial as P p = P . fromroots ( self . roots ) return p . deriv ( 1 ) . roots ( )
def normalize_mode ( mode ) : """Returns a ( Micro ) QR Code mode constant which is equivalent to the provided ` mode ` . In case the provided ` mode ` is ` ` None ` ` , this function returns ` ` None ` ` . Otherwise a mode constant is returned unless the provided parameter cannot be mapped to a valid mode ...
if mode is None or ( isinstance ( mode , int ) and mode in consts . MODE_MAPPING . values ( ) ) : return mode try : return consts . MODE_MAPPING [ mode . lower ( ) ] except : # KeyError or mode . lower ( ) fails raise ModeError ( 'Illegal mode "{0}". Supported values: {1}' . format ( mode , ', ' . join ( so...
def countByValue ( self ) : """Return the count of each unique value in this RDD as a dictionary of ( value , count ) pairs . > > > sorted ( sc . parallelize ( [ 1 , 2 , 1 , 2 , 2 ] , 2 ) . countByValue ( ) . items ( ) ) [ ( 1 , 2 ) , ( 2 , 3 ) ]"""
def countPartition ( iterator ) : counts = defaultdict ( int ) for obj in iterator : counts [ obj ] += 1 yield counts def mergeMaps ( m1 , m2 ) : for k , v in m2 . items ( ) : m1 [ k ] += v return m1 return self . mapPartitions ( countPartition ) . reduce ( mergeMaps )
def has_reg ( value ) : """Return True if the given key exists in HKEY _ LOCAL _ MACHINE , False otherwise ."""
try : SCons . Util . RegOpenKeyEx ( SCons . Util . HKEY_LOCAL_MACHINE , value ) ret = True except SCons . Util . WinError : ret = False return ret
def __trim_extensions_dot ( exts ) : """trim leading dots from extensions and drop any empty strings ."""
if exts is None : return None res = [ ] for i in range ( 0 , len ( exts ) ) : if exts [ i ] == "" : continue res . append ( __trim_extension_dot ( exts [ i ] ) ) return res
def parse_namespaces ( source_dirs , search_dirs = None ) : """Use only this function to parse DSDL definitions . This function takes a list of root namespace directories ( containing DSDL definition files to parse ) and an optional list of search directories ( containing DSDL definition files that can be refer...
# noinspection PyShadowingNames def walk ( ) : import fnmatch from functools import partial def on_walk_error ( directory , ex ) : raise DsdlException ( 'OS error in [%s]: %s' % ( directory , str ( ex ) ) ) for source_dir in source_dirs : walker = os . walk ( source_dir , onerror = parti...
def get_metric_type ( measure , aggregation ) : """Get the corresponding metric type for the given stats type . : type measure : ( : class : ' ~ opencensus . stats . measure . BaseMeasure ' ) : param measure : the measure for which to find a metric type : type aggregation : ( : class : ' ~ opencensus . stat...
if aggregation . aggregation_type == aggregation_module . Type . NONE : raise ValueError ( "aggregation type must not be NONE" ) assert isinstance ( aggregation , AGGREGATION_TYPE_MAP [ aggregation . aggregation_type ] ) if aggregation . aggregation_type == aggregation_module . Type . SUM : if isinstance ( meas...
def on_train_end ( self , logs ) : """Print training time at end of training"""
duration = timeit . default_timer ( ) - self . train_start print ( 'done, took {:.3f} seconds' . format ( duration ) )
def zsh_mode ( self , delay_factor = 1 , prompt_terminator = "$" ) : """Run zsh command to unify the environment"""
delay_factor = self . select_delay_factor ( delay_factor ) self . clear_buffer ( ) command = self . RETURN + "zsh" + self . RETURN self . write_channel ( command ) time . sleep ( 1 * delay_factor ) self . set_prompt ( ) self . clear_buffer ( )
def from_dataframe ( df , name = 'df' , client = None ) : """convenience function to construct an ibis table from a DataFrame EXPERIMENTAL API Parameters df : DataFrame name : str , default ' df ' client : Client , default new PandasClient client dictionary will be mutated with the name of the DataF...
if client is None : return connect ( { name : df } ) . table ( name ) client . dictionary [ name ] = df return client . table ( name )
def data_to_list ( self , sysbase = False ) : """Return the loaded model data as a list of dictionaries . Each dictionary contains the full parameters of an element . : param sysbase : use system base quantities : type sysbase : bool"""
ret = list ( ) # for each element for i in range ( self . n ) : # read the parameter values and put in the temp dict ` ` e ` ` e = { } for key in self . data_keys : if sysbase and ( key in self . _store ) : val = self . _store [ key ] [ i ] else : val = self . __dict__ [ ...
def copy_function ( func , name = None ) : """Copy a function object with different name . Args : func ( function ) : Function to be copied . name ( string , optional ) : Name of the new function . If not spacified , the same name of ` func ` will be used . Returns : newfunc ( function ) : New function ...
code = func . __code__ newname = name or func . __name__ newcode = CodeType ( code . co_argcount , code . co_kwonlyargcount , code . co_nlocals , code . co_stacksize , code . co_flags , code . co_code , code . co_consts , code . co_names , code . co_varnames , code . co_filename , newname , code . co_firstlineno , code...
def configfilepopulator ( self ) : """Populates an unpopulated config . xml file with run - specific values and creates the file in the appropriate location"""
# Set the number of cycles for each read and index using the number of reads specified in the sample sheet self . forwardlength = self . metadata . header . forwardlength self . reverselength = self . metadata . header . reverselength # Create a list of lists containing [ cycle start , cycle end , and : runid ] for eac...
def edit ( self , index , name = None , priority = None , comment = None , done = None , parent = None ) : """Modifies : index : to specified data . Every argument , which is not None , will get changed . If parent is not None , the item will get reparented . Use parent = - 1 or parent = ' ' for reparenting t...
if parent == - 1 : parent = '' parent = self . _split ( parent ) index = self . _split ( index ) item = self . data for j , c in enumerate ( index ) : item = item [ int ( c ) - 1 ] if j + 1 != len ( index ) : item = item [ 4 ] if name is not None : item [ 0 ] = name if priority is not None : ...
def get_all_tags_of_confirmation ( self , confirmation_id ) : """Get all tags of confirmation This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param confirmation _ id : the confirmation id : return : list"""
return self . _iterate_through_pages ( get_function = self . get_tags_of_confirmation_per_page , resource = CONFIRMATION_TAGS , ** { 'confirmation_id' : confirmation_id } )
def _op ( self , operation , other , * allowed ) : """A basic operation operating on a single value ."""
f = self . _field if self . _combining : # We are a field - compound query fragment , e . g . ( Foo . bar & Foo . baz ) . return reduce ( self . _combining , ( q . _op ( operation , other , * allowed ) for q in f ) ) # pylint : disable = protected - access # Optimize this away in production ; diagnosic aide . if __...
def decode_schedule ( string ) : """Decodes a string into a schedule tuple . Args : string : The string encoding of a schedule tuple . Returns : A schedule tuple , see encode _ schedule for details ."""
splits = string . split ( ) steps = [ int ( x [ 1 : ] ) for x in splits [ 1 : ] if x [ 0 ] == '@' ] pmfs = np . reshape ( [ float ( x ) for x in splits [ 1 : ] if x [ 0 ] != '@' ] , [ len ( steps ) , - 1 ] ) return splits [ 0 ] , tuplize ( steps ) , tuplize ( pmfs )
def _restricted_growth_notation ( l ) : """The clustering returned by the hcluster module gives group membership without regard for numerical order This function preserves the group membership , but sorts the labelling into numerical order"""
list_length = len ( l ) d = defaultdict ( list ) for ( i , element ) in enumerate ( l ) : d [ element ] . append ( i ) l2 = [ None ] * list_length for ( name , index_list ) in enumerate ( sorted ( d . values ( ) , key = min ) ) : for index in index_list : l2 [ index ] = name return tuple ( l2 )
def get_jaro_distance ( first , second , winkler = True , winkler_ajustment = True , scaling = 0.1 ) : """: param first : word to calculate distance for : param second : word to calculate distance with : param winkler : same as winkler _ ajustment : param winkler _ ajustment : add an adjustment factor to the ...
if not first or not second : raise JaroDistanceException ( "Cannot calculate distance from NoneType ({0}, {1})" . format ( first . __class__ . __name__ , second . __class__ . __name__ ) ) jaro = _score ( first , second ) cl = min ( len ( _get_prefix ( first , second ) ) , 4 ) if all ( [ winkler , winkler_ajustment ...
def compliance_tensor ( self ) : """returns the Voigt - notation compliance tensor , which is the matrix inverse of the Voigt - notation elastic tensor"""
s_voigt = np . linalg . inv ( self . voigt ) return ComplianceTensor . from_voigt ( s_voigt )
def header_canonical ( self , header_name ) : """Translate HTTP headers to Django header names ."""
# Translate as stated in the docs : # https : / / docs . djangoproject . com / en / 1.6 / ref / request - response / # django . http . HttpRequest . META header_name = header_name . lower ( ) if header_name == 'content-type' : return 'CONTENT-TYPE' elif header_name == 'content-length' : return 'CONTENT-LENGTH' ...
def hpai_body ( self ) : """Create a body with HPAI information . This is used for disconnect and connection state requests ."""
body = [ ] # = = = = = IP Body = = = = = body . extend ( [ self . channel ] ) # Communication Channel Id body . extend ( [ 0x00 ] ) # Reserverd # = = = = = Client HPAI = = = = = body . extend ( [ 0x08 ] ) # HPAI Length body . extend ( [ 0x01 ] ) # Host Protocol # Tunnel Client Socket IP body . extend ( ip_to_array ( se...