signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def update_docs ( self , t , module ) : """Updates the documentation for the specified type using the module predocs ."""
# We need to look in the parent module docstrings for this types decorating tags . key = "{}.{}" . format ( module . name , t . name ) if key in module . predocs : t . docstring = self . docparser . to_doc ( module . predocs [ key ] [ 0 ] , t . name ) t . docstart , t . docend = ( module . predocs [ key ] [ 1 ]...
def resource_url ( self , entity_id , name , revision ) : '''Return the resource url for a given resource on an entity . @ param entity _ id The id of the entity to get resource for . @ param name The name of the resource . @ param revision The revision of the resource .'''
return '{}/{}/resource/{}/{}' . format ( self . url , _get_path ( entity_id ) , name , revision )
def get_assessment_taken_mdata ( ) : """Return default mdata map for AssessmentTaken"""
return { 'assessment_offered' : { 'element_label' : { 'text' : 'assessment offered' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'accepts an osid.id.Id object' , 'languageTypeId' : str (...
def xyz ( self ) : """: returns : an array of shape ( N , 3 ) with the cartesian coordinates"""
return geo_utils . spherical_to_cartesian ( self . lons . flat , self . lats . flat , self . depths . flat )
def exists ( self , vars_list : List [ str ] ) -> 'TensorFluent' : '''Returns the TensorFluent for the exists aggregation function . Args : vars _ list : The list of variables to be aggregated over . Returns : A TensorFluent wrapping the exists aggregation function .'''
return self . _aggregation_op ( tf . reduce_any , self , vars_list )
def str ( self , indent = 0 ) : """Get a string representation of this XML fragment . @ param indent : The indent to be used in formatting the output . @ type indent : int @ return : A I { pretty } string . @ rtype : basestring"""
tab = "%*s" % ( indent * 3 , "" ) result = [ ] result . append ( "%s<%s" % ( tab , self . qname ( ) ) ) result . append ( self . nsdeclarations ( ) ) for a in self . attributes : result . append ( " %s" % ( unicode ( a ) , ) ) if self . isempty ( ) : result . append ( "/>" ) return "" . join ( result ) resu...
def add_dispatcher ( self , dsp , inputs , outputs , dsp_id = None , input_domain = None , weight = None , inp_weight = None , description = None , include_defaults = False , await_domain = None , ** kwargs ) : """Add a single sub - dispatcher node to dispatcher . : param dsp : Child dispatcher that is added as...
from . utils . blue import _init dsp = _init ( dsp ) if not isinstance ( dsp , self . __class__ ) : kw = dsp dsp = self . __class__ ( name = dsp_id or 'unknown' , executor = self . executor ) dsp . add_from_lists ( ** kw ) if not dsp_id : # Get the dsp id . dsp_id = dsp . name or 'unknown' if descriptio...
def _salt_send_domain_event ( opaque , conn , domain , event , event_data ) : '''Helper function send a salt event for a libvirt domain . : param opaque : the opaque data that is passed to the callback . This is a dict with ' prefix ' , ' object ' and ' event ' keys . : param conn : libvirt connection : par...
data = { 'domain' : { 'name' : domain . name ( ) , 'id' : domain . ID ( ) , 'uuid' : domain . UUIDString ( ) } , 'event' : event } data . update ( event_data ) _salt_send_event ( opaque , conn , data )
def get_session_url ( session_id , type = 'view' , ** params ) : """Allowed types are : ` view ` , ` assets ` , ` download ` ."""
url = 'sessions/{}/{}' . format ( session_id , type ) url = urljoin ( API_URL , url ) return add_to_url ( url , ** params )
def findCommunities ( G ) : """Partition network with the Infomap algorithm . Annotates nodes with ' community ' id and return number of communities found ."""
infomapWrapper = infomap . Infomap ( "--two-level" ) print ( "Building Infomap network from a NetworkX graph..." ) for e in G . edges ( ) : infomapWrapper . addLink ( * e ) print ( "Find communities with Infomap..." ) infomapWrapper . run ( ) ; tree = infomapWrapper . tree print ( "Found %d top modules with codelen...
def show_in_notebook ( self , labels = None , predict_proba = True , show_predicted_value = True , ** kwargs ) : """Shows html explanation in ipython notebook . See as _ html ( ) for parameters . This will throw an error if you don ' t have IPython installed"""
from IPython . core . display import display , HTML display ( HTML ( self . as_html ( labels = labels , predict_proba = predict_proba , show_predicted_value = show_predicted_value , ** kwargs ) ) )
def search_reports_page ( self , search_term = None , enclave_ids = None , from_time = None , to_time = None , tags = None , excluded_tags = None , page_size = None , page_number = None ) : """Search for reports containing a search term . : param str search _ term : The term to search for . If empty , no search t...
body = { 'searchTerm' : search_term } params = { 'enclaveIds' : enclave_ids , 'from' : from_time , 'to' : to_time , 'tags' : tags , 'excludedTags' : excluded_tags , 'pageSize' : page_size , 'pageNumber' : page_number } resp = self . _client . post ( "reports/search" , params = params , data = json . dumps ( body ) ) pa...
def write_hdf5_flag_group ( flag , h5group , ** kwargs ) : """Write a ` DataQualityFlag ` into the given HDF5 group"""
# write segmentlists flag . active . write ( h5group , 'active' , ** kwargs ) kwargs [ 'append' ] = True flag . known . write ( h5group , 'known' , ** kwargs ) # store metadata for attr in [ 'name' , 'label' , 'category' , 'description' , 'isgood' , 'padding' ] : value = getattr ( flag , attr ) if value is None...
def delete_releasefile ( self , release ) : """Delete the releasefile of the given release This is inteded to be used in a action unit . : param release : the release with the releasefile : type release : : class : ` Release ` : returns : an action status : rtype : : class : ` ActionStatus ` : raises : ...
fp = release . _releasefile . get_fullpath ( ) log . info ( "Deleting release file %s" , fp ) delete_file ( release . _releasefile ) return ActionStatus ( ActionStatus . SUCCESS , msg = "Deleted %s" % fp )
def FindRegex ( self , regex , data ) : """Search the data for a hit ."""
for match in re . finditer ( regex , data , flags = re . I | re . S | re . M ) : yield ( match . start ( ) , match . end ( ) )
def list_resourcepools ( kwargs = None , call = None ) : '''List all the resource pools for this VMware environment CLI Example : . . code - block : : bash salt - cloud - f list _ resourcepools my - vmware - config'''
if call != 'function' : raise SaltCloudSystemExit ( 'The list_resourcepools function must be called with ' '-f or --function.' ) return { 'Resource Pools' : salt . utils . vmware . list_resourcepools ( _get_si ( ) ) }
def to_index_variable ( self ) : """Return this variable as an xarray . IndexVariable"""
return IndexVariable ( self . dims , self . _data , self . _attrs , encoding = self . _encoding , fastpath = True )
def init_params ( self , initializer = Uniform ( 0.01 ) , arg_params = None , aux_params = None , allow_missing = False , force_init = False , allow_extra = False ) : """Initializes the parameters and auxiliary states . By default this function does nothing . Subclass should override this method if contains param...
pass
def aliased_slot_name ( self , slot : SLOT_OR_SLOTNAME ) -> str : """Return the overloaded slot name - - the alias if one exists otherwise the actual name @ param slot : either a slot name or a definition @ return : overloaded name"""
if isinstance ( slot , str ) : slot = self . schema . slots [ slot ] return slot . alias if slot . alias else slot . name
def rstrip_extra ( fname ) : """Strip extraneous , non - discriminative filename info from the end of a file ."""
to_strip = ( "_R" , ".R" , "-R" , "_" , "fastq" , "." , "-" ) while fname . endswith ( to_strip ) : for x in to_strip : if fname . endswith ( x ) : fname = fname [ : len ( fname ) - len ( x ) ] break return fname
def add_certificate ( self , body , ** kwargs ) : # noqa : E501 """Upload a new trusted certificate . # noqa : E501 An endpoint for uploading new trusted certificates . * * Example usage : * * ` curl - X POST https : / / api . us - east - 1 . mbedcloud . com / v3 / trusted - certificates - d { \" name \" : \" myC...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . add_certificate_with_http_info ( body , ** kwargs ) # noqa : E501 else : ( data ) = self . add_certificate_with_http_info ( body , ** kwargs ) # noqa : E501 return data
def lemmatize ( text , lowercase = True , remove_stopwords = True ) : """Return the lemmas of the tokens in a text ."""
doc = nlp ( text ) if lowercase and remove_stopwords : lemmas = [ t . lemma_ . lower ( ) for t in doc if not ( t . is_stop or t . orth_ . lower ( ) in STOPWORDS ) ] elif lowercase : lemmas = [ t . lemma_ . lower ( ) for t in doc ] elif remove_stopwords : lemmas = [ t . lemma_ for t in doc if not ( t . is_st...
def set_timestamp_to_current ( self ) : """Set timestamp to current time utc : rtype : None"""
# Good form to add tzinfo self . timestamp = pytz . UTC . localize ( datetime . datetime . utcnow ( ) )
def update_company ( self , company , update_mask = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Updates specified company . Example : > > > from google . cloud import talent _ v4beta1 > > > client = talen...
# Wrap the transport method to add retry and timeout logic . if "update_company" not in self . _inner_api_calls : self . _inner_api_calls [ "update_company" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . update_company , default_retry = self . _method_configs [ "UpdateCompany" ] . retr...
def _prepare_quote ( quote , author , max_len = 78 ) : """This function processes a quote and returns a string that is ready to be used in the fancy prompt ."""
quote = quote . split ( ' ' ) max_len -= 6 lines = [ ] cur_line = [ ] def _len ( line ) : return sum ( len ( elt ) for elt in line ) + len ( line ) - 1 while quote : if not cur_line or ( _len ( cur_line ) + len ( quote [ 0 ] ) - 1 <= max_len ) : cur_line . append ( quote . pop ( 0 ) ) continue ...
def setContentFor ( self , widget ) : """Updates toolbox contents with a data corresponding to a given tab ."""
for i in range ( self . count ( ) ) : item = self . widget ( i ) if widget . isStatic : item . setStaticContent ( widget ) else : item . setContent ( widget )
def _request ( self , method , path , server = None , ** kwargs ) : """Execute a request to the cluster A server is selected from the server pool ."""
while True : next_server = server or self . _get_server ( ) try : response = self . server_pool [ next_server ] . request ( method , path , username = self . username , password = self . password , schema = self . schema , ** kwargs ) redirect_location = response . get_redirect_location ( ) ...
def write_metadata ( self , fp ) : """Writes metadata to the given file handler . Parameters fp : pycbc . inference . io . BaseInferenceFile instance The inference file to write to ."""
fp . attrs [ 'model' ] = self . name fp . attrs [ 'variable_params' ] = list ( self . variable_params ) fp . attrs [ 'sampling_params' ] = list ( self . sampling_params ) fp . write_kwargs_to_attrs ( fp . attrs , static_params = self . static_params )
def get_file_handle ( file_path ) : """Return cyvcf2 VCF object Args : file _ path ( str ) Returns : vcf _ obj ( cyvcf2 . VCF )"""
LOG . debug ( "Check if file end is correct" ) if not os . path . exists ( file_path ) : raise IOError ( "No such file:{0}" . format ( file_path ) ) if not os . path . splitext ( file_path ) [ - 1 ] in VALID_ENDINGS : raise IOError ( "Not a valid vcf file name: {}" . format ( file_path ) ) vcf_obj = VCF ( file_...
def agent_for_socks_port ( reactor , torconfig , socks_config , pool = None ) : """This returns a Deferred that fires with an object that implements : class : ` twisted . web . iweb . IAgent ` and is thus suitable for passing to ` ` treq ` ` as the ` ` agent = ` ` kwarg . Of course can be used directly ; see ...
# : param tls : True ( the default ) will use Twisted ' s default options # with the hostname in the URI - - that is , TLS verification # similar to a Browser . Otherwise , you can pass whatever Twisted # returns for ` optionsForClientTLS # < https : / / twistedmatrix . com / documents / current / api / twisted . inter...
def register_share_command ( self , share_func ) : """Add ' share ' command for adding view only project permissions and sending email via another service . : param share _ func : function to run when user choses this option"""
description = "Share a project with another user with specified permissions. " "Sends the other user an email message via D4S2 service. " "If not specified this command gives user download permissions." share_parser = self . subparsers . add_parser ( 'share' , description = description ) add_project_name_or_id_arg ( s...
import re def delete_leading_zeroes_in_ip ( ip_address : str ) -> str : """Function that removes leading zeroes from an IP address . Args : ip _ address ( str ) : an ip address . Returns : str : IP address without leading zeroes . Examples : > > > delete _ leading _ zeroes _ in _ ip ( ' 216.08.094.196 '...
return re . sub ( r'\.0*' , '.' , ip_address )
def _match_value_filter ( self , p , value ) : """Returns True of False if value in the pattern p matches the filter ."""
return self . _VALUE_FILTER_MAP [ p [ 0 ] ] ( value [ p [ 1 ] ] , p [ 2 ] )
def info ( self , verbose = None ) : """Prints and formats the results of the timing @ _ print : # bool whether or not to print out to terminal @ verbose : # bool True if you ' d like to print the individual timing results in additions to the comparison results"""
if self . name : flag ( bold ( self . name ) ) flag ( "Results after {} intervals" . format ( bold ( self . num_intervals , close = False ) ) , colors . notice_color , padding = "top" ) line ( "‒" ) verbose = verbose if verbose is not None else self . verbose if verbose : for result in self . _callable_results ...
def _get_recursive_difference ( self , type ) : '''Returns the recursive diff between dict values'''
if type == 'intersect' : return [ recursive_diff ( item [ 'old' ] , item [ 'new' ] ) for item in self . _intersect ] elif type == 'added' : return [ recursive_diff ( { } , item ) for item in self . _added ] elif type == 'removed' : return [ recursive_diff ( item , { } , ignore_missing_keys = False ) for ite...
def path ( self , goal ) : """Get the shortest way between two nodes of the graph Args : goal ( str ) : Name of the targeted node Return : list of Node"""
if goal == self . name : return [ self ] if goal not in self . routes : raise ValueError ( "Unknown '{0}'" . format ( goal ) ) obj = self path = [ obj ] while True : obj = obj . routes [ goal ] . direction path . append ( obj ) if obj . name == goal : break return path
def keltner ( self , n , dev , array = False ) : """肯特纳通道"""
mid = self . sma ( n , array ) atr = self . atr ( n , array ) up = mid + atr * dev down = mid - atr * dev return up , down
def predict_type ( self ) : """Traverse the ref _ elements path and determine the component type being referenced . Also do some checks on the array indexes"""
current_comp = self . ref_root for name , array_suffixes , name_src_ref in self . ref_elements : # find instance current_comp = current_comp . get_child_by_name ( name ) if current_comp is None : # Not found ! self . msg . fatal ( "Could not resolve hierarchical reference to '%s'" % name , name_src_ref ...
def latex2png ( snippet , outfile ) : """Compiles a LaTeX snippet to png"""
pngimage = os . path . join ( IMAGEDIR , outfile + '.png' ) texdocument = os . path . join ( IMAGEDIR , 'tmp.tex' ) with open ( texdocument , 'w' ) as doc : doc . write ( LATEX_DOC % ( snippet ) ) environment = os . environ environment [ 'shell_escape_commands' ] = "bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopd...
def get_poll ( poll_id ) : """Get a strawpoll . Example : poll = strawpy . get _ poll ( ' 11682852 ' ) : param poll _ id : : return : strawpy . Strawpoll object"""
return StrawPoll ( requests . get ( '{api_url}/{poll_id}' . format ( api_url = api_url , poll_id = poll_id ) ) )
def update_alert ( self , id , ** kwargs ) : # noqa : E501 """Update a specific alert # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . update _ alert ( id , async _ req = True ) ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . update_alert_with_http_info ( id , ** kwargs ) # noqa : E501 else : ( data ) = self . update_alert_with_http_info ( id , ** kwargs ) # noqa : E501 return data
def _run__exec ( self , action , replace ) : """Run a system command > > > Action ( ) . run ( " hello " , actions = { . . . " hello " : { . . . " type " : " exec " , . . . " cmd " : " echo version = % { version } " . . . } } , replace = { . . . " version " : " 1712.10" version = 1712.10"""
cmd = action . get ( 'cmd' ) shell = False if isinstance ( cmd , str ) : shell = True if replace and action . get ( "template" , True ) : if shell : cmd = self . rfxcfg . macro_expand ( cmd , replace ) else : cmd = [ self . rfxcfg . macro_expand ( x , replace ) for x in cmd ] self . logf ( "...
def newComment ( content ) : """Creation of a new node containing a comment ."""
ret = libxml2mod . xmlNewComment ( content ) if ret is None : raise treeError ( 'xmlNewComment() failed' ) return xmlNode ( _obj = ret )
def make_response ( obj ) : """Try to coerce an object into a Response object ."""
if obj is None : raise TypeError ( "Handler return value cannot be None." ) if isinstance ( obj , Response ) : return obj return Response ( 200 , body = obj )
def insert_global_var ( self , vname , vtype ) : "Inserts a new global variable"
return self . insert_id ( vname , SharedData . KINDS . GLOBAL_VAR , [ SharedData . KINDS . GLOBAL_VAR , SharedData . KINDS . FUNCTION ] , vtype )
def add_speaker ( self , ** kwargs ) : """Creates a new BGPSpeaker instance . Usage : Method URI POST / vtep / speakers Request parameters : Attribute Description dpid ID of Datapath binding to speaker . ( e . g . 1) as _ number AS number . ( e . g . 65000) router _ id Router ID . ( e . g . " 172.17...
try : body = self . vtep_app . add_speaker ( ** kwargs ) except DatapathNotFound as e : return e . to_response ( status = 404 ) return Response ( content_type = 'application/json' , body = json . dumps ( body ) )
def _pre_compute_secondary ( self , positive_vals , negative_vals ) : """Compute secondary y min and max"""
self . _secondary_min = ( negative_vals and min ( min ( negative_vals ) , self . zero ) ) or self . zero self . _secondary_max = ( positive_vals and max ( max ( positive_vals ) , self . zero ) ) or self . zero
def delete_config ( self , mount_point = DEFAULT_MOUNT_POINT ) : """Delete the stored Azure configuration and credentials . Supported methods : DELETE : / auth / { mount _ point } / config . Produces : 204 ( empty body ) : param mount _ point : The " path " the method / backend was mounted on . : type mount...
api_path = '/v1/{mount_point}/config' . format ( mount_point = mount_point ) return self . _adapter . delete ( url = api_path , )
def _start ( self ) : """Start a task , which may involve starting zero or more processes . This is indicated as an internal method because tasks are really only ever marked as startable by the configuration . Any task that should be running and is not will be started during regular manage ( ) calls . A tas...
log = self . _params . get ( 'log' , self . _discard ) if self . _stopping : log . debug ( "%s task is stopping" , self . _name ) return True now = time . time ( ) conf = self . _config_running control = self . _get ( conf . get ( 'control' ) ) once = ( control in self . _legion . once_controls ) # Tasks with "...
def check ( text ) : """Check the text ."""
err = "strunk_white.greylist" msg = "Use of '{}'. {}" bad_words = [ "obviously" , "utilize" ] explanations = { "obviously" : "This is obviously an inadvisable word to use." , "utilize" : r"Do you know anyone who *needs* to utilize the word utilize?" } errors = [ ] for word in bad_words : occ = [ m for m in re . fin...
def _round ( self ) : """Subclasses may override this method ."""
for contour in self . contours : contour . round ( ) for component in self . components : component . round ( ) for anchor in self . anchors : anchor . round ( ) for guideline in self . guidelines : guideline . round ( ) self . width = normalizers . normalizeRounding ( self . width ) self . height = nor...
def patch ( nml_path , nml_patch , out_path = None ) : """Create a new namelist based on an input namelist and reference dict . > > > f90nml . patch ( ' data . nml ' , nml _ patch , ' patched _ data . nml ' ) This function is equivalent to the ` ` read ` ` function of the ` ` Parser ` ` object with the patch ...
parser = Parser ( ) return parser . read ( nml_path , nml_patch , out_path )
def style ( text , fg = None , bg = None , bold = None , dim = None , underline = None , blink = None , reverse = None , reset = True ) : """Styles a text with ANSI styles and returns the new string . By default the styling is self contained which means that at the end of the string a reset code is issued . Thi...
bits = [ ] if fg : try : bits . append ( '\033[%dm' % ( _ansi_colors . index ( fg ) + 30 ) ) except ValueError : raise TypeError ( 'Unknown color %r' % fg ) if bg : try : bits . append ( '\033[%dm' % ( _ansi_colors . index ( bg ) + 40 ) ) except ValueError : raise TypeErr...
def _writeText ( self , image , text , pos ) : """Write morphed text in Image object ."""
offset = 0 x , y = pos for c in text : # Write letter c_size = self . font . getsize ( c ) c_image = Image . new ( 'RGBA' , c_size , ( 0 , 0 , 0 , 0 ) ) c_draw = ImageDraw . Draw ( c_image ) c_draw . text ( ( 0 , 0 ) , c , font = self . font , fill = ( 0 , 0 , 0 , 255 ) ) # Transform c_image = s...
def calc_v_qa_v1 ( self ) : """Update the stored water volume based on the equation of continuity . Note that for too high outflow values , which would result in overdraining the lake , the outflow is trimmed . Required derived parameters : | Seconds | | NmbSubsteps | Required flux sequence : | QZ | ...
der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess aid = self . sequences . aides . fastaccess aid . qa = min ( aid . qa , flu . qz + der . nmbsubsteps / der . seconds * aid . v ) aid . v = max ( aid . v + der . seconds / der . nmbsubsteps * ( flu . qz - aid . qa ) , 0. )
def create ( self , ticket , payload = None , expires = None ) : '''Create a session identifier in memcache associated with ` ` ticket ` ` .'''
if not payload : payload = True self . _client . set ( str ( ticket ) , payload , expires )
def _output_dirnames ( workflow = None , leaf = False ) : """Args : workflow : optional collection of steps leaf : only include leaves of the workflow Returns : If workflow is specified , returns output directories for all target steps in the workflow . If no workflow specified , returns all extant output...
if workflow is None : dirs = set ( ) for cls in os . listdir ( drain . PATH ) : for step in os . listdir ( os . path . join ( drain . PATH , cls ) ) : dirs . add ( os . path . join ( drain . PATH , cls , step ) ) return dirs else : if leaf : steps = [ step for step in workflo...
def unset ( ctx , key ) : '''Removes the given key .'''
file = ctx . obj [ 'FILE' ] quote = ctx . obj [ 'QUOTE' ] success , key = unset_key ( file , key , quote ) if success : click . echo ( "Successfully removed %s" % key ) else : exit ( 1 )
def all ( self , paths , access = None , recursion = False ) : """Iterates over ` paths ` ( which may consist of files and / or directories ) . Removes duplicates and returns list of valid paths meeting access criteria ."""
self . __init__ ( ) self . access = access self . filetype = 'all' self . paths = paths self . recursion = recursion return _sorter ( self . _generator_other ( ) )
def _node_loop ( stations , lags , stream , clip_level , i = 0 , mem_issue = False , instance = 0 , plot = False ) : """Internal function to allow for brightness to be paralleled . : type stations : list : param stations : List of stations to use . : type lags : numpy . ndarray : param lags : List of lags w...
import matplotlib . pyplot as plt # Set up some overhead for plotting energy_stream = Stream ( ) # Using a stream as a handy container for # plotting for l , tr in enumerate ( stream ) : j = [ k for k in range ( len ( stations ) ) if stations [ k ] == tr . stats . station ] # Check that there is only one matchi...
def sortedby ( item_list , key_list , reverse = False ) : """sorts ` ` item _ list ` ` using key _ list Args : list _ ( list ) : list to sort key _ list ( list ) : list to sort by reverse ( bool ) : sort order is descending ( largest first ) if reverse is True else acscending ( smallest first ) Returns ...
assert len ( item_list ) == len ( key_list ) , ( 'Expected same len. Got: %r != %r' % ( len ( item_list ) , len ( key_list ) ) ) sorted_list = [ item for ( key , item ) in sorted ( list ( zip ( key_list , item_list ) ) , reverse = reverse ) ] return sorted_list
def clone ( self , name = None ) : """: param name : new env name : rtype : Environment"""
resp = self . _router . post_env_clone ( env_id = self . environmentId , json = dict ( name = name ) if name else { } ) . json ( ) return Environment ( self . organization , id = resp [ 'id' ] ) . init_router ( self . _router )
def connect ( self , protocol = None ) : """Initialize DAP IO pins for JTAG or SWD"""
# Convert protocol to port enum . if protocol is not None : port = self . PORT_MAP [ protocol ] else : port = DAPAccess . PORT . DEFAULT try : self . _link . connect ( port ) except DAPAccess . Error as exc : six . raise_from ( self . _convert_exception ( exc ) , exc ) # Read the current mode and save i...
def _calc_frames ( stats ) : """Compute a DataFrame summary of a Stats object ."""
timings = [ ] callers = [ ] for key , values in iteritems ( stats . stats ) : timings . append ( pd . Series ( key + values [ : - 1 ] , index = timing_colnames , ) ) for caller_key , caller_values in iteritems ( values [ - 1 ] ) : callers . append ( pd . Series ( key + caller_key + caller_values , index...
def _modifier ( self , operator , params ) : '''$ orderby : sorts the results of a query in ascending ( 1 ) or descending ( - 1 ) order .'''
if operator == '$orderby' : order_types = { - 1 : 'DESC' , 1 : 'ASC' } if not isinstance ( params , dict ) : raise RuntimeError ( 'Incorrect parameter type, %s' % params ) return 'ORDER BY %s' % ',' . join ( [ "%s %s" % ( p , order_types [ params [ p ] ] ) for p in params ] ) else : raise Runtim...
def add_message_listener ( self , name , fn ) : """Adds a message listener function that will be called every time the specified message is received . . . tip : : We recommend you use : py : func : ` on _ message ` instead of this method as it has a more elegant syntax . This method is only preferred if you n...
name = str ( name ) if name not in self . _message_listeners : self . _message_listeners [ name ] = [ ] if fn not in self . _message_listeners [ name ] : self . _message_listeners [ name ] . append ( fn )
def selected_fields ( self ) : """Obtain the fields selected by user . : returns : Keyword of the selected field . : rtype : list , str"""
items = self . lstFields . selectedItems ( ) if items and self . mode == MULTI_MODE : return [ item . text ( ) for item in items ] elif items and self . mode == SINGLE_MODE : return items [ 0 ] . text ( ) else : return [ ]
def reset ( self ) : """Resets the internal evaluation result to initial state ."""
self . num_inst = 0 self . sum_metric = 0.0 self . global_num_inst = 0 self . global_sum_metric = 0.0
def get_content ( self , params = None ) : """Returns the raw byte content of a given Filelink * returns * [ Bytes ] ` ` ` python from filestack import Client client = Client ( ' API _ KEY ' ) filelink = client . upload ( filepath = ' / path / to / file / foo . jpg ' ) byte _ content = filelink . get _ ...
if params : CONTENT_DOWNLOAD_SCHEMA . check ( params ) response = utils . make_call ( CDN_URL , 'get' , handle = self . handle , params = params , security = self . security , transform_url = ( self . url if isinstance ( self , filestack . models . Transform ) else None ) ) return response . content
def distance_matrix ( a , b , periodic ) : '''Calculate a distrance matrix between coordinates sets a and b'''
a = a b = b [ : , np . newaxis ] return periodic_distance ( a , b , periodic )
def turn_physical_on ( self , ro = None , vo = None ) : """NAME : turn _ physical _ on PURPOSE : turn on automatic returning of outputs in physical units INPUT : ro = reference distance ( kpc ; can be Quantity ) vo = reference velocity ( km / s ; can be Quantity ) OUTPUT : ( none ) HISTORY : 201...
self . _roSet = True self . _voSet = True if not ro is None : if _APY_LOADED and isinstance ( ro , units . Quantity ) : ro = ro . to ( units . kpc ) . value self . _ro = ro if not vo is None : if _APY_LOADED and isinstance ( vo , units . Quantity ) : vo = vo . to ( units . km / units . s ) ....
def get_postgresql_args ( db_config , extra_args = None ) : """Returns an array of argument values that will be passed to a ` psql ` or ` pg _ dump ` process when it is started based on the given database configuration ."""
db = db_config [ 'NAME' ] mapping = [ ( '--username={0}' , db_config . get ( 'USER' ) ) , ( '--host={0}' , db_config . get ( 'HOST' ) ) , ( '--port={0}' , db_config . get ( 'PORT' ) ) ] args = apply_arg_values ( mapping ) if extra_args is not None : args . extend ( shlex . split ( extra_args ) ) args . append ( db ...
def mergeCatalogs ( catalog_list ) : """Merge a list of Catalogs . Parameters : catalog _ list : List of Catalog objects . Returns : catalog : Combined Catalog object"""
# Check the columns for c in catalog_list : if c . data . dtype . names != catalog_list [ 0 ] . data . dtype . names : msg = "Catalog data columns not the same." raise Exception ( msg ) data = np . concatenate ( [ c . data for c in catalog_list ] ) config = catalog_list [ 0 ] . config return Catalog...
def chain_2 ( d2f_dg2 , dg_dx , df_dg , d2g_dx2 ) : """Generic chaining function for second derivative . . math : : \\ frac { d ^ { 2 } ( f . g ) } { dx ^ { 2 } } = \\ frac { d ^ { 2 } f } { dg ^ { 2 } } ( \\ frac { dg } { dx } ) ^ { 2 } + \\ frac { df } { dg } \\ frac { d ^ { 2 } g } { dx ^ { 2 } }"""
if np . all ( dg_dx == 1. ) and np . all ( d2g_dx2 == 0 ) : return d2f_dg2 dg_dx_2 = np . clip ( dg_dx , - np . inf , _lim_val_square ) ** 2 # dg _ dx _ 2 = dg _ dx * * 2 return d2f_dg2 * ( dg_dx_2 ) + df_dg * d2g_dx2
def available_files ( url ) : """Extract and return urls for all available . tgz files ."""
req = requests . get ( url ) if req . status_code != 200 : raise base . FailedDownloadException ( 'Failed to download data (status {}) from {}!' . format ( req . status_code , url ) ) page_content = req . text link_pattern = re . compile ( r'<a href="(.*?)">(.*?)</a>' ) available_files = [ ] for match in link_patte...
def describe_apis ( name = None , description = None , region = None , key = None , keyid = None , profile = None ) : '''Returns all rest apis in the defined region . If optional parameter name is included , returns all rest apis matching the name in the defined region . CLI Example : . . code - block : : bas...
if name : return _find_apis_by_name ( name , description = description , region = region , key = key , keyid = keyid , profile = profile ) else : return _find_apis_by_name ( '' , description = description , region = region , key = key , keyid = keyid , profile = profile )
def add_vlan_to_interface ( self , interface , vlan_id ) : """Add vlan interface . ip link add link eth0 name eth0.10 type vlan id 10"""
subif = '%s.%s' % ( interface , vlan_id ) vlan_id = '%s' % vlan_id cmd = [ 'ip' , 'link' , 'add' , 'link' , interface , 'name' , subif , 'type' , 'vlan' , 'id' , vlan_id ] stdcode , stdout = agent_utils . execute ( cmd , root = True ) if stdcode == 0 : return agent_utils . make_response ( code = stdcode ) # execute...
def _buildKnownDataSearchString ( reg_key , reg_valueName , reg_vtype , reg_data , check_deleted = False ) : '''helper function similar to _ processValueItem to build a search string for a known key / value / type / data'''
registry = Registry ( ) this_element_value = None expected_string = b'' encoded_semicolon = ';' . encode ( 'utf-16-le' ) encoded_null = chr ( 0 ) . encode ( 'utf-16-le' ) if reg_key : reg_key = reg_key . encode ( 'utf-16-le' ) if reg_valueName : reg_valueName = reg_valueName . encode ( 'utf-16-le' ) if reg_data...
def calc_contriarea_v1 ( self ) : """Determine the relative size of the contributing area of the whole subbasin . Required control parameters : | NmbZones | | ZoneType | | RespArea | | FC | | Beta | Required derived parameter : | RelSoilArea | Required state sequence : | SM | Calculated flux...
con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess if con . resparea and ( der . relsoilarea > 0. ) : flu . contriarea = 0. for k in range ( con . nmbzones ) : if con . zo...
def parse_number ( d , key , regex , s ) : """Find a number using a given regular expression . If the number is found , sets it under the key in the given dictionary . d - The dictionary that will contain the data . key - The key into the dictionary . regex - A string containing the regular expression . s...
result = find_number ( regex , s ) if result is not None : d [ key ] = result
def minWidth ( self ) : """Attempt to determine a minimum sensible width"""
frags = self . frags nFrags = len ( frags ) if not nFrags : return 0 if nFrags == 1 : f = frags [ 0 ] fS = f . fontSize fN = f . fontName words = hasattr ( f , 'text' ) and split ( f . text , ' ' ) or f . words func = lambda w , fS = fS , fN = fN : stringWidth ( w , fN , fS ) else : words = ...
def config ( commands = None , config_file = None , template_engine = 'jinja' , context = None , defaults = None , saltenv = 'base' , ** kwargs ) : '''Configures the node with the specified commands . This method is used to send configuration commands to the node . It will take either a string or a list and pre...
initial_config = get_config ( as_string = True , ** kwargs ) if config_file : file_str = __salt__ [ 'cp.get_file_str' ] ( config_file , saltenv = saltenv ) if file_str is False : raise CommandExecutionError ( 'Source file {} not found' . format ( config_file ) ) log . debug ( 'Fetched from %s' , con...
def move ( self , delta ) : """Move the node . Args : delta ( tupel ) : A tupel , holding the adjustment of the position ."""
self . pos = ( self . pos [ 0 ] + delta [ 0 ] , self . pos [ 1 ] + delta [ 1 ] )
def evaluate ( self , batchsize ) : """Evaluate how well the classifier is doing . Return mean loss and mean accuracy"""
sum_loss , sum_accuracy = 0 , 0 for i in range ( 0 , self . testsize , batchsize ) : x = Variable ( self . x_test [ i : i + batchsize ] ) y = Variable ( self . y_test [ i : i + batchsize ] ) loss = self . model ( x , y ) sum_loss += loss . data * batchsize sum_accuracy += self . model . accuracy . d...
def cleanup_tmpdir ( dirname ) : """Removes the given temporary directory if it exists ."""
if dirname is not None and os . path . exists ( dirname ) : shutil . rmtree ( dirname )
def includeme ( config ) : """Add pyramid _ webpack methods and config to the app"""
settings = config . registry . settings root_package_name = config . root_package . __name__ config . registry . webpack = { 'DEFAULT' : WebpackState ( settings , root_package_name ) } for extra_config in aslist ( settings . get ( 'webpack.configs' , [ ] ) ) : state = WebpackState ( settings , root_package_name , n...
def update_aliases ( self , body , params = None ) : """Update specified aliases . ` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / indices - aliases . html > ` _ : arg body : The definition of ` actions ` to perform : arg master _ timeout : Specify timeout for connection...
if body in SKIP_IN_PATH : raise ValueError ( "Empty value passed for a required argument 'body'." ) return self . transport . perform_request ( "POST" , "/_aliases" , params = params , body = body )
def copy ( self ) : """Create a copy of the animation ."""
animation = AnimationList ( ) animation . set_frame_rate ( self . frame_rate ) animation . __coords = self . __coords animation . __horizontal_flip = self . __horizontal_flip animation . __vertical_flip = self . __vertical_flip animation . should_repeat = self . should_repeat animation . draw_order = self . draw_order ...
async def AddPortMapping ( NewRemoteHost : str , NewExternalPort : int , NewProtocol : str , NewInternalPort : int , NewInternalClient : str , NewEnabled : int , NewPortMappingDescription : str , NewLeaseDuration : str ) -> None : """Returns None"""
raise NotImplementedError ( )
def set_master_logging_params ( self , enable = None , dedicate_thread = None , buffer = None , sock_stream = None , sock_stream_requests_only = None ) : """Sets logging params for delegating logging to master process . : param bool enable : Delegate logging to master process . Delegate the write of the logs to...
self . _set ( 'log-master' , enable , cast = bool ) self . _set ( 'threaded-logger' , dedicate_thread , cast = bool ) self . _set ( 'log-master-bufsize' , buffer ) self . _set ( 'log-master-stream' , sock_stream , cast = bool ) if sock_stream_requests_only : self . _set ( 'log-master-req-stream' , sock_stream_reque...
def get_bibtex ( arxiv_id ) : """Get a BibTeX entry for a given arXiv ID . . . note : : Using awesome https : / / pypi . python . org / pypi / arxiv2bib / module . : param arxiv _ id : The canonical arXiv id to get BibTeX from . : returns : A BibTeX string or ` ` None ` ` . > > > get _ bibtex ( ' 1506.066...
# Fetch bibtex using arxiv2bib module try : bibtex = arxiv2bib . arxiv2bib ( [ arxiv_id ] ) except HTTPError : bibtex = [ ] for bib in bibtex : if isinstance ( bib , arxiv2bib . ReferenceErrorInfo ) : continue else : # Return fetched bibtex return bib . bibtex ( ) # An error occurred , r...
def add_filter ( self , filter ) : """Add filter to property : param filter : object , extending from AbstractFilter : return : None"""
if not isinstance ( filter , AbstractFilter ) : err = 'Filters must be of type {}' . format ( AbstractFilter ) raise InvalidFilter ( err ) if filter not in self . filters : self . filters . append ( filter ) return self
def get_diff ( value1 , value2 , name1 , name2 ) : """Get a diff between two strings . Args : value1 ( str ) : First string to be compared . value2 ( str ) : Second string to be compared . name1 ( str ) : Name of the first string . name2 ( str ) : Name of the second string . Returns : str : The full d...
lines1 = [ line + "\n" for line in value1 . splitlines ( ) ] lines2 = [ line + "\n" for line in value2 . splitlines ( ) ] diff_lines = difflib . context_diff ( lines1 , lines2 , fromfile = name1 , tofile = name2 ) return "" . join ( diff_lines )
def info_file ( distro = None ) : """Return default distroinfo info file"""
if not distro : distro = cfg [ 'DISTRO' ] info_file_conf = distro . upper ( ) + 'INFO_FILE' try : return cfg [ info_file_conf ] except KeyError : raise exception . InvalidUsage ( why = "Couldn't find config option %s for distro: %s" % ( info_file_conf , distro ) )
def download_file ( self , fname , output_dir ) : """Downloads competition file to output _ dir ."""
if fname not in self . competition_files : # pylint : disable = unsupported - membership - test raise ValueError ( "%s is not one of the competition's " "files: %s" % ( fname , self . competition_files ) ) command = [ "kaggle" , "competitions" , "download" , "--file" , fname , "--path" , output_dir , "-c" , self . ...
def plugged_usbs ( multiple = True ) -> map or dict : """Gets the plugged - in USB Flash drives ( pen - drives ) . If multiple is true , it returns a map , and a dict otherwise . If multiple is false , this method will raise a : class : ` . NoUSBFound ` if no USB is found ."""
class FindPenDrives ( object ) : # From https : / / github . com / pyusb / pyusb / blob / master / docs / tutorial . rst def __init__ ( self , class_ ) : self . _class = class_ def __call__ ( self , device ) : # first , let ' s check the device if device . bDeviceClass == self . _class : ...
def load ( self ) : """Return the current load . The load is represented as a float , where 1.0 represents having hit one of the flow control limits , and values between 0.0 and 1.0 represent how close we are to them . ( 0.5 means we have exactly half of what the flow control setting allows , for example . ...
if self . _leaser is None : return 0 return max ( [ self . _leaser . message_count / self . _flow_control . max_messages , self . _leaser . bytes / self . _flow_control . max_bytes , ] )
def filter ( self , criteria : Q , offset : int = 0 , limit : int = 10 , order_by : list = ( ) ) : """Read the repository and return results as per the filer"""
if criteria . children : items = list ( self . _filter ( criteria , self . conn [ 'data' ] [ self . schema_name ] ) . values ( ) ) else : items = list ( self . conn [ 'data' ] [ self . schema_name ] . values ( ) ) # Sort the filtered results based on the order _ by clause for o_key in order_by : reverse = F...
def gossip_bind ( self , format , * args ) : """Set - up gossip discovery of other nodes . At least one node in the cluster must bind to a well - known gossip endpoint , so other nodes can connect to it . Note that gossip endpoints are completely distinct from Zyre node endpoints , and should not overlap ( th...
return lib . zyre_gossip_bind ( self . _as_parameter_ , format , * args )
def validate_metadata ( self , xml ) : """Validates an XML SP Metadata . : param xml : Metadata ' s XML that will be validate : type xml : string : returns : The list of found errors : rtype : list"""
assert isinstance ( xml , basestring ) if len ( xml ) == 0 : raise Exception ( 'Empty string supplied as input' ) errors = [ ] res = OneLogin_Saml2_Utils . validate_xml ( xml , 'saml-schema-metadata-2.0.xsd' , self . __debug ) if not isinstance ( res , Document ) : errors . append ( res ) else : dom = res ...