signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _parse_proc_pid_cgroup ( content ) : """Parse a / proc / * / cgroup file into tuples of ( subsystem , cgroup ) . @ param content : An iterable over the lines of the file . @ return : a generator of tuples"""
for ownCgroup in content : # each line is " id : subsystem , subsystem : path " ownCgroup = ownCgroup . strip ( ) . split ( ':' ) try : path = ownCgroup [ 2 ] [ 1 : ] # remove leading / except IndexError : raise IndexError ( "index out of range for " + str ( ownCgroup ) ) for sub...
def joint ( self , table , fields , join_table , join_fields , condition_field , condition_join_field , join_method = 'left_join' ) : """. . : py : method : : Usage : : > > > joint ( ' user ' , ' name , id _ number ' , ' medical _ card ' , ' number ' , ' id ' , ' user _ id ' , ' inner _ join ' ) select u . na...
import string fields = map ( string . strip , fields . split ( ',' ) ) select = ', ' . join ( [ 'u.{}' . format ( field ) for field in fields ] ) join_fields = map ( string . strip , join_fields . split ( ',' ) ) join_select = ', ' . join ( [ 'v.{}' . format ( field ) for field in join_fields ] ) sql = "select {select}...
def _rlimit_min ( one_val , nother_val ) : """Returns the more stringent rlimit value . - 1 means no limit ."""
if one_val < 0 or nother_val < 0 : return max ( one_val , nother_val ) else : return min ( one_val , nother_val )
def Glob2Regex ( glob_pattern ) : """Converts a glob pattern to a regular expression . This function supports basic glob patterns that consist of : * matches everything ? matches any single character [ seq ] matches any character in sequence [ ! seq ] matches any character not in sequence Args : glob ...
if not glob_pattern : raise ValueError ( 'Missing glob pattern.' ) regex_pattern = [ ] glob_pattern_index = 0 glob_pattern_length = len ( glob_pattern ) while glob_pattern_index < glob_pattern_length : character = glob_pattern [ glob_pattern_index ] glob_pattern_index += 1 if character == '*' : ...
def links ( self , r_server = None , mask = None ) : """Get LINKS information . Optional arguments : * r _ server = None - Forward the query to this server . * mask = None - Match mask servers ."""
with self . lock : if not r_server : self . send ( 'LINKS' ) elif not mask and r_server : self . send ( 'LINKS %s' % r_server ) else : self . send ( 'LINKS %s %s' % ( r_server , mask ) ) links = { } while self . readable ( ) : msg = self . _recv ( expected_replies = (...
def graph_to_svg ( graph ) : """Turn a networkx graph into an SVG string , using graphviz dot . Parameters graph : networkx graph Returns svg : string , pictoral layout in SVG format"""
import tempfile import subprocess with tempfile . NamedTemporaryFile ( ) as dot_file : nx . drawing . nx_agraph . write_dot ( graph , dot_file . name ) svg = subprocess . check_output ( [ 'dot' , dot_file . name , '-Tsvg' ] ) return svg
def pts_change_axis ( pts = [ ] , flip = [ False , False ] , offset = [ 0.0 , 0.0 ] ) : '''Return given point with axes flipped and offset , converting points between cartesian axis layouts . For example , SVG Y - axis increases top to bottom but DXF is bottom to top .'''
assert isinstance ( pts , list ) and len ( pts ) > 0 l_pt_prev = None for pt in pts : assert isinstance ( pt , tuple ) l_pt = len ( pt ) assert l_pt > 1 for i in pt : assert isinstance ( i , float ) if l_pt_prev is not None : assert l_pt == l_pt_prev l_pt_prev = l_pt assert isins...
def period_max_neighborhood_probability ( self , threshold , radius , sigmas = None ) : """Calculates the neighborhood probability of exceeding a threshold at any time over the period loaded . Args : threshold ( float ) : splitting threshold for probability calculatations radius ( int ) : distance from point ...
if sigmas is None : sigmas = [ 0 ] weights = disk ( radius ) neighborhood_prob = np . zeros ( self . data . shape [ 2 : ] , dtype = np . float32 ) thresh_data = np . zeros ( self . data . shape [ 2 : ] , dtype = np . uint8 ) for m in range ( self . data . shape [ 0 ] ) : thresh_data [ self . data [ m ] . max ( ...
def horn_sat ( formula ) : """Solving a HORN Sat formula : param formula : list of couple ( posvar , negvars ) . negvars is a list of the negative variables and can be empty . posvar is the positive variable and can be None . Variables can be any hashable objects , as integers or strings for example . :...
# - - - construct data structures CLAUSES = range ( len ( formula ) ) score = [ 0 for c in CLAUSES ] # number of negative vars that are not yet in solution posvar_in_clause = [ None for c in CLAUSES ] # the unique positive variable of a clause ( if any ) clauses_with_negvar = defaultdict ( set ) # all clauses where a v...
def open_output ( self , fname ) : """Open the output file FNAME . Returns tuple ( FD , NEED _ CLOSE ) , where FD is a file ( or file - like ) object , and NEED _ CLOSE is a boolean flag that tells whether FD . close ( ) should be called after finishing writing to the file . FNAME can be one of the three th...
if not fname : return ( sys . stdout , False ) elif isinstance ( fname , str ) : return ( file ( fname , "wb" ) , True ) else : if not hasattr ( fname , "write" ) : raise Exception ( "Expecting either a filename or a file-like object, but got %s" % fname ) return ( fname , False )
def read_registry ( self ) : """Extract resolver configuration from the Windows registry ."""
lm = _winreg . ConnectRegistry ( None , _winreg . HKEY_LOCAL_MACHINE ) want_scan = False try : try : # XP , 2000 tcp_params = _winreg . OpenKey ( lm , r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters' ) want_scan = True except EnvironmentError : # ME tcp_params = _winreg . OpenKe...
def get_plugins ( self , plugin_type = None ) : """Retrieve a list of plugins in the PluginManager . All plugins if no arguments are provides , or of the specified type . : param plugin _ type : list : Types of plugins to retrieve from the plugin manager . : return : Plugins being managed by the Manager ( opt...
if plugin_type is None : return self . plugins . values ( ) plugin_list = [ ] for name , plugin in self . plugins . items ( ) : if isinstance ( plugin , plugin_type if inspect . isclass ( plugin_type ) else type ( plugin_type ) ) : plugin_list . append ( plugin ) return plugin_list
def create ( cls , name , billing_group = None , description = None , tags = None , settings = None , api = None ) : """Create a project . : param name : Project name . : param billing _ group : Project billing group . : param description : Project description . : param tags : Project tags . : param setti...
api = api if api else cls . _API if name is None : raise SbgError ( 'Project name is required!' ) data = { 'name' : name , } if billing_group : data [ 'billing_group' ] = Transform . to_billing_group ( billing_group ) if description : data [ 'description' ] = description if tags : data [ 'tags' ] = tags...
def is_same_host ( self , url ) : """Check if the given ` ` url ` ` is a member of the same host as this conncetion pool ."""
# TODO : Add optional support for socket . gethostbyname checking . return ( url . startswith ( '/' ) or get_host ( url ) == ( self . scheme , self . host , self . port ) )
async def _send_command ( self , command ) : """This is a private utility method . The method sends a non - sysex command to Firmata . : param command : command data : returns : length of data sent"""
send_message = "" for i in command : send_message += chr ( i ) result = None for data in send_message : try : result = await self . write ( data ) except ( ) : if self . log_output : logging . exception ( 'cannot send command' ) else : print ( 'cannot send com...
def findUniques ( mapF ) : """Finds the unique markers in a MAP . : param mapF : representation of a ` ` map ` ` file . : type mapF : list : returns : a : py : class : ` dict ` containing unique markers ( according to their genomic localisation ) ."""
uSNPs = { } dSNPs = defaultdict ( list ) for i , row in enumerate ( mapF ) : chromosome = row [ 0 ] position = row [ 3 ] snpID = ( chromosome , position ) if snpID not in uSNPs : # This is the first time we see this sample uSNPs [ snpID ] = i else : # We have seen this sample at least once ....
def listen ( self ) : """Listen / Connect to message service loop to start receiving messages . Do not include in constructor , in this way it can be included in tasks"""
self . listening = True try : self . service_backend . listen ( ) except AuthenticationError : self . listening = False raise else : self . listening = False
def create ( self , name , search , ** kwargs ) : """Creates a saved search . : param name : The name for the saved search . : type name : ` ` string ` ` : param search : The search query . : type search : ` ` string ` ` : param kwargs : Additional arguments ( optional ) . For a list of available parame...
return Collection . create ( self , name , search = search , ** kwargs )
def _extract_error ( self , resp ) : """Extract the actual error message from a solr response ."""
reason = resp . headers . get ( 'reason' , None ) full_response = None if reason is None : try : # if response is in json format reason = resp . json ( ) [ 'error' ] [ 'msg' ] except KeyError : # if json response has unexpected structure full_response = resp . content except ValueError : # o...
def assert_results_contain ( check_results , expected_status , expected_msgcode = None ) : """This helper function is useful when we want to make sure that a certain log message is emited by a check but it can be in any order among other log messages ."""
found = False for status , message in check_results : if status == expected_status and message . code == expected_msgcode : found = True break assert ( found )
def apply_numpy_specials ( self , copy = True ) : """Convert isis special pixel values to numpy special pixel values . Isis Numpy Null nan Lrs - inf Lis - inf His inf Hrs inf Parameters copy : bool [ True ] Whether to apply the new special values to a copy of the pixel data and leave the origina...
if copy : data = self . data . astype ( numpy . float64 ) elif self . data . dtype != numpy . float64 : data = self . data = self . data . astype ( numpy . float64 ) else : data = self . data data [ data == self . specials [ 'Null' ] ] = numpy . nan data [ data < self . specials [ 'Min' ] ] = numpy . NINF d...
def setenv ( name , value , false_unsets = False , clear_all = False , update_minion = False , permanent = False ) : '''Set the salt process environment variables . name The environment key to set . Must be a string . value Either a string or dict . When string , it will be the value set for the environme...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } environ = { } if isinstance ( value , six . string_types ) or value is False : environ [ name ] = value elif isinstance ( value , dict ) : environ = value else : ret [ 'result' ] = False ret [ 'comment' ] = 'Environ value must ...
def close ( self , * args , ** kwds ) : """Close database ."""
self . cur . close ( ) self . commit ( ) self . DB . close ( )
def bitswap_wantlist ( self , peer = None , ** kwargs ) : """Returns blocks currently on the bitswap wantlist . . . code - block : : python > > > c . bitswap _ wantlist ( ) { ' Keys ' : [ ' QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb ' , ' QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7MtCm7nTZZE9K ' , ' QmVQ1XvY...
args = ( peer , ) return self . _client . request ( '/bitswap/wantlist' , args , decoder = 'json' , ** kwargs )
def bypass ( * inputs , copy = False ) : """Returns the same arguments . : param inputs : Inputs values . : type inputs : T : param copy : If True , it returns a deepcopy of input values . : type copy : bool , optional : return : Same input values . : rtype : ( T , . . . ) , T Example : : > > ...
if len ( inputs ) == 1 : inputs = inputs [ 0 ] # Same inputs . return _copy . deepcopy ( inputs ) if copy else inputs
def verify_state ( self ) : """Verify if session was not yet opened . If it is , open it and call connections ` on _ open `"""
if self . state == CONNECTING : self . state = OPEN self . conn . on_open ( self . conn_info )
def write ( self , name , ** data ) : """Write the metric to elasticsearch Args : name ( str ) : The name of the metric to write data ( dict ) : Additional data to store with the metric"""
data [ "name" ] = name if not ( "timestamp" in data ) : data [ "timestamp" ] = datetime . utcnow ( ) try : self . client . index ( index = self . get_index ( ) , doc_type = self . doc_type , id = None , body = data ) except TransportError as exc : logger . warning ( 'writing metric %r failure %r' , data , e...
def get_form_data ( chart_id , dashboard = None ) : """Build ` form _ data ` for chart GET request from dashboard ' s ` default _ filters ` . When a dashboard has ` default _ filters ` they need to be added as extra filters in the GET request for charts ."""
form_data = { 'slice_id' : chart_id } if dashboard is None or not dashboard . json_metadata : return form_data json_metadata = json . loads ( dashboard . json_metadata ) # do not apply filters if chart is immune to them if chart_id in json_metadata . get ( 'filter_immune_slices' , [ ] ) : return form_data defau...
def p_enumerated_subtype_field ( self , p ) : 'subtype _ field : ID type _ ref NL'
p [ 0 ] = AstSubtypeField ( self . path , p . lineno ( 1 ) , p . lexpos ( 1 ) , p [ 1 ] , p [ 2 ] )
def contains_regex ( path , regex , lchar = '' ) : '''. . deprecated : : 0.17.0 Use : func : ` search ` instead . Return True if the given regular expression matches on any line in the text of a given file . If the lchar argument ( leading char ) is specified , it will strip ` lchar ` from the left side o...
path = os . path . expanduser ( path ) if not os . path . exists ( path ) : return False try : with salt . utils . files . fopen ( path , 'r' ) as target : for line in target : line = salt . utils . stringutils . to_unicode ( line ) if lchar : line = line . lstrip...
def enforce_cf_variable ( var , mask_and_scale = True ) : """Given a Variable constructed from GEOS - Chem output , enforce CF - compliant metadata and formatting . Until a bug with lazily - loaded data and masking / scaling is resolved in xarray , you have the option to manually mask and scale the data here ...
var = as_variable ( var ) data = var . _data # avoid loading by accessing _ data instead of data dims = var . dims attrs = var . attrs . copy ( ) encoding = var . encoding . copy ( ) orig_dtype = data . dtype # Process masking / scaling coordinates . We only expect a " scale " value # for the units with this output . i...
def api ( server , command , * args , ** kwargs ) : '''Call the Spacewalk xmlrpc api . CLI Example : . . code - block : : bash salt - run spacewalk . api spacewalk01 . domain . com systemgroup . create MyGroup Description salt - run spacewalk . api spacewalk01 . domain . com systemgroup . create arguments =...
if 'arguments' in kwargs : arguments = kwargs [ 'arguments' ] else : arguments = args call = '{0} {1}' . format ( command , arguments ) try : client , key = _get_session ( server ) except Exception as exc : err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}' . format ( server , e...
def _send ( self , message ) : """Send an email . Helper method that does the actual sending ."""
if not message . recipients ( ) : return False try : self . connection . sendmail ( message . sender , message . recipients ( ) , message . message ( ) . as_string ( ) , ) except Exception as e : logger . error ( "Error sending a message to server %s:%s: %s" , self . host , self . port , e , ) if not se...
def cmd_xor ( k , i , o ) : """XOR cipher . Note : XOR is not a ' secure cipher ' . If you need strong crypto you must use algorithms like AES . You can use habu . fernet for that . Example : $ habu . xor - k mysecretkey - i / bin / ls > xored $ habu . xor - k mysecretkey - i xored > uxored $ sha1sum / ...
o . write ( xor ( i . read ( ) , k . encode ( ) ) )
def validate_password_reset ( cls , code , new_password ) : """Validates an unhashed code against a hashed code . Once the code has been validated and confirmed new _ password will replace the old users password"""
password_reset_model = PasswordResetModel . where_code ( code ) if password_reset_model is None : return None jwt = JWT ( ) if jwt . verify_token ( password_reset_model . token ) : user = cls . where_id ( jwt . data [ 'data' ] [ 'user_id' ] ) if user is not None : user . set_password ( new_password ...
def filter_queryset ( self , request , queryset , view ) : """This method overrides the standard filter _ queryset method . This method will check to see if the view calling this is from a list type action . This function will also route the filter by action type if action _ routing is set to True ."""
# Check if this is a list type request if view . lookup_field not in view . kwargs : if not self . action_routing : return self . filter_list_queryset ( request , queryset , view ) else : method_name = "filter_{action}_queryset" . format ( action = view . action ) return getattr ( self ,...
def save ( self , * args , ** kwargs ) : """Clean text and save formatted version ."""
self . text = clean_text ( self . text ) self . text_formatted = format_text ( self . text ) super ( BaseUserContentModel , self ) . save ( * args , ** kwargs )
def guest_resize_cpus ( self , userid , cpu_cnt ) : """Resize virtual cpus of guests . : param userid : ( str ) the userid of the guest to be resized : param cpu _ cnt : ( int ) The number of virtual cpus that the guest should have defined in user directory after resize . The value should be an integer betw...
action = "resize guest '%s' to have '%i' virtual cpus" % ( userid , cpu_cnt ) LOG . info ( "Begin to %s" % action ) with zvmutils . log_and_reraise_sdkbase_error ( action ) : self . _vmops . resize_cpus ( userid , cpu_cnt ) LOG . info ( "%s successfully." % action )
def get_subscriptions ( self , publication_id = None , owner_id = None , since_when = None , limit_to = 200 , max_calls = None , start_record = 0 , verbose = False ) : """Fetches all subscriptions from Membersuite of a particular ` publication _ id ` if set ."""
query = "SELECT Objects() FROM Subscription" # collect all where parameters into a list of # ( key , operator , value ) tuples where_params = [ ] if owner_id : where_params . append ( ( 'owner' , '=' , "'%s'" % owner_id ) ) if publication_id : where_params . append ( ( 'publication' , '=' , "'%s'" % publication...
def insert_many ( self , rows , chunk_size = 1000 ) : """Add many rows at a time , which is significantly faster than adding them one by one . Per default the rows are processed in chunks of 1000 per commit , unless you specify a different ` ` chunk _ size ` ` . See : py : meth : ` insert ( ) < dataset . Tabl...
def _process_chunk ( chunk ) : self . table . insert ( ) . execute ( chunk ) self . _check_dropped ( ) chunk = [ ] for i , row in enumerate ( rows , start = 1 ) : chunk . append ( row ) if i % chunk_size == 0 : _process_chunk ( chunk ) chunk = [ ] if chunk : _process_chunk ( chunk )
def make_install_requirement ( name , version , extras , markers , constraint = False ) : """Generates an : class : ` ~ pip . _ internal . req . req _ install . InstallRequirement ` . Create an InstallRequirement from the supplied metadata . : param name : The requirement ' s name . : type name : str : para...
# If no extras are specified , the extras string is blank from pip_shims . shims import install_req_from_line extras_string = "" if extras : # Sort extras for stability extras_string = "[{}]" . format ( "," . join ( sorted ( extras ) ) ) if not markers : return install_req_from_line ( str ( "{}{}=={}" . format ...
def _safe_sparse_mask ( tensor : torch . Tensor , mask : torch . Tensor ) -> torch . Tensor : """In PyTorch 1.0 , Tensor . _ sparse _ mask was changed to Tensor . sparse _ mask . This wrapper allows AllenNLP to ( temporarily ) work with both 1.0 and 0.4.1."""
# pylint : disable = protected - access try : return tensor . sparse_mask ( mask ) except AttributeError : # TODO ( joelgrus ) : remove this and / or warn at some point return tensor . _sparse_mask ( mask )
def initialize ( self , stormconf , context ) : """Initialization steps : 1 . Prepare sequence of terms based on config : TermCycleSpout / terms ."""
self . terms = get_config ( ) [ 'TermCycleSpout' ] [ 'terms' ] self . term_seq = itertools . cycle ( self . terms )
def get_iss_serial_no ( self ) : """Get serial number of USB - ISS module"""
self . write_data ( [ self . ISS_CMD , self . ISS_SER_NUM ] ) # Return 8 bytes serial number self . iss_sn = self . read_data ( 8 )
def _ProcessHistogram ( self , tag , wall_time , step , histo ) : """Processes a proto histogram by adding it to accumulated state ."""
histo = self . _ConvertHistogramProtoToTuple ( histo ) histo_ev = HistogramEvent ( wall_time , step , histo ) self . histograms . AddItem ( tag , histo_ev ) self . compressed_histograms . AddItem ( tag , histo_ev , self . _CompressHistogram )
def privateKeyToAccount ( self , private_key ) : '''Returns a convenient object for working with the given private key . : param private _ key : The raw private key : type private _ key : hex str , bytes , int or : class : ` eth _ keys . datatypes . PrivateKey ` : return : object with methods for signing and ...
key = self . _parsePrivateKey ( private_key ) return LocalAccount ( key , self )
def rate_matrix ( C , dt = 1.0 , method = 'KL' , sparsity = None , t_agg = None , pi = None , tol = 1.0E7 , K0 = None , maxiter = 100000 , on_error = 'raise' ) : r"""Estimate a reversible rate matrix from a count matrix . Parameters C : ( N , N ) ndarray count matrix at a lag time dt dt : float , optional ,...
from . dense . ratematrix import estimate_rate_matrix return estimate_rate_matrix ( C , dt = dt , method = method , sparsity = sparsity , t_agg = t_agg , pi = pi , tol = tol , K0 = K0 , maxiter = maxiter , on_error = on_error )
def surface_state ( num_lat = 90 , num_lon = None , water_depth = 10. , T0 = 12. , T2 = - 40. ) : """Sets up a state variable dictionary for a surface model ( e . g . : class : ` ~ climlab . model . ebm . EBM ` ) with a uniform slab ocean depth . The domain is either 1D ( latitude ) or 2D ( latitude , longitude...
if num_lon is None : sfc = domain . zonal_mean_surface ( num_lat = num_lat , water_depth = water_depth ) else : sfc = domain . surface_2D ( num_lat = num_lat , num_lon = num_lon , water_depth = water_depth ) if 'lon' in sfc . axes : lon , lat = np . meshgrid ( sfc . axes [ 'lon' ] . points , sfc . axes [ 'l...
def rmdir ( path ) : """Recursively deletes a directory . Includes an error handler to retry with different permissions on Windows . Otherwise , removing directories ( eg . cloned via git ) can cause rmtree to throw a PermissionError exception"""
logger . debug ( "DEBUG** Window rmdir sys.platform: {}" . format ( sys . platform ) ) if sys . platform == 'win32' : onerror = _windows_rmdir_readonly else : onerror = None return shutil . rmtree ( path , onerror = onerror )
def salt_syndic ( ) : '''Start the salt syndic .'''
import salt . utils . process salt . utils . process . notify_systemd ( ) import salt . cli . daemons pid = os . getpid ( ) try : syndic = salt . cli . daemons . Syndic ( ) syndic . start ( ) except KeyboardInterrupt : os . kill ( pid , 15 )
def max_electronegativity ( self ) : '''returns the maximum pairwise electronegativity difference'''
maximum = 0 for e1 , e2 in combinations ( self . elements , 2 ) : if abs ( Element ( e1 ) . X - Element ( e2 ) . X ) > maximum : maximum = abs ( Element ( e1 ) . X - Element ( e2 ) . X ) return maximum
def _check_and_assign_normalization_members ( self , normalization_ctor , normalization_kwargs ) : """Checks that the normalization constructor is callable ."""
if isinstance ( normalization_ctor , six . string_types ) : normalization_ctor = util . parse_string_to_constructor ( normalization_ctor ) if normalization_ctor is not None and not callable ( normalization_ctor ) : raise ValueError ( "normalization_ctor must be a callable or a string that specifies " "a callabl...
def parse_references ( cls , filename ) : """Read filename line by line searching for pattern : - r file . in or - - requirement file . in return set of matched file names without extension . E . g . [ ' file ' ]"""
references = set ( ) for line in open ( filename ) : matched = cls . RE_REF . match ( line ) if matched : reference = matched . group ( 'path' ) reference_base = os . path . splitext ( reference ) [ 0 ] references . add ( reference_base ) return references
def update_info ( user_id , newemail , extinfo = None ) : '''Update the user info by user _ id . 21 : standsfor invalide E - mail . 91 : standsfor unkown reson .'''
if extinfo is None : extinfo = { } out_dic = { 'success' : False , 'code' : '00' } if not tools . check_email_valid ( newemail ) : out_dic [ 'code' ] = '21' return out_dic cur_info = MUser . get_by_uid ( user_id ) cur_extinfo = cur_info . extinfo for key in extinfo : cur_extinfo [ key ] = extinfo [ key ...
def get_urls ( session , name , data , find_changelogs_fn , ** kwargs ) : """Gets URLs to changelogs . : param session : requests Session instance : param name : str , package name : param data : dict , meta data : param find _ changelogs _ fn : function , find _ changelogs : return : tuple , ( set ( chan...
# if this package has valid meta data , build up a list of URL candidates we can possibly # search for changelogs on if "versions" in data : candidates = set ( ) for version , item in data [ "versions" ] . items ( ) : if "homepage" in item and item [ "homepage" ] is not None : if isinstance ...
def addldapgrouplink ( self , group_id , cn , group_access , provider ) : """Add LDAP group link : param id : The ID of a group : param cn : The CN of a LDAP group : param group _ access : Minimum access level for members of the LDAP group : param provider : LDAP provider for the LDAP group ( when using sev...
data = { 'id' : group_id , 'cn' : cn , 'group_access' : group_access , 'provider' : provider } request = requests . post ( '{0}/{1}/ldap_group_links' . format ( self . groups_url , group_id ) , headers = self . headers , data = data , verify = self . verify_ssl ) return request . status_code == 201
def parse_task_declaration ( self , declaration_subAST ) : '''Parses the declaration section of the WDL task AST subtree . Examples : String my _ name String your _ name Int two _ chains _ i _ mean _ names = 0 : param declaration _ subAST : Some subAST representing a task declaration like : ' String fil...
var_name = self . parse_declaration_name ( declaration_subAST . attr ( "name" ) ) var_type = self . parse_declaration_type ( declaration_subAST . attr ( "type" ) ) var_expressn = self . parse_declaration_expressn ( declaration_subAST . attr ( "expression" ) , es = '' ) return ( var_name , var_type , var_expressn )
def make_constrained_cfg_and_lbl_list ( varied_dict , constraint_func = None , slice_dict = None , defaultslice = slice ( 0 , 1 ) ) : r"""Args : varied _ dict ( dict ) : parameters to vary with possible variations constraint _ func ( func ) : function to restirct parameter variations slice _ dict ( dict ) : d...
# Restrict via slices if slice_dict is None : varied_dict_ = varied_dict else : varied_dict_ = { key : val [ slice_dict . get ( key , defaultslice ) ] for key , val in six . iteritems ( varied_dict ) } # Enumerate all combinations cfgdict_list_ = util_dict . all_dict_combinations ( varied_dict_ ) if constraint_...
def datetimes ( self ) : """Return datetimes for this collection as a tuple ."""
if self . _datetimes is None : self . _datetimes = tuple ( self . header . analysis_period . datetimes ) return self . _datetimes
def register_json ( ) : """Register a encoder / decoder for JSON serialization ."""
from anyjson import serialize as json_serialize from anyjson import deserialize as json_deserialize registry . register ( 'json' , json_serialize , json_deserialize , content_type = 'application/json' , content_encoding = 'utf-8' )
async def zmq_ipc_pipe_end ( ctx , side , endpoint , * , serializer : Optional [ Serializer ] = None , initialize = True ) : """Returns a ` ZmqPipeEnd ` backed by an ` ipc ` connection ; the endpoint must contain the scheme part . If both ends of the connection are created on the same thread / task , to avoid a d...
if side == 'a' : result = ZmqPipeEnd ( ctx , zmq . ROUTER , endpoint , port = None , bind = True , serializer = serializer ) elif side == 'b' : result = ZmqPipeEnd ( ctx , zmq . DEALER , endpoint , port = None , serializer = serializer ) else : raise ValueError ( "side must be 'a' or 'b'" ) if initialize : ...
def rebase ( self , text , char = 'X' ) : """Rebases text with stop words removed ."""
regexp = re . compile ( r'\b(%s)\b' % '|' . join ( self . collection ) , re . IGNORECASE | re . UNICODE ) def replace ( m ) : word = m . group ( 1 ) return char * len ( word ) return regexp . sub ( replace , text )
def _jzerostr ( ins ) : """Jumps if top of the stack contains a NULL pointer or its len is Zero"""
output = [ ] disposable = False # True if string must be freed from memory if ins . quad [ 1 ] [ 0 ] == '_' : # Variable ? output . append ( 'ld hl, (%s)' % ins . quad [ 1 ] [ 0 ] ) else : output . append ( 'pop hl' ) output . append ( 'push hl' ) # Saves it for later disposable = True output . appe...
def dump_string_to_file ( string , filepath ) : """Dump @ string as a line to @ filepath ."""
create_dirs ( os . path . dirname ( filepath ) ) with open ( filepath , 'a' ) as outfile : outfile . write ( string ) outfile . write ( '\n' )
def xcode ( text , encoding = 'utf8' , mode = 'ignore' ) : '''Converts unicode encoding to str > > > xcode ( b ' hello ' ) b ' hello ' > > > xcode ( ' hello ' ) b ' hello ' '''
return text . encode ( encoding , mode ) if isinstance ( text , str ) else text
def get_profile_configs ( profile = None , use_cache = True ) : """Returns upload configs for profile ."""
if use_cache and profile in _profile_configs_cache : return _profile_configs_cache [ profile ] profile_conf = None if profile is not None : try : profile_conf = dju_settings . DJU_IMG_UPLOAD_PROFILES [ profile ] except KeyError : if profile != 'default' : raise ValueError ( unico...
def pretty_print_config_to_json ( self , services , hostname = None ) : """JSON string description of a protorpc . remote . Service in API format . Args : services : Either a single protorpc . remote . Service or a list of them that implements an api / version . hostname : string , Hostname of the API , to ...
descriptor = self . get_config_dict ( services , hostname ) return json . dumps ( descriptor , sort_keys = True , indent = 2 , separators = ( ',' , ': ' ) )
def create ( self , ** kwargs ) : """Create a notification ."""
body = self . client . create ( url = self . base_url , json = kwargs ) return body
def get_compound_bodies ( node ) : """Returns a list of bodies of a compound statement node . Args : node : AST node . Returns : A list of bodies of the node . If the given node does not represent a compound statement , an empty list is returned ."""
if isinstance ( node , ( ast . Module , ast . FunctionDef , ast . ClassDef , ast . With ) ) : return [ node . body ] elif isinstance ( node , ( ast . If , ast . While , ast . For ) ) : return [ node . body , node . orelse ] elif PY2 and isinstance ( node , ast . TryFinally ) : return [ node . body , node . ...
def match ( self , cond , node ) : """See Also : : py : meth : ` IMatcher . match < poco . sdk . DefaultMatcher . IMatcher . match > `"""
op , args = cond # 条件匹配 if op == 'and' : for arg in args : if not self . match ( arg , node ) : return False return True if op == 'or' : for arg in args : if self . match ( arg , node ) : return True return False # 属性匹配 comparator = self . comparators . get ( op )...
def p_delays ( self , p ) : 'delays : DELAY LPAREN expression RPAREN'
p [ 0 ] = DelayStatement ( p [ 3 ] , lineno = p . lineno ( 1 ) ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def save_fileAs ( self ) : """Saves current * * Script _ Editor _ tabWidget * * Widget tab Model editor file as user chosen file . : return : Method success . : rtype : bool"""
editor = self . get_current_editor ( ) if not editor : return False file = umbra . ui . common . store_last_browsed_path ( QFileDialog . getSaveFileName ( self , "Save As:" , editor . file ) ) if not file : return False candidate_editor = self . get_editor ( file ) if candidate_editor : if not candidate_edi...
def _update_parent_attachments ( self ) : """Tries to update the parent property ' has _ attachments '"""
try : self . _parent . has_attachments = bool ( len ( self . __attachments ) ) except AttributeError : pass
def _run ( self , url , auth ) : '''Performs a multiprocess depth - first - search of the catalog references and yields a URL for each leaf dataset found : param str url : URL for the current catalog : param requests . auth . AuthBase auth : requets auth object to use'''
if url in self . visited : logger . debug ( "Skipping %s (already crawled)" % url ) return self . visited . append ( url ) logger . info ( "Crawling: %s" % url ) url = self . _get_catalog_url ( url ) # Get an etree object xml_content = request_xml ( url , auth ) for ds in self . _build_catalog ( url , xml_conte...
def format_exp_floats ( decimals ) : """sometimes the exp . column can be too large"""
threshold = 10 ** 5 return ( lambda n : "{:.{prec}e}" . format ( n , prec = decimals ) if n > threshold else "{:4.{prec}f}" . format ( n , prec = decimals ) )
def intern ( self , text ) : """Interns the given Unicode sequence into the symbol table . Note : This operation is only valid on local symbol tables . Args : text ( unicode ) : The target to intern . Returns : SymbolToken : The mapped symbol token which may already exist in the table ."""
if self . table_type . is_shared : raise TypeError ( 'Cannot intern on shared symbol table' ) if not isinstance ( text , six . text_type ) : raise TypeError ( 'Cannot intern non-Unicode sequence into symbol table: %r' % text ) token = self . get ( text ) if token is None : token = self . __add_text ( text )...
def immediateAssignmentReject ( ) : """IMMEDIATE ASSIGNMENT REJECT Section 9.1.20"""
a = L2PseudoLength ( l2pLength = 0x13 ) b = TpPd ( pd = 0x6 ) c = MessageType ( mesType = 0x3a ) # 00111010 d = PageModeAndSpareHalfOctets ( ) f = RequestReference ( ) g = WaitIndication ( ) h = RequestReference ( ) i = WaitIndication ( ) j = RequestReference ( ) k = WaitIndication ( ) l = RequestReference ( ) m = Wait...
def _loadSCPD ( self , serviceType , timeout ) : """Internal method to load the action definitions . : param str serviceType : the service type to load : param int timeout : the timeout for downloading"""
if serviceType not in self . __deviceServiceDefinitions . keys ( ) : raise ValueError ( "Can not load SCPD, no service type defined for: " + serviceType ) if "scpdURL" not in self . __deviceServiceDefinitions [ serviceType ] . keys ( ) : raise ValueError ( "No SCPD URL defined for: " + serviceType ) # remove ac...
def list_nodes ( kwargs = None , call = None ) : """This function returns a list of nodes available on this cloud provider , using the following fields : id ( str ) image ( str ) size ( str ) state ( str ) private _ ips ( list ) public _ ips ( list ) No other fields should be returned in this function...
if call == 'action' : raise SaltCloudSystemExit ( 'The list_nodes function must be called ' 'with -f or --function.' ) attributes = [ "id" , "image" , "size" , "state" , "private_ips" , "public_ips" , ] return __utils__ [ 'cloud.list_nodes_select' ] ( list_nodes_full ( 'function' ) , attributes , call , )
def _check_dn ( self , dn , attr_value ) : """Check dn attribute for issues ."""
if dn is not None : self . _error ( 'Two lines starting with dn: in one record.' ) if not is_dn ( attr_value ) : self . _error ( 'No valid string-representation of ' 'distinguished name %s.' % attr_value )
def inherit_docstring_from ( cls ) : """This decorator modifies the decorated function ' s docstring by replacing occurrences of ' % ( super ) s ' with the docstring of the method of the same name from the class ` cls ` . If the decorated method has no docstring , it is simply given the docstring of cls met...
def _doc ( func ) : cls_docstring = getattr ( cls , func . __name__ ) . __doc__ func_docstring = func . __doc__ if func_docstring is None : func . __doc__ = cls_docstring else : new_docstring = func_docstring % dict ( super = cls_docstring ) func . __doc__ = new_docstring ret...
def brent_kung_add ( A , B , cin = 0 ) : """Return symbolic logic for an N - bit Brent - Kung adder ."""
if len ( A ) != len ( B ) : raise ValueError ( "expected A and B to be equal length" ) N = len ( A ) # generate / propagate logic gs = [ A [ i ] & B [ i ] for i in range ( N ) ] ps = [ A [ i ] ^ B [ i ] for i in range ( N ) ] # carry tree for i in range ( floor ( log ( N , 2 ) ) ) : step = 2 ** i for start ...
def pick ( self , starting_node = None ) : """Pick a node on the graph based on the links in a starting node . Additionally , set ` ` self . current _ node ` ` to the newly picked node . * if ` ` starting _ node ` ` is specified , start from there * if ` ` starting _ node ` ` is ` ` None ` ` , start from ` ` ...
if starting_node is None : if self . current_node is None : random_node = random . choice ( self . node_list ) self . current_node = random_node return random_node else : starting_node = self . current_node # Use weighted _ choice on start _ node . link _ list self . current_node...
def copy_from_csv_sql ( qualified_name : str , delimiter = ',' , encoding = 'utf8' , null_str = '' , header = True , escape_str = '\\' , quote_char = '"' , force_not_null = None , force_null = None ) : """Generate copy from csv statement ."""
options = [ ] options . append ( "DELIMITER '%s'" % delimiter ) options . append ( "NULL '%s'" % null_str ) if header : options . append ( 'HEADER' ) options . append ( "QUOTE '%s'" % quote_char ) options . append ( "ESCAPE '%s'" % escape_str ) if force_not_null : options . append ( _format_force_not_null ( col...
def entity ( ctx , debug , uncolorize , ** kwargs ) : """CLI for tonomi . com using contrib - python - qubell - client To enable completion : eval " $ ( _ NOMI _ COMPLETE = source nomi ) " """
global PROVIDER_CONFIG if debug : log . basicConfig ( level = log . DEBUG ) log . getLogger ( "requests.packages.urllib3.connectionpool" ) . setLevel ( log . DEBUG ) for ( k , v ) in kwargs . iteritems ( ) : if v : QUBELL [ k ] = v PROVIDER_CONFIG = { 'configuration.provider' : PROVIDER [ 'provider_...
def _check_intemediate ( self , myntr , maxstate ) : """For each state Apq which is a known terminal , this function searches for rules Apr - > Apq Aqr and Arq - > Arp Apq where Aqr is also a known terminal or Arp is also a known terminal . It is mainly used as an optimization in order to avoid the O ( n ^ 3)...
# print ' BFS Dictionary Update - Intermediate ' x_term = myntr . rfind ( '@' ) y_term = myntr . rfind ( 'A' ) if y_term > x_term : x_term = y_term ids = myntr [ x_term + 1 : ] . split ( ',' ) if len ( ids ) < 2 : return 0 i = ids [ 0 ] j = ids [ 1 ] r = 0 find = 0 while r < maxstate : if r != i and r != j ...
def flexifunction_command_send ( self , target_system , target_component , command_type , force_mavlink1 = False ) : '''Acknowldge sucess or failure of a flexifunction command target _ system : System ID ( uint8 _ t ) target _ component : Component ID ( uint8 _ t ) command _ type : Flexifunction command type ...
return self . send ( self . flexifunction_command_encode ( target_system , target_component , command_type ) , force_mavlink1 = force_mavlink1 )
def setitem_without_overwrite ( d , key , value ) : """@ param d : An instance of dict , that is : isinstance ( d , dict ) @ param key : a key @ param value : a value to associate with the key @ return : None @ raise : OverwriteError if the key is already present in d ."""
if key in d : raise OverwriteError ( key , value , d [ key ] ) else : dict . __setitem__ ( d , key , value )
def get_states ( self , devices ) : """Get States of Devices ."""
header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie json_data = self . _create_get_state_request ( devices ) request = requests . post ( BASE_URL + 'getStates' , headers = header , data = json_data , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) ...
async def container_dump ( self , container , container_type , params = None ) : """Dumps container of elements to the writer . : param writer : : param container : : param container _ type : : param params : : param field _ archiver : : return :"""
await self . container_size ( len ( container ) , container_type , params ) elem_type = x . container_elem_type ( container_type , params ) for idx , elem in enumerate ( container ) : try : self . tracker . push_index ( idx ) await self . _dump_field ( elem , elem_type , params [ 1 : ] if params els...
def oauth2callback ( self , view_func ) : """Decorator for OAuth2 callback . Calls ` GoogleLogin . login ` then passes results to ` view _ func ` ."""
@ wraps ( view_func ) def decorated ( * args , ** kwargs ) : params = { } # Check sig if 'state' in request . args : params . update ( ** self . parse_state ( request . args . get ( 'state' ) ) ) if params . pop ( 'sig' , None ) != make_secure_token ( ** params ) : return self . ...
def parse_event_xml ( xml_event ) : """Parse the body of a UPnP event . Args : xml _ event ( bytes ) : bytes containing the body of the event encoded with utf - 8. Returns : dict : A dict with keys representing the evented variables . The relevant value will usually be a string representation of the v...
result = { } tree = XML . fromstring ( xml_event ) # property values are just under the propertyset , which # uses this namespace properties = tree . findall ( '{urn:schemas-upnp-org:event-1-0}property' ) for prop in properties : # pylint : disable = too - many - nested - blocks for variable in prop : # Special han...
def loads ( s , ** kwargs ) : """Loads JSON object ."""
try : return _engine [ 0 ] ( s ) except _engine [ 2 ] : # except _ clause : ' except ' [ test [ ' as ' NAME ] ] # grammar for py3x # except _ clause : ' except ' [ test [ ( ' as ' | ' , ' ) test ] ] # grammar for py2x why = sys . exc_info ( ) [ 1 ] raise JSONError ( why )
def cut_segments ( x2d , tr , start , stop ) : """Cut continuous signal into segments . Parameters x2d : array , shape ( m , n ) Input data with m signals and n samples . tr : list of int Trigger positions . start : int Window start ( offset relative to trigger ) . stop : int Window end ( offset r...
if start != int ( start ) : raise ValueError ( "start index must be an integer" ) if stop != int ( stop ) : raise ValueError ( "stop index must be an integer" ) x2d = np . atleast_2d ( x2d ) tr = np . asarray ( tr , dtype = int ) . ravel ( ) win = np . arange ( start , stop , dtype = int ) return np . concatena...
def get_metrics ( self ) : """Retrieve the current metric values for this : term : ` Metrics Context ` resource from the HMC . The metric values are returned by this method as a string in the ` MetricsResponse ` format described with the ' Get Metrics ' operation in the : term : ` HMC API ` book . The : c...
metrics_response = self . manager . session . get ( self . uri ) return metrics_response
def get_aliasing ( * extra ) : """The assembles the dict mapping strings and functions to the list of supported function names : e . g . alias [ ' add ' ] = ' sum ' and alias [ sorted ] = ' sort ' This funciton should only be called during import ."""
alias = dict ( ( k , k ) for k in funcs_common ) alias . update ( _alias_str ) alias . update ( ( fn , fn ) for fn in _alias_builtin . values ( ) ) alias . update ( _alias_builtin ) for d in extra : alias . update ( d ) alias . update ( ( k , k ) for k in set ( alias . values ( ) ) ) # Treat nan - functions as firs...
def rstyle ( self , name ) : """Remove one style"""
try : del self . chart_style [ name ] except KeyError : self . warning ( "Style " + name + " is not set" ) except : self . err ( "Can not remove style " + name )
def apply ( self , query , data ) : """Filter a query ."""
field = self . model_field or query . model_class . _meta . fields . get ( self . name ) if not field or self . name not in data : return query value = self . value ( data ) if value is self . default : return query value = field . db_value ( value ) return self . filter_query ( query , field , value )
def version ( context = None ) : '''Attempts to run systemctl - - version . Returns None if unable to determine version .'''
contextkey = 'salt.utils.systemd.version' if isinstance ( context , dict ) : # Can ' t put this if block on the same line as the above if block , # because it will break the elif below . if contextkey in context : return context [ contextkey ] elif context is not None : raise SaltInvocationError ( 'cont...
def prox_dca ( x , f , g , niter , gamma , callback = None ) : r"""Proximal DCA of Sun , Sampaio and Candido . This algorithm solves a problem of the form : : min _ x f ( x ) - g ( x ) where ` ` f ` ` and ` ` g ` ` are two proper , convex and lower semicontinuous functions . Parameters x : ` LinearSpace...
space = f . domain if g . domain != space : raise ValueError ( '`f.domain` and `g.domain` need to be equal, but ' '{} != {}' . format ( space , g . domain ) ) for _ in range ( niter ) : f . proximal ( gamma ) ( x . lincomb ( 1 , x , gamma , g . gradient ( x ) ) , out = x ) if callback is not None : ...