signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def show_linkinfo_output_show_link_info_linkinfo_domain_reachable ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_linkinfo = ET . Element ( "show_linkinfo" ) config = show_linkinfo output = ET . SubElement ( show_linkinfo , "output" ) show_link_info = ET . SubElement ( output , "show-link-info" ) linkinfo_rbridgeid_key = ET . SubElement ( show_link_info , "linkinfo-rbridgeid" ) linkinfo_rbri...
def _parse_structured_metadata ( obj , xml ) : """Parse an XML object for structured metadata : param obj : Object whose metadata are parsed : param xml : XML that needs to be parsed"""
for metadata in xml . xpath ( "cpt:structured-metadata/*" , namespaces = XPATH_NAMESPACES ) : tag = metadata . tag if "{" in tag : ns , tag = tuple ( tag . split ( "}" ) ) tag = URIRef ( ns [ 1 : ] + tag ) s_m = str ( metadata ) if s_m . startswith ( "urn:" ) or s_m . startswith ...
def add_arguments ( cls , parser , sys_arg_list = None ) : """Arguments for the configfile mode ."""
parser . add_argument ( '-f' , '--file' , dest = 'file' , required = True , help = "config file for routing groups " "(only in configfile mode)" ) return [ "file" ]
async def on_isupport_casemapping ( self , value ) : """IRC case mapping for nickname and channel name comparisons ."""
if value in rfc1459 . protocol . CASE_MAPPINGS : self . _case_mapping = value self . channels = rfc1459 . parsing . NormalizingDict ( self . channels , case_mapping = value ) self . users = rfc1459 . parsing . NormalizingDict ( self . users , case_mapping = value )
def flush_incoming ( self ) : """Flush all incoming queues to the respective processing methods . The handlers are called as usual , thus it may require at least one iteration through the asyncio event loop before effects can be seen . The incoming queues are empty after a call to this method . It is legal ...
while True : try : stanza_obj = self . _incoming_queue . get_nowait ( ) except asyncio . QueueEmpty : break self . _process_incoming ( None , stanza_obj )
def _get_group ( conn = None , name = None , vpc_id = None , vpc_name = None , group_id = None , region = None , key = None , keyid = None , profile = None ) : # pylint : disable = W0613 '''Get a group object given a name , name and vpc _ id / vpc _ name or group _ id . Return a boto . ec2 . securitygroup . Secur...
if vpc_name and vpc_id : raise SaltInvocationError ( 'The params \'vpc_id\' and \'vpc_name\' ' 'are mutually exclusive.' ) if vpc_name : try : vpc_id = _vpc_name_to_id ( vpc_id = vpc_id , vpc_name = vpc_name , region = region , key = key , keyid = keyid , profile = profile ) except boto . exception ...
def _prepare_pattern ( self , pattern ) : """Strip out key : value pairs from the pattern and compile the regular expression ."""
regex , _ , rest = pattern . partition ( '\\;' ) try : return re . compile ( regex , re . I ) except re . error as e : warnings . warn ( "Caught '{error}' compiling regex: {regex}" . format ( error = e , regex = regex ) ) # regex that never matches : # http : / / stackoverflow . com / a / 1845097/413622...
def commentless ( data ) : """Generator that removes from a list of strings the double dot reStructuredText comments and its contents based on indentation , removing trailing empty lines after each comment as well ."""
it = iter ( data ) while True : line = next ( it ) while ":" in line or not line . lstrip ( ) . startswith ( ".." ) : yield line line = next ( it ) indent = indent_size ( line ) it = itertools . dropwhile ( lambda el : indent_size ( el ) > indent or not el . strip ( ) , it )
def is_docstring ( self , node ) : """Determine if the given node is a docstring , as long as it is at the correct place in the node tree ."""
return isinstance ( node , ast . Str ) or ( isinstance ( node , ast . Expr ) and isinstance ( node . value , ast . Str ) )
def close_on_esc_or_middlemouse ( event , x , y , obj ) : """Closes canvases when escape is pressed or the canvas area is clicked with the middle mouse button . ( ROOT requires that the mouse is over the canvas area itself before sending signals of any kind . )"""
# print " Event handler called : " , args if ( event == ROOT . kButton2Down # User pressed middle mouse or ( event == ROOT . kMouseMotion and x == y == 0 and # User pressed escape . Yes . Don ' t ask me why kMouseMotion . ROOT . gROOT . IsEscaped ( ) ) ) : # Defer the close because otherwise root segfaults when it trie...
def find_reasonable_designs ( workspaces , condition = None , verbose = False ) : """Return a list of design where the representative model has a restraint distance less that the given threshold . The default threshold ( 1.2 ) is fairly lenient ."""
print "Loading designs..." designs = [ ] if condition is None : condition = 'restraint_dist < 1.2' for workspace in workspaces : for directory in workspace . output_subdirs : if verbose : print ' ' + directory design = structures . Design ( directory ) vars = design . struct...
def _parse_authors ( details ) : """Parse authors of the book . Args : details ( obj ) : HTMLElement containing slice of the page with details . Returns : list : List of : class : ` structures . Author ` objects . Blank if no author found ."""
authors = details . find ( "tr" , { "id" : "ctl00_ContentPlaceHolder1_tblRowAutor" } ) if not authors : return [ ] # book with unspecified authors # parse authors from HTML and convert them to Author objects author_list = [ ] for author in authors [ 0 ] . find ( "a" ) : author_obj = Author ( author . getContent...
def calculate_u ( big_a , big_b ) : """Calculate the client ' s value U which is the hash of A and B : param { Long integer } big _ a Large A value . : param { Long integer } big _ b Server B value . : return { Long integer } Computed U value ."""
u_hex_hash = hex_hash ( pad_hex ( big_a ) + pad_hex ( big_b ) ) return hex_to_long ( u_hex_hash )
def cummin ( x ) : """A python implementation of the cummin function in R"""
for i in range ( 1 , len ( x ) ) : if x [ i - 1 ] < x [ i ] : x [ i ] = x [ i - 1 ] return x
def _should_skip_region ( self , region_start ) : """Some regions usually do not contain any executable code , but are still marked as executable . We should skip those regions by default . : param int region _ start : Address of the beginning of the region . : return : True / False : rtype : bool"""
obj = self . project . loader . find_object_containing ( region_start , membership_check = False ) if obj is None : return False if isinstance ( obj , PE ) : section = obj . find_section_containing ( region_start ) if section is None : return False if section . name in { '.textbss' } : r...
def get_outputs ( self , merge_multi_context = True ) : """Gets outputs from a previous forward computation . Parameters merge _ multi _ context : bool Default is ` ` True ` ` . In the case when data - parallelism is used , the outputs will be collected from multiple devices . A ` ` True ` ` value indicate ...
assert self . binded and self . params_initialized return self . _modules [ - 1 ] . get_outputs ( merge_multi_context = merge_multi_context )
def get_most_recent_versions ( self , group , artifact , limit , remote = False , integration = False ) : """Get a list of the version numbers of the most recent artifacts ( integration or non - integration ) , ordered by the version number , for a particular group and artifact combination . : param str group...
if limit < 1 : raise ValueError ( "Releases limit must be positive" ) url = self . _base_url + '/api/search/versions' params = { 'g' : group , 'a' : artifact , 'repos' : self . _repo , 'remote' : int ( remote ) } self . _logger . debug ( "Using all version API at %s - params %s" , url , params ) response = self . _...
def replace ( oldstr , newstr , infile , dryrun = False ) : """Sed - like Replace function . . Usage : pysed . replace ( < Old string > , < Replacement String > , < Text File > ) Example : pysed . replace ( ' xyz ' , ' XYZ ' , ' / path / to / file . txt ' ) This will dump the output to STDOUT instead of chang...
linelist = [ ] with open ( infile ) as reader : for item in reader : newitem = re . sub ( oldstr , newstr , item ) linelist . append ( newitem ) if dryrun is False : with open ( infile , "w" ) as writer : writer . truncate ( ) for line in linelist : writer . writeline...
def run ( self ) : """Parse a tabs directive"""
self . assert_has_content ( ) env = self . state . document . settings . env node = nodes . container ( ) node [ 'classes' ] = [ 'sphinx-tabs' ] if 'next_tabs_id' not in env . temp_data : env . temp_data [ 'next_tabs_id' ] = 0 if 'tabs_stack' not in env . temp_data : env . temp_data [ 'tabs_stack' ] = [ ] tabs_...
def save ( self , path ) : """Writes file to a particular location This won ' t work for cloud environments like Google ' s App Engine , use with caution ensure to catch exceptions so you can provide informed feedback . prestans does not mask File IO exceptions so your handler can respond better ."""
file_handle = open ( path , 'wb' ) file_handle . write ( self . _file_contents ) file_handle . close ( )
def edit ( self , name , description = None , homepage = None , private = None , has_issues = None , has_wiki = None , has_downloads = None , default_branch = None ) : """Edit this repository . : param str name : ( required ) , name of the repository : param str description : ( optional ) , If not ` ` None ` ` ...
edit = { 'name' : name , 'description' : description , 'homepage' : homepage , 'private' : private , 'has_issues' : has_issues , 'has_wiki' : has_wiki , 'has_downloads' : has_downloads , 'default_branch' : default_branch } self . _remove_none ( edit ) json = None if edit : json = self . _json ( self . _patch ( self...
def get_scripts ( self ) : """Get the scripts at the path in sorted order as set in the module properties : return : a sorted list of scripts"""
ret = list ( ) for d in self . allpaths : scripts = filter ( lambda x : x . startswith ( self . prefix ) , os . listdir ( d ) ) scripts . sort ( reverse = ( not self . sort_ascending ) ) ret = ret + [ os . path . join ( d , x ) for x in scripts ] return ( ret )
def format_help ( self , ctx , formatter ) : """Writes the help into the formatter if it exists . This calls into the following methods : - : meth : ` format _ usage ` - : meth : ` format _ help _ text ` - : meth : ` format _ options ` - : meth : ` format _ epilog `"""
self . format_usage ( ctx , formatter ) self . format_help_text ( ctx , formatter ) self . format_options ( ctx , formatter ) self . format_epilog ( ctx , formatter )
def bin_pkg_info ( path , saltenv = 'base' ) : '''. . versionadded : : 2015.8.0 Parses RPM metadata and returns a dictionary of information about the package ( name , version , etc . ) . path Path to the file . Can either be an absolute path to a file on the minion , or a salt fileserver URL ( e . g . ` `...
# If the path is a valid protocol , pull it down using cp . cache _ file if __salt__ [ 'config.valid_fileproto' ] ( path ) : newpath = __salt__ [ 'cp.cache_file' ] ( path , saltenv ) if not newpath : raise CommandExecutionError ( 'Unable to retrieve {0} from saltenv \'{1}\'' . format ( path , saltenv ) ...
def make_random_key ( ) -> Text : """Generates a secure random string"""
r = SystemRandom ( ) allowed = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+/[]' return '' . join ( [ r . choice ( allowed ) for _ in range ( 0 , 50 ) ] )
def modpath_all ( module , entry_point ) : """Provides the raw _ _ path _ _ . Incompatible with PEP 302 - based import hooks and incompatible with zip _ safe packages . Deprecated . Will be removed by calmjs - 4.0."""
module_paths = getattr ( module , '__path__' , [ ] ) if not module_paths : logger . warning ( "module '%s' does not appear to be a namespace module or does not " "export available paths onto the filesystem; JavaScript source " "files cannot be extracted from this module." , module . __name__ ) return module_paths
def cartesian_to_barycentric_3D ( tri , xy ) : '''cartesian _ to _ barycentric _ 3D ( tri , xy ) is identical to cartesian _ to _ barycentric _ 2D ( tri , xy ) except it works on 3D data . Note that if tri is a 3 x 3 x n , a 3 x n x 3 or an n x 3 x 3 matrix , the first dimension must always be the triangle vert...
xy = np . asarray ( xy ) tri = np . asarray ( tri ) if len ( xy . shape ) == 1 : return cartesian_to_barycentric_3D ( np . transpose ( np . asarray ( [ tri ] ) , ( 1 , 2 , 0 ) ) , np . asarray ( [ xy ] ) . T ) [ : , 0 ] xy = xy if xy . shape [ 0 ] == 3 else xy . T if tri . shape [ 0 ] == 3 : tri = tri if tri . ...
def get_magnitude_scaling_term ( self , C , rup ) : """Returns magnitude scaling term , which is dependent on top of rupture depth - as described in equations 1 and 2"""
if rup . ztor > 25.0 : # Deep interface events c_int = C [ "cint" ] else : c_int = C [ "cintS" ] if rup . mag <= self . CONSTANTS [ "m_c" ] : return c_int * rup . mag else : return ( c_int * self . CONSTANTS [ "m_c" ] ) + ( C [ "dint" ] * ( rup . mag - self . CONSTANTS [ "m_c" ] ) )
def cget ( self , key ) : """Query widget option . : param key : option name : type key : str : return : value of the option To get the list of options for this widget , call the method : meth : ` ~ ItemsCanvas . keys ` ."""
if key is "canvaswidth" : return self . _canvaswidth elif key is "canvasheight" : return self . _canvasheight elif key is "function_new" : return self . _function_new elif key is "callback_add" : return self . _callback_add elif key is "callback_del" : return self . _callback_del elif key is "callba...
def to_native ( self , value , context = None ) : """Schematics deserializer override : return : ToOne instance"""
if isinstance ( value , ToOne ) : return value value = self . _cast_rid ( value ) return ToOne ( self . rtype , self . field , rid = value )
def serialize_footnote ( ctx , document , el , root ) : "Serializes footnotes ."
footnote_num = el . rid if el . rid not in ctx . footnote_list : ctx . footnote_id += 1 ctx . footnote_list [ el . rid ] = ctx . footnote_id footnote_num = ctx . footnote_list [ el . rid ] note = etree . SubElement ( root , 'sup' ) link = etree . SubElement ( note , 'a' ) link . set ( 'href' , '#' ) link . text...
def Publish ( self , event_name , msg , delay = 0 ) : """Sends the message to event listeners ."""
events_lib . Events . PublishEvent ( event_name , msg , delay = delay )
def from_hdf5 ( cls , f ) : """Load an object from an HDF5 file . Requires ` ` h5py ` ` . Parameters f : str , : class : ` h5py . File ` Either the filename or an open HDF5 file ."""
if isinstance ( f , str ) : import h5py f = h5py . File ( f ) pos = quantity_from_hdf5 ( f [ 'pos' ] ) vel = quantity_from_hdf5 ( f [ 'vel' ] ) frame = None if 'frame' in f : g = f [ 'frame' ] frame_mod = g . attrs [ 'module' ] frame_cls = g . attrs [ 'class' ] frame_units = [ u . Unit ( x . dec...
def from_array_list ( cls , result , list_level ) : """Tries to parse the ` result ` as type given in ` required _ type ` , while traversing into lists as often as specified in ` list _ level ` . : param cls : Type as what it should be parsed as . Can be any class extending : class : ` TgBotApiObject ` . E . g ...
return from_array_list ( cls , result , list_level , is_builtin = False )
def _get_local_rev_and_branch ( target , user , password , output_encoding = None ) : '''Return the local revision for before / after comparisons'''
log . info ( 'Checking local revision for %s' , target ) try : local_rev = __salt__ [ 'git.revision' ] ( target , user = user , password = password , ignore_retcode = True , output_encoding = output_encoding ) except CommandExecutionError : log . info ( 'No local revision for %s' , target ) local_rev = None...
def read_namespaced_endpoints ( self , name , namespace , ** kwargs ) : # noqa : E501 """read _ namespaced _ endpoints # noqa : E501 read the specified Endpoints # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_namespaced_endpoints_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . read_namespaced_endpoints_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 return d...
def extract ( self , html : str , return_text : bool = False ) -> List [ Extraction ] : """Args : html ( str ) : raw html of the page return _ text ( bool ) : if True , return the visible text in the page removing all the data tables Returns : List [ Extraction ] : a list of Extractions"""
results = list ( ) temp_res = TableExtractor . tableExtractorInstance . extract ( html ) if return_text : results . append ( self . _wrap_value_with_context ( temp_res [ 'html_text' ] , "text_without_tables" ) ) results . extend ( map ( lambda t : self . _wrap_value_with_context ( t , "tables" ) , temp_res [ 'table...
def format_num ( num , unit = 'bytes' ) : """Returns a human readable string of a byte - value . If ' num ' is bits , set unit = ' bits ' ."""
if unit == 'bytes' : extension = 'B' else : # if it ' s not bytes , it ' s bits extension = 'Bit' for dimension in ( unit , 'K' , 'M' , 'G' , 'T' ) : if num < 1024 : if dimension == unit : return '%3.1f %s' % ( num , dimension ) return '%3.1f %s%s' % ( num , dimension , extension...
def regexp ( input , ** params ) : """Parses input according to pattern : param input : : param params : : return :"""
PARAM_FIELD_TO_PARSE = 'input.field' PARAM_PATTERN = 'pattern' PARAM_OUTPUT = 'output' OUT_DESC_FIELD = 'field' OUT_DESC_IDX = 'idx' OUT_DESC_TYPE = 'type' res = [ ] regex = re . compile ( params . get ( PARAM_PATTERN ) ) field2parse = params . get ( PARAM_FIELD_TO_PARSE ) out_desc = params . get ( PARAM_OUTPUT ) for r...
def idxmin ( self , ** kwargs ) : """Returns the first occurrence of the minimum over requested axis . Returns : A new QueryCompiler object containing the minimum of each column or axis ."""
if self . _is_transposed : kwargs [ "axis" ] = kwargs . get ( "axis" , 0 ) ^ 1 return self . transpose ( ) . idxmin ( ** kwargs ) axis = kwargs . get ( "axis" , 0 ) index = self . index if axis == 0 else self . columns def idxmin_builder ( df , ** kwargs ) : if axis == 0 : df . index = index els...
def run_command ( self , command , timeout = - 1 ) : """Send a command to the REPL , wait for and return output . : param str command : The command to send . Trailing newlines are not needed . This should be a complete block of input that will trigger execution ; if a continuation prompt is found after sendin...
# Split up multiline commands and feed them in bit - by - bit cmdlines = command . splitlines ( ) # splitlines ignores trailing newlines - add it back in manually if command . endswith ( '\n' ) : cmdlines . append ( '' ) if not cmdlines : raise ValueError ( "No command was given" ) res = [ ] self . child . send...
def network_kubernetes_from_context ( reactor , context = None , path = None , environ = None , default_config_path = FilePath ( expanduser ( u"~/.kube/config" ) ) , ) : """Create a new ` ` IKubernetes ` ` provider based on a kube config file . : param reactor : A Twisted reactor which will be used for I / O and ...
if path is None : if environ is None : from os import environ try : kubeconfigs = environ [ u"KUBECONFIG" ] except KeyError : config = KubeConfig . from_file ( default_config_path . path ) else : config = _merge_configs_from_env ( kubeconfigs ) else : config = KubeCon...
def _normalize_label ( self , s , wsmap ) : """normalized form of a synonym"""
toks = [ ] for tok in list ( set ( self . npattern . sub ( ' ' , s ) . split ( ' ' ) ) ) : if tok in wsmap : tok = wsmap [ tok ] if tok != "" : toks . append ( tok ) toks . sort ( ) return " " . join ( toks )
def getElementsByAttr ( self , attr , value ) : '''getElementsByAttr - Get elements within this collection posessing a given attribute / value pair @ param attr - Attribute name ( lowercase ) @ param value - Matching value @ return - TagCollection of all elements matching name / value'''
ret = TagCollection ( ) if len ( self ) == 0 : return ret attr = attr . lower ( ) _cmpFunc = lambda tag : tag . getAttribute ( attr ) == value for tag in self : TagCollection . _subset ( ret , _cmpFunc , tag ) return ret
def fbeta ( log_preds , targs , beta , thresh = 0.5 , epsilon = 1e-8 ) : """Calculates the F - beta score ( the weighted harmonic mean of precision and recall ) . This is the micro averaged version where the true positives , false negatives and false positives are calculated globally ( as opposed to on a per la...
assert beta > 0 , 'beta needs to be greater than 0' beta2 = beta ** 2 rec = recall ( log_preds , targs , thresh ) prec = precision ( log_preds , targs , thresh ) return ( 1 + beta2 ) * prec * rec / ( beta2 * prec + rec + epsilon )
def validate_svc_catalog_endpoint_data ( self , expected , actual , openstack_release = None ) : """Validate service catalog endpoint data . Pick the correct validator for the OpenStack version . Expected data should be in the v2 format : ' service _ name1 ' : [ ' adminURL ' : adminURL , ' id ' : id , ' r...
validation_function = self . validate_v2_svc_catalog_endpoint_data xenial_queens = OPENSTACK_RELEASES_PAIRS . index ( 'xenial_queens' ) if openstack_release and openstack_release >= xenial_queens : validation_function = self . validate_v3_svc_catalog_endpoint_data expected = self . convert_svc_catalog_endpoint_...
def load_job_from_ref ( self ) : """Loads the job . json into self . job"""
if not self . job_id : raise Exception ( 'Job not loaded yet. Use load(id) first.' ) if not os . path . exists ( self . git . work_tree + '/aetros/job.json' ) : raise Exception ( 'Could not load aetros/job.json from git repository. Make sure you have created the job correctly.' ) with open ( self . git . work_t...
def get_potential_satellites_by_type ( self , satellites , s_type ) : """Generic function to access one of the potential satellite attribute ie : self . potential _ pollers , self . potential _ reactionners . . . : param satellites : list of SatelliteLink objects : type satellites : SatelliteLink list : par...
if not hasattr ( self , 'potential_' + s_type + 's' ) : logger . debug ( "[realm %s] do not have this kind of satellites: %s" , self . name , s_type ) return [ ] matching_satellites = [ ] for sat_link in satellites : if sat_link . uuid in getattr ( self , s_type + 's' ) : matching_satellites . appen...
async def redirect_async ( self , redirect , auth ) : """Redirect the client endpoint using a Link DETACH redirect response . : param redirect : The Link DETACH redirect details . : type redirect : ~ uamqp . errors . LinkRedirect : param auth : Authentication credentials to the redirected endpoint . : typ...
if self . _ext_connection : raise ValueError ( "Clients with a shared connection cannot be " "automatically redirected." ) if self . message_handler : await self . message_handler . destroy_async ( ) self . message_handler = None async with self . _pending_messages_lock : self . _pending_messages = [ ] ...
def create_dev_vlan ( devid , vlanid , vlan_name , auth , url ) : """function takes devid and vlanid vlan _ name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device . VLAN Name MUST be valid on target device . : param devid : int or str value of the ...
create_dev_vlan_url = "/imcrs/vlan?devId=" + str ( devid ) f_url = url + create_dev_vlan_url payload = '''{ "vlanId": "''' + str ( vlanid ) + '''", "vlanName" : "''' + str ( vlan_name ) + '''"}''' r = requests . post ( f_url , data = payload , auth = auth , headers = HEADERS ) # creates the URL using the payload variab...
def calculate_sun_from_date_time ( self , datetime , is_solar_time = False ) : """Get Sun for an hour of the year . This code is originally written by Trygve Wastvedt ( Trygve . Wastvedt @ gmail . com ) based on ( NOAA ) and modified by Chris Mackey and Mostapha Roudsari Args : datetime : Ladybug datetime ...
# TODO ( mostapha ) : This should be more generic and based on a method if datetime . year != 2016 and self . is_leap_year : datetime = DateTime ( datetime . month , datetime . day , datetime . hour , datetime . minute , True ) sol_dec , eq_of_time = self . _calculate_solar_geometry ( datetime ) hour = datetime . f...
def dispatch ( self ) : """Command - line dispatch ."""
parser = argparse . ArgumentParser ( description = 'Run an Inbox server.' ) parser . add_argument ( 'addr' , metavar = 'addr' , type = str , help = 'addr to bind to' ) parser . add_argument ( 'port' , metavar = 'port' , type = int , help = 'port to bind to' ) args = parser . parse_args ( ) self . serve ( port = args . ...
def _get_modules ( path ) : """Finds modules in folder recursively : param path : directory : return : list of modules"""
lst = [ ] folder_contents = os . listdir ( path ) is_python_module = "__init__.py" in folder_contents if is_python_module : for file in folder_contents : full_path = os . path . join ( path , file ) if is_file ( full_path ) : lst . append ( full_path ) if is_folder ( full_path ) ...
def write_targets ( targets , ** params ) : """Writes version info into version file"""
handler = ReplacementHandler ( ** params ) for target , regexer in regexer_for_targets ( targets ) : with open ( target ) as fh : lines = fh . readlines ( ) lines = replace_lines ( regexer , handler , lines ) with open ( target , "w" ) as fh : fh . writelines ( lines ) if handler . missing :...
def _get_private_room ( self , invitees : List [ User ] ) : """Create an anonymous , private room and invite peers"""
return self . _client . create_room ( None , invitees = [ user . user_id for user in invitees ] , is_public = False , )
def _register_default_option ( nsobj , opt ) : """Register default ConfigOption value if it doesn ' t exist . If does exist , update the description if needed"""
item = ConfigItem . get ( nsobj . namespace_prefix , opt . name ) if not item : logger . info ( 'Adding {} ({}) = {} to {}' . format ( opt . name , opt . type , opt . default_value , nsobj . namespace_prefix ) ) item = ConfigItem ( ) item . namespace_prefix = nsobj . namespace_prefix item . key = opt . ...
def querySQL ( self , sql , args = ( ) ) : """For use with SELECT ( or SELECT - like PRAGMA ) statements ."""
if self . debug : result = timeinto ( self . queryTimes , self . _queryandfetch , sql , args ) else : result = self . _queryandfetch ( sql , args ) return result
def input_option ( message , options = "yn" , error_message = None ) : """Reads an option from the screen , with a specified prompt . Keeps asking until a valid option is sent by the user ."""
def _valid ( character ) : if character not in options : print ( error_message % character ) return input ( "%s [%s]" % ( message , options ) , _valid , True , lambda a : a . lower ( ) )
def reset ( self ) : """Reset emulator . All registers and memory are reset ."""
self . __mem . reset ( ) self . __cpu . reset ( ) self . __tainter . reset ( ) # Instructions pre and post handlers . self . __instr_handler_pre = None , None self . __instr_handler_post = None , None self . __set_default_handlers ( )
def _set_repositories ( self , node ) : '''Create repositories . : param node : : return :'''
priority = 99 for repo_id , repo_data in self . _data . software . get ( 'repositories' , { } ) . items ( ) : if type ( repo_data ) == list : repo_data = repo_data [ 0 ] if repo_data . get ( 'enabled' ) or not repo_data . get ( 'disabled' ) : # RPM and Debian , respectively uri = repo_data . get...
def to_gnuplot_datafile ( self , datafilepath ) : """Dumps the TimeSeries into a gnuplot compatible data file . : param string datafilepath : Path used to create the file . If that file already exists , it will be overwritten ! : return : Returns : py : const : ` True ` if the data could be written , : py : c...
try : datafile = file ( datafilepath , "wb" ) except Exception : return False if self . _timestampFormat is None : self . _timestampFormat = _STR_EPOCHS datafile . write ( "# time_as_<%s> value\n" % self . _timestampFormat ) convert = TimeSeries . convert_epoch_to_timestamp for datapoint in self . _timeseri...
def create ( parameter_names , parameter_types , return_type ) : """Returns a signature object ensuring order of parameter names and types . : param parameter _ names : A list of ordered parameter names : type parameter _ names : list [ str ] : param parameter _ types : A dictionary of parameter names to type...
ordered_pairs = [ ( name , parameter_types [ name ] ) for name in parameter_names ] return MethodSignature ( ordered_pairs , return_type )
def eval_linear_approx ( self , Dxy , gradY ) : r"""Compute term : math : ` \ langle \ nabla f ( \ mathbf { y } ) , \ mathbf { x } - \ mathbf { y } \ rangle ` ( in frequency domain ) that is part of the quadratic function : math : ` Q _ L ` used for backtracking . Since this class computes the backtracking in...
return np . sum ( np . real ( np . conj ( Dxy ) * gradY ) )
def CreateNewZipWithSignedLibs ( z_in , z_out , ignore_files = None , signer = None , skip_signing_files = None ) : """Copies files from one zip to another , signing all qualifying files ."""
ignore_files = ignore_files or [ ] skip_signing_files = skip_signing_files or [ ] extensions_to_sign = [ ".sys" , ".exe" , ".dll" , ".pyd" ] to_sign = [ ] for template_file in z_in . namelist ( ) : if template_file not in ignore_files : extension = os . path . splitext ( template_file ) [ 1 ] . lower ( ) ...
def select ( select , tag , namespaces = None , limit = 0 , flags = 0 , ** kwargs ) : """Select the specified tags ."""
return compile ( select , namespaces , flags , ** kwargs ) . select ( tag , limit )
def redshift_from_comoving_volume ( vc , ** kwargs ) : r"""Returns the redshift from the given comoving volume . Parameters vc : float The comoving volume , in units of cubed Mpc . \ * * kwargs : All other keyword args are passed to : py : func : ` get _ cosmology ` to select a cosmology . If none provi...
cosmology = get_cosmology ( ** kwargs ) return z_at_value ( cosmology . comoving_volume , vc , units . Mpc ** 3 )
def cumulative_time_on_drug ( drug_events_df : DataFrame , query_times_df : DataFrame , event_lasts_for_timedelta : datetime . timedelta = None , event_lasts_for_quantity : float = None , event_lasts_for_units : str = None , patient_colname : str = DEFAULT_PATIENT_COLNAME , event_datetime_colname : str = DEFAULT_DRUG_E...
if event_lasts_for_timedelta is None : assert event_lasts_for_quantity and event_lasts_for_units timedelta_dict = { event_lasts_for_units : event_lasts_for_quantity } event_lasts_for_timedelta = datetime . timedelta ( ** timedelta_dict ) if debug : log . critical ( "drug_events_df:\n{!r}" , drug_events_...
def ping ( self ) : """Ping the broker . Send a MQTT ` PINGREQ < http : / / docs . oasis - open . org / mqtt / mqtt / v3.1.1 / os / mqtt - v3.1.1 - os . html # _ Toc398718081 > ` _ message for response . This method is a * coroutine * ."""
if self . session . transitions . is_connected ( ) : yield from self . _handler . mqtt_ping ( ) else : self . logger . warning ( "MQTT PING request incompatible with current session state '%s'" % self . session . transitions . state )
def process_sample ( job , inputs , tar_id ) : """Converts sample . tar ( . gz ) into two fastq files . Due to edge conditions . . . BEWARE : HERE BE DRAGONS : param JobFunctionWrappingJob job : passed by Toil automatically : param Namespace inputs : Stores input arguments ( see main ) : param str tar _ id ...
job . fileStore . logToMaster ( 'Processing sample into read pairs: {}' . format ( inputs . uuid ) ) work_dir = job . fileStore . getLocalTempDir ( ) # I / O tar_path = job . fileStore . readGlobalFile ( tar_id , os . path . join ( work_dir , 'sample.tar' ) ) # Untar File and concat subprocess . check_call ( [ 'tar' , ...
def length ( self , threshold = 0.2 , phys = False , ang = False , tdisrupt = None , ** kwargs ) : """NAME : length PURPOSE : calculate the length of the stream INPUT : threshold - threshold down from the density near the progenitor at which to define the ' end ' of the stream phys = ( False ) if True ,...
peak_dens = self . density_par ( 0.1 , tdisrupt = tdisrupt , ** kwargs ) # assume that this is the peak try : result = optimize . brentq ( lambda x : self . density_par ( x , tdisrupt = tdisrupt , ** kwargs ) - peak_dens * threshold , 0.1 , self . _deltaAngleTrack ) except RuntimeError : # pragma : no cover rai...
def _fetchOrFallback ( self , _ = None ) : """Handles fallbacks for failure of fetch , wrapper for self . _ fetch"""
res = yield self . _fetch ( None ) if res == RC_SUCCESS : return res elif self . retryFetch : yield self . _fetch ( None ) elif self . clobberOnFailure : yield self . clobber ( ) else : raise buildstep . BuildStepFailed ( )
def works ( self , prefix_id ) : """This method retrieve a iterable of Works of the given prefix . args : Crossref Prefix ( String ) return : Works ( )"""
context = '%s/%s' % ( self . ENDPOINT , str ( prefix_id ) ) return Works ( context = context )
def internal_run_container ( name , callback_method , foreground = False ) : """Internal method what runs container process : param name : str - name of container : param callback _ method : list - how to invoke container : param foreground : bool run in background by default : return : suprocess instance""...
if not foreground : logger . info ( "Stating machine (boot nspawn container) {}" . format ( name ) ) # wait until machine is booted when running at background , unable to execute commands without logind # in running container nspawn_process = NspawnContainer . _internal_reschedule ( callback_method ) ...
def get_gradebook_ids_by_gradebook_column ( self , gradebook_column_id ) : """Gets the list of ` ` Gradebook ` ` ` ` Ids ` ` mapped to a ` ` GradebookColumn ` ` . arg : gradebook _ column _ id ( osid . id . Id ) : ` ` Id ` ` of a ` ` GradebookColumn ` ` return : ( osid . id . IdList ) - list of gradebook ` ` ...
# Implemented from template for # osid . resource . ResourceBinSession . get _ bin _ ids _ by _ resource mgr = self . _get_provider_manager ( 'GRADING' , local = True ) lookup_session = mgr . get_gradebook_column_lookup_session ( proxy = self . _proxy ) lookup_session . use_federated_gradebook_view ( ) gradebook_column...
def _open_for_write ( filename ) : """Opens filename for writing , creating the directories if needed ."""
dirname = os . path . dirname ( filename ) pathlib . Path ( dirname ) . mkdir ( parents = True , exist_ok = True ) return io . open ( filename , 'w' )
def kwargs_to_spec ( self , ** kwargs ) : """Turn the provided kwargs into arguments ready for toolchain ."""
spec = self . create_spec ( ** kwargs ) self . prepare_spec ( spec , ** kwargs ) return spec
def get_state ( self , as_str = False ) : """Returns user state . See ` ` UserState ` ` . : param bool as _ str : Return human - friendly state name instead of an ID . : rtype : int | str"""
uid = self . user_id if self . _iface_user . get_id ( ) == uid : result = self . _iface . get_my_state ( ) else : result = self . _iface . get_state ( uid ) if as_str : return UserState . get_alias ( result ) return result
def groupby ( expr , by , * bys ) : """Group collection by a series of sequences . : param expr : collection : param by : columns to group : param bys : columns to group : return : GroupBy instance : rtype : : class : ` odps . df . expr . groupby . GroupBy `"""
if not isinstance ( by , list ) : by = [ by , ] if len ( bys ) > 0 : by = by + list ( bys ) return GroupBy ( _input = expr , _by = by )
def clone ( self , source_id , backup_id , size , volume_id = None , source_host = None ) : """create a volume then clone the contents of the backup into the new volume"""
volume_id = volume_id or str ( uuid . uuid4 ( ) ) return self . http_put ( '/volumes/%s' % volume_id , params = self . unused ( { 'source_host' : source_host , 'source_volume_id' : source_id , 'backup_id' : backup_id , 'size' : size } ) )
def prop2qid ( self , prop , value ) : """Lookup the local item QID for a Wikidata item that has a certain ` prop ` - > ` value ` in the case where the local item has a ` equivalent item ` statement to that wikidata item Example : In my wikibase , I have CDK2 ( Q79363 ) with the only statement : equivalent cl...
equiv_class_pid = self . URI_PID [ 'http://www.w3.org/2002/07/owl#equivalentClass' ] query = """ PREFIX wwdt: <http://www.wikidata.org/prop/direct/> SELECT ?wditem ?localitem ?id WHERE {{ SERVICE <https://query.wikidata.org/sparql> {{ ?wditem wwdt:{prop} "{value}" }} ...
def create_table_level ( self ) : """Create the QTableView that will hold the level model ."""
self . table_level = QTableView ( ) self . table_level . setEditTriggers ( QTableWidget . NoEditTriggers ) self . table_level . setHorizontalScrollBarPolicy ( Qt . ScrollBarAlwaysOff ) self . table_level . setVerticalScrollBarPolicy ( Qt . ScrollBarAlwaysOff ) self . table_level . setFrameStyle ( QFrame . Plain ) self ...
def unwraplist ( v ) : """LISTS WITH ZERO AND ONE element MAP TO None AND element RESPECTIVELY"""
if is_list ( v ) : if len ( v ) == 0 : return None elif len ( v ) == 1 : return unwrap ( v [ 0 ] ) else : return unwrap ( v ) else : return unwrap ( v )
def prepend_zeros ( self , num ) : """Prepend num zeros onto the beginning of this TimeSeries . Update also epoch to include this prepending ."""
self . resize ( len ( self ) + num ) self . roll ( num ) self . _epoch = self . _epoch - num * self . _delta_t
def get_effort_streams ( self , effort_id , types = None , resolution = None , series_type = None ) : """Returns an streams for an effort . http : / / strava . github . io / api / v3 / streams / # effort Streams represent the raw data of the uploaded file . External applications may only access this informati...
# stream are comma seperated list if types is not None : types = "," . join ( types ) params = { } if resolution is not None : params [ "resolution" ] = resolution if series_type is not None : params [ "series_type" ] = series_type result_fetcher = functools . partial ( self . protocol . get , '/segment_eff...
def call ( self , func , * api_args , ** api_kwargs ) : """Send API call to SDK server and return results"""
if not isinstance ( func , str ) or ( func == '' ) : msg = ( 'Invalid input for API name, should be a' 'string, type: %s specified.' ) % type ( func ) return self . _construct_api_name_error ( msg ) # Create client socket try : cs = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) except socket ....
def _32bit_oper ( op1 , op2 = None , reversed = False , preserveHL = False ) : """Returns pop sequence for 32 bits operands 1st operand in HLDE , 2nd operand remains in the stack Now it does support operands inversion calling _ _ SWAP32. However , if 1st operand is integer ( immediate ) or indirect , the stac...
output = [ ] if op1 is not None : op1 = str ( op1 ) if op2 is not None : op2 = str ( op2 ) op = op2 if op2 is not None else op1 int1 = False # whether op1 ( 2nd operand ) is integer indirect = ( op [ 0 ] == '*' ) if indirect : op = op [ 1 : ] immediate = ( op [ 0 ] == '#' ) if immediate : op = op [ 1 : ...
def _parse_access_vlan ( self , config ) : """Scans the specified config and parse the access - vlan value Args : config ( str ) : The interface configuration block to scan Returns : dict : A Python dict object with the value of switchport access value . The dict returned is intended to be merged into the...
value = re . search ( r'switchport access vlan (\d+)' , config ) return dict ( access_vlan = value . group ( 1 ) )
def records ( self ) : '''Return a list of dicts corresponding to the data returned by Factual .'''
if self . _records == None : self . _records = self . _get_records ( ) return self . _records
def _on_set_auth ( self , sock , token ) : """Set Auth request received from websocket"""
self . log . info ( f"Token received: {token}" ) sock . setAuthtoken ( token )
def _get_asconv_headers ( mosaic ) : """Getter for the asconv headers ( asci header info stored in the dicom )"""
asconv_headers = re . findall ( r'### ASCCONV BEGIN(.*)### ASCCONV END ###' , mosaic [ Tag ( 0x0029 , 0x1020 ) ] . value . decode ( encoding = 'ISO-8859-1' ) , re . DOTALL ) [ 0 ] return asconv_headers
def has_path ( nodes , A , B ) : r"""Test if nodes from a breadth _ first _ order search lead from A to Parameters nodes : array _ like Nodes from breadth _ first _ oder _ seatch A : array _ like The set of educt states B : array _ like The set of product states Returns has _ path : boolean True...
x1 = np . intersect1d ( nodes , A ) . size > 0 x2 = np . intersect1d ( nodes , B ) . size > 0 return x1 and x2
def get ( self , key ) : """Returns an individual Location by query lookup , e . g . address or point ."""
if isinstance ( key , tuple ) : # TODO handle different ordering try : x , y = float ( key [ 0 ] ) , float ( key [ 1 ] ) except IndexError : raise ValueError ( "Two values are required for a coordinate pair" ) except ValueError : raise ValueError ( "Only float or float-coercable valu...
def truncate ( string , length , ellipsis = "…" ) : """Truncate a string to a length , ending with ' . . . ' if it overflows"""
if len ( string ) > length : return string [ : length - len ( ellipsis ) ] + ellipsis return string
def as_native_str ( encoding = 'utf-8' ) : '''A decorator to turn a function or method call that returns text , i . e . unicode , into one that returns a native platform str . Use it as a decorator like this : : from _ _ future _ _ import unicode _ literals class MyClass ( object ) : @ as _ native _ str (...
if PY3 : return lambda f : f else : def encoder ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : return f ( * args , ** kwargs ) . encode ( encoding = encoding ) return wrapper return encoder
def count_rows_with_nans ( X ) : """Count the number of rows in 2D arrays that contain any nan values ."""
if X . ndim == 2 : return np . where ( np . isnan ( X ) . sum ( axis = 1 ) != 0 , 1 , 0 ) . sum ( )
def rpc_get_atlas_peers ( self , ** con_info ) : """Get the list of peer atlas nodes . Give its own atlas peer hostport . Return at most atlas _ max _ neighbors ( ) peers Return { ' status ' : True , ' peers ' : . . . } on success Return { ' error ' : . . . } on failure"""
conf = get_blockstack_opts ( ) if not conf . get ( 'atlas' , False ) : return { 'error' : 'Not an atlas node' , 'http_status' : 404 } # identify the client . . . client_host = con_info [ 'client_host' ] client_port = con_info [ 'client_port' ] peers = self . peer_exchange ( client_host , client_port ) return self ....
def copy ( self : BaseBoardT ) -> BaseBoardT : """Creates a copy of the board ."""
board = type ( self ) ( None ) board . pawns = self . pawns board . knights = self . knights board . bishops = self . bishops board . rooks = self . rooks board . queens = self . queens board . kings = self . kings board . occupied_co [ WHITE ] = self . occupied_co [ WHITE ] board . occupied_co [ BLACK ] = self . occup...
def download_to_bytesio ( url ) : """Return a bytesio object with a download bar"""
logger . info ( "Downloading url: {0}" . format ( url ) ) r = cleaned_request ( 'get' , url , stream = True ) stream = io . BytesIO ( ) total_length = int ( r . headers . get ( 'content-length' ) ) for chunk in progress . bar ( r . iter_content ( chunk_size = 1024 ) , expected_size = ( total_length / 1024 ) + 1 ) : ...
def make_qs ( n , m = None ) : """Make sympy symbols q0 , q1 , . . . Args : n ( int ) , m ( int , optional ) : If specified both n and m , returns [ qn , q ( n + 1 ) , . . . , qm ] , Only n is specified , returns [ q0 , q1 , . . . , qn ] . Return : tuple ( Symbol ) : Tuple of sympy symbols ."""
try : import sympy except ImportError : raise ImportError ( "This function requires sympy. Please install it." ) if m is None : syms = sympy . symbols ( " " . join ( f"q{i}" for i in range ( n ) ) ) if isinstance ( syms , tuple ) : return syms else : return ( syms , ) syms = sympy . ...
def stream ( self , code ) : """Stream in RiveScript source code dynamically . : param code : Either a string containing RiveScript code or an array of lines of RiveScript code ."""
self . _say ( "Streaming code." ) if type ( code ) in [ str , text_type ] : code = code . split ( "\n" ) self . _parse ( "stream()" , code )