signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def add_routes ( self , routes ) : '''Merges a Bottle application into this one . : param routes : A Bottle application or a sequence of routes . : type routes : : class : ` bottle . Bottle ` or ` [ bottle route ] ` . : rtype : : class : ` WebBuilder `'''
# Basically the same as ` self . app . merge ( routes ) ` , except this # changes the owner of the route so that plugins on ` self . app ` # apply to the routes given here . if isinstance ( routes , bottle . Bottle ) : routes = routes . routes for route in routes : route . app = self . app self . app . add_...
def load_mmd ( ) : """Loads libMultiMarkdown for usage"""
global _MMD_LIB global _LIB_LOCATION try : lib_file = 'libMultiMarkdown' + SHLIB_EXT [ platform . system ( ) ] _LIB_LOCATION = os . path . abspath ( os . path . join ( DEFAULT_LIBRARY_DIR , lib_file ) ) if not os . path . isfile ( _LIB_LOCATION ) : _LIB_LOCATION = ctypes . util . find_library ( 'Mul...
def get_view_by_env ( self , env ) : """Returns the view of ` env ` ."""
version , data = self . _get ( self . _get_view_path ( env ) ) return data
def catalog_sections ( context , slug = None , level = 3 , ** kwargs ) : """Отображает иерерхический список категорий каталога . Для каждой категории отображается количество содержащегося в ней товара . Пример использования : : { % catalog _ sections ' section _ slug ' 2 class = ' catalog - class ' % } ...
count_products = Count ( Case ( When ( product__active = True , then = Value ( 1 ) ) , output_field = IntegerField ( ) ) ) if slug is None : sections = Section . objects . annotate ( product__count = count_products ) . all ( ) max_level = level - 1 else : section = Section . objects . get ( slug = slug ) ...
def medial_axis ( self , resolution = None , clip = None ) : """Find the approximate medial axis based on a voronoi diagram of evenly spaced points on the boundary of the polygon . Parameters resolution : None or float Distance between each sample on the polygon boundary clip : None , or ( 2 , ) float ...
if resolution is None : resolution = self . scale / 1000.0 # convert the edges to Path2D kwargs from . exchange . misc import edges_to_path # edges and vertices edge_vert = [ polygons . medial_axis ( i , resolution , clip ) for i in self . polygons_full ] # create a Path2D object for each region medials = [ Path2D ...
def from_json ( cls , data , api = None ) : """Create a new instance and load data from json object . : param data : JSON data returned by the Overpass API : type data : Dict : param api : : type api : overpy . Overpass : return : New instance of Result object : rtype : overpy . Result"""
result = cls ( api = api ) for elem_cls in [ Node , Way , Relation , Area ] : for element in data . get ( "elements" , [ ] ) : e_type = element . get ( "type" ) if hasattr ( e_type , "lower" ) and e_type . lower ( ) == elem_cls . _type_value : result . append ( elem_cls . from_json ( ele...
def mark ( self , channel , ts ) : """https : / / api . slack . com / methods / im . mark"""
self . params . update ( { 'channel' : channel , 'ts' : ts , } ) return FromUrl ( 'https://slack.com/api/im.mark' , self . _requests ) ( data = self . params ) . post ( )
def add_mvn ( self , name , input_name , output_name , across_channels = True , normalize_variance = True , epsilon = 1e-5 ) : """Add an MVN ( mean variance normalization ) layer . Computes mean , variance and normalizes the input . Parameters name : str The name of this layer . input _ name : str The inp...
spec = self . spec nn_spec = self . nn_spec # Add a new layer spec_layer = nn_spec . layers . add ( ) spec_layer . name = name spec_layer . input . append ( input_name ) spec_layer . output . append ( output_name ) spec_layer_params = spec_layer . mvn spec_layer_params . acrossChannels = across_channels spec_layer_para...
def machineCurrents ( self , Xg , U ) : """Based on MachineCurrents . m from MatDyn by Stijn Cole , developed at Katholieke Universiteit Leuven . See U { http : / / www . esat . kuleuven . be / electa / teaching / matdyn / } for more information . @ param Xg : Generator state variables . @ param U : Generat...
generators = self . dyn_generators # Initialise . ng = len ( generators ) Id = zeros ( ng ) Iq = zeros ( ng ) Pe = zeros ( ng ) typ1 = [ g . _i for g in generators if g . model == CLASSICAL ] typ2 = [ g . _i for g in generators if g . model == FOURTH_ORDER ] # Generator type 1 : classical model delta = Xg [ typ1 , 0 ] ...
def count ( self , value ) : """The count property . Args : value ( int ) . the property value ."""
if value == self . _defaults [ 'count' ] and 'count' in self . _values : del self . _values [ 'count' ] else : self . _values [ 'count' ] = value
def authenticate ( db , user , password ) : """Return True / False on authentication success . PyMongo 2.6 changed the auth API to raise on Auth failure ."""
try : logger . debug ( "Authenticating {} with {}" . format ( db , user ) ) return db . authenticate ( user , password ) except OperationFailure as e : logger . debug ( "Auth Error %s" % e ) return False
def _build_late_dispatcher ( func_name ) : """Return a function that calls method ' func _ name ' on objects . This is useful for building late - bound dynamic dispatch . Arguments : func _ name : The name of the instance method that should be called . Returns : A function that takes an ' obj ' parameter ...
def _late_dynamic_dispatcher ( obj , * args ) : method = getattr ( obj , func_name , None ) if not callable ( method ) : raise NotImplementedError ( "Instance method %r is not implemented by %r." % ( func_name , obj ) ) return method ( * args ) return _late_dynamic_dispatcher
def extract_context_data ( self ) : """Returns the contents of a AWS Lambda context . : returns : A dict of relevant context data . : rtype : dict"""
data = { } for k , v in { # camel case names in the report to align with AWS standards "functionName" : "function_name" , "functionVersion" : "function_version" , "memoryLimitInMB" : "memory_limit_in_mb" , "invokedFunctionArn" : "invoked_function_arn" , "awsRequestId" : "aws_request_id" , "logGroupName" : "log_group_na...
def parse_line ( self , line_str ) : """Parse line from file ( including trailing line break ) and return resulting Record"""
line_str = line_str . rstrip ( ) if not line_str : return None # empty line , EOF arr = self . _split_line ( line_str ) # CHROM chrom = arr [ 0 ] # POS pos = int ( arr [ 1 ] ) # IDS if arr [ 2 ] == "." : ids = [ ] else : ids = arr [ 2 ] . split ( ";" ) # REF ref = arr [ 3 ] # ALT alts = [ ] if arr [ 4 ]...
def node_to_nodal_planes ( node ) : """Parses the nodal plane distribution to a PMF"""
if not len ( node ) : return None npd_pmf = [ ] for plane in node . nodes : if not all ( plane . attrib [ key ] for key in plane . attrib ) : # One plane fails - return None return None npd = NodalPlane ( float ( plane . attrib [ "strike" ] ) , float ( plane . attrib [ "dip" ] ) , float ( plane . at...
def generate_request_xml ( message_identifier_id , operation , lis_result_sourcedid , score ) : # pylint : disable = too - many - locals """Generates LTI 1.1 XML for posting result to LTI consumer . : param message _ identifier _ id : : param operation : : param lis _ result _ sourcedid : : param score : ...
root = etree . Element ( u'imsx_POXEnvelopeRequest' , xmlns = u'http://www.imsglobal.org/services/' u'ltiv1p1/xsd/imsoms_v1p0' ) header = etree . SubElement ( root , 'imsx_POXHeader' ) header_info = etree . SubElement ( header , 'imsx_POXRequestHeaderInfo' ) version = etree . SubElement ( header_info , 'imsx_version' )...
def _get_and_start_work ( self ) : "return ( async _ result , work _ unit ) or ( None , None )"
worker_id = nice_identifier ( ) work_unit = self . task_master . get_work ( worker_id , available_gb = self . available_gb ( ) ) if work_unit is None : return None , None async_result = self . pool . apply_async ( run_worker , ( HeadlessWorker , self . task_master . registry . config , worker_id , work_unit . work_...
async def edit ( self , ** fields ) : """| coro | Edits the message . The content must be able to be transformed into a string via ` ` str ( content ) ` ` . Parameters content : Optional [ : class : ` str ` ] The new content to replace the message with . Could be ` ` None ` ` to remove the content . e...
try : content = fields [ 'content' ] except KeyError : pass else : if content is not None : fields [ 'content' ] = str ( content ) try : embed = fields [ 'embed' ] except KeyError : pass else : if embed is not None : fields [ 'embed' ] = embed . to_dict ( ) data = await self . _s...
def aes_decrypt ( key : bytes , cipher_text : bytes ) -> bytes : """AES - GCM decryption Parameters key : bytes AES session key , which derived from two secp256k1 keys cipher _ text : bytes Encrypted text : nonce ( 16 bytes ) + tag ( 16 bytes ) + encrypted data Returns bytes Plain text > > > dat...
nonce = cipher_text [ : 16 ] tag = cipher_text [ 16 : 32 ] ciphered_data = cipher_text [ 32 : ] aes_cipher = AES . new ( key , AES_CIPHER_MODE , nonce = nonce ) return aes_cipher . decrypt_and_verify ( ciphered_data , tag )
def svd_flip ( u , v , u_based_decision = True ) : """Sign correction to ensure deterministic output from SVD . Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive . Parameters u , v : ndarray u and v are the output o...
if u_based_decision : # columns of u , rows of v max_abs_cols = np . argmax ( np . abs ( u ) , axis = 0 ) signs = np . sign ( u [ max_abs_cols , xrange ( u . shape [ 1 ] ) ] ) u *= signs v *= signs [ : , np . newaxis ] else : # rows of v , columns of u max_abs_rows = np . argmax ( np . abs ( v ) , a...
def make_sized_handler ( size , const_values , non_minimal_data_handler ) : """Create a handler for a data opcode that returns literal data of a fixed size ."""
const_values = list ( const_values ) def constant_size_opcode_handler ( script , pc , verify_minimal_data = False ) : pc += 1 data = bytes_as_hex ( script [ pc : pc + size ] ) if len ( data ) < size : return pc + 1 , None if verify_minimal_data and data in const_values : non_minimal_data...
def _add_parent_cnt ( self , hdr , goobj , c2ps ) : """Add the parent count to the GO term box for if not all parents are plotted ."""
if goobj . id in c2ps : parents = c2ps [ goobj . id ] if 'prt_pcnt' in self . present or parents and len ( goobj . parents ) != len ( parents ) : assert len ( goobj . parents ) == len ( set ( goobj . parents ) ) hdr . append ( "p{N}" . format ( N = len ( set ( goobj . parents ) ) ) )
def timesince ( self , when ) : """Returns human friendly version of the timespan between now and the given datetime ."""
units = ( ( "year" , 60 * 60 * 24 * 365 ) , ( "week" , 60 * 60 * 24 * 7 ) , ( "day" , 60 * 60 * 24 ) , ( "hour" , 60 * 60 ) , ( "minute" , 60 ) , ( "second" , 1 ) , ) delta = datetime . now ( ) - when total_seconds = delta . days * 60 * 60 * 24 + delta . seconds parts = [ ] for name , seconds in units : value = tot...
def plot ( self , data , w = 800 , h = 420 ) : """Output an iframe containing the plot in the notebook without saving ."""
return HTML ( self . iframe . format ( source = self . render ( data = data , div_id = "chart" , head = self . head ) , w = w , h = h ) )
def get_sequence_rule_mdata ( ) : """Return default mdata map for SequenceRule"""
return { 'next_assessment_part' : { 'element_label' : { 'text' : 'next assessment part' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'accepts an osid.id.Id object' , 'languageTypeId' : s...
def get_types ( obj , ** kwargs ) : """Get the types of an iterable ."""
max_iterable_length = kwargs . get ( 'max_iterable_length' , 100000 ) it , = itertools . tee ( obj , 1 ) s = set ( ) too_big = False for i , v in enumerate ( it ) : if i <= max_iterable_length : s . add ( type ( v ) ) else : too_big = True break return { "types" : s , "too_big" : too_big...
def dispatch_command ( self , command , params = None ) : """Dispatch device commands to the appropriate handler ."""
try : if command in self . handlers : self . handlers [ command ] ( ** params ) else : logging . warning ( 'Unsupported command: %s: %s' , command , params ) except Exception as e : logging . warning ( 'Error during command execution' , exc_info = sys . exc_info ( ) ) raise e
def ean ( self ) : """EAN . : return : EAN ( string )"""
ean = self . _safe_get_element_text ( 'ItemAttributes.EAN' ) if ean is None : ean_list = self . _safe_get_element_text ( 'ItemAttributes.EANList' ) if ean_list : ean = self . _safe_get_element_text ( 'EANListElement' , root = ean_list [ 0 ] ) return ean
def _CreateSingleValueCondition ( self , value , operator ) : """Creates a single - value condition with the provided value and operator ."""
if isinstance ( value , str ) or isinstance ( value , unicode ) : value = '"%s"' % value return '%s %s %s' % ( self . _field , operator , value )
def _get_alpha ( self , C , vs30 , pga_rock ) : """Returns the alpha , the linearised functional relationship between the site amplification and the PGA on rock . Equation 31."""
alpha = np . zeros ( len ( pga_rock ) ) idx = vs30 < C [ "k1" ] if np . any ( idx ) : af1 = pga_rock [ idx ] + self . CONSTS [ "c" ] * ( ( vs30 [ idx ] / C [ "k1" ] ) ** self . CONSTS [ "n" ] ) af2 = pga_rock [ idx ] + self . CONSTS [ "c" ] alpha [ idx ] = C [ "k2" ] * pga_rock [ idx ] * ( ( 1.0 / af1 ) - (...
def center_crop ( src , size , interp = 2 ) : """Crops the image ` src ` to the given ` size ` by trimming on all four sides and preserving the center of the image . Upsamples if ` src ` is smaller than ` size ` . . . note : : This requires MXNet to be compiled with USE _ OPENCV . Parameters src : NDArray...
h , w , _ = src . shape new_w , new_h = scale_down ( ( w , h ) , size ) x0 = int ( ( w - new_w ) / 2 ) y0 = int ( ( h - new_h ) / 2 ) out = fixed_crop ( src , x0 , y0 , new_w , new_h , size , interp ) return out , ( x0 , y0 , new_w , new_h )
def refresh ( self ) : """Keeps the lease alive by streaming keep alive requests from the client to the server and streaming keep alive responses from the server to the client . : returns : Response header . : rtype : instance of : class : ` txaioetcd . Header `"""
if self . _expired : raise Expired ( ) obj = { # ID is the lease ID for the lease to keep alive . u'ID' : self . lease_id , } data = json . dumps ( obj ) . encode ( 'utf8' ) url = u'{}/v3alpha/lease/keepalive' . format ( self . _client . _url ) . encode ( ) response = yield treq . post ( url , data , headers = self...
def str_numerator ( self ) : """Returns the numerator with formatting ."""
if not self . undefined : return None unit_numerator , unit = self . _unit_class ( self . numerator ) . auto formatter = '%d' if unit_numerator == self . numerator else '%0.2f' numerator = locale . format ( formatter , unit_numerator , grouping = True ) return '{0} {1}' . format ( numerator , unit )
def plotMT ( T , N , P , size = 200 , plot_zerotrace = True , x0 = 0 , y0 = 0 , xy = ( 0 , 0 ) , width = 200 ) : """Uses a principal axis T , N and P to draw a beach ball plot . : param ax : axis object of a matplotlib figure : param T : : class : ` ~ PrincipalAxis ` : param N : : class : ` ~ PrincipalAxis ` ...
# check if one or two widths are specified ( Circle or Ellipse ) try : assert ( len ( width ) == 2 ) except TypeError : width = ( width , width ) collect = [ ] colors = [ ] res = [ value / float ( size ) for value in width ] b = 1 big_iso = 0 j = 1 j2 = 0 j3 = 0 n = 0 azi = np . zeros ( ( 3 , 2 ) ) x = np . zer...
def _serialize ( self , element , # type : ET . Element value , # type : Any state # type : _ ProcessorState ) : # type : ( . . . ) - > None """Serialize the value to the element ."""
xml_value = _hooks_apply_before_serialize ( self . _hooks , state , value ) # A value is only considered missing , and hence eligible to be replaced by its # default only if it is None . Falsey values are not considered missing and are # not replaced by the default . if xml_value is None : if self . _default is Non...
def chimera_layout ( G , scale = 1. , center = None , dim = 2 ) : """Positions the nodes of graph G in a Chimera cross topology . NumPy ( http : / / scipy . org ) is required for this function . Parameters G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph . If every node in G h...
if not isinstance ( G , nx . Graph ) : empty_graph = nx . Graph ( ) empty_graph . add_edges_from ( G ) G = empty_graph # now we get chimera coordinates for the translation # first , check if we made it if G . graph . get ( "family" ) == "chimera" : m = G . graph [ 'rows' ] n = G . graph [ 'columns' ...
def _add_msg ( self , m ) : '''add a new message'''
type = m . get_type ( ) self . messages [ type ] = m if self . clock : self . clock . message_arrived ( m ) if type == 'MSG' : if m . Message . find ( "Rover" ) != - 1 : self . mav_type = mavutil . mavlink . MAV_TYPE_GROUND_ROVER elif m . Message . find ( "Plane" ) != - 1 : self . mav_type =...
def read_string ( self ) : """Read string from input file with UTF - 8 encoding ."""
length = self . read_int ( ) return str ( self . read ( length ) . decode ( "UTF-8" ) )
def concatenate ( self , tup , axis = 0 ) : """Join a sequence of Timeseries to this one Args : tup ( sequence of Timeseries ) : timeseries to be joined with this one . They must have the same shape as this Timeseries , except in the dimension corresponding to ` axis ` . axis ( int , optional ) : The axis...
if not isinstance ( tup , Sequence ) : tup = ( tup , ) if tup is ( None , ) or len ( tup ) is 0 : return self tup = ( self , ) + tuple ( tup ) new_array = np . concatenate ( tup , axis ) if not all ( hasattr ( ts , 'tspan' ) and hasattr ( ts , 'labels' ) for ts in tup ) : return new_array if axis == 0 : ...
def _set_bridge_domain_counter ( self , v , load = False ) : """Setter method for bridge _ domain _ counter , mapped from YANG variable / bridge _ domain _ state / bridge _ domain _ counter ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ bridge _ domain _ ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = bridge_domain_counter . bridge_domain_counter , is_container = 'container' , presence = False , yang_name = "bridge-domain-counter" , rest_name = "bridge-domain-counter" , parent = self , path_helper = self . _path_helper , e...
def _get_mosaik_nn_args ( out_file ) : """Retrieve default neural network files from GitHub to pass to Mosaik ."""
base_nn_url = "https://raw.github.com/wanpinglee/MOSAIK/master/src/networkFile/" out = [ ] for arg , fname in [ ( "-annse" , "2.1.26.se.100.005.ann" ) , ( "-annpe" , "2.1.26.pe.100.0065.ann" ) ] : arg_fname = os . path . join ( os . path . dirname ( out_file ) , fname ) if not file_exists ( arg_fname ) : ...
def flow_ramp ( self ) : """An equally spaced array representing flow at each row ."""
return np . linspace ( 1 / self . n_rows , 1 , self . n_rows ) * self . q
def get_extensions ( cls ) : """: return : Available file extensions . : rtype : list : Example : . . code : : python > > > import pytablewriter as ptw > > > for name in ptw . TableWriterFactory . get _ extensions ( ) : . . . print ( name ) csv htm html js json jsonl ldjson ltsv md n...
file_extension_set = set ( ) for table_format in TableFormat : for file_extension in table_format . file_extensions : file_extension_set . add ( file_extension ) return sorted ( list ( file_extension_set ) )
def factory ( start_immediately = True ) : """This is a decorator function that creates new ` Job ` s with the wrapped function as the target . # Example ` ` ` python @ Job . factory ( ) def some _ longish _ function ( job , seconds ) : time . sleep ( seconds ) return 42 job = some _ longish _ funct...
def decorator ( func ) : def wrapper ( * args , ** kwargs ) : job = Job ( task = lambda j : func ( j , * args , ** kwargs ) ) if start_immediately : job . start ( ) return job return wrapper return decorator
def peddy_het_check_plot ( self ) : """plot the het _ check scatter plot"""
# empty dictionary to add sample names , and dictionary of values data = { } # for each sample , and list in self . peddy _ data for s_name , d in self . peddy_data . items ( ) : # check the sample contains the required columns if 'median_depth_het_check' in d and 'het_ratio_het_check' in d : # add sample to dictio...
def verify_checksum ( self ) : """Verify the checksum in the header for this HDU ."""
res = self . _FITS . verify_checksum ( self . _ext + 1 ) if res [ 'dataok' ] != 1 : raise ValueError ( "data checksum failed" ) if res [ 'hduok' ] != 1 : raise ValueError ( "hdu checksum failed" )
def log_request_end_send ( self , target_system , target_component , force_mavlink1 = False ) : '''Stop log transfer and resume normal logging target _ system : System ID ( uint8 _ t ) target _ component : Component ID ( uint8 _ t )'''
return self . send ( self . log_request_end_encode ( target_system , target_component ) , force_mavlink1 = force_mavlink1 )
def _get_plunger_position ( self , position ) : """Returns the calibrated coordinate of a given plunger position Raises exception if the position has not been calibrated yet"""
try : value = self . plunger_positions [ position ] if helpers . is_number ( value ) : return value else : raise RuntimeError ( 'Plunger position "{}" not yet calibrated' . format ( position ) ) except KeyError : raise RuntimeError ( 'Plunger position "{}" does not exist' . format ( posi...
def get ( self , uid ) : """Get a user ' s information by their id . : param uid str : User ID : return : The user ' s information or None : rtype : Dictionary or None"""
r = requests . get ( self . apiurl + "/users/{}" . format ( uid ) , headers = self . header ) if r . status_code != 200 : raise ServerError jsd = r . json ( ) if jsd [ 'data' ] : return jsd [ 'data' ] else : return None
def generate_noise ( shape : List [ int ] , porosity = None , octaves : int = 3 , frequency : int = 32 , mode : str = 'simplex' ) : r"""Generate a field of spatially correlated random noise using the Perlin noise algorithm , or the updated Simplex noise algorithm . Parameters shape : array _ like The size o...
try : import noise except ModuleNotFoundError : raise Exception ( "The noise package must be installed" ) shape = sp . array ( shape ) if sp . size ( shape ) == 1 : Lx , Ly , Lz = sp . full ( ( 3 , ) , int ( shape ) ) elif len ( shape ) == 2 : Lx , Ly = shape Lz = 1 elif len ( shape ) == 3 : Lx ...
def render ( template_file , saltenv = 'base' , sls = '' , context = None , tmplpath = None , ** kws ) : '''Render the template _ file , passing the functions and grains into the Mako rendering system . : rtype : string'''
tmp_data = salt . utils . templates . MAKO ( template_file , to_str = True , salt = __salt__ , grains = __grains__ , opts = __opts__ , pillar = __pillar__ , saltenv = saltenv , sls = sls , context = context , tmplpath = tmplpath , ** kws ) if not tmp_data . get ( 'result' , False ) : raise SaltRenderError ( tmp_dat...
async def addNode ( self , name , valu , props = None ) : '''Add a node by form name and value with optional props . Args : name ( str ) : The form of node to add . valu ( obj ) : The value for the node . props ( dict ) : Optional secondary properties for the node .'''
try : fnib = self . _getNodeFnib ( name , valu ) retn = await self . _addNodeFnib ( fnib , props = props ) return retn except asyncio . CancelledError : raise except Exception : mesg = f'Error adding node: {name} {valu!r} {props!r}' logger . exception ( mesg ) if self . strict : rais...
def index ( self , key ) : """Get the index of a given entry , raising an IndexError if it ' s not present . ` key ` can be an iterable of entries that is not a string , in which case this returns a list of indices ."""
if is_iterable ( key ) : return [ self . index ( subkey ) for subkey in key ] return self . map [ key ]
def MAFFT ( sequences , gap_open = 1.53 , gap_extension = 0.0 , retree = 2 ) : '''A Coral wrapper for the MAFFT command line multiple sequence aligner . : param sequences : A list of sequences to align . : type sequences : List of homogeneous sequences ( all DNA , or all RNA , etc . ) : param gap _ open : -...
arguments = [ 'mafft' ] arguments += [ '--op' , str ( gap_open ) ] arguments += [ '--ep' , str ( gap_extension ) ] arguments += [ '--retree' , str ( retree ) ] arguments . append ( 'input.fasta' ) tempdir = tempfile . mkdtemp ( ) try : with open ( os . path . join ( tempdir , 'input.fasta' ) , 'w' ) as f : ...
def generation_termination ( population , num_generations , num_evaluations , args ) : """Return True if the number of generations meets or exceeds a maximum . This function compares the number of generations with a specified maximum . It returns True if the maximum is met or exceeded . . . Arguments : popu...
max_generations = args . setdefault ( 'max_generations' , 1 ) return num_generations >= max_generations
def get_index ( self ) : '''Convert an interface name to an index value .'''
ifreq = struct . pack ( '16si' , self . name , 0 ) res = fcntl . ioctl ( sockfd , SIOCGIFINDEX , ifreq ) return struct . unpack ( "16si" , res ) [ 1 ]
def load_object_from_string ( fqcn ) : """Converts " . " delimited strings to a python object . Given a " . " delimited string representing the full path to an object ( function , class , variable ) inside a module , return that object . Example : load _ object _ from _ string ( " os . path . basename " ) l...
module_path = "__main__" object_name = fqcn if "." in fqcn : module_path , object_name = fqcn . rsplit ( "." , 1 ) importlib . import_module ( module_path ) return getattr ( sys . modules [ module_path ] , object_name )
def _convert_to_lexicon ( self , record ) : """converts from namecheap raw record format to lexicon format record"""
name = record [ 'Name' ] if self . domain not in name : name = "{}.{}" . format ( name , self . domain ) processed_record = { 'type' : record [ 'Type' ] , 'name' : '{0}.{1}' . format ( record [ 'Name' ] , self . domain ) , 'ttl' : record [ 'TTL' ] , 'content' : record [ 'Address' ] , 'id' : record [ 'HostId' ] } re...
def get_account ( self , account ) : '''check the account whether in the protfolio dict or not : param account : QA _ Account : return : QA _ Account if in dict None not in list'''
try : return self . get_account_by_cookie ( account . account_cookie ) except : QA_util_log_info ( 'Can not find this account with cookies %s' % account . account_cookie ) return None
def polyds ( coeffs , deg , nderiv , t ) : """Compute the value of a polynomial and it ' s first n derivatives at the value t . https : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / polyds _ c . html : param coeffs : Coefficients of the polynomial to be evaluated . : type coeffs :...
coeffs = stypes . toDoubleVector ( coeffs ) deg = ctypes . c_int ( deg ) p = stypes . emptyDoubleVector ( nderiv + 1 ) nderiv = ctypes . c_int ( nderiv ) t = ctypes . c_double ( t ) libspice . polyds_c ( ctypes . byref ( coeffs ) , deg , nderiv , t , p ) return stypes . cVectorToPython ( p )
def accumulate ( a_generator , cooperator = None ) : """Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a _ generator . : param a _ generator : An iterator which yields some not None values . : return : A Deferred to which the next callback will be called with t...
if cooperator : own_cooperate = cooperator . cooperate else : own_cooperate = cooperate spigot = ValueBucket ( ) items = stream_tap ( ( spigot , ) , a_generator ) d = own_cooperate ( items ) . whenDone ( ) d . addCallback ( accumulation_handler , spigot ) return d
def eigenvalues_auto ( mat , n_eivals = 'auto' ) : """Automatically computes the spectrum of a given Laplacian matrix . Parameters mat : numpy . ndarray or scipy . sparse Laplacian matrix n _ eivals : string or int or tuple Number of eigenvalues to compute / use for approximation . If string , we expect...
do_full = True n_lower = 150 n_upper = 150 nv = mat . shape [ 0 ] if n_eivals == 'auto' : if mat . shape [ 0 ] > 1024 : do_full = False if n_eivals == 'full' : do_full = True if isinstance ( n_eivals , int ) : n_lower = n_upper = n_eivals do_full = False if isinstance ( n_eivals , tuple ) : ...
def main ( ) : """Measure capnp serialization performance of a network containing a simple python region that in - turn contains a Random instance ."""
engine . Network . registerPyRegion ( __name__ , SerializationTestPyRegion . __name__ ) try : _runTest ( ) finally : engine . Network . unregisterPyRegion ( SerializationTestPyRegion . __name__ )
def split_package ( package ) : """Split package in name , version arch and build tag ."""
name = ver = arch = build = [ ] split = package . split ( "-" ) if len ( split ) > 2 : build = split [ - 1 ] build_a , build_b = "" , "" build_a = build [ : 1 ] if build [ 1 : 2 ] . isdigit ( ) : build_b = build [ 1 : 2 ] build = build_a + build_b arch = split [ - 2 ] ver = split [ -...
def get_default_save_path ( ) : """Return default save path for the packages"""
macro = '%{_topdir}' if rpm : save_path = rpm . expandMacro ( macro ) else : save_path = rpm_eval ( macro ) if not save_path : logger . warn ( "rpm tools are missing, using default save path " "~/rpmbuild/." ) save_path = os . path . expanduser ( '~/rpmbuild' ) return save_path
def capture_delete_records ( records ) : """Writes all of our delete events to DynamoDB ."""
for rec in records : model = create_delete_model ( rec ) if model : try : model . delete ( condition = ( CurrentSecurityGroupModel . eventTime <= rec [ 'detail' ] [ 'eventTime' ] ) ) except DeleteError : LOG . warning ( f'[X] Unable to delete security group. Security grou...
def can_create_gradebook_column_with_record_types ( self , gradebook_column_record_types ) : """Tests if this user can create a single ` ` GradebookColumn ` ` using the desired record types . While ` ` GradingManager . getGradebookColumnRecordTypes ( ) ` ` can be used to examine which records are supported , th...
# Implemented from template for # osid . resource . BinAdminSession . can _ create _ bin _ with _ record _ types # NOTE : It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl . if self . _catalog_session is not None : return self . _catalog_session . ...
def start_at ( self , start_at ) : """Sets the start _ at of this Shift . RFC 3339 ; shifted to location timezone + offset . Precision up to the minute is respected ; seconds are truncated . : param start _ at : The start _ at of this Shift . : type : str"""
if start_at is None : raise ValueError ( "Invalid value for `start_at`, must not be `None`" ) if len ( start_at ) < 1 : raise ValueError ( "Invalid value for `start_at`, length must be greater than or equal to `1`" ) self . _start_at = start_at
def gen_opf ( self , book_idx ) : """生成项目文件 : return : : rtype :"""
if self . _chapterization : title = '{title}-{book_idx}' . format ( title = self . _title , book_idx = book_idx ) book = 'book-{book_idx}' . format ( book_idx = book_idx ) toc = 'toc-{book_idx}' . format ( book_idx = book_idx ) else : title = '{title}' . format ( title = self . _title ) book = 'book...
def all_sample_md5s ( self , type_tag = None ) : """Return a list of all md5 matching the type _ tag ( ' exe ' , ' pdf ' , etc ) . Args : type _ tag : the type of sample . Returns : a list of matching samples ."""
if type_tag : cursor = self . database [ self . sample_collection ] . find ( { 'type_tag' : type_tag } , { 'md5' : 1 , '_id' : 0 } ) else : cursor = self . database [ self . sample_collection ] . find ( { } , { 'md5' : 1 , '_id' : 0 } ) return [ match . values ( ) [ 0 ] for match in cursor ]
def MFI ( frame , n = 14 , high_col = 'high' , low_col = 'low' , close_col = 'close' , vol_col = 'Volume' ) : """money flow inedx"""
return _frame_to_series ( frame , [ high_col , low_col , close_col , vol_col ] , talib . MFI , n )
def sentence_spans ( self ) : """The list of spans representing ` ` sentences ` ` layer elements ."""
if not self . is_tagged ( SENTENCES ) : self . tokenize_sentences ( ) return self . spans ( SENTENCES )
def is_ready ( self , key ) : """Returns true if a result is available for ` ` key ` ` ."""
if self . pending_callbacks is None or key not in self . pending_callbacks : raise UnknownKeyError ( "key %r is not pending" % ( key , ) ) return key in self . results
def _load_vector_fit ( self , fit_key , h5file ) : """Loads a vector of fits"""
vector_fit = [ ] for i in range ( len ( h5file [ fit_key ] . keys ( ) ) ) : fit_data = self . _read_dict ( h5file [ fit_key ] [ 'comp_%d' % i ] ) vector_fit . append ( self . _load_scalar_fit ( fit_data = fit_data ) ) return vector_fit
def get_counter ( self , redis_conn = None , host = 'localhost' , port = 6379 , key = 'counter' , cycle_time = 5 , start_time = None , window = SECONDS_1_HOUR , roll = True , keep_max = 12 , start_at = 0 ) : '''Generate a new Counter Useful for generic distributed counters @ param redis _ conn : A premade redis...
counter = Counter ( key = key , cycle_time = cycle_time , start_time = start_time , window = window , roll = roll , keep_max = keep_max ) counter . setup ( redis_conn = redis_conn , host = host , port = port ) return counter
def convert_machine_list_value ( name : str , value : str ) -> Union [ datetime . datetime , str , int ] : '''Convert sizes and time values . Size will be ` ` int ` ` while time value will be : class : ` datetime . datetime ` .'''
if name == 'modify' : return convert_machine_list_time_val ( value ) elif name == 'size' : return int ( value ) else : return value
def available_digests ( family = None , name = None ) : """Return names of available generators : param family : name of hash - generator family to select : param name : name of hash - generator to select : return : set of int"""
generators = WHash . available_generators ( family = family , name = name ) return set ( [ WHash . generator ( x ) . generator_digest_size ( ) for x in generators ] )
def create_atari_environment ( name ) : """Create OpenAI Gym atari environment : param name : name of the atari game : return : Preconfigured environment suitable for atari games"""
env = gym . make ( name ) env = NoopResetEnv ( env , noop_max = 30 ) env = EpisodicLifeEnv ( env ) env = ClipRewardEnv ( env ) action_names = env . unwrapped . get_action_meanings ( ) if 'FIRE' in action_names : env = FireResetEnv ( env ) env = WarpFrame ( env ) env = FrameStack ( env , k = 4 ) return env
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : PayloadContext for this PayloadInstance : rtype : twilio . rest . api . v2010 . account . recording . add _ on _ result . ...
if self . _context is None : self . _context = PayloadContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , reference_sid = self . _solution [ 'reference_sid' ] , add_on_result_sid = self . _solution [ 'add_on_result_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def attach_storage ( self , server , storage , storage_type , address ) : """Attach a Storage object to a Server . Return a list of the server ' s storages ."""
body = { 'storage_device' : { } } if storage : body [ 'storage_device' ] [ 'storage' ] = str ( storage ) if storage_type : body [ 'storage_device' ] [ 'type' ] = storage_type if address : body [ 'storage_device' ] [ 'address' ] = address url = '/server/{0}/storage/attach' . format ( server ) res = self . po...
def stopService ( self ) : """Gracefully stop the service . Returns : defer . Deferred : a Deferred which is triggered when the service has finished shutting down ."""
self . _service . factory . stopTrying ( ) yield self . _service . factory . stopFactory ( ) yield service . MultiService . stopService ( self )
def get_operation_root_type ( schema : GraphQLSchema , operation : Union [ OperationDefinitionNode , OperationTypeDefinitionNode ] , ) -> GraphQLObjectType : """Extract the root type of the operation from the schema ."""
operation_type = operation . operation if operation_type == OperationType . QUERY : query_type = schema . query_type if not query_type : raise GraphQLError ( "Schema does not define the required query root type." , operation ) return query_type elif operation_type == OperationType . MUTATION : m...
def _walk_through ( job_dir ) : '''Walk though the jid dir and look for jobs'''
serial = salt . payload . Serial ( __opts__ ) for top in os . listdir ( job_dir ) : t_path = os . path . join ( job_dir , top ) if not os . path . exists ( t_path ) : continue for final in os . listdir ( t_path ) : load_path = os . path . join ( t_path , final , LOAD_P ) if not os . ...
def find_ips_by_equip ( self , id_equip ) : """Get Ips related to equipment by its identifier : param id _ equip : Equipment identifier . Integer value and greater than zero . : return : Dictionary with the following structure : { ips : { ipv4 : [ id : < id _ ip4 > , oct1 : < oct1 > , oct2 : < oct2 > , ...
url = 'ip/getbyequip/' + str ( id_equip ) + "/" code , xml = self . submit ( None , 'GET' , url ) return self . response ( code , xml , [ 'ipv4' , 'ipv6' ] )
def headers ( self , url ) : """Returns the https headers with credentials , if token is used and url is https : param url : url to be queried , including scheme : return : dict or None"""
if self . _token and url . lower ( ) . startswith ( 'https' ) : return { 'Authorization' : 'Bearer {}' . format ( self . _token ) } else : return None
def initFromDict ( self , adict , ** kwargs ) : """Initialize self from dictionary . : param adict : : return :"""
# First , flatten the dictionary into a dictionary of paths / files a_flat = C_stree . flatten ( adict ) l_dir = [ ] # Now , build a tree from this structure by generating a list of paths for k , v in a_flat . items ( ) : l_dir . append ( k . split ( '/' ) [ 1 : - 1 ] ) # remove duplicates . . . l_dir = [ list ( x ...
def conv2d_fixed_padding ( inputs , filters , kernel_size , strides , data_format ) : """Strided 2 - D convolution with explicit padding ."""
# The padding is consistent and is based only on ` kernel _ size ` , not on the # dimensions of ` inputs ` ( as opposed to using ` tf . layers . conv2d ` alone ) . inputs_for_logging = inputs if strides > 1 : inputs = fixed_padding ( inputs , kernel_size , data_format ) outputs = tf . layers . conv2d ( inputs = inp...
def input_text ( self , locator , text ) : """Types the given ` text ` into text field identified by ` locator ` . See ` introduction ` for details about locating elements ."""
self . _info ( "Typing text '%s' into text field '%s'" % ( text , locator ) ) self . _element_input_text_by_locator ( locator , text )
def _write_csv ( self , df , csv_path , chunksize = 10 ** 5 ) : """Parameters df : pandas . DataFrame csv _ path : str chunksize : int Number of rows to write at a time . Helps to limit memory consumption while writing a CSV ."""
logger . info ( "Saving DataFrame to %s" , csv_path ) df . to_csv ( csv_path , index = False , chunksize = chunksize )
def add_handler ( self , iface_name , handler ) : """Associates the given handler with the interface name . If the interface does not exist in the Contract , an RpcException is raised . : Parameters : iface _ name Name of interface that this handler implements handler Instance of a class that implements...
if self . contract . has_interface ( iface_name ) : self . handlers [ iface_name ] = handler else : raise RpcException ( ERR_INVALID_REQ , "Unknown interface: '%s'" , iface_name )
def Ode ( self , z ) : """Returns the sum of : func : ` ~ classylss . binding . Background . Omega _ lambda ` and : func : ` ~ classylss . binding . Background . Omega _ fld ` ."""
return self . bg . Omega_lambda ( z ) + self . bg . Omega_fld ( z )
def tell ( self ) : """Return the file ' s current position . Returns : int , file ' s current position in bytes ."""
self . _check_open_file ( ) if self . _flushes_after_tell ( ) : self . flush ( ) if not self . _append : return self . _io . tell ( ) if self . _read_whence : write_seek = self . _io . tell ( ) self . _io . seek ( self . _read_seek , self . _read_whence ) self . _read_seek = self . _io . tell ( ) ...
def dense_to_one_hot ( labels_dense , num_classes ) : """Convert class labels from scalars to one - hot vectors ."""
num_labels = labels_dense . shape [ 0 ] index_offset = np . arange ( num_labels ) * num_classes labels_one_hot = np . zeros ( ( num_labels , num_classes ) ) labels_one_hot . flat [ index_offset + labels_dense . ravel ( ) ] = 1 return labels_one_hot
def login_create ( login , new_login_password = None , new_login_domain = '' , new_login_roles = None , new_login_options = None , ** kwargs ) : '''Creates a new login . Does not update password of existing logins . For Windows authentication , provide ` ` new _ login _ domain ` ` . For SQL Server authenticatio...
# One and only one of password and domain should be specifies if bool ( new_login_password ) == bool ( new_login_domain ) : return False if login_exists ( login , new_login_domain , ** kwargs ) : return False if new_login_domain : login = '{0}\\{1}' . format ( new_login_domain , login ) if not new_login_rol...
def get_fault_term ( self , rake ) : """Returns coefficient for faulting style ( pg 156)"""
rake = rake + 360 if rake < 0 else rake if ( rake >= 45 ) & ( rake <= 135 ) : f = 1. elif ( rake >= 225 ) & ( rake <= 315 ) : f = 0.5 else : f = 0. return f
def mfpt ( T , target , origin = None , tau = 1 , mu = None ) : r"""Mean first passage times ( from a set of starting states - optional ) to a set of target states . Parameters T : ndarray or scipy . sparse matrix , shape = ( n , n ) Transition matrix . target : int or list of int Target states for mfpt...
# check inputs T = _types . ensure_ndarray_or_sparse ( T , ndim = 2 , uniform = True , kind = 'numeric' ) target = _types . ensure_int_vector ( target ) origin = _types . ensure_int_vector_or_None ( origin ) # go if _issparse ( T ) : if origin is None : t_tau = sparse . mean_first_passage_time . mfpt ( T , ...
def type_string ( self ) : '''Returns the names of the flags that are set in the Type field It can be used to format the counter .'''
type = self . get_info ( ) [ 'type' ] type_list = [ ] for member in dir ( self ) : if member . startswith ( "PERF_" ) : bit = getattr ( self , member ) if bit and bit & type : type_list . append ( member [ 5 : ] ) return type_list
def login_required ( view_func ) : """Decorator for command views that checks that the chat is authenticated , sends message with link for authenticated if necessary ."""
@ wraps ( view_func ) def wrapper ( bot , update , ** kwargs ) : chat = Chat . objects . get ( id = update . message . chat . id ) if chat . is_authenticated ( ) : return view_func ( bot , update , ** kwargs ) from telegrambot . bot_views . login import LoginBotView login_command_view = LoginBot...
def wait_for_successful_query ( name , wait_for = 300 , ** kwargs ) : '''Like query but , repeat and wait until match / match _ type or status is fulfilled . State returns result from last query state in case of success or if no successful query was made within wait _ for timeout . name The name of the query ...
starttime = time . time ( ) while True : caught_exception = None ret = None try : ret = query ( name , ** kwargs ) if ret [ 'result' ] : return ret except Exception as exc : caught_exception = exc if time . time ( ) > starttime + wait_for : if not ret and ...
def delete_package ( owner , repo , identifier ) : """Delete a package in a repository ."""
client = get_packages_api ( ) with catch_raise_api_exception ( ) : _ , _ , headers = client . packages_delete_with_http_info ( owner = owner , repo = repo , identifier = identifier ) ratelimits . maybe_rate_limit ( client , headers ) return True