signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _to_string ( val ) : """Convert to text ."""
if isinstance ( val , binary_type ) : return val . decode ( 'utf-8' ) assert isinstance ( val , text_type ) return val
def predict ( self , data , output_margin = False , ntree_limit = None , validate_features = True ) : """Predict with ` data ` . . . note : : This function is not thread safe . For each booster object , predict can only be called from one thread . If you want to run prediction using multiple thread , call ` `...
# pylint : disable = missing - docstring , invalid - name test_dmatrix = DMatrix ( data , missing = self . missing , nthread = self . n_jobs ) # get ntree _ limit to use - if none specified , default to # best _ ntree _ limit if defined , otherwise 0. if ntree_limit is None : ntree_limit = getattr ( self , "best_nt...
def unregister_editor ( self , editor_node , raise_exception = False ) : """Unregisters given : class : ` umbra . components . factory . script _ editor . nodes . EditorNode ` class Node from the Model . : param editor _ node : EditorNode to unregister . : type editor _ node : EditorNode : param raise _ excep...
if raise_exception : if not editor_node in self . list_editor_nodes ( ) : raise foundations . exceptions . ProgrammingError ( "{0} | '{1}' editor 'EditorNode' isn't registered!" . format ( self . __class__ . __name__ , editor_node ) ) LOGGER . debug ( "> Unregistering '{0}' editor 'EditorNode'." . format ( ...
def _create_produce_requests ( self , collated ) : """Transfer the record batches into a list of produce requests on a per - node basis . Arguments : collated : { node _ id : [ RecordBatch ] } Returns : dict : { node _ id : ProduceRequest } ( version depends on api _ version )"""
requests = { } for node_id , batches in six . iteritems ( collated ) : requests [ node_id ] = self . _produce_request ( node_id , self . config [ 'acks' ] , self . config [ 'request_timeout_ms' ] , batches ) return requests
def getActionHandle ( self , pchActionName ) : """Returns a handle for an action . This handle is used for all performance - sensitive calls ."""
fn = self . function_table . getActionHandle pHandle = VRActionHandle_t ( ) result = fn ( pchActionName , byref ( pHandle ) ) return result , pHandle
def thresh ( dset , p , positive_only = False , prefix = None ) : '''returns a string containing an inline ` ` 3dcalc ` ` command that thresholds the given dataset at the specified * p * - value , or will create a new dataset if a suffix or prefix is given'''
return available_method ( 'thresh' ) ( dset , p , positive_only , prefix )
def gelman_rubin ( mcmc ) : """Args : mcmc ( MCMCResults ) : Pre - sliced MCMC samples to compute diagnostics for ."""
if mcmc . n_chains < 2 : raise ValueError ( 'Gelman-Rubin diagnostic requires multiple chains ' 'of the same length.' ) # get Vhat and within - chain variance Vhat , W = _vhat_w ( mcmc ) # compute and return Gelman - Rubin statistic Rhat = np . sqrt ( Vhat / W ) return pd . DataFrame ( { 'gelman_rubin' : Rhat } , i...
def forward ( self , x ) : """Returns a list of outputs for tasks 0 , . . . t - 1 Args : x : a [ batch _ size , . . . ] batch from X"""
head_outputs = [ None ] * self . t # Execute input layer if isinstance ( self . input_layer , list ) : # One input _ module per task input_outputs = [ mod ( x ) for mod , x in zip ( self . input_layer , x ) ] x = torch . stack ( input_outputs , dim = 1 ) # Execute level - 0 task heads from their respective ...
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
# get mean and std using the superclass mean , stddevs = super ( ) . get_mean_and_stddevs ( sites , rup , dists , imt , stddev_types ) A08 = self . A08_COEFFS [ imt ] f_ena = 10.0 ** ( A08 [ "c" ] + A08 [ "d" ] * dists . rjb ) return np . log ( np . exp ( mean ) * f_ena ) , stddevs
def findNode ( class_ , hot_map , targetNode , parentNode = None ) : '''Find the target node in the hot _ map .'''
for index , ( rect , node , children ) in enumerate ( hot_map ) : if node == targetNode : return parentNode , hot_map , index result = class_ . findNode ( children , targetNode , node ) if result : return result return None
async def register_service ( self , short_name , long_name , allow_duplicate = True ) : """Register a new service with the service manager . Args : short _ name ( string ) : A unique short name for this service that functions as an id long _ name ( string ) : A user facing name for this service allow _ du...
try : await self . send_command ( OPERATIONS . CMD_REGISTER_SERVICE , dict ( name = short_name , long_name = long_name ) , MESSAGES . RegisterServiceResponse ) except ArgumentError : if not allow_duplicate : raise
def identify_pycbc_live ( origin , filepath , fileobj , * args , ** kwargs ) : """Identify a PyCBC Live file as an HDF5 with the correct name"""
if identify_hdf5 ( origin , filepath , fileobj , * args , ** kwargs ) and ( filepath is not None and PYCBC_FILENAME . match ( basename ( filepath ) ) ) : return True return False
def close ( self , cursor_id , address ) : """Kill a cursor . Raises TypeError if cursor _ id is not an instance of ( int , long ) . : Parameters : - ` cursor _ id ` : cursor id to close - ` address ` : the cursor ' s server ' s ( host , port ) pair . . versionchanged : : 3.0 Now requires an ` address `...
if not isinstance ( cursor_id , integer_types ) : raise TypeError ( "cursor_id must be an integer" ) self . __client ( ) . kill_cursors ( [ cursor_id ] , address )
def as_dict ( self ) : """Additionally encodes headers . : return :"""
data = super ( BaseEmail , self ) . as_dict ( ) data [ "Headers" ] = [ { "Name" : name , "Value" : value } for name , value in data [ "Headers" ] . items ( ) ] for field in ( "To" , "Cc" , "Bcc" ) : if field in data : data [ field ] = list_to_csv ( data [ field ] ) data [ "Attachments" ] = [ prepare_attachm...
def invalidate_cache ( user , size = None ) : """Function to be called when saving or changing an user ' s avatars ."""
sizes = set ( settings . AVATAR_AUTO_GENERATE_SIZES ) if size is not None : sizes . add ( size ) for prefix in cached_funcs : for size in sizes : cache . delete ( get_cache_key ( user , size , prefix ) )
def total ( self ) : """Total cost of the order"""
total = 0 for item in self . items . all ( ) : total += item . total return total
def console_from_file ( filename : str ) -> tcod . console . Console : """Return a new console object from a filename . The file format is automactially determined . This can load REXPaint ` . xp ` , ASCII Paint ` . apf ` , or Non - delimited ASCII ` . asc ` files . Args : filename ( Text ) : The path to th...
return tcod . console . Console . _from_cdata ( lib . TCOD_console_from_file ( filename . encode ( "utf-8" ) ) )
def get_extrema ( self , normalize_rxn_coordinate = True ) : """Returns the positions of the extrema along the MEP . Both local minimums and maximums are returned . Args : normalize _ rxn _ coordinate ( bool ) : Whether to normalize the reaction coordinate to between 0 and 1 . Defaults to True . Returns :...
x = np . arange ( 0 , np . max ( self . r ) , 0.01 ) y = self . spline ( x ) * 1000 scale = 1 if not normalize_rxn_coordinate else 1 / self . r [ - 1 ] min_extrema = [ ] max_extrema = [ ] for i in range ( 1 , len ( x ) - 1 ) : if y [ i ] < y [ i - 1 ] and y [ i ] < y [ i + 1 ] : min_extrema . append ( ( x [...
def check_rights ( self , resources , request = None ) : """Check rights for resources . : return bool : True if operation is success else HTTP _ 403 _ FORBIDDEN"""
if not self . auth : return True try : if not self . auth . test_rights ( resources , request = request ) : raise AssertionError ( ) except AssertionError , e : raise HttpError ( "Access forbiden. {0}" . format ( e ) , status = status . HTTP_403_FORBIDDEN )
def network_expansion ( network , method = 'rel' , ext_min = 0.1 , ext_width = False , filename = None , boundaries = [ ] ) : """Plot relative or absolute network extension of AC - and DC - lines . Parameters network : PyPSA network container Holds topology of grid including results from powerflow analysis ...
cmap = plt . cm . jet overlay_network = network . copy ( ) overlay_network . lines = overlay_network . lines [ overlay_network . lines . s_nom_extendable & ( ( overlay_network . lines . s_nom_opt - overlay_network . lines . s_nom_min ) / overlay_network . lines . s_nom >= ext_min ) ] overlay_network . links = overlay_n...
def log_of_array_ignoring_zeros ( M ) : """Returns an array containing the logs of the nonzero elements of M . Zeros are left alone since log ( 0 ) isn ' t defined . Parameters M : array - like Returns array - like Shape matches ` M `"""
log_M = M . copy ( ) mask = log_M > 0 log_M [ mask ] = np . log ( log_M [ mask ] ) return log_M
def get_setting_list ( self , key , default_value = None , delimiter = ',' , value_type = str ) : """Get the setting stored at the given key and split it to a list . Args : key ( str ) : the setting key default _ value ( list , optional ) : The default value , if none is found . Defaults to None . delimit...
value = self . get_setting ( key ) if value is not None : setting_list = [ value_type ( v ) for v in value . split ( delimiter ) ] else : setting_list = default_value return setting_list
def _generate_signature_for_function ( self , func ) : """Given a function , returns a string representing its args ."""
args_list = [ ] argspec = inspect . getargspec ( func ) first_arg_with_default = ( len ( argspec . args or [ ] ) - len ( argspec . defaults or [ ] ) ) for arg in argspec . args [ : first_arg_with_default ] : if arg == "self" : # Python documentation typically skips ` self ` when printing method # signatures . ...
def set_uint_info ( self , field , data ) : """Set uint type property into the DMatrix . Parameters field : str The field name of the information data : numpy array The array of data to be set"""
if getattr ( data , 'base' , None ) is not None and data . base is not None and isinstance ( data , np . ndarray ) and isinstance ( data . base , np . ndarray ) and ( not data . flags . c_contiguous ) : warnings . warn ( "Use subset (sliced data) of np.ndarray is not recommended " + "because it will generate extra ...
def _count_pixels_on_line ( self , y , p ) : """Count the number of pixels rendered on this line ."""
h = line ( y , self . _effective_thickness ( p ) , 0.0 ) return h . sum ( )
async def slowlog_get ( self , num = None ) : """Get the entries from the slowlog . If ` ` num ` ` is specified , get the most recent ` ` num ` ` items ."""
args = [ 'SLOWLOG GET' ] if num is not None : args . append ( num ) return await self . execute_command ( * args )
def _update_triangles ( self , triangles_list ) : """From a set of variables forming a triangle in the model , we form the corresponding Clusters . These clusters are then appended to the code . Parameters triangle _ list : list The list of variables forming the triangles to be updated . It is of the form o...
new_intersection_set = [ ] for triangle_vars in triangles_list : cardinalities = [ self . cardinality [ variable ] for variable in triangle_vars ] current_intersection_set = [ frozenset ( intersect ) for intersect in it . combinations ( triangle_vars , 2 ) ] current_factor = DiscreteFactor ( triangle_vars ,...
def quick_search ( limit , pretty , sort , ** kw ) : '''Execute a quick search .'''
req = search_req_from_opts ( ** kw ) cl = clientv1 ( ) page_size = min ( limit , 250 ) echo_json_response ( call_and_wrap ( cl . quick_search , req , page_size = page_size , sort = sort ) , pretty , limit )
def view_task_hazard ( token , dstore ) : """Display info about a given task . Here are a few examples of usage : : $ oq show task _ hazard : 0 # the fastest task $ oq show task _ hazard : - 1 # the slowest task"""
tasks = set ( dstore [ 'task_info' ] ) if 'source_data' not in dstore : return 'Missing source_data' if 'classical_split_filter' in tasks : data = dstore [ 'task_info/classical_split_filter' ] . value else : data = dstore [ 'task_info/compute_gmfs' ] . value data . sort ( order = 'duration' ) rec = data [ i...
def get_size ( vm_ ) : '''Return the VM ' s size object'''
vm_size = config . get_cloud_config_value ( 'size' , vm_ , __opts__ ) sizes = avail_sizes ( ) if not vm_size : return sizes [ 'Small Instance' ] for size in sizes : combinations = ( six . text_type ( sizes [ size ] [ 'id' ] ) , six . text_type ( size ) ) if vm_size and six . text_type ( vm_size ) in combina...
def _validate ( self , val ) : """Checks that the value is numeric and that it is within the hard bounds ; if not , an exception is raised ."""
if self . allow_None and val is None : return if not isinstance ( val , dt_types ) and not ( self . allow_None and val is None ) : raise ValueError ( "Date '%s' only takes datetime types." % self . name ) if self . step is not None and not isinstance ( self . step , dt_types ) : raise ValueError ( "Step par...
def digicam_configure_encode ( self , target_system , target_component , mode , shutter_speed , aperture , iso , exposure_type , command_id , engine_cut_off , extra_param , extra_value ) : '''Configure on - board Camera Control System . target _ system : System ID ( uint8 _ t ) target _ component : Component ID...
return MAVLink_digicam_configure_message ( target_system , target_component , mode , shutter_speed , aperture , iso , exposure_type , command_id , engine_cut_off , extra_param , extra_value )
def compress ( data , mode = DEFAULT_MODE , quality = lib . BROTLI_DEFAULT_QUALITY , lgwin = lib . BROTLI_DEFAULT_WINDOW , lgblock = 0 , dictionary = b'' ) : """Compress a string using Brotli . . . versionchanged : : 0.5.0 Added ` ` mode ` ` , ` ` quality ` ` , ` lgwin ` ` , ` ` lgblock ` ` , and ` ` dictionary...
# This method uses private variables on the Compressor object , and # generally does a whole lot of stuff that ' s not supported by the public # API . The goal here is to minimise the number of allocations and copies # we have to do . Users should prefer this method over the Compressor if # they know they have single -...
def has_predecessor ( self , graph , dest , orig , branch , turn , tick , * , forward = None ) : """Return whether an edge connects the destination to the origin at the given time . Doesn ' t require the edge ' s index , which makes it slower than retrieving a particular edge ."""
if forward is None : forward = self . db . _forward return orig in self . _get_origcache ( graph , dest , branch , turn , tick , forward = forward )
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_blade_swbd ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) logical_chassis_fwdl_status = ET . Element ( "logical_chassis_fwdl_status" ) config = logical_chassis_fwdl_status output = ET . SubElement ( logical_chassis_fwdl_status , "output" ) cluster_fwdl_entries = ET . SubElement ( output , "cluster-fwdl-entries" ) fwdl_entries = ET . SubEleme...
def cache_if_needed ( cacheKey , result , menu , context , meta ) : """Cache the result , if needed"""
if cacheKey : # This will be a method in django 1.7 flat_context = { } for d in context . dicts : flat_context . update ( d ) del flat_context [ 'csrf_token' ] data = { 'result' : result , 'menu' : menu , 'context' : flat_context } cache . set ( 'plugit-cache-' + cacheKey , data , meta [ 'ca...
def dump ( self ) : """Print a formatted summary of the current solve state ."""
from rez . utils . formatting import columnise rows = [ ] for i , phase in enumerate ( self . phase_stack ) : rows . append ( ( self . _depth_label ( i ) , phase . status , str ( phase ) ) ) print "status: %s (%s)" % ( self . status . name , self . status . description ) print "initial request: %s" % str ( self . r...
def pull ( self ) : """Pull topics from Transifex ."""
topic_stats = txlib . api . statistics . Statistics . get ( project_slug = self . tx_project_slug , resource_slug = self . TOPIC_STRINGS_SLUG , ) translated = { } # for each language for locale in self . enabled_locales : if not self . _process_locale ( locale ) : continue locale_stats = getattr ( topic...
def echo_with_markers ( text , marker = '=' , marker_color = 'blue' , text_color = None ) : """Print a text to the screen with markers surrounding it . The output looks like : = = = = = text = = = = = with marker = ' = ' right now . In the event that the terminal window is too small , the text is printed ...
text = ' ' + text + ' ' width , _ = click . get_terminal_size ( ) if len ( text ) >= width : click . echo ( text ) # this is probably never the case else : leftovers = width - len ( text ) click . secho ( marker * ( leftovers / 2 ) , fg = marker_color , nl = False ) click . secho ( text , nl = False...
def send_backspace ( self , count ) : """Sends the given number of backspace key presses ."""
for i in range ( count ) : self . interface . send_key ( Key . BACKSPACE )
def _addRule ( self , isWhitelist , rule ) : """Add an ( isWhitelist , rule ) pair to the rule list ."""
if isinstance ( rule , six . string_types ) or hasattr ( rule , '__call__' ) : self . rules . append ( ( isWhitelist , rule ) ) else : raise TypeError ( 'Graphite logging rules must be glob pattern or callable. Invalid: %r' % rule )
def clear_all ( ) : """Clears all parameters , variables , and shocks defined previously"""
frame = inspect . currentframe ( ) . f_back try : if frame . f_globals . get ( 'variables_order' ) : # we should avoid to declare symbols twice ! del frame . f_globals [ 'variables_order' ] if frame . f_globals . get ( 'parameters_order' ) : # we should avoid to declare symbols twice ! del frame...
def _gql ( cls , query_string , * args , ** kwds ) : """Run a GQL query ."""
from . query import gql # Import late to avoid circular imports . return gql ( 'SELECT * FROM %s %s' % ( cls . _class_name ( ) , query_string ) , * args , ** kwds )
def setup_session ( endpoint_context , areq , uid , client_id = '' , acr = '' , salt = 'salt' , authn_event = None ) : """Setting up a user session : param endpoint _ context : : param areq : : param uid : : param acr : : param client _ id : : param salt : : param authn _ event : A already made AuthnE...
if authn_event is None and acr : authn_event = AuthnEvent ( uid = uid , salt = salt , authn_info = acr , authn_time = time . time ( ) ) if not client_id : client_id = areq [ 'client_id' ] sid = endpoint_context . sdb . create_authz_session ( authn_event , areq , client_id = client_id , uid = uid ) endpoint_cont...
def get_instance ( cls , device ) : """This is only a slot to store and get already initialized poco instance rather than initializing again . You can simply pass the ` ` current device instance ` ` provided by ` ` airtest ` ` to get the AndroidUiautomationPoco instance . If no such AndroidUiautomationPoco inst...
if cls . _nuis . get ( device ) is None : cls . _nuis [ device ] = AndroidUiautomationPoco ( device ) return cls . _nuis [ device ]
def competition_leaderboard_cli ( self , competition , competition_opt = None , path = None , view = False , download = False , csv_display = False , quiet = False ) : """a wrapper for competition _ leaderbord _ view that will print the results as a table or comma separated values Parameters competition : the...
competition = competition or competition_opt if not view and not download : raise ValueError ( 'Either --show or --download must be specified' ) if competition is None : competition = self . get_config_value ( self . CONFIG_NAME_COMPETITION ) if competition is not None and not quiet : print ( 'Using...
def create_expanded_design_for_mixing ( design , draw_list , mixing_pos , rows_to_mixers ) : """Parameters design : 2D ndarray . All elements should be ints , floats , or longs . Each row corresponds to an available alternative for a given individual . There should be one column per index coefficient being ...
if len ( mixing_pos ) != len ( draw_list ) : msg = "mixing_pos == {}" . format ( mixing_pos ) msg_2 = "len(draw_list) == {}" . format ( len ( draw_list ) ) raise ValueError ( msg + "\n" + msg_2 ) # Determine the number of draws being used . Note the next line assumes an # equal number of draws from each ran...
def pythag ( a , b ) : """Computer c = ( a ^ 2 + b ^ 2 ) ^ 0.5 without destructive underflow or overflow It solves the Pythagorean theorem a ^ 2 + b ^ 2 = c ^ 2"""
absA = abs ( a ) absB = abs ( b ) if absA > absB : return absA * sqrt ( 1.0 + ( absB / float ( absA ) ) ** 2 ) elif absB == 0.0 : return 0.0 else : return absB * sqrt ( 1.0 + ( absA / float ( absB ) ) ** 2 )
def workon ( ctx , issue_id , new , base_branch ) : """Start work on a given issue . This command retrieves the issue from the issue tracker , creates and checks out a new aptly - named branch , puts the issue in the configured active , status , assigns it to you and starts a correctly linked Harvest timer . ...
lancet = ctx . obj if not issue_id and not new : raise click . UsageError ( "Provide either an issue ID or the --new flag." ) elif issue_id and new : raise click . UsageError ( "Provide either an issue ID or the --new flag, but not both." ) if new : # Create a new issue summary = click . prompt ( "Issue sum...
def add_ldap_group_link ( self , cn , group_access , provider , ** kwargs ) : """Add an LDAP group link . Args : cn ( str ) : CN of the LDAP group group _ access ( int ) : Minimum access level for members of the LDAP group provider ( str ) : LDAP provider for the LDAP group * * kwargs : Extra options to...
path = '/groups/%s/ldap_group_links' % self . get_id ( ) data = { 'cn' : cn , 'group_access' : group_access , 'provider' : provider } self . manager . gitlab . http_post ( path , post_data = data , ** kwargs )
def get_stockprices ( chart_range = '1y' ) : '''This is a proxy to the main fetch function to cache the result based on the chart range parameter .'''
all_symbols = list_symbols ( ) @ daily_cache ( filename = 'iex_chart_{}' . format ( chart_range ) ) def get_stockprices_cached ( all_symbols ) : return _get_stockprices ( all_symbols , chart_range ) return get_stockprices_cached ( all_symbols )
def get_plaintext_citations ( bibtex ) : """Parse a BibTeX file to get a clean list of plaintext citations . : param bibtex : Either the path to the BibTeX file or the content of a BibTeX file . : returns : A list of cleaned plaintext citations ."""
parser = BibTexParser ( ) parser . customization = convert_to_unicode # Load the BibTeX if os . path . isfile ( bibtex ) : with open ( bibtex ) as fh : bib_database = bibtexparser . load ( fh , parser = parser ) else : bib_database = bibtexparser . loads ( bibtex , parser = parser ) # Convert bibentries...
def length ( time_flags ) : # type : ( int ) - > int '''Static method to return the length of the Rock Ridge Time Stamp record . Parameters : time _ flags - Integer representing the flags to use . Returns : The length of this record in bytes .'''
tf_each_size = 7 if time_flags & ( 1 << 7 ) : tf_each_size = 17 time_flags &= 0x7f tf_num = 0 while time_flags : time_flags &= time_flags - 1 tf_num += 1 return 5 + tf_each_size * tf_num
def check_session_id_signature ( session_id , secret_key = settings . secret_key_bytes ( ) , signed = settings . sign_sessions ( ) ) : """Check the signature of a session ID , returning True if it ' s valid . The server uses this function to check whether a session ID was generated with the correct secret key ....
secret_key = _ensure_bytes ( secret_key ) if signed : pieces = session_id . split ( '-' , 1 ) if len ( pieces ) != 2 : return False base_id = pieces [ 0 ] provided_signature = pieces [ 1 ] expected_signature = _signature ( base_id , secret_key ) # hmac . compare _ digest ( ) uses a strin...
def _matching_string ( matched , string ) : """Return the string as byte or unicode depending on the type of matched , assuming string is an ASCII string ."""
if string is None : return string if IS_PY2 : # pylint : disable = undefined - variable if isinstance ( matched , text_type ) : return text_type ( string ) else : if isinstance ( matched , bytes ) and isinstance ( string , str ) : return string . encode ( locale . getpreferredencoding ( Fals...
def _file_md5 ( file_ ) : """Compute the md5 digest of a file in base64 encoding ."""
md5 = hashlib . md5 ( ) chunk_size = 128 * md5 . block_size for chunk in iter ( lambda : file_ . read ( chunk_size ) , b'' ) : md5 . update ( chunk ) file_ . seek ( 0 ) byte_digest = md5 . digest ( ) return base64 . b64encode ( byte_digest ) . decode ( )
def rate_limited ( max_per_second ) : """Sort of based off of an answer about rate limiting on Stack Overflow . Definitely * * not * * thread safe , so don ' t even think about it , buddy ."""
import datetime min_request_time = datetime . timedelta ( seconds = max_per_second ) last_time_called = [ None ] def decorate ( func ) : def rate_limited_function ( * args , ** kwargs ) : if last_time_called [ 0 ] : delta = datetime . datetime . now ( ) - last_time_called [ 0 ] if de...
def _on_context_disconnect ( self , context ) : """Respond to Context disconnect event by deleting any record of the no longer reachable context . This method runs in the Broker thread and must not to block ."""
self . _lock . acquire ( ) try : LOG . info ( '%r: Forgetting %r due to stream disconnect' , self , context ) self . _forget_context_unlocked ( context ) finally : self . _lock . release ( )
def _handle_compound ( self , node , scope , ctxt , stream ) : """Handle Compound nodes : node : TODO : scope : TODO : ctxt : TODO : stream : TODO : returns : TODO"""
self . _dlog ( "handling compound statement" ) # scope . push ( ) try : for child in node . children ( ) : self . _handle_node ( child , scope , ctxt , stream ) # in case a return occurs , be sure to pop the scope # ( returns are implemented by raising an exception ) finally : # scope . pop ( ) pass
def isAuthorized ( self , pid , action , vendorSpecific = None ) : """Return True if user is allowed to perform ` ` action ` ` on ` ` pid ` ` , else False ."""
response = self . isAuthorizedResponse ( pid , action , vendorSpecific ) return self . _read_boolean_401_response ( response )
def get ( cls , sha1 = '' ) : # type : ( str ) - > CommitDetails """Return details about a given commit . Args : sha1 ( str ) : The sha1 of the commit to query . If not given , it will return the details for the latest commit . Returns : CommitDetails : Commit details . You can use the instance of the ...
with conf . within_proj_dir ( ) : cmd = 'git show -s --format="%H||%an||%ae||%s||%b||%P" {}' . format ( sha1 ) result = shell . run ( cmd , capture = True , never_pretend = True ) . stdout sha1 , name , email , title , desc , parents = result . split ( '||' ) return CommitDetails ( sha1 = sha1 , author = Author...
def uncontract_general ( basis , use_copy = True ) : """Removes the general contractions from a basis set The input basis set is not modified . The returned basis may have functions with coefficients of zero and may have duplicate shells . If use _ copy is True , the input basis set is not modified ."""
if use_copy : basis = copy . deepcopy ( basis ) for k , el in basis [ 'elements' ] . items ( ) : if not 'electron_shells' in el : continue newshells = [ ] for sh in el [ 'electron_shells' ] : # See if we actually have to uncontract # Also , don ' t uncontract sp , spd , . . . . orbitals ...
def get_method ( self , cls_name ) : """Generator that returns all registered authenticators based on a specific authentication class . : param acr : Authentication Class : return : generator"""
for id , spec in self . db . items ( ) : if spec [ "method" ] . __class__ . __name__ == cls_name : yield spec [ "method" ]
def legends ( value ) : """list or KeyedList of ` ` Legends ` ` : Legend definitions Legends visualize scales , and take one or more scales as their input . They can be customized via a LegendProperty object ."""
for i , entry in enumerate ( value ) : _assert_is_type ( 'legends[{0}]' . format ( i ) , entry , Legend )
def name ( self ) : """Give back tab name if is set else generate name by code"""
if self . _name : return self . _name return self . code . replace ( '_' , ' ' ) . capitalize ( )
def _StrftimeLocal ( value , unused_context , args ) : """Convert a timestamp in seconds to a string based on the format string . Returns local time ."""
time_tuple = time . localtime ( value ) return _StrftimeHelper ( args , time_tuple )
def find_wheels ( projects , search_dirs ) : """Find wheels from which we can import PROJECTS . Scan through SEARCH _ DIRS for a wheel for each PROJECT in turn . Return a list of the first wheel found for each PROJECT"""
wheels = [ ] # Look through SEARCH _ DIRS for the first suitable wheel . Don ' t bother # about version checking here , as this is simply to get something we can # then use to install the correct version . for project in projects : for dirname in search_dirs : # This relies on only having " universal " wheels avail...
def point_to_line ( point , segment_start , segment_end ) : """Given a point and a line segment , return the vector from the point to the closest point on the segment ."""
# TODO : Needs unittests . segment_vec = segment_end - segment_start # t is distance along line t = - ( segment_start - point ) . dot ( segment_vec ) / ( segment_vec . length_squared ( ) ) closest_point = segment_start + scale_v3 ( segment_vec , t ) return point - closest_point
def request_object ( self ) : """Grab an object from the pool . If the pool is empty , a new object will be generated and returned ."""
obj_to_return = None if self . queue . count > 0 : obj_to_return = self . __dequeue ( ) else : # The queue is empty , generate a new item . self . __init_object ( ) object_to_return = self . __dequeue ( ) self . active_objects += 1 return obj_to_return
def _get ( url , headers = { } , params = None ) : """Tries to GET data from an endpoint using retries"""
param_string = _foursquare_urlencode ( params ) for i in xrange ( NUM_REQUEST_RETRIES ) : try : try : response = requests . get ( url , headers = headers , params = param_string , verify = VERIFY_SSL ) return _process_response ( response ) except requests . exceptions . Reque...
def find_config_file ( self , project = None , extension = '.conf' ) : """Return the config file . : param project : " zvmsdk " : param extension : the type of the config file"""
cfg_dirs = self . _get_config_dirs ( ) config_files = self . _search_dirs ( cfg_dirs , project , extension ) return config_files
def expect_column_values_to_be_decreasing ( self , column , strictly = None , parse_strings_as_datetimes = None , mostly = None , result_format = None , include_config = False , catch_exceptions = None , meta = None ) : """Expect column values to be decreasing . By default , this expectation only works for numeri...
raise NotImplementedError
def _update_marshallers ( self ) : """Update the full marshaller list and other data structures . Makes a full list of both builtin and user marshallers and rebuilds internal data structures used for looking up which marshaller to use for reading / writing Python objects to / from file . Also checks for w...
# Combine all sets of marshallers . self . _marshallers = [ ] for v in self . _priority : if v == 'builtin' : self . _marshallers . extend ( self . _builtin_marshallers ) elif v == 'plugin' : self . _marshallers . extend ( self . _plugin_marshallers ) elif v == 'user' : self . _marsh...
def addnot ( self , action = None , subject = None , ** conditions ) : """Defines an ability which cannot be done ."""
self . add_rule ( Rule ( False , action , subject , ** conditions ) )
def ParsedSections ( file_val ) : """Get the sections and options of a file returned as a dictionary"""
try : template_dict = { } cur_section = '' for val in file_val . split ( '\n' ) : val = val . strip ( ) if val != '' : section_match = re . match ( r'\[.+\]' , val ) if section_match : cur_section = section_match . group ( ) [ 1 : - 1 ] ...
def get_data_files ( top ) : """Get data files"""
data_files = [ ] ntrim = len ( here + os . path . sep ) for ( d , _ , filenames ) in os . walk ( top ) : data_files . append ( ( d [ ntrim : ] , [ os . path . join ( d , f ) for f in filenames ] ) ) return data_files
def get_preds ( model : nn . Module , dl : DataLoader , pbar : Optional [ PBar ] = None , cb_handler : Optional [ CallbackHandler ] = None , activ : nn . Module = None , loss_func : OptLossFunc = None , n_batch : Optional [ int ] = None ) -> List [ Tensor ] : "Tuple of predictions and targets , and optional losses ...
res = [ torch . cat ( o ) . cpu ( ) for o in zip ( * validate ( model , dl , cb_handler = cb_handler , pbar = pbar , average = False , n_batch = n_batch ) ) ] if loss_func is not None : with NoneReduceOnCPU ( loss_func ) as lf : res . append ( lf ( res [ 0 ] , res [ 1 ] ) ) if activ is not None : res [ ...
def client_port ( self ) : """Client connection ' s TCP port ."""
address = self . _client . getpeername ( ) if isinstance ( address , tuple ) : return address [ 1 ] # Maybe a Unix domain socket connection . return 0
def assignment_action ( self , text , loc , assign ) : """Code executed after recognising an assignment statement"""
exshared . setpos ( loc , text ) if DEBUG > 0 : print ( "ASSIGN:" , assign ) if DEBUG == 2 : self . symtab . display ( ) if DEBUG > 2 : return var_index = self . symtab . lookup_symbol ( assign . var , [ SharedData . KINDS . GLOBAL_VAR , SharedData . KINDS . PARAMETER , SharedData . KINDS . ...
def nsx_controller_name ( self , ** kwargs ) : """Get / Set nsx controller name Args : name : ( str ) : Name of the nsx controller get ( bool ) : Get nsx controller config ( True , False ) callback ( function ) : A function executed upon completion of the method . Returns : Return value of ` callback ...
name = kwargs . pop ( 'name' ) name_args = dict ( name = name ) method_name = 'nsx_controller_name' method_class = self . _brocade_tunnels nsxcontroller_attr = getattr ( method_class , method_name ) config = nsxcontroller_attr ( ** name_args ) if kwargs . pop ( 'get' , False ) : output = self . _callback ( config ,...
def save_config ( self , config_file_name ) : """Save configuration file from prt or str . Configuration file type is extracted from the file suffix - prt or str . : param config _ file _ name : full path to the configuration file . IxTclServer must have access to the file location . either : The config fil...
config_file_name = config_file_name . replace ( '\\' , '/' ) ext = path . splitext ( config_file_name ) [ - 1 ] . lower ( ) if ext == '.prt' : self . api . call_rc ( 'port export "{}" {}' . format ( config_file_name , self . uri ) ) elif ext == '.str' : # self . reset ( ) self . api . call_rc ( 'stream export "...
def move_tab ( self , index_from , index_to ) : """Move tab ."""
client = self . clients . pop ( index_from ) self . clients . insert ( index_to , client )
def get_alignak_status ( self , details = False ) : # pylint : disable = too - many - locals , too - many - branches """Push the alignak overall state as a passive check Build all the daemons overall state as a passive check that can be notified to the Alignak WS The Alignak Arbiter is considered as an host w...
now = int ( time . time ( ) ) # Get the arbiter statistics inner_stats = self . get_daemon_stats ( details = details ) res = { "name" : inner_stats [ 'alignak' ] , "template" : { "_templates" : [ "alignak" , "important" ] , "alias" : inner_stats [ 'alignak' ] , "active_checks_enabled" : False , "passive_checks_enabled"...
def add_word ( self , word ) : """Parameters word : etree . Element etree representation of a < word > element ( i . e . a token , which might contain child elements )"""
word_id = self . get_element_id ( word ) if word . getparent ( ) . tag in ( 'node' , 'sentence' ) : parent_id = self . get_parent_id ( word ) else : # ExportXML is an inline XML format . Therefore , a < word > # might be embedded in weird elements . If this is the case , # attach it directly to the closest < node >...
def unicode ( expr , cache = None , ** settings ) : """Return a unicode representation of the given object / expression Args : expr : Expression to print cache ( dict or None ) : dictionary to use for caching show _ hs _ label ( bool or str ) : Whether to a label for the Hilbert space of ` expr ` . By def...
try : if cache is None and len ( settings ) == 0 : return unicode . printer . doprint ( expr ) else : printer = unicode . _printer_cls ( cache , settings ) return printer . doprint ( expr ) except AttributeError : # init _ printing was not called . Setting up defaults unicode . _prin...
def _root_mean_square_error ( y , y_pred , w ) : """Calculate the root mean square error ."""
return np . sqrt ( np . average ( ( ( y_pred - y ) ** 2 ) , weights = w ) )
def list_feeds ( ) : """List all feeds in plain text and give their aliases"""
with Database ( "feeds" ) as feeds , Database ( "aliases" ) as aliases_db : for feed in feeds : name = feed url = feeds [ feed ] aliases = [ ] for k , v in zip ( list ( aliases_db . keys ( ) ) , list ( aliases_db . values ( ) ) ) : if v == name : aliases ....
def update ( self , stats , duration = 3 , cs_status = None , return_to_browser = False ) : """Update the screen . INPUT stats : Stats database to display duration : duration of the loop cs _ status : " None " : standalone or server mode " Connected " : Client is connected to the server " Disconnected...
# Flush display self . flush ( stats , cs_status = cs_status ) # If the duration is < 0 ( update + export time > refresh _ time ) # Then display the interface and log a message if duration <= 0 : logger . warning ( 'Update and export time higher than refresh_time.' ) duration = 0.1 # Wait duration ( in s ) time...
def _get_storage ( cls , uri ) : """Given a URI like local : / / / srv / repo or s3 : / / key : secret @ apt . example . com , return a libcloud storage or container object ."""
driver = cls . _get_driver ( uri . scheme ) key = uri . username secret = uri . password container = uri . netloc driver_kwargs = { } if uri . scheme . startswith ( 's3' ) : if not key : key = os . environ . get ( 'AWS_ACCESS_KEY_ID' ) if not secret : secret = os . environ . get ( 'AWS_SECRET_AC...
def convert_camel_case_string ( name : str ) -> str : """Convert camel case string to snake case"""
string = re . sub ( "(.)([A-Z][a-z]+)" , r"\1_\2" , name ) return re . sub ( "([a-z0-9])([A-Z])" , r"\1_\2" , string ) . lower ( )
def _collected_label ( collect , label ) : """Label of a collected column ."""
if not collect . __name__ . startswith ( '<' ) : return label + ' ' + collect . __name__ else : return label
def _pseudoinverse ( self , A , tol = 1.0e-10 ) : """Compute the Moore - Penrose pseudoinverse , wraps np . linalg . pinv REQUIRED ARGUMENTS A ( np KxK matrix ) - the square matrix whose pseudoinverse is to be computed RETURN VALUES Ainv ( np KxK matrix ) - the pseudoinverse OPTIONAL VALUES tol - the to...
return np . linalg . pinv ( A , rcond = tol )
def odd_digit_product ( num : int ) -> int : """Calculate the product of odd digits in a positive integer . Return 0 if all numbers are even . Args : num ( int ) : Input positive Integer . Returns : int : Product of odd digits if there are any , 0 otherwise . Examples : > > > odd _ digit _ product ( 1) ...
product = 1 has_odd_digit = False for digit in str ( num ) : if int ( digit ) % 2 : product *= int ( digit ) has_odd_digit = True return 0 if not has_odd_digit else product
def clear_stats ( self ) : """Reset server stat counters . ."""
self . _start_time = None self . _run_time = 0 self . stats = { 'Enabled' : False , 'Bind Address' : lambda s : repr ( self . bind_addr ) , 'Run time' : lambda s : ( not s [ 'Enabled' ] ) and - 1 or self . runtime ( ) , 'Accepts' : 0 , 'Accepts/sec' : lambda s : s [ 'Accepts' ] / self . runtime ( ) , 'Queue' : lambda s...
def generate_mavlink ( directory , xml ) : '''generate MVMavlink header and implementation'''
f = open ( os . path . join ( directory , "MVMavlink.h" ) , mode = 'w' ) t . write ( f , ''' // // MVMavlink.h // MAVLink communications protocol built from ${basename}.xml // // Created on ${parse_time} by mavgen_objc.py // http://qgroundcontrol.org/mavlink // #import "MVMessage.h" ${{message_definition_files:#im...
def get_agile_board ( self , board_id ) : """Get agile board info by id : param board _ id : : return :"""
url = 'rest/agile/1.0/board/{}' . format ( str ( board_id ) ) return self . get ( url )
def VerifyServerPEM ( self , http_object ) : """Check the server PEM for validity . This is used to determine connectivity to the server . Sometimes captive portals return a valid HTTP status , but the data is corrupted . Args : http _ object : The response received from the server . Returns : True if t...
try : server_pem = http_object . data server_url = http_object . url if b"BEGIN CERTIFICATE" in server_pem : # Now we know that this proxy is working . We still have to verify the # certificate . This will raise if the server cert is invalid . server_certificate = rdf_crypto . RDFX509Cert ( serv...
def serialize_encryption_context ( encryption_context ) : """Serializes the contents of a dictionary into a byte string . : param dict encryption _ context : Dictionary of encrytion context keys / values . : returns : Serialized encryption context : rtype : bytes"""
if not encryption_context : return bytes ( ) serialized_context = bytearray ( ) dict_size = len ( encryption_context ) if dict_size > aws_encryption_sdk . internal . defaults . MAX_BYTE_ARRAY_SIZE : raise SerializationError ( "The encryption context contains too many elements." ) serialized_context . extend ( s...
def get_area_def ( self , key , info = None ) : """Create AreaDefinition for specified product . Projection information are hard coded for 0 degree geos projection Test dataset doesn ' t provide the values in the file container . Only fill values are inserted ."""
# TODO Get projection information from input file a = 6378169. h = 35785831. b = 6356583.8 lon_0 = 0. # area _ extent = ( - 5432229.9317116784 , - 5429229.5285458621, # 5429229.5285458621 , 5432229.9317116784) area_extent = ( - 5570248.4773392612 , - 5567248.074173444 , 5567248.074173444 , 5570248.4773392612 ) proj_dic...
def camelHump ( text ) : """Converts the inputted text to camel humps by joining all capital letters toegether ( The Quick , Brown , Fox . Tail - > TheQuickBrownFoxTail ) : param : text < str > text to be changed : return : < str > : usage : | import projex . text | print projex . text . camelHump ( ' T...
# make sure the first letter is upper case output = '' . join ( [ word [ 0 ] . upper ( ) + word [ 1 : ] for word in words ( text ) ] ) if output : output = output [ 0 ] . lower ( ) + output [ 1 : ] return output