signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def annotation_id ( self , value ) : """Set ID for Annotation"""
if value in [ None , '' ] or str ( value ) . strip ( ) == '' : raise AttributeError ( "Invalid ID value supplied" ) self . _id = value
def tail ( f , window = 20 ) : """Returns the last ` window ` lines of file ` f ` as a list . @ param window : the number of lines ."""
if window == 0 : return [ ] BUFSIZ = 1024 f . seek ( 0 , 2 ) bytes = f . tell ( ) size = window + 1 block = - 1 data = [ ] while size > 0 and bytes > 0 : if bytes - BUFSIZ > 0 : # Seek back one whole BUFSIZ f . seek ( block * BUFSIZ , 2 ) # read BUFFER data . insert ( 0 , f . read ( BUFS...
async def answer_pre_checkout_query ( self , pre_checkout_query_id : base . String , ok : base . Boolean , error_message : typing . Union [ base . String , None ] = None ) -> base . Boolean : """Once the user has confirmed their payment and shipping details , the Bot API sends the final confirmation in the form o...
payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . ANSWER_PRE_CHECKOUT_QUERY , payload ) return result
def is_uniform ( self ) : """Return if file contains a uniform series of pages ."""
# the hashes of IFDs 0 , 7 , and - 1 are the same pages = self . pages page = pages [ 0 ] if page . is_scanimage or page . is_nih : return True try : useframes = pages . useframes pages . useframes = False h = page . hash for i in ( 1 , 7 , - 1 ) : if pages [ i ] . aspage ( ) . hash != h : ...
def get_available_parameters ( self ) : """Return a list of the parameters made available by the script ."""
# At the moment , we rely on regex to extract the list of available # parameters . A tighter integration with waf would allow for a more # natural extraction of the information . stdout = self . run_program ( "%s %s" % ( self . script_executable , '--PrintHelp' ) , environment = self . environment , native_spec = BUILD...
def get_charge ( max_tdc , tdc_calibration_values , tdc_pixel_calibration ) : # Return the charge from calibration '''Interpolatet the TDC calibration for each pixel from 0 to max _ tdc'''
charge_calibration = np . zeros ( shape = ( 80 , 336 , max_tdc ) ) for column in range ( 80 ) : for row in range ( 336 ) : actual_pixel_calibration = tdc_pixel_calibration [ column , row , : ] if np . any ( actual_pixel_calibration != 0 ) and np . any ( np . isfinite ( actual_pixel_calibration ) ) :...
def Emulation_setNavigatorOverrides ( self , platform ) : """Function path : Emulation . setNavigatorOverrides Domain : Emulation Method name : setNavigatorOverrides WARNING : This function is marked ' Experimental ' ! Parameters : Required arguments : ' platform ' ( type : string ) - > The platform nav...
assert isinstance ( platform , ( str , ) ) , "Argument 'platform' must be of type '['str']'. Received type: '%s'" % type ( platform ) subdom_funcs = self . synchronous_command ( 'Emulation.setNavigatorOverrides' , platform = platform ) return subdom_funcs
def close ( self ) : """Closes all the iterators . This is particularly important if the iterators are files ."""
if hasattr ( self , 'iterators' ) : for it in self . iterators : if hasattr ( it , 'close' ) : it . close ( )
def delete_stream ( stream_name , region = None , key = None , keyid = None , profile = None ) : '''Delete the stream with name stream _ name . This cannot be undone ! All data will be lost ! ! CLI example : : salt myminion boto _ kinesis . delete _ stream my _ stream region = us - east - 1'''
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) r = _execute_with_retries ( conn , "delete_stream" , StreamName = stream_name ) if 'error' not in r : r [ 'result' ] = True return r
def _parseline ( self , line ) : """Result CSV Line Parser . : param line : a to parse : returns : the number of rows to jump and parse the next data line or return the code error - 1"""
sline = line . split ( SEPARATOR ) if is_header ( sline ) : return self . _handle_header ( sline ) # If it is not an header it contains some data . but we need data only # from the RESULT TABLE section . elif not self . _cur_section == SECTION_RESULT_TABLE : return 0 # If line starts with ' Sample ID ' , then i...
def set_own_module ( self , path ) : """This is provided so the calling process can arrange for processing to be stopped and a LegionReset exception raised when any part of the program ' s own module tree changes ."""
log = self . _params . get ( 'log' , self . _discard ) self . _name = path self . module_add ( event_target ( self , 'legion_reset' , key = path , log = log ) , path )
def _stub_attr ( obj , attr_name ) : '''Stub an attribute of an object . Will return an existing stub if there already is one .'''
# Annoying circular reference requires importing here . Would like to see # this cleaned up . @ AW from . mock import Mock # Check to see if this a property , this check is only for when dealing # with an instance . getattr will work for classes . is_property = False if not inspect . isclass ( obj ) and not inspect . i...
def uri_path ( self , path ) : """Set the Uri - Path of a request . : param path : the Uri - Path"""
path = path . strip ( "/" ) tmp = path . split ( "?" ) path = tmp [ 0 ] paths = path . split ( "/" ) for p in paths : option = Option ( ) option . number = defines . OptionRegistry . URI_PATH . number option . value = p self . add_option ( option ) if len ( tmp ) > 1 : query = tmp [ 1 ] self . u...
def kalman_filter ( points , noise ) : """Smooths points with kalman filter See https : / / github . com / open - city / ikalman Args : points ( : obj : ` list ` of : obj : ` Point ` ) : points to smooth noise ( float ) : expected noise"""
kalman = ikalman . filter ( noise ) for point in points : kalman . update_velocity2d ( point . lat , point . lon , point . dt ) ( lat , lon ) = kalman . get_lat_long ( ) point . lat = lat point . lon = lon return points
def declareLegacyItem ( typeName , schemaVersion , attributes , dummyBases = ( ) ) : """Generate a dummy subclass of Item that will have the given attributes , and the base Item methods , but no methods of its own . This is for use with upgrading . @ param typeName : a string , the Axiom TypeName to have attr...
if ( typeName , schemaVersion ) in _legacyTypes : return _legacyTypes [ typeName , schemaVersion ] if dummyBases : realBases = [ declareLegacyItem ( * A ) for A in dummyBases ] else : realBases = ( Item , ) attributes = attributes . copy ( ) attributes [ '__module__' ] = 'item_dummy' attributes [ '__legacy_...
def get_value_at ( all_info , current_path , key , to_string = False ) : """Get value located at a given path : param all _ info : : param current _ path : : param key : : param to _ string : : return :"""
keys = key . split ( '.' ) if keys [ - 1 ] == 'id' : target_obj = current_path [ len ( keys ) - 1 ] else : if key == 'this' : target_path = current_path elif '.' in key : target_path = [ ] for i , key in enumerate ( keys ) : if key == 'id' : target_path . ...
def restore ( s , t ) : """s is the source string , it can contain ' . ' t is the target , it ' s smaller than s by the number of ' . ' s in s Each char in s is replaced by the corresponding char in t , jumping over ' . ' s in s . > > > restore ( ' ABC . DEF ' , ' XYZABC ' ) ' XYZ . ABC '"""
t = ( c for c in t ) return '' . join ( next ( t ) if not is_blacksquare ( c ) else c for c in s )
def _get_http_crl_distribution_points ( self , crl_distribution_points ) : """Fetches the DistributionPoint object for non - relative , HTTP CRLs referenced by the certificate : param crl _ distribution _ points : A CRLDistributionPoints object to grab the DistributionPoints from : return : A list of zero...
output = [ ] if crl_distribution_points is None : return [ ] for distribution_point in crl_distribution_points : distribution_point_name = distribution_point [ 'distribution_point' ] if distribution_point_name is VOID : continue # RFC 5280 indicates conforming CA should not use the relative form...
def _get_spacewalk_configuration ( spacewalk_url = '' ) : '''Return the configuration read from the master configuration file or directory'''
spacewalk_config = __opts__ [ 'spacewalk' ] if 'spacewalk' in __opts__ else None if spacewalk_config : try : for spacewalk_server , service_config in six . iteritems ( spacewalk_config ) : username = service_config . get ( 'username' , None ) password = service_config . get ( 'passwo...
def dynamical_potential ( xdata , dt , order = 3 ) : """Computes potential from spring function Parameters xdata : ndarray Position data for a degree of freedom , at which to calculate potential dt : float time between measurements order : int order of polynomial to fit Returns Potential : ndarr...
import numpy as _np adata = calc_acceleration ( xdata , dt ) xdata = xdata [ 2 : ] # removes first 2 values as differentiating twice means # we have acceleration [ n ] corresponds to position [ n - 2] z = _np . polyfit ( xdata , adata , order ) p = _np . poly1d ( z ) spring_pot = _np . polyint ( p ) return - spring_pot
def writeCache ( self , filename ) : """Write the graph to a cache file ."""
with open ( filename , 'wb' ) as f : pickle . dump ( self . modules , f )
def filter ( self , u ) : """Filter the valid identities for this matcher . : param u : unique identity which stores the identities to filter : returns : a list of identities valid to work with this matcher . : raises ValueError : when the unique identity is not an instance of UniqueIdentity class"""
if not isinstance ( u , UniqueIdentity ) : raise ValueError ( "<u> is not an instance of UniqueIdentity" ) filtered = [ ] for id_ in u . identities : username = None if self . sources and id_ . source . lower ( ) not in self . sources : continue if self . _check_username ( id_ . username ) : ...
def compute ( self , base , * args , ** kwargs ) : '''Returns the value of the discount . @ param base : float Computation base . @ return : Decimal'''
return min ( base , super ( Discount , self ) . compute ( base , * args , ** kwargs ) )
def check ( text ) : """Suggest the preferred forms ."""
err = "pinker.latin" msg = "Use English. '{}' is the preferred form." list = [ [ "other things being equal" , [ "ceteris paribus" ] ] , [ "among other things" , [ "inter alia" ] ] , [ "in and of itself" , [ "simpliciter" ] ] , [ "having made the necessary changes" , [ "mutatis mutandis" ] ] , ] return preferred_forms_c...
def steady_state_replacement ( random , population , parents , offspring , args ) : """Performs steady - state replacement for the offspring . This function performs steady - state replacement , which means that the offspring replace the least fit individuals in the existing population , even if those offspri...
population . sort ( ) num_to_replace = min ( len ( offspring ) , len ( population ) ) population [ : num_to_replace ] = offspring [ : num_to_replace ] return population
def parse_form_data ( environ , stream_factory = None , charset = 'utf-8' , errors = 'replace' , max_form_memory_size = None , max_content_length = None , cls = None , silent = True ) : """Parse the form data in the environ and return it as tuple in the form ` ` ( stream , form , files ) ` ` . You should only cal...
return FormDataParser ( stream_factory , charset , errors , max_form_memory_size , max_content_length , cls , silent ) . parse_from_environ ( environ )
def build ( self , X , Y , w = None , edges = None ) : """Assigns data to this object and builds the requested topological structure @ In , X , an m - by - n array of values specifying m n - dimensional samples @ In , Y , a m vector of values specifying the output responses corresponding to the m samples ...
self . reset ( ) if X is None or Y is None : return self . __set_data ( X , Y , w ) if self . debug : sys . stdout . write ( "Graph Preparation: " ) start = time . clock ( ) self . graph_rep = nglpy . Graph ( self . Xnorm , self . graph , self . max_neighbors , self . beta , connect = self . connect , ) if ...
def retrieve ( self , request , project , pk = None ) : """Retrieve a bug - job - map entry . pk is a composite key in the form bug _ id - job _ id"""
job_id , bug_id = map ( int , pk . split ( "-" ) ) job = Job . objects . get ( repository__name = project , id = job_id ) try : bug_job_map = BugJobMap . objects . get ( job = job , bug_id = bug_id ) serializer = BugJobMapSerializer ( bug_job_map ) return Response ( serializer . data ) except BugJobMap . Do...
def _get_zone_name ( self ) : """Get receivers zone name if not set yet ."""
if self . _name is None : # Collect tags for AppCommand . xml call tags = [ "GetZoneName" ] # Execute call root = self . exec_appcommand_post ( tags ) # Check result if root is None : _LOGGER . error ( "Getting ZoneName failed." ) else : zone = self . _get_own_zone ( ) tr...
def feature_from_line ( line , dialect = None , strict = True , keep_order = False ) : """Given a line from a GFF file , return a Feature object Parameters line : string strict : bool If True ( default ) , assume ` line ` is a single , tab - delimited string that has at least 9 fields . If False , then ...
if not strict : lines = line . splitlines ( False ) _lines = [ ] for i in lines : i = i . strip ( ) if len ( i ) > 0 : _lines . append ( i ) assert len ( _lines ) == 1 , _lines line = _lines [ 0 ] if '\t' in line : fields = line . rstrip ( '\n\r' ) . split ( '...
def WriteIntermediateInit ( self , out ) : """Write a simple _ _ init _ _ . py for an intermediate directory ."""
printer = self . _GetPrinter ( out ) printer ( '#!/usr/bin/env python' ) printer ( '"""Shared __init__.py for apitools."""' ) printer ( ) printer ( 'from pkgutil import extend_path' ) printer ( '__path__ = extend_path(__path__, __name__)' )
def gpib_command ( library , session , data ) : """Write GPIB command bytes on the bus . Corresponds to viGpibCommand function of the VISA library . : param library : the visa library wrapped by ctypes . : param session : Unique logical identifier to a session . : param data : data tor write . : type data...
return_count = ViUInt32 ( ) # [ ViSession , ViBuf , ViUInt32 , ViPUInt32] ret = library . viGpibCommand ( session , data , len ( data ) , byref ( return_count ) ) return return_count . value , ret
def instruction_LSR_memory ( self , opcode , ea , m ) : """Logical shift right memory location"""
r = self . LSR ( m ) # log . debug ( " $ % x LSR memory value $ % x > > 1 = $ % x and write it to $ % x \ t | % s " % ( # self . program _ counter , # m , r , ea , # self . cfg . mem _ info . get _ shortest ( ea ) return ea , r & 0xff
def _monitor_task ( self ) : """Wrapper that handles the actual asynchronous monitoring of the task state ."""
if self . task . state in states . UNREADY_STATES : reactor . callLater ( self . POLL_PERIOD , self . _monitor_task ) return if self . task . state == 'SUCCESS' : self . callback ( self . task . result ) elif self . task . state == 'FAILURE' : self . errback ( Failure ( self . task . result ) ) elif sel...
def get_post_alter_table_index_foreign_key_sql ( self , diff ) : """: param diff : The table diff : type diff : orator . dbal . table _ diff . TableDiff : rtype : list"""
if not isinstance ( diff . from_table , Table ) : raise DBALException ( "Sqlite platform requires for alter table the table" "diff with reference to original table schema" ) sql = [ ] if diff . new_name : table_name = diff . get_new_name ( ) else : table_name = diff . get_name ( self ) for index in self . _...
def substitute_group ( self , index , func_grp , strategy , bond_order = 1 , graph_dict = None , strategy_params = None , reorder = True , extend_structure = True ) : """Builds off of Molecule . substitute to replace an atom in self . molecule with a functional group . This method also amends self . graph to in...
def map_indices ( grp ) : grp_map = { } # Get indices now occupied by functional group # Subtracting 1 because the dummy atom X should not count atoms = len ( grp ) - 1 offset = len ( self . molecule ) - atoms for i in range ( atoms ) : grp_map [ i ] = i + offset return grp_map # Wor...
def get_potential_files ( self , ignore_list ) : """Get a listing of files for the appropriate task which may or may not be locked and / or done ."""
exclude_prefix = self . taskid == tasks . suffixes . get ( tasks . REALS_TASK , '' ) and 'fk' or None filenames = [ filename for filename in self . directory_context . get_listing ( self . taskid , exclude_prefix = exclude_prefix ) if filename not in ignore_list and filename not in self . _done and filename not in self...
def get_doc ( self , objtxt ) : """Get object documentation dictionary"""
obj , valid = self . _eval ( objtxt ) if valid : return getdoc ( obj )
def find_child ( sexpr : Sexpr , * tags : str ) -> Optional [ Sexpr ] : """Search for a tag among direct children of the s - expression ."""
_assert_valid_sexpr ( sexpr ) for child in sexpr [ 1 : ] : if _is_sexpr ( child ) and child [ 0 ] in tags : return child return None
def parent ( self , index ) : """Returns the parent of the model item with the given index . If the item has no parent , an invalid QModelIndex is returned ."""
if not index . isValid ( ) : return QtCore . QModelIndex ( ) childItem = index . internalPointer ( ) # the only place where the parent item is queried parentItem = childItem . getParent ( ) if parentItem == self . root : return QtCore . QModelIndex ( ) return self . createIndex ( parentItem . row ( ) , 0 , pare...
def split ( s , delimter , trim = True , limit = 0 ) : # pragma : no cover """Split a string using a single - character delimter @ params : ` s ` : the string ` delimter ` : the single - character delimter ` trim ` : whether to trim each part . Default : True @ examples : ` ` ` python ret = split ( " ...
ret = [ ] special1 = [ '(' , ')' , '[' , ']' , '{' , '}' ] special2 = [ '\'' , '"' ] special3 = '\\' flags1 = [ 0 , 0 , 0 ] flags2 = [ False , False ] flags3 = False start = 0 nlim = 0 for i , c in enumerate ( s ) : if c == special3 : # next char is escaped flags3 = not flags3 elif not flags3 : # no esc...
def _set_bfd_l3 ( self , v , load = False ) : """Setter method for bfd _ l3 , mapped from YANG variable / hardware / custom _ profile / kap _ custom _ profile / bfd _ l3 ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ bfd _ l3 is considered as a private ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = bfd_l3 . bfd_l3 , is_container = 'container' , presence = False , yang_name = "bfd-l3" , rest_name = "bfd-l3" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext...
def render ( file ) : """Pretty print the XML file for rendering ."""
with file . open ( ) as fp : encoding = detect_encoding ( fp , default = 'utf-8' ) file_content = fp . read ( ) . decode ( encoding ) parsed_xml = xml . dom . minidom . parseString ( file_content ) return parsed_xml . toprettyxml ( indent = ' ' , newl = '' )
def _handle_wrapper ( self ) : """The helper method for handling JSON Post and Get requests ."""
if self . request . headers . get ( "X-Requested-With" ) != "XMLHttpRequest" : logging . error ( "Got JSON request with no X-Requested-With header" ) self . response . set_status ( 403 , message = "Got JSON request with no X-Requested-With header" ) return self . json_response . clear ( ) try : self . h...
def delete_message_from_handle ( self , queue , receipt_handle ) : """Delete a message from a queue , given a receipt handle . : type queue : A : class : ` boto . sqs . queue . Queue ` object : param queue : The Queue from which messages are read . : type receipt _ handle : str : param receipt _ handle : Th...
params = { 'ReceiptHandle' : receipt_handle } return self . get_status ( 'DeleteMessage' , params , queue . id )
def add_redistribution ( self , protocol , route_map_name = None ) : """Adds a protocol redistribution to OSPF Args : protocol ( str ) : protocol to redistribute route _ map _ name ( str ) : route - map to be used to filter the protocols Returns : bool : True if the command completes successfully Exce...
protocols = [ 'bgp' , 'rip' , 'static' , 'connected' ] if protocol not in protocols : raise ValueError ( 'redistributed protocol must be' 'bgp, connected, rip or static' ) if route_map_name is None : cmd = 'redistribute {}' . format ( protocol ) else : cmd = 'redistribute {} route-map {}' . format ( protoco...
def _from_dict ( cls , _dict ) : """Initialize a QueryEntitiesResponse object from a json dictionary ."""
args = { } if 'entities' in _dict : args [ 'entities' ] = [ QueryEntitiesResponseItem . _from_dict ( x ) for x in ( _dict . get ( 'entities' ) ) ] return cls ( ** args )
def main ( args = None ) : """Decodes bencoded files to python syntax ( like JSON , but with bytes support )"""
import sys , pprint from argparse import ArgumentParser , FileType parser = ArgumentParser ( description = main . __doc__ ) parser . add_argument ( 'infile' , nargs = '?' , type = FileType ( 'rb' ) , default = sys . stdin . buffer , help = 'bencoded file (e.g. torrent) [Default: stdin]' ) parser . add_argument ( 'outfi...
def get_symbol_ids ( symbol_yml_file , metadata ) : """Get a list of ids which describe which class they get mapped to . Parameters symbol _ yml _ file : string Path to a YAML file . metadata : dict Metainformation of symbols , like the id on write - math . com . Has keys ' symbols ' , ' tags ' , ' tags...
with open ( symbol_yml_file , 'r' ) as stream : symbol_cfg = yaml . load ( stream ) symbol_ids = [ ] symbol_ids_set = set ( ) for symbol in symbol_cfg : if 'latex' not in symbol : logging . error ( "Key 'latex' not found for a symbol in %s (%s)" , symbol_yml_file , symbol ) sys . exit ( - 1 ) ...
def cublasSgemm ( handle , transa , transb , m , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) : """Matrix - matrix product for real general matrix ."""
status = _libcublas . cublasSgemm_v2 ( handle , _CUBLAS_OP [ transa ] , _CUBLAS_OP [ transb ] , m , n , k , ctypes . byref ( ctypes . c_float ( alpha ) ) , int ( A ) , lda , int ( B ) , ldb , ctypes . byref ( ctypes . c_float ( beta ) ) , int ( C ) , ldc ) cublasCheckStatus ( status )
def get_qubits ( self , indices = True ) : """Returns all of the qubit indices used in this program , including gate applications and allocated qubits . e . g . > > > p = Program ( ) > > > p . inst ( ( " H " , 1 ) ) > > > p . get _ qubits ( ) > > > q = p . alloc ( ) > > > p . inst ( H ( q ) ) > > > le...
qubits = set ( ) for instr in self . instructions : if isinstance ( instr , ( Gate , Measurement ) ) : qubits |= instr . get_qubits ( indices = indices ) return qubits
def to_snake_case ( name ) : """Convert the input string to snake - cased string ."""
s1 = first_cap_re . sub ( r'\1_\2' , name ) # handle acronym words return all_cap_re . sub ( r'\1_\2' , s1 ) . lower ( )
def n_list_comp ( self , node ) : """List comprehensions"""
p = self . prec self . prec = 27 n = node [ - 1 ] assert n == 'list_iter' # find innermost node while n == 'list_iter' : n = n [ 0 ] # recurse one step if n == 'list_for' : n = n [ 3 ] elif n == 'list_if' : n = n [ 2 ] elif n == 'list_if_not' : n = n [ 2 ] assert n == 'lc_bod...
def load_msgpack ( blob , ** kwargs ) : """Load a dict packed with msgpack into kwargs for a Trimesh constructor Parameters blob : bytes msgpack packed dict containing keys ' vertices ' and ' faces ' Returns loaded : dict Keyword args for Trimesh constructor , aka mesh = trimesh . Trimesh ( * * lo...
import msgpack if hasattr ( blob , 'read' ) : data = msgpack . load ( blob ) else : data = msgpack . loads ( blob ) loaded = load_dict ( data ) return loaded
def pub_date ( soup ) : """Return the publishing date in struct format pub _ date _ date , pub _ date _ day , pub _ date _ month , pub _ date _ year , pub _ date _ timestamp Default date _ type is pub"""
pub_date = first ( raw_parser . pub_date ( soup , date_type = "pub" ) ) if pub_date is None : pub_date = first ( raw_parser . pub_date ( soup , date_type = "publication" ) ) if pub_date is None : return None ( day , month , year ) = ymd ( pub_date ) return date_struct ( year , month , day )
def remove ( self , tag , nth = 1 ) : """Remove the n - th occurrence of tag in this message . : param tag : FIX field tag number to be removed . : param nth : Index of tag if repeating , first is 1. : returns : Value of the field if removed , None otherwise ."""
tag = fix_tag ( tag ) nth = int ( nth ) for i in range ( len ( self . pairs ) ) : t , v = self . pairs [ i ] if t == tag : nth -= 1 if nth == 0 : self . pairs . pop ( i ) return v return None
def _generate_notebooks_by_category ( notebook_object , dict_by_tag ) : """Internal function that is used for generation of the page " Notebooks by Category " . Parameters notebook _ object : notebook object Object of " notebook " class where the body will be created . dict _ by _ tag : dict Dictionary wh...
# = = = = = Insertion of an opening text = = = = = markdown_cell = OPEN_IMAGE # = = Generation of a table that group Notebooks by category the information about each signal = = category_list = list ( NOTEBOOK_KEYS . keys ( ) ) tag_keys = list ( dict_by_tag . keys ( ) ) markdown_cell += """\n<table id="notebook_list" wi...
def create ( self , url , pathToWebarchive ) : """* create the webarchive object * * * Key Arguments : * * - ` ` url ` ` - - the url of the webpage to generate the webarchive for - ` ` pathToWebarchive ` ` - - tthe path to output the the webarchive file to * * Return : * * - ` ` webarchive ` ` - - the pat...
self . log . debug ( 'starting the ``create`` method' ) from subprocess import Popen , PIPE , STDOUT webarchiver = self . settings [ "executables" ] [ "webarchiver" ] cmd = """%(webarchiver)s -url %(url)s -output "%(pathToWebarchive)s" """ % locals ( ) p = Popen ( cmd , stdout = PIPE , stderr = PIPE , shell = True ) s...
def RCScan ( ) : """Return a prototype Scanner instance for scanning RC source files"""
res_re = r'^(?:\s*#\s*(?:include)|' '.*?\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)' '\s*.*?)' '\s*(<|"| )([^>"\s]+)(?:[>"\s])*$' resScanner = SCons . Scanner . ClassicCPP ( "ResourceScanner" , "$RCSUFFIXES" , "CPPPATH" , res_re , recursive = no_tlb ) return resScanner
def define_contributor ( self , request ) : """Define contributor by adding it to request . data ."""
request . data [ 'contributor' ] = self . resolve_user ( request . user ) . pk
def make_instance ( cls , id , client , parent_id = None , json = None ) : """Makes an instance of the class this is called on and returns it . The intended usage is : instance = Linode . make _ instance ( 123 , client , json = response ) : param cls : The class this was called on . : param id : The id of t...
return Base . make ( id , client , cls , parent_id = parent_id , json = json )
def _get_value ( context , key ) : """Retrieve a key ' s value from a context item . Returns _ NOT _ FOUND if the key does not exist . The ContextStack . get ( ) docstring documents this function ' s intended behavior ."""
if isinstance ( context , dict ) : # Then we consider the argument a " hash " for the purposes of the spec . # We do a membership test to avoid using exceptions for flow control # ( e . g . catching KeyError ) . if key in context : return context [ key ] elif type ( context ) . __module__ != _BUILTIN_MODULE...
def get_static_lib_paths ( ) : """Return the required static libraries path"""
libs = [ ] is_linux = sys . platform . startswith ( 'linux' ) if is_linux : libs += [ '-Wl,--start-group' ] libs += get_raw_static_lib_path ( ) if is_linux : libs += [ '-Wl,--end-group' ] return libs
def _handle_nice_params ( optim_params : dict ) -> None : """Convert the user friendly params into something the optimizer can understand ."""
# Handle callbacks optim_params [ "callbacks" ] = _check_callbacks ( optim_params . get ( "callbacks" ) ) optim_params [ "use_callbacks" ] = optim_params [ "callbacks" ] is not None # Handle negative gradient method negative_gradient_method = optim_params . pop ( "negative_gradient_method" ) if callable ( negative_grad...
def exonic_transcript_effect ( variant , exon , exon_number , transcript ) : """Effect of this variant on a Transcript , assuming we already know that this variant overlaps some exon of the transcript . Parameters variant : Variant exon : pyensembl . Exon Exon which this variant overlaps exon _ number :...
genome_ref = variant . trimmed_ref genome_alt = variant . trimmed_alt variant_start = variant . trimmed_base1_start variant_end = variant . trimmed_base1_end # clip mutation to only affect the current exon if variant_start < exon . start : # if mutation starts before current exon then only look # at nucleotides which o...
def get_mesh ( oqparam ) : """Extract the mesh of points to compute from the sites , the sites _ csv , or the region . : param oqparam : an : class : ` openquake . commonlib . oqvalidation . OqParam ` instance"""
global pmap , exposure , gmfs , eids if 'exposure' in oqparam . inputs and exposure is None : # read it only once exposure = get_exposure ( oqparam ) if oqparam . sites : return geo . Mesh . from_coords ( oqparam . sites ) elif 'sites' in oqparam . inputs : fname = oqparam . inputs [ 'sites' ] header = ...
def update_release_environment ( self , environment_update_data , project , release_id , environment_id ) : """UpdateReleaseEnvironment . [ Preview API ] Update the status of a release environment : param : class : ` < ReleaseEnvironmentUpdateMetadata > < azure . devops . v5_0 . release . models . ReleaseEnviro...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if release_id is not None : route_values [ 'releaseId' ] = self . _serialize . url ( 'release_id' , release_id , 'int' ) if environment_id is not None : route_values [ 'environmen...
def add_github_roles ( app , repo ) : """Add ` ` gh ` ` role to your sphinx documents . It can generate GitHub links easily : : : gh : ` issue # 57 ` will generate the issue link : gh : ` PR # 85 ` will generate the pull request link Use this function in ` ` conf . py ` ` to enable this feature : : def se...
from docutils . nodes import reference from docutils . parsers . rst . roles import set_classes base_url = 'https://github.com/{}' . format ( repo ) def github_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : if '#' in text : t , n = text . split ( '#' , 1 ) if t...
def usearch_cluster_seqs_ref ( fasta_filepath , output_filepath = None , percent_id = 0.97 , sizein = True , sizeout = True , w = 64 , slots = 16769023 , maxrejects = 64 , log_name = "usearch_cluster_seqs.log" , usersort = True , HALT_EXEC = False , save_intermediate_files = False , remove_usearch_logs = False , suppre...
if not output_filepath : _ , output_filepath = mkstemp ( prefix = 'usearch_cluster_ref_based' , suffix = '.uc' ) log_filepath = join ( working_dir , log_name ) uc_filepath = join ( working_dir , "clustered_seqs_post_chimera.uc" ) params = { '--sizein' : sizein , '--sizeout' : sizeout , '--id' : percent_id , '--w' :...
def create_or_update_policy ( self , name , policy , pretty_print = True ) : """Add a new or update an existing policy . Once a policy is updated , it takes effect immediately to all associated users . Supported methods : PUT : / sys / policy / { name } . Produces : 204 ( empty body ) : param name : Specifi...
if isinstance ( policy , dict ) : if pretty_print : policy = json . dumps ( policy , indent = 4 , sort_keys = True ) else : policy = json . dumps ( policy ) params = { 'policy' : policy , } api_path = '/v1/sys/policy/{name}' . format ( name = name ) return self . _adapter . put ( url = api_path ...
def compare ( self , statement_a , statement_b ) : """Return the calculated similarity of two statements based on the Jaccard index ."""
# Make both strings lowercase document_a = self . nlp ( statement_a . text . lower ( ) ) document_b = self . nlp ( statement_b . text . lower ( ) ) statement_a_lemmas = set ( [ token . lemma_ for token in document_a if not token . is_stop ] ) statement_b_lemmas = set ( [ token . lemma_ for token in document_b if not to...
def path ( ) : """Detect config file path"""
# Detect config directory try : directory = os . environ [ "DID_DIR" ] except KeyError : directory = CONFIG # Detect config file ( even before options are parsed ) filename = "config" matched = re . search ( "--confi?g?[ =](\S+)" , " " . join ( sys . argv ) ) if matched : filename = matched . groups ( ) [ 0...
def export_mesh ( mesh , file_obj , file_type = None , ** kwargs ) : """Export a Trimesh object to a file - like object , or to a filename Parameters file _ obj : str , file - like Where should mesh be exported to file _ type : str or None Represents file type ( eg : ' stl ' ) Returns exported : bytes...
# if we opened a file object in this function # we will want to close it when we ' re done was_opened = False if util . is_string ( file_obj ) : if file_type is None : file_type = ( str ( file_obj ) . split ( '.' ) [ - 1 ] ) . lower ( ) if file_type in _mesh_exporters : was_opened = True ...
def task_delete ( self , ** kw ) : """Marks a task as deleted , optionally specifying a completion date with the ' end ' argument ."""
def validate ( task ) : if task [ 'status' ] == Status . DELETED : raise ValueError ( "Task is already deleted." ) return self . _task_change_status ( Status . DELETED , validate , ** kw )
def set_tag ( self , ip_dest , next_hop , ** kwargs ) : """Set the tag value for the specified route Args : ip _ dest ( string ) : The ip address of the destination in the form of A . B . C . D / E next _ hop ( string ) : The next hop interface or ip address * * kwargs [ ' next _ hop _ ip ' ] ( string ) :...
# Call _ set _ route with the new tag information return self . _set_route ( ip_dest , next_hop , ** kwargs )
def _check_FITS_extvers ( img , extname , extvers ) : """Returns True if all ( except None ) extension versions specified by the argument ' extvers ' and that are of the type specified by the argument ' extname ' are present in the ' img ' FITS file . Returns False if some of the extension versions for a give...
default_extn = 1 if isinstance ( extname , str ) else 0 if isinstance ( extvers , list ) : extv = [ default_extn if ext is None else ext for ext in extvers ] else : extv = [ default_extn if extvers is None else extvers ] extv_in_fits = get_extver_list ( img , extname ) return set ( extv ) . issubset ( set ( ext...
def get_log_rhos ( target_action_log_probs , behaviour_action_log_probs ) : """With the selected log _ probs for multi - discrete actions of behaviour and target policies we compute the log _ rhos for calculating the vtrace ."""
t = tf . stack ( target_action_log_probs ) b = tf . stack ( behaviour_action_log_probs ) log_rhos = tf . reduce_sum ( t - b , axis = 0 ) return log_rhos
def eradicate_pgroup ( self , pgroup , ** kwargs ) : """Eradicate a destroyed pgroup . : param pgroup : Name of pgroup to be eradicated . : type pgroup : str : param \ * \ * kwargs : See the REST API Guide on your array for the documentation on the request : * * DELETE pgroup / : pgroup * * : type \ * \...
eradicate = { "eradicate" : True } eradicate . update ( kwargs ) return self . _request ( "DELETE" , "pgroup/{0}" . format ( pgroup ) , eradicate )
def find ( self , item , description = '' , event_type = '' ) : """Find regexp in activitylog find record as if type are in description ."""
# TODO : should be refactored , dumb logic if ': ' in item : splited = item . split ( ': ' , 1 ) if splited [ 0 ] in self . TYPES : description = item . split ( ': ' ) [ 1 ] event_type = item . split ( ': ' ) [ 0 ] else : description = item else : if not description : des...
def exclude_file ( self , file ) : """True if file should be exclude based on name pattern ."""
for pattern in self . compiled_exclude_files : if ( pattern . match ( file ) ) : return ( True ) return ( False )
def parse ( cls : Type [ MessageT ] , uid : int , data : bytes , permanent_flags : Iterable [ Flag ] , internal_date : datetime , expunged : bool = False , ** kwargs : Any ) -> MessageT : """Parse the given file object containing a MIME - encoded email message into a : class : ` BaseLoadedMessage ` object . Arg...
content = MessageContent . parse ( data ) return cls ( uid , permanent_flags , internal_date , expunged , content , ** kwargs )
def appt_exists ( self , complex : str , house : str , appt : str ) -> bool : """Shortcut to check if appt exists in our database ."""
try : self . check_appt ( complex , house , appt ) except exceptions . RumetrApptNotFound : return False return True
def add_otp_style ( self , zip_odp , style_file ) : """takes the slide content and merges in the style _ file"""
style = zipwrap . Zippier ( style_file ) for picture_file in style . ls ( "Pictures" ) : zip_odp . write ( picture_file , style . cat ( picture_file , True ) ) xml_data = style . cat ( "styles.xml" , False ) # import pdb ; pdb . set _ trace ( ) xml_data = self . override_styles ( xml_data ) zip_odp . write ( "style...
def ph_basename ( self , ph_type ) : """Return the base name for a placeholder of * ph _ type * in this shape collection . A notes slide uses a different name for the body placeholder and has some unique placeholder types , so this method overrides the default in the base class ."""
return { PP_PLACEHOLDER . BODY : 'Notes Placeholder' , PP_PLACEHOLDER . DATE : 'Date Placeholder' , PP_PLACEHOLDER . FOOTER : 'Footer Placeholder' , PP_PLACEHOLDER . HEADER : 'Header Placeholder' , PP_PLACEHOLDER . SLIDE_IMAGE : 'Slide Image Placeholder' , PP_PLACEHOLDER . SLIDE_NUMBER : 'Slide Number Placeholder' , } ...
def _adorn_subplots ( self ) : """Common post process unrelated to data"""
if len ( self . axes ) > 0 : all_axes = self . _get_subplots ( ) nrows , ncols = self . _get_axes_layout ( ) _handle_shared_axes ( axarr = all_axes , nplots = len ( all_axes ) , naxes = nrows * ncols , nrows = nrows , ncols = ncols , sharex = self . sharex , sharey = self . sharey ) for ax in self . axes : ...
def find_dotenv ( filename = '.env' , raise_error_if_not_found = False , usecwd = False ) : """Search in increasingly higher folders for the given file Returns path to the file if found , or an empty string otherwise"""
if usecwd or '__file__' not in globals ( ) : # should work without _ _ file _ _ , e . g . in REPL or IPython notebook path = os . getcwd ( ) else : # will work for . py files frame_filename = sys . _getframe ( ) . f_back . f_code . co_filename path = os . path . dirname ( os . path . abspath ( frame_filenam...
def miller_index_from_sites ( lattice , coords , coords_are_cartesian = True , round_dp = 4 , verbose = True ) : """Get the Miller index of a plane from a list of site coordinates . A minimum of 3 sets of coordinates are required . If more than 3 sets of coordinates are given , the best plane that minimises the...
if not isinstance ( lattice , Lattice ) : lattice = Lattice ( lattice ) return lattice . get_miller_index_from_coords ( coords , coords_are_cartesian = coords_are_cartesian , round_dp = round_dp , verbose = verbose )
def urlretrieve ( self , url , filename , data = None ) : """Similar to urllib . urlretrieve or urllib . request . urlretrieve only that * filname * is required . : param url : URL to download . : param filename : Filename to save the content to . : param data : Valid URL - encoded data . : return : Tuple...
logger . info ( 'saving: \'%s\' to \'%s\'' , url , filename ) if _is_py3 : return _urlretrieve_with_opener ( self . opener , url , filename , data = data ) return self . opener2 . retrieve ( url , filename , data = data )
def plot ( self , numPoints = 100 ) : """Specific plotting method for cylinders ."""
fig = plt . figure ( ) ax = fig . add_subplot ( 111 , projection = '3d' ) # generate sphere phi , theta = np . meshgrid ( np . linspace ( 0 , pi , numPoints ) , np . linspace ( 0 , 2 * pi , numPoints ) ) x = self . radius * np . sin ( phi ) * np . cos ( theta ) y = self . radius * np . sin ( phi ) * np . sin ( theta ) ...
def startSubscription ( self , reqId , subscriber , contract = None ) : """Register a live subscription ."""
self . _reqId2Contract [ reqId ] = contract self . reqId2Subscriber [ reqId ] = subscriber
def main ( ) : """Be the top - level entrypoint . Return a shell status code ."""
commands = { 'hash' : peep_hash , 'install' : peep_install , 'port' : peep_port } try : if len ( argv ) >= 2 and argv [ 1 ] in commands : return commands [ argv [ 1 ] ] ( argv [ 2 : ] ) else : # Fall through to top - level pip main ( ) for everything else : return pip . main ( ) except PipExcept...
def _get_unique_index ( self , dropna = False ) : """Returns an index containing unique values . Parameters dropna : bool If True , NaN values are dropped . Returns uniques : index"""
if self . is_unique and not dropna : return self values = self . values if not self . is_unique : values = self . unique ( ) if dropna : try : if self . hasnans : values = values [ ~ isna ( values ) ] except NotImplementedError : pass return self . _shallow_copy ( values )
def create_room ( self , vc_room , event ) : """Create a new Vidyo room for an event , given a VC room . In order to create the Vidyo room , the function will try to do so with all the available identities of the user based on the authenticators defined in Vidyo plugin ' s settings , in that order . : param...
client = AdminClient ( self . settings ) owner = retrieve_principal ( vc_room . data [ 'owner' ] ) login_gen = iter_user_identities ( owner ) login = next ( login_gen , None ) if login is None : raise VCRoomError ( _ ( "No valid Vidyo account found for this user" ) , field = 'owner_user' ) extension_gen = iter_exte...
def do_part ( self , cmdargs , nick , target , msgtype , send , c ) : """Leaves a channel . Prevent user from leaving the primary channel ."""
channel = self . config [ 'core' ] [ 'channel' ] botnick = self . config [ 'core' ] [ 'nick' ] if not cmdargs : # don ' t leave the primary channel if target == channel : send ( "%s must have a home." % botnick ) return else : cmdargs = target if not cmdargs . startswith ( ( '#' , '+' , ...
def Geldart_Ling ( mp , rhog , D , mug ) : r'''Calculates saltation velocity of the gas for pneumatic conveying , according to [ 1 ] _ as described in [ 2 ] _ and [ 3 ] _ . if Gs / D < 47000 , use equation 1 , otherwise use equation 2. . . math : : V _ { salt } = 1.5G _ s ^ { 0.465 } D ^ { - 0.01 } \ mu ^ {...
Gs = mp / ( pi / 4 * D ** 2 ) if Gs / D <= 47000 : V = 1.5 * Gs ** 0.465 * D ** - 0.01 * mug ** 0.055 * rhog ** - 0.42 else : V = 8.7 * Gs ** 0.302 * D ** 0.153 * mug ** 0.055 * rhog ** - 0.42 return V
def _eval ( self , e , n , extra_constraints = ( ) , exact = None ) : """Evaluate an expression , using the solver if necessary . Returns primitives . : param e : the expression : param n : the number of desired solutions : param extra _ constraints : extra constraints to apply to the solver : param exact :...
return self . _solver . eval ( e , n , extra_constraints = self . _adjust_constraint_list ( extra_constraints ) , exact = exact )
def push ( h , x ) : """Push a new value into heap ."""
h . push ( x ) up ( h , h . size ( ) - 1 )
def returner ( load ) : '''Write return to all returners in multi _ returner'''
for returner_ in __opts__ [ CONFIG_KEY ] : _mminion ( ) . returners [ '{0}.returner' . format ( returner_ ) ] ( load )
def trigger ( self , transport ) : """Triggers the transport ."""
logger . debug ( 'IEC60488 trigger' ) with transport : try : transport . trigger ( ) except AttributeError : trigger_msg = self . create_message ( '*TRG' ) transport . write ( trigger_msg )
def get_changes ( self , getter = None , setter = None , resources = None , task_handle = taskhandle . NullTaskHandle ( ) ) : """Get the changes this refactoring makes If ` getter ` is not ` None ` , that will be the name of the getter , otherwise ` ` get _ $ { field _ name } ` ` will be used . The same is tr...
if resources is None : resources = self . project . get_python_files ( ) changes = ChangeSet ( 'Encapsulate field <%s>' % self . name ) job_set = task_handle . create_jobset ( 'Collecting Changes' , len ( resources ) ) if getter is None : getter = 'get_' + self . name if setter is None : setter = 'set_' + s...