signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def align ( time , time2 , magnitude , magnitude2 , error , error2 ) : """Synchronizes the light - curves in the two different bands . Returns aligned _ time aligned _ magnitude aligned _ magnitude2 aligned _ error aligned _ error2"""
error = np . zeros ( time . shape ) if error is None else error error2 = np . zeros ( time2 . shape ) if error2 is None else error2 # this asume that the first series is the short one sserie = pd . DataFrame ( { "mag" : magnitude , "error" : error } , index = time ) lserie = pd . DataFrame ( { "mag" : magnitude2 , "err...
def set_querier_mode ( self , dpid , server_port ) : """set the datapath to work as a querier . note that you can set up only the one querier . when you called this method several times , only the last one becomes effective ."""
self . dpid = dpid self . server_port = server_port if self . _querier_thread : hub . kill ( self . _querier_thread ) self . _querier_thread = None
def failed_request_exception ( message , r ) : """Build ClickException from a failed request ."""
try : resp = json . loads ( r . text ) message = '%s: %d\n%s' % ( message , resp [ 'error' ] [ 'code' ] , resp [ 'error' ] [ 'message' ] ) return click . ClickException ( message ) except ValueError : # fallback on raw text response if error is not structured . return click . ClickException ( '%s: %d\n%...
def update_file ( filename , items ) : '''Edits the given file in place , replacing any instances of { key } with the appropriate value from the provided items dict . If the given filename ends with " . xml " values will be quoted and escaped for XML .'''
# TODO : Implement something in the templates to denote whether the value # being replaced is an XML attribute or a value . Perhaps move to dyanmic # XML tree building rather than string replacement . should_escape = filename . endswith ( 'addon.xml' ) with open ( filename , 'r' ) as inp : text = inp . read ( ) for...
def _evalTimeStr ( self , datetimeString , sourceTime ) : """Evaluate text passed by L { _ partialParseTimeStr ( ) }"""
s = datetimeString . strip ( ) sourceTime = self . _evalDT ( datetimeString , sourceTime ) if s in self . ptc . re_values [ 'now' ] : self . currentContext . updateAccuracy ( pdtContext . ACU_NOW ) else : # Given string is a natural language time string like # lunch , midnight , etc sTime = self . ptc . getSour...
def add_method ( self , loop , callback ) : """Add a coroutine function Args : loop : The : class : ` event loop < asyncio . BaseEventLoop > ` instance on which to schedule callbacks callback : The : term : ` coroutine function ` to add"""
f , obj = get_method_vars ( callback ) wrkey = ( f , id ( obj ) ) self [ wrkey ] = obj self . event_loop_map [ wrkey ] = loop
def go_to ( self , url_or_text ) : """Go to page * address *"""
if is_text_string ( url_or_text ) : url = QUrl ( url_or_text ) else : url = url_or_text self . webview . load ( url )
def get_description_metadata ( self ) : """Gets the metadata for a description . return : ( osid . Metadata ) - metadata for the description * compliance : mandatory - - This method must be implemented . *"""
metadata = dict ( self . _mdata [ 'description' ] ) metadata . update ( { 'existing_string_values' : self . _my_map [ 'description' ] [ 'text' ] } ) return Metadata ( ** metadata )
def transform ( self , v3 ) : """Calculates the vector transformed by this quaternion : param v3 : Vector3 to be transformed : returns : transformed vector"""
if isinstance ( v3 , Vector3 ) : t = super ( Quaternion , self ) . transform ( [ v3 . x , v3 . y , v3 . z ] ) return Vector3 ( t [ 0 ] , t [ 1 ] , t [ 2 ] ) elif len ( v3 ) == 3 : return super ( Quaternion , self ) . transform ( v3 ) else : raise TypeError ( "param v3 is not a vector type" )
def __dict_to_deployment_spec ( spec ) : '''Converts a dictionary into kubernetes AppsV1beta1DeploymentSpec instance .'''
spec_obj = AppsV1beta1DeploymentSpec ( template = spec . get ( 'template' , '' ) ) for key , value in iteritems ( spec ) : if hasattr ( spec_obj , key ) : setattr ( spec_obj , key , value ) return spec_obj
def Planck_2015 ( flat = False , extras = True ) : """Planck 2015 XII : Cosmological parameters Table 4 column Planck TT , TE , EE + lowP + lensing + ext from Ade et al . ( 2015 ) A & A in press ( arxiv : 1502.01589v1) Parameters flat : boolean If True , sets omega _ lambda _ 0 = 1 - omega _ M _ 0 to ensu...
omega_b_0 = 0.02230 / ( 0.6774 ** 2 ) cosmo = { 'omega_b_0' : omega_b_0 , 'omega_M_0' : 0.3089 , 'omega_lambda_0' : 0.6911 , 'h' : 0.6774 , 'n' : 0.9667 , 'sigma_8' : 0.8159 , 'tau' : 0.066 , 'z_reion' : 8.8 , 't_0' : 13.799 , } if flat : cosmo [ 'omega_lambda_0' ] = 1 - cosmo [ 'omega_M_0' ] cosmo [ 'omega_k_0...
def parse_account_key ( ) : """Parse account key to get public key"""
LOGGER . info ( "Parsing account key..." ) cmd = [ 'openssl' , 'rsa' , '-in' , os . path . join ( gettempdir ( ) , 'account.key' ) , '-noout' , '-text' ] devnull = open ( os . devnull , 'wb' ) return subprocess . check_output ( cmd , stderr = devnull )
def removeAll ( self ) : """Remove all selectables , and return a list of them ."""
rv = self . _removeAll ( self . _reads , self . _writes ) return rv
def matrix_to_lines ( matrix , x , y , incby = 1 ) : """Converts the ` matrix ` into an iterable of ( ( x1 , y1 ) , ( x2 , y2 ) ) tuples which represent a sequence ( horizontal line ) of dark modules . The path starts at the 1st row of the matrix and moves down to the last row . : param matrix : An iterable...
y -= incby # Move along y - axis so we can simply increment y in the loop last_bit = 0x1 for row in matrix : x1 = x x2 = x y += incby for bit in row : if last_bit != bit and not bit : yield ( x1 , y ) , ( x2 , y ) x1 = x2 x2 += 1 if not bit : x...
def subscribe ( self , method , * params ) : '''Perform a remote command which will stream events / data to us . Expects a method name , which look like : server . peers . subscribe . . and sometimes take arguments , all of which are positional . Returns a tuple : ( Future , asyncio . Queue ) . The future...
assert '.' in method assert method . endswith ( 'subscribe' ) return self . _send_request ( method , params , is_subscribe = True )
def price ( self ) : """Current price ."""
# if accessing and stale - update first if self . _needupdate or self . now != self . parent . now : self . update ( self . root . now ) return self . _price
def request_entity ( self , request_entity ) : """Sets the request _ entity of this FileSourceCreateOrUpdateRequest . : param request _ entity : The request _ entity of this FileSourceCreateOrUpdateRequest . : type : str"""
if request_entity is not None and len ( request_entity ) > 10000 : raise ValueError ( "Invalid value for `request_entity`, length must be less than or equal to `10000`" ) self . _request_entity = request_entity
def related_items_changed ( self , instance , related_manager ) : """Stores the number of comments . A custom ` ` count _ filter ` ` queryset gets checked for , allowing managers to implement custom count logic ."""
try : count = related_manager . count_queryset ( ) except AttributeError : count = related_manager . count ( ) count_field_name = list ( self . fields . keys ( ) ) [ 0 ] % self . related_field_name setattr ( instance , count_field_name , count ) instance . save ( )
def cmd_fence ( self , args ) : '''fence commands'''
if len ( args ) < 1 : self . print_usage ( ) return if args [ 0 ] == "enable" : self . set_fence_enabled ( 1 ) elif args [ 0 ] == "disable" : self . set_fence_enabled ( 0 ) elif args [ 0 ] == "load" : if len ( args ) != 2 : print ( "usage: fence load <filename>" ) return self . l...
def revoke ( self , paths : Union [ str , Iterable [ str ] ] , users : Union [ str , Iterable [ str ] , User , Iterable [ User ] ] ) : """Revokes all access controls that are associated to the given path or collection of paths . : param paths : the paths to remove access controls on : param users : the users to...
def sag_entropic_transport ( a , b , M , reg , numItermax = 10000 , lr = None ) : '''Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem : . . math : : \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(...
if lr is None : lr = 1. / max ( a / reg ) n_source = np . shape ( M ) [ 0 ] n_target = np . shape ( M ) [ 1 ] cur_beta = np . zeros ( n_target ) stored_gradient = np . zeros ( ( n_source , n_target ) ) sum_stored_gradient = np . zeros ( n_target ) for _ in range ( numItermax ) : i = np . random . randint ( n_so...
def write_str2file ( pathname , astr ) : """writes a string to file"""
fname = pathname fhandle = open ( fname , 'wb' ) fhandle . write ( astr ) fhandle . close ( )
def _key ( self ) : """A tuple key that uniquely describes this field . Used to compute this instance ' s hashcode and evaluate equality . Returns : Tuple [ str ] : The contents of this : class : ` . RowRange ` ."""
return ( self . start_key , self . start_inclusive , self . end_key , self . end_inclusive )
def _add_ps2q ( self , throat , queue ) : """Helper method to add pores to the cluster queue"""
net = self . project . network elem_type = 'pore' # Find pores connected to newly invaded throat Ps = net [ 'throat.conns' ] [ throat ] # Remove already invaded pores from Ps Ps = Ps [ self [ 'pore.invasion_sequence' ] [ Ps ] <= 0 ] if len ( Ps ) > 0 : self . _interface_Ps [ Ps ] = True for P in Ps : da...
def is_valid_hostname ( hostname ) : '''Return True if hostname is valid , otherwise False .'''
if not isinstance ( hostname , str ) : raise TypeError ( 'hostname must be a string' ) # strip exactly one dot from the right , if present if hostname and hostname [ - 1 ] == "." : hostname = hostname [ : - 1 ] if not hostname or len ( hostname ) > 253 : return False labels = hostname . split ( '.' ) # the ...
def _int_generator ( descriptor , bitwidth , unsigned ) : 'Helper to create a basic integer value generator'
vals = list ( values . get_integers ( bitwidth , unsigned ) ) return gen . IterValueGenerator ( descriptor . name , vals )
def get_extra_claims ( self , claims_set ) : """Get claims holding extra identity info from the claims set . Returns a dictionary of extra claims or None if there are none . : param claims _ set : set of claims , which was included in the received token ."""
reserved_claims = ( self . userid_claim , "iss" , "aud" , "exp" , "nbf" , "iat" , "jti" , "refresh_until" , "nonce" ) extra_claims = { } for claim in claims_set : if claim not in reserved_claims : extra_claims [ claim ] = claims_set [ claim ] if not extra_claims : return None return extra_claims
def depthfirstsearch ( self , function ) : """Generic depth first search algorithm using a callback function , continues as long as the callback function returns None"""
result = function ( self ) if result is not None : return result for e in self : result = e . depthfirstsearch ( function ) if result is not None : return result return None
def all_on_off ( self , power ) : """Turn all zones on or off Note that the all on function is not supported by the Russound CAA66 , although it does support the all off . On and off are supported by the CAV6.6. Note : Not tested ( acambitsis )"""
send_msg = self . create_send_message ( "F0 7F 00 7F 00 00 @kk 05 02 02 00 00 F1 22 00 00 @pr 00 00 01" , None , None , power ) self . send_data ( send_msg ) self . get_response_message ( )
def quantity_yXL ( fig , left , bottom , top , quantity = params . L_yXL , label = r'$\mathcal{L}_{yXL}$' ) : '''make a bunch of image plots , each showing the spatial normalized connectivity of synapses'''
layers = [ 'L1' , 'L2/3' , 'L4' , 'L5' , 'L6' ] ncols = len ( params . y ) / 4 # assess vlims vmin = 0 vmax = 0 for y in params . y : if quantity [ y ] . max ( ) > vmax : vmax = quantity [ y ] . max ( ) gs = gridspec . GridSpec ( 4 , 4 , left = left , bottom = bottom , top = top ) for i , y in enumerate ( p...
def past_trades ( self , symbol = 'btcusd' , limit_trades = 50 , timestamp = 0 ) : """Send a trade history request , return the response . Arguements : symbol - - currency symbol ( default ' btcusd ' ) limit _ trades - - maximum number of trades to return ( default 50) timestamp - - only return trades after...
request = '/v1/mytrades' url = self . base_url + request params = { 'request' : request , 'nonce' : self . get_nonce ( ) , 'symbol' : symbol , 'limit_trades' : limit_trades , 'timestamp' : timestamp } return requests . post ( url , headers = self . prepare ( params ) )
def _default ( cls , opts ) : """Setup default logger"""
logging . basicConfig ( level = logging . INFO , format = cls . _log_format ) return True
def pairwise_permutations ( i , j ) : '''Return all permutations of a set of groups This routine takes two vectors : i - the label of each group j - the members of the group . For instance , take a set of two groups with several members each : i | j 1 | 1 1 | 2 1 | 3 2 | 1 2 | 4 2 | 5 2 | 6 ...
if len ( i ) == 0 : return ( np . array ( [ ] , int ) , np . array ( [ ] , j . dtype ) , np . array ( [ ] , j . dtype ) ) # Sort by i then j index = np . lexsort ( ( j , i ) ) i = i [ index ] j = j [ index ] # map the values of i to a range r r_to_i = np . sort ( np . unique ( i ) ) i_to_r_off = np . min ( i ) i_to...
def enter ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : """Press enter key n times . * * 中文文档 * * 按回车键 / 换行键 n 次 。"""
self . delay ( pre_dl ) self . k . tap_key ( self . k . enter_key , n , interval ) self . delay ( post_dl )
def get_nested ( self , * args ) : """get a nested value , returns None if path does not exist"""
data = self . data for key in args : if key not in data : return None data = data [ key ] return data
def get_sensor_data ( self ) : """Get sensor reading objects Iterates sensor reading objects pertaining to the currently managed BMC . : returns : Iterator of sdr . SensorReading objects"""
self . init_sdr ( ) for sensor in self . _sdr . get_sensor_numbers ( ) : rsp = self . raw_command ( command = 0x2d , netfn = 4 , data = ( sensor , ) ) if 'error' in rsp : if rsp [ 'code' ] == 203 : # Sensor does not exist , optional dev continue raise exc . IpmiException ( rsp [ 'err...
async def graphql ( schema : GraphQLSchema , source : Union [ str , Source ] , root_value : Any = None , context_value : Any = None , variable_values : Dict [ str , Any ] = None , operation_name : str = None , field_resolver : GraphQLFieldResolver = None , type_resolver : GraphQLTypeResolver = None , middleware : Middl...
# Always return asynchronously for a consistent API . result = graphql_impl ( schema , source , root_value , context_value , variable_values , operation_name , field_resolver , type_resolver , middleware , execution_context_class , ) if isawaitable ( result ) : return await cast ( Awaitable [ ExecutionResult ] , re...
def to_tag ( self ) -> str : """Convert a Language back to a standard language tag , as a string . This is also the str ( ) representation of a Language object . > > > Language . make ( language = ' en ' , region = ' GB ' ) . to _ tag ( ) ' en - GB ' > > > Language . make ( language = ' yue ' , script = ' H...
if self . _str_tag is not None : return self . _str_tag subtags = [ 'und' ] if self . language : subtags [ 0 ] = self . language if self . extlangs : for extlang in sorted ( self . extlangs ) : subtags . append ( extlang ) if self . script : subtags . append ( self . script ) if self . region : ...
def ProgramScanner ( ** kw ) : """Return a prototype Scanner instance for scanning executable files for static - lib dependencies"""
kw [ 'path_function' ] = SCons . Scanner . FindPathDirs ( 'LIBPATH' ) ps = SCons . Scanner . Base ( scan , "ProgramScanner" , ** kw ) return ps
def _lookup_unconflicted_symbol ( self , symbol ) : """Attempt to find a unique asset whose symbol is the given string . If multiple assets have held the given symbol , return a 0. If no asset has held the given symbol , return a NaN ."""
try : uppered = symbol . upper ( ) except AttributeError : # The mapping fails because symbol was a non - string return numpy . nan try : return self . finder . lookup_symbol ( uppered , as_of_date = None , country_code = self . country_code , ) except MultipleSymbolsFound : # Fill conflicted entries with z...
def _fitnesses_to_probabilities ( fitnesses ) : """Return a list of probabilities proportional to fitnesses ."""
# Do not allow negative fitness values min_fitness = min ( fitnesses ) if min_fitness < 0.0 : # Make smallest fitness value 0 fitnesses = map ( lambda f : f - min_fitness , fitnesses ) fitness_sum = sum ( fitnesses ) # Generate probabilities # Creates a list of increasing values . # The greater the gap between two ...
def set_stream_rates ( ) : '''set mavlink stream rates'''
if ( not msg_period . trigger ( ) and mpstate . status . last_streamrate1 == mpstate . settings . streamrate and mpstate . status . last_streamrate2 == mpstate . settings . streamrate2 ) : return mpstate . status . last_streamrate1 = mpstate . settings . streamrate mpstate . status . last_streamrate2 = mpstate . se...
def get_axes ( self , projection = None ) : """Find all ` Axes ` , optionally matching the given projection Parameters projection : ` str ` name of axes types to return Returns axlist : ` list ` of ` ~ matplotlib . axes . Axes `"""
if projection is None : return self . axes return [ ax for ax in self . axes if ax . name == projection . lower ( ) ]
def delete_message ( self , message_id ) : """Delete message from this chat : param int message _ id : ID of the message"""
return self . bot . api_call ( "deleteMessage" , chat_id = self . id , message_id = message_id )
def get_vault_form ( self , * args , ** kwargs ) : """Pass through to provider VaultAdminSession . get _ vault _ form _ for _ update"""
# Implemented from kitosid template for - # osid . resource . BinAdminSession . get _ bin _ form _ for _ update _ template # This method might be a bit sketchy . Time will tell . if isinstance ( args [ - 1 ] , list ) or 'vault_record_types' in kwargs : return self . get_vault_form_for_create ( * args , ** kwargs ) ...
def plot_spectrogram ( self , fmin = None , fmax = None , method = 'scipy-fourier' , deg = False , window = 'hann' , detrend = 'linear' , nperseg = None , noverlap = None , boundary = 'constant' , padded = True , wave = 'morlet' , invert = True , plotmethod = 'imshow' , cmap_f = None , cmap_img = None , ms = 4 , ntMax ...
if self . _isSpectral ( ) : msg = "spectrogram not implemented yet for spectral data class" raise Exception ( msg ) tf , f , lpsd , lang = _comp . spectrogram ( self . data , self . t , fmin = fmin , deg = deg , method = method , window = window , detrend = detrend , nperseg = nperseg , noverlap = noverlap , bo...
def get_data ( self , data_format ) : """Reads the common format and converts to output data data _ format - the format of the output data . See utils . input . dataformats"""
if data_format not in self . output_formats : raise Exception ( "Output format {0} not available with this class. Available formats are {1}." . format ( data_format , self . output_formats ) ) data_converter = getattr ( self , "to_" + data_format ) return data_converter ( )
def add_view ( self , view_name , map_func , reduce_func = None , ** kwargs ) : """Appends a MapReduce view to the locally cached DesignDocument View dictionary . To create a JSON query index use : func : ` ~ cloudant . database . CloudantDatabase . create _ query _ index ` instead . A CloudantException is ra...
if self . get_view ( view_name ) is not None : raise CloudantArgumentError ( 107 , view_name ) if self . get ( 'language' , None ) == QUERY_LANGUAGE : raise CloudantDesignDocumentException ( 101 ) view = View ( self , view_name , map_func , reduce_func , ** kwargs ) self . views . __setitem__ ( view_name , view...
def create_from_euler_angles ( cls , rx , ry , rz , degrees = False ) : """Classmethod to create a quaternion given the euler angles ."""
if degrees : rx , ry , rz = np . radians ( [ rx , ry , rz ] ) # Obtain quaternions qx = Quaternion ( np . cos ( rx / 2 ) , 0 , 0 , np . sin ( rx / 2 ) ) qy = Quaternion ( np . cos ( ry / 2 ) , 0 , np . sin ( ry / 2 ) , 0 ) qz = Quaternion ( np . cos ( rz / 2 ) , np . sin ( rz / 2 ) , 0 , 0 ) # Almost done return qx...
def x10 ( cls , housecode , unitcode ) : """Create an X10 device address ."""
if housecode . lower ( ) in [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' ] : byte_housecode = insteonplm . utils . housecode_to_byte ( housecode ) else : if isinstance ( housecode , str ) : _LOGGER . error ( 'X10 house code error: %s' , housecode ) ...
def wtime_to_minutes ( time_string ) : '''wtime _ to _ minutes Convert standard wallclock time string to minutes . Args : - Time _ string in HH : MM : SS format Returns : ( int ) minutes'''
hours , mins , seconds = time_string . split ( ':' ) return int ( hours ) * 60 + int ( mins ) + 1
def run_delete_sm ( self , tenant_id , fw_dict , is_fw_virt ) : """Runs the delete State Machine . Goes through every state function until the end or when one state returns failure ."""
# Read the current state from the DB ret = True serv_obj = self . get_service_obj ( tenant_id ) state = serv_obj . get_state ( ) # Preserve the ordering of the next lines till while new_state = serv_obj . fixup_state ( fw_const . FW_DEL_OP , state ) serv_obj . store_local_final_result ( fw_const . RESULT_FW_DELETE_INIT...
def clear ( self ) : """Removes all data from the buffer ."""
self . io . seek ( 0 ) self . io . truncate ( ) for item in self . monitors : item [ 2 ] = 0
def _git_run ( command , cwd = None , user = None , password = None , identity = None , ignore_retcode = False , failhard = True , redirect_stderr = False , saltenv = 'base' , output_encoding = None , ** kwargs ) : '''simple , throw an exception with the error message on an error return code . this function may b...
env = { } if identity : _salt_cli = __opts__ . get ( '__cli' , '' ) errors = [ ] missing_keys = [ ] # if the statefile provides multiple identities , they need to be tried # ( but also allow a string instead of a list ) if not isinstance ( identity , list ) : # force it into a list ident...
def draw ( self , ** kwargs ) : """Called from the fit method , this method creates the canvas and draws the part - of - speech tag mapping as a bar chart . Parameters kwargs : dict generic keyword arguments . Returns ax : matplotlib axes Axes on which the PosTagVisualizer was drawn ."""
colors = resolve_colors ( n_colors = len ( self . pos_tag_counts_ ) , colormap = self . colormap , colors = self . colors , ) if self . frequency : # Sort tags with respect to frequency in corpus sorted_tags = sorted ( self . pos_tag_counts_ , key = self . pos_tag_counts_ . get , reverse = True ) sorted_counts ...
def add_request_participants ( self , issue_id_or_key , users_list ) : """Add users as participants to an existing customer request The calling user must have permission to manage participants for this customer request : param issue _ id _ or _ key : str : param users _ list : list : return :"""
url = 'rest/servicedeskapi/request/{}/participant' . format ( issue_id_or_key ) data = { 'usernames' : users_list } return self . post ( url , data = data )
def ncbi_geneid ( self ) : """Retrieve this feature ' s NCBI GeneID if it ' s present . NCBI GFF3 files contain gene IDs encoded in * * Dbxref * * attributes ( example : ` Dbxref = GeneID : 103504972 ` ) . This function locates and returns the GeneID if present , or returns ` None ` otherwise ."""
values = self . get_attribute ( 'Dbxref' , as_list = True ) if values is None : return None for value in values : if value . startswith ( 'GeneID:' ) : key , geneid = value . split ( ':' ) return geneid return None
def by_user_and_perm ( cls , user_id , perm_name , db_session = None ) : """return by user and permission name : param user _ id : : param perm _ name : : param db _ session : : return :"""
db_session = get_db_session ( db_session ) query = db_session . query ( cls . model ) . filter ( cls . model . user_id == user_id ) query = query . filter ( cls . model . perm_name == perm_name ) return query . first ( )
def _check_infinite_flows ( self , steps , flows = None ) : """Recursively loop through the flow _ config and check if there are any cycles . : param steps : Set of step definitions to loop through : param flows : Flows already visited . : return : None"""
if flows is None : flows = [ ] for step in steps . values ( ) : if "flow" in step : flow = step [ "flow" ] if flow == "None" : continue if flow in flows : raise FlowInfiniteLoopError ( "Infinite flows detected with flow {}" . format ( flow ) ) flows . appe...
def list_tokens ( opts ) : '''List all tokens in the store . : param opts : Salt master config options : returns : List of dicts ( token _ data )'''
ret = [ ] redis_client = _redis_client ( opts ) if not redis_client : return [ ] serial = salt . payload . Serial ( opts ) try : return [ k . decode ( 'utf8' ) for k in redis_client . keys ( ) ] except Exception as err : log . warning ( 'Failed to list keys: %s' , err ) return [ ]
def check_token ( request ) : """Resource check is token valid . request _ serializer : serializers . CheckToken type : username : required : true type : string description : token related user responseMessages : - code : 200 message : Token is valid - code : 400 message : Token is not valid ...
serializer = serializers . CheckToken ( data = request . data ) serializer . is_valid ( raise_exception = True ) token = serializer . validated_data [ 'token' ] logger . debug ( 'Token correct' , extra = { 'token' : token , 'username' : token . user . username } ) return Response ( { 'username' : token . user . usernam...
def get ( self , rel ) : """Get the resource by rel name : param str rel _ name : name of rel : raises UnsupportedEntryPoint : entry point not found in this version of the API"""
for link in self . _entry_points : if link . get ( 'rel' ) == rel : return link . get ( 'href' ) raise UnsupportedEntryPoint ( "The specified entry point '{}' was not found in this " "version of the SMC API. Check the element documentation " "to determine the correct version and specify the api_version " "p...
def checkImportBindingsExtensions ( ) : """Check that nupic . bindings extension libraries can be imported . Throws ImportError on failure ."""
import nupic . bindings . math import nupic . bindings . algorithms import nupic . bindings . engine_internal
def get_next_page ( self ) : """Returns the next page of results as a sequence of Track objects ."""
master_node = self . _retrieve_next_page ( ) seq = [ ] for node in master_node . getElementsByTagName ( "track" ) : track = Track ( _extract ( node , "artist" ) , _extract ( node , "name" ) , self . network , info = { "image" : _extract_all ( node , "image" ) } , ) track . listener_count = _number ( _extract ( ...
def score_for_task ( properties , category , result ) : """Return the possible score of task , depending on whether the result is correct or not ."""
assert result is not None if properties and Property . create_from_names ( properties ) . is_svcomp : return _svcomp_score ( category , result ) return None
def text_to_data ( self , text , elt , ps ) : '''convert text into typecode specific data .'''
prefix , localName = SplitQName ( text ) nsdict = ps . GetElementNSdict ( elt ) prefix = prefix or '' try : namespaceURI = nsdict [ prefix ] except KeyError , ex : raise EvaluateException ( 'cannot resolve prefix(%s)' % prefix , ps . Backtrace ( elt ) ) v = ( namespaceURI , localName ) if self . pyclass is not ...
def on_post ( self , req , resp ) : """Send a POST request with id / nic / interval / filter / iters and it will start a container for collection with those specifications"""
resp . content_type = falcon . MEDIA_TEXT resp . status = falcon . HTTP_200 # verify payload is in the correct format # default to no filter payload = { } if req . content_length : try : payload = json . load ( req . stream ) except Exception as e : # pragma : no cover resp . body = "(False, 'ma...
def get_molecule ( self , index = 0 ) : """Get a molecule from the trajectory Optional argument : | ` ` index ` ` - - The frame index [ default = 0]"""
return Molecule ( self . numbers , self . geometries [ index ] , self . titles [ index ] , symbols = self . symbols )
def reifyWidget ( self , parent , item ) : '''Convert a JSON description of a widget into a WxObject'''
from gooey . gui . components import widgets widgetClass = getattr ( widgets , item [ 'type' ] ) return widgetClass ( parent , item )
def pow ( base , exp ) : """Returns element - wise result of base element raised to powers from exp element . Both inputs can be Symbol or scalar number . Broadcasting is not supported . Use ` broadcast _ pow ` instead . ` sym . pow ` is being deprecated , please use ` sym . power ` instead . Parameters b...
if isinstance ( base , Symbol ) and isinstance ( exp , Symbol ) : return _internal . _Power ( base , exp ) if isinstance ( base , Symbol ) and isinstance ( exp , Number ) : return _internal . _PowerScalar ( base , scalar = exp ) if isinstance ( base , Number ) and isinstance ( exp , Symbol ) : return _inter...
def create_syslog ( self , service_id , version_number , name , address , port = 514 , use_tls = "0" , tls_ca_cert = None , token = None , _format = None , response_condition = None ) : """Create a Syslog for a particular service and version ."""
body = self . _formdata ( { "name" : name , "address" : address , "port" : port , "use_tls" : use_tls , "tls_ca_cert" : tls_ca_cert , "token" : token , "format" : _format , "response_condition" : response_condition , } , FastlySyslog . FIELDS ) content = self . _fetch ( "/service/%s/version/%d/syslog" % ( service_id , ...
def get_max_seq_len ( self ) -> Optional [ int ] : """: return : The maximum length supported by the encoder if such a restriction exists ."""
max_seq_len = min ( ( encoder . get_max_seq_len ( ) for encoder in self . encoders if encoder . get_max_seq_len ( ) is not None ) , default = None ) return max_seq_len
def revision ( directory , message , autogenerate , sql , head , splice , branch_label , version_path , rev_id ) : """Create a new revision file ."""
_revision ( directory , message , autogenerate , sql , head , splice , branch_label , version_path , rev_id )
def bot_config ( player_config_path : Path , team : Team ) -> 'PlayerConfig' : """A function to cover the common case of creating a config for a bot ."""
bot_config = PlayerConfig ( ) bot_config . bot = True bot_config . rlbot_controlled = True bot_config . team = team . value bot_config . config_path = str ( player_config_path . absolute ( ) ) # TODO : Refactor to use Path ' s config_bundle = get_bot_config_bundle ( bot_config . config_path ) bot_config . name = config...
def get ( section , key ) : """returns the value of a given key of a given section of the main config file . : param section : the section . : type section : str . : param key : the key . : type key : str . : returns : the value which will be casted to float , int or boolean . if no cast is successful...
# FILE = ' config _ misc ' if not _loaded : init ( FILE ) try : return cfg . getfloat ( section , key ) except Exception : try : return cfg . getint ( section , key ) except : try : return cfg . getboolean ( section , key ) except : return cfg . get ( sect...
def processPrePrepare ( self , pre_prepare : PrePrepare , sender : str ) : """Validate and process provided PRE - PREPARE , create and broadcast PREPARE for it . : param pre _ prepare : message : param sender : name of the node that sent this message"""
key = ( pre_prepare . viewNo , pre_prepare . ppSeqNo ) self . logger . debug ( "{} received PRE-PREPARE{} from {}" . format ( self , key , sender ) ) # TODO : should we still do it ? # Converting each req _ idrs from list to tuple req_idrs = { f . REQ_IDR . nm : [ key for key in pre_prepare . reqIdr ] } pre_prepare = u...
def get_lang ( tweet ) : """Get the language that the Tweet is written in . Args : tweet ( Tweet or dict ) : A Tweet object or dictionary Returns : str : 2 - letter BCP 47 language code ( or None if undefined ) Example : > > > from tweet _ parser . getter _ methods . tweet _ text import get _ lang > >...
if is_original_format ( tweet ) : lang_field = "lang" else : lang_field = "twitter_lang" if tweet [ lang_field ] is not None and tweet [ lang_field ] != "und" : return tweet [ lang_field ] else : return None
def _insert_automodapi_configs ( c ) : """Add configurations related to automodapi , autodoc , and numpydoc to the state ."""
# Don ' t show summaries of the members in each class along with the # class ' docstring c [ 'numpydoc_show_class_members' ] = False c [ 'autosummary_generate' ] = True c [ 'automodapi_toctreedirnm' ] = 'py-api' c [ 'automodsumm_inherited_members' ] = True # Docstrings for classes and methods are inherited from parents...
def p_expression_ulnot ( self , p ) : 'expression : LNOT expression % prec ULNOT'
p [ 0 ] = Ulnot ( p [ 2 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def deobfuscate_email ( text ) : """Deobfuscate email addresses in provided text"""
text = unescape ( text ) # Find the " dot " text = _deobfuscate_dot1_re . sub ( '.' , text ) text = _deobfuscate_dot2_re . sub ( r'\1.\2' , text ) text = _deobfuscate_dot3_re . sub ( r'\1.\2' , text ) # Find the " at " text = _deobfuscate_at1_re . sub ( '@' , text ) text = _deobfuscate_at2_re . sub ( r'\1@\2' , text ) ...
def run ( exe , args , capturestd = False , env = None ) : """Runs an executable with an array of arguments , optionally in the specified environment . Returns stdout and stderr"""
command = [ exe ] + args if env : log . info ( "Executing [custom environment]: %s" , " " . join ( command ) ) else : log . info ( "Executing : %s" , " " . join ( command ) ) start = time . time ( ) # Temp files will be automatically deleted on close ( ) # If run ( ) throws the garbage collector should call clo...
def atomic ( self , func ) : """A decorator that wraps a function in an atomic block . Example : : db = CustomSQLAlchemy ( ) @ db . atomic def f ( ) : write _ to _ db ( ' a message ' ) return ' OK ' assert f ( ) = = ' OK ' This code defines the function ` ` f ` ` , which is wrapped in an atomic bl...
@ wraps ( func ) def wrapper ( * args , ** kwargs ) : session = self . session session_info = session . info if session_info . get ( _ATOMIC_FLAG_SESSION_INFO_KEY ) : return func ( * args , ** kwargs ) f = retry_on_deadlock ( session ) ( func ) session_info [ _ATOMIC_FLAG_SESSION_INFO_KEY ] ...
def can_route ( self , endpoint , method = None , ** kwargs ) : """Make sure we can route to the given endpoint or url . This checks for ` http . get ` permission ( or other methods ) on the ACL of route functions , attached via the ` ACL ` decorator . : param endpoint : A URL or endpoint to check for permiss...
view = flask . current_app . view_functions . get ( endpoint ) if not view : endpoint , args = flask . _request_ctx . top . match ( endpoint ) view = flask . current_app . view_functions . get ( endpoint ) if not view : return False return self . can ( 'http.' + ( method or 'GET' ) . lower ( ) , view , ** k...
def help ( self ) : '''Prints exposed methods and their docstrings .'''
cmds = self . get_exposed_cmds ( ) t = text_helper . Table ( fields = [ 'command' , 'doc' ] , lengths = [ 50 , 85 ] ) return t . render ( ( reflect . formatted_function_name ( x ) , x . __doc__ , ) for x in cmds . values ( ) )
def check_outputs ( self ) : """Check for the existence of output files"""
self . outputs = self . expand_filenames ( self . outputs ) result = False if self . files_exist ( self . outputs ) : if self . dependencies_are_newer ( self . outputs , self . inputs ) : result = True print ( "Dependencies are newer than outputs." ) print ( "Running task." ) elif self ....
def delete ( all = False , * databases ) : '''Remove description snapshots from the system . : : parameter : all . Default : False . Remove all snapshots , if set to True . CLI example : . . code - block : : bash salt myminion inspector . delete < ID > < ID1 > < ID2 > . . salt myminion inspector . delete ...
if not all and not databases : raise CommandExecutionError ( 'At least one database ID required.' ) try : ret = dict ( ) inspector = _ ( "collector" ) . Inspector ( cachedir = __opts__ [ 'cachedir' ] , piddir = os . path . dirname ( __opts__ [ 'pidfile' ] ) ) for dbid in all and inspector . db . list ( ...
def create_token ( self , user ) : """Create a signed token from a user ."""
# The password is expected to be a secure hash but we hash it again # for additional safety . We default to MD5 to minimize the length of # the token . ( Remember , if an attacker obtains the URL , he can already # log in . This isn ' t high security . ) h = crypto . pbkdf2 ( self . get_revocation_key ( user ) , self ....
def add_edge ( self , u , v , ** kwargs ) : """Add an edge between u and v . The nodes u and v will be automatically added if they are not already in the graph Parameters u , v : nodes Nodes can be any hashable Python object . Examples > > > from pgmpy . models import MarkovModel > > > G = MarkovMod...
# check that there is no self loop . if u != v : super ( MarkovModel , self ) . add_edge ( u , v , ** kwargs ) else : raise ValueError ( 'Self loops are not allowed' )
def post_process ( self , layer ) : """More process after getting the impact layer with data . : param layer : The vector layer to use for post processing . : type layer : QgsVectorLayer"""
LOGGER . info ( 'ANALYSIS : Post processing' ) # Set the layer title purpose = layer . keywords [ 'layer_purpose' ] if purpose != layer_purpose_aggregation_summary [ 'key' ] : # On an aggregation layer , the default title does make any sense . layer_title ( layer ) for post_processor in post_processors : run , ...
def open_state_machine ( path = None , recent_opened_notification = False ) : """Open a state machine from respective file system path : param str path : file system path to the state machine : param bool recent _ opened _ notification : flags that indicates that this call also should update recently open : r...
start_time = time . time ( ) if path is None : if interface . open_folder_func is None : logger . error ( "No function defined for opening a folder" ) return load_path = interface . open_folder_func ( "Please choose the folder of the state machine" ) if load_path is None : return els...
def is_intersect ( line_a , line_b ) : """Determine if lina _ a intersect with line _ b : param lina _ a : : type lina _ a : models . Line : param lina _ b : : type line _ b : models . Line : return : : rtype : bool"""
# Find the four orientations needed for general and special cases orientation_1 = orientation ( line_a . endpoint_a , line_a . endpoint_b , line_b . endpoint_a ) orientation_2 = orientation ( line_a . endpoint_a , line_a . endpoint_b , line_b . endpoint_b ) orientation_3 = orientation ( line_b . endpoint_a , line_b . e...
def _import ( self , record_key , record_data , overwrite = True , last_modified = 0.0 , ** kwargs ) : '''a helper method for other storage clients to import into appdata : param record _ key : string with key for record : param record _ data : byte data for body of record : param overwrite : [ optional ] boo...
title = '%s._import' % self . __class__ . __name__ # check overwrite if not overwrite : if self . exists ( record_key ) : return False # check max size import sys record_max = self . fields . metadata [ 'record_max_bytes' ] record_size = sys . getsizeof ( record_data ) error_prefix = '%s(record_key="%s", re...
def get_content_descendants_by_type ( self , content_id , child_type , expand = None , start = None , limit = None , callback = None ) : """Returns the direct descendants of a piece of Content , limited to a single descendant type . The { @ link ContentType } ( s ) of the descendants returned is specified by the ...
params = { } if expand : params [ "expand" ] = expand if start is not None : params [ "start" ] = int ( start ) if limit is not None : params [ "limit" ] = int ( limit ) return self . _service_get_request ( "rest/api/content/{id}/descendant/{type}" "" . format ( id = content_id , type = child_type ) , param...
def DbGetAliasAttribute ( self , argin ) : """Get the attribute name from the given alias . If the given alias is not found in database , returns an empty string : param argin : The attribute alias : type : tango . DevString : return : The attribute name ( dev _ name / att _ name ) : rtype : tango . DevSt...
self . _log . debug ( "In DbGetAliasAttribute()" ) alias_name = argin [ 0 ] return self . db . get_alias_attribute ( alias_name )
def generate_secret_key ( ) : """Generate secret key ."""
import string import random rng = random . SystemRandom ( ) return '' . join ( rng . choice ( string . ascii_letters + string . digits ) for dummy in range ( 0 , 256 ) )
def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_action ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) hide_ext_community_list_holder = ET . SubElement ( ip , "hide-ext-community-list-holder" , xmlns = "urn:brocade.com:mgmt:brocade-ip-policy" ) extcommunity_list = ET . SubElement ( hide_ext_commu...
def construct_api_url ( input , representation , resolvers = None , get3d = False , tautomers = False , xml = True , ** kwargs ) : """Return the URL for the desired API endpoint . : param string input : Chemical identifier to resolve : param string representation : Desired output representation : param list (...
# File formats require representation = file and the format in the querystring if representation in FILE_FORMATS : kwargs [ 'format' ] = representation representation = 'file' # Prepend input with ' tautomers : ' to return all tautomers if tautomers : input = 'tautomers:%s' % input url = '%s/%s/%s' % ( API_...
def h ( self , * args , ** kwargs ) : """This function searches through hkeys for one * containing * a key string supplied by args [ 0 ] and returns that header value . Also can take integers , returning the key ' th header value . kwargs can be specified to set header elements . Finally , if called with no...
# If not arguments , print everything if len ( args ) + len ( kwargs ) == 0 : print ( "Headers" ) for n in range ( len ( self . hkeys ) ) : print ( ' ' + str ( n ) + ': ' + str ( self . hkeys [ n ] ) + ' = ' + repr ( self . h ( n ) ) ) return # first loop over kwargs if there are any to set header ...
def step ( self , step , total , label = 'STEP' , speed_label = 'STEPS/S' , size = 1 ) : """Increase the step indicator , which is a sub progress circle of the actual main progress circle ( epoch , progress ( ) method ) ."""
self . lock . acquire ( ) try : time_diff = time . time ( ) - self . last_step_time if self . last_step > step : # it restarted self . last_step = 0 made_steps_since_last_call = step - self . last_step self . last_step = step self . made_steps_since_last_sync += made_steps_since_last_call ...
def get_default_session ( self ) : """The default session is nothing more than the first session added into the session handler pool . This will likely change in the future but for now each session identifies the domain and also manages domain switching within a single session . : rtype : Session"""
if self . _sessions : return self . get_session ( next ( iter ( self . _sessions ) ) ) return self . get_session ( )