signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def do_usemacro ( parser , token ) : """The function taking a parsed template tag and returning a UseMacroNode ."""
tag_name , macro_name , args , kwargs = parse_macro_params ( token ) try : macro = parser . _macros [ macro_name ] except ( AttributeError , KeyError ) : raise template . TemplateSyntaxError ( "Macro '{0}' is not defined previously to the {1} tag" . format ( macro_name , tag_name ) ) macro . parser = parser ret...
def cmd_whois_domain ( domain ) : """Simple whois client to check domain names . Example : $ habu . whois . domain portantier . com " domain _ name " : " portantier . com " , " registrar " : " Amazon Registrar , Inc . " , " whois _ server " : " whois . registrar . amazon . com " ,"""
warnings . filterwarnings ( "ignore" ) data = whois . whois ( domain ) data = remove_duplicates ( data ) print ( json . dumps ( data , indent = 4 , default = str ) )
def get_setup ( Cnt = { } ) : '''Return a dictionary of GPU , mu - map hardware and third party set - up .'''
# the name of the folder for NiftyPET tools Cnt [ 'DIRTOOLS' ] = DIRTOOLS # additional paramteres for compiling tools with cmake Cnt [ 'CMAKE_TLS_PAR' ] = CMAKE_TLS_PAR # hardware mu - maps Cnt [ 'HMULIST' ] = hrdwr_mu # Microsoft Visual Studio Compiler version Cnt [ 'MSVC_VRSN' ] = MSVC_VRSN # GPU related setup Cnt = ...
def sum ( context , key , value , multiplier = 1 ) : """Adds the given value to the total value currently held in ` ` key ` ` . Use the multiplier if you want to turn a positive value into a negative and actually substract from the current total sum . Usage : : { % sum " MY _ TOTAL " 42 - 1 % } { { MY _ T...
if key not in context . dicts [ 0 ] : context . dicts [ 0 ] [ key ] = 0 context . dicts [ 0 ] [ key ] += value * multiplier return ''
def readLine ( self ) : """read a line Maintains its own buffer , callers of the transport should not mix calls to readBytes and readLine ."""
if self . buf is None : self . buf = [ ] # Buffer may already have a line if we ' ve received unilateral # response ( s ) from the server if len ( self . buf ) == 1 and b"\n" in self . buf [ 0 ] : ( line , b ) = self . buf [ 0 ] . split ( b"\n" , 1 ) self . buf = [ b ] return line while True : b = s...
def is_a_sequence ( var , allow_none = False ) : """Returns True if var is a list or a tuple ( but not a string ! )"""
return isinstance ( var , ( list , tuple ) ) or ( var is None and allow_none )
def _set_subject_alt ( self , name , values ) : """Replaces all existing asn1crypto . x509 . GeneralName objects of the choice represented by the name parameter with the values : param name : A unicode string of the choice name of the x509 . GeneralName object : param values : A list of unicode strings to...
if self . _subject_alt_name is not None : filtered_general_names = [ ] for general_name in self . _subject_alt_name : if general_name . name != name : filtered_general_names . append ( general_name ) self . _subject_alt_name = x509 . GeneralNames ( filtered_general_names ) else : sel...
def _le_circle ( self , annot , p1 , p2 , lr ) : """Make stream commands for circle line end symbol . " lr " denotes left ( False ) or right point ."""
m , im , L , R , w , scol , fcol , opacity = self . _le_annot_parms ( annot , p1 , p2 ) shift = 2.5 # 2 * shift * width = length of square edge d = shift * max ( 1 , w ) M = R - ( d / 2. , 0 ) if lr else L + ( d / 2. , 0 ) r = Rect ( M , M ) + ( - d , - d , d , d ) # the square ap = "q\n" + opacity + self . _oval_strin...
def authenticate_cinder_admin ( self , keystone , api_version = 2 ) : """Authenticates admin user with cinder ."""
self . log . debug ( 'Authenticating cinder admin...' ) _clients = { 1 : cinder_client . Client , 2 : cinder_clientv2 . Client } return _clients [ api_version ] ( session = keystone . session )
def cast ( cls , value_type , value , visitor = None , ** kwargs ) : """Cast is for visitors where you are visiting some random data structure ( perhaps returned by a previous ` ` VisitorPattern . visit ( ) ` ` operation ) , and you want to convert back to the value type . This function also takes positional ...
if visitor is None : visitor = cls . Visitor ( cls . grok , cls . reverse , cls . collect , cls . produce , ** kwargs ) return cls . map ( visitor , value , value_type )
def p_casecontent_statements ( self , p ) : 'casecontent _ statements : casecontent _ statements casecontent _ statement'
p [ 0 ] = p [ 1 ] + ( p [ 2 ] , ) p . set_lineno ( 0 , p . lineno ( 1 ) )
def _connect_lxd ( spec ) : """Return ContextService arguments for an LXD container connection ."""
return { 'method' : 'lxd' , 'kwargs' : { 'container' : spec . remote_addr ( ) , 'python_path' : spec . python_path ( ) , 'lxc_path' : spec . mitogen_lxc_path ( ) , 'connect_timeout' : spec . ansible_ssh_timeout ( ) or spec . timeout ( ) , 'remote_name' : get_remote_name ( spec ) , } }
def log_flush_with_xml ( self , data ) : """Flush logs for devices with a supplied xml string . From the Casper API docs : log , log _ id , interval , and devices specified in an XML file . Sample file : < logflush > < log > policy < / log > < log _ id > 2 < / log _ id > < interval > THREE MONTHS < / ...
if not isinstance ( data , basestring ) : data = ElementTree . tostring ( data ) response = self . delete ( data )
def get_scaled_state ( self ) : '''Get full state , scaled into ( approximately ) [ 0 , 1 ] .'''
return [ 0.5 * ( self . x + self . position_limit ) / self . position_limit , ( self . dx + 0.75 ) / 1.5 , 0.5 * ( self . theta + self . angle_limit_radians ) / self . angle_limit_radians , ( self . dtheta + 1.0 ) / 2.0 ]
def execute_no_wait ( self , cmd , walltime , envs = { } ) : '''Synchronously execute a commandline string on the shell . Args : - cmd ( string ) : Commandline string to execute - walltime ( int ) : walltime in seconds , this is not really used now . Returns : - retcode : Return code from the execution , ...
current_env = copy . deepcopy ( self . _envs ) current_env . update ( envs ) try : proc = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE , cwd = self . userhome , env = current_env , shell = True , preexec_fn = os . setpgrp ) pid = proc . pid except Exception as e : print...
def run_ffmpeg_command ( self ) : """Run an ffmpeg command , trying to capture the process output and calculate the duration / progress . Yields the progress in percent ."""
logger . debug ( "Running ffmpeg command: {}" . format ( self . cmd ) ) if self . dry : logger . debug ( "Dry mode specified, not actually running command" ) return total_dur = None stderr = [ ] p = subprocess . Popen ( self . cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE , universal_newlines = ...
def compute ( self , x , yerr = 0.0 , ** kwargs ) : """Pre - compute the covariance matrix and factorize it for a set of times and uncertainties . : param x : ` ` ( nsamples , ) ` ` or ` ` ( nsamples , ndim ) ` ` The independent coordinates of the data points . : param yerr : ( optional ) ` ` ( nsamples , )...
# Parse the input coordinates and ensure the right memory layout . self . _x = self . parse_samples ( x ) self . _x = np . ascontiguousarray ( self . _x , dtype = np . float64 ) try : self . _yerr2 = float ( yerr ) ** 2 * np . ones ( len ( x ) ) except TypeError : self . _yerr2 = self . _check_dimensions ( yerr...
def parser ( rules = None , ** kwargs ) : """Instantiate a parser with the default Splunk command rules ."""
rules = RULES_SPLUNK if rules is None else dict ( RULES_SPLUNK , ** rules ) return Parser ( rules , ** kwargs )
def meta ( args ) : """% prog meta data . bin samples STR . ids STR - exons . wo . bed Compute allele frequencies and prune sites based on missingness . Filter subset of loci that satisfy : 1 . no redundancy ( unique chr : pos ) 2 . variable ( n _ alleles > 1) 3 . low level of missing data ( > = 50 % auto...
p = OptionParser ( meta . __doc__ ) p . add_option ( "--cutoff" , default = .5 , type = "float" , help = "Percent observed required (chrY half cutoff)" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) binfile , sampleids , strids , wobed = args cu...
def open ( self ) : """Open a connection to the AMQP compliant broker ."""
self . _connection = amqp . Connection ( host = '%s:%s' % ( self . hostname , self . port ) , userid = self . username , password = self . password , virtual_host = self . virtual_host , insist = False ) self . channel = self . _connection . channel ( )
def getIndex ( reference ) : '''Find the reference folder using the location of the script file Create the index , test if successful'''
if reference : reffas = reference else : parent_directory = path . dirname ( path . abspath ( path . dirname ( __file__ ) ) ) reffas = path . join ( parent_directory , "reference/DNA_CS.fasta" ) if not path . isfile ( reffas ) : logging . error ( "Could not find reference fasta for lambda genome." ) ...
def subdomain_row_factory ( cls , cursor , row ) : """Dict row factory for subdomains"""
d = { } for idx , col in enumerate ( cursor . description ) : d [ col [ 0 ] ] = row [ idx ] return d
def exec_container ( self , asset_url , algorithm_url , resource_group_name , account_name , account_key , location , share_name_input = 'compute' , share_name_output = 'output' , docker_image = 'python:3.6-alpine' , memory = 1.5 , cpu = 1 ) : """Prepare a docker image that will run in the cloud , mounting the asse...
try : container_group_name = 'compute' + str ( int ( time . time ( ) ) ) result_file = self . _create_container_group ( resource_group_name = resource_group_name , name = container_group_name , image = docker_image , location = location , memory = memory , cpu = cpu , algorithm = algorithm_url , asset = asset_u...
def config ( self , averaging = 1 , datarate = 15 , mode = MODE_NORMAL ) : """Set the base config for sensor : param averaging : Sets the numer of samples that are internally averaged : param datarate : Datarate in hertz : param mode : one of the MODE _ * constants"""
averaging_conf = { 1 : 0 , 2 : 1 , 4 : 2 , 8 : 3 } if averaging not in averaging_conf . keys ( ) : raise Exception ( 'Averaging should be one of: 1,2,4,8' ) datarates = { 0.75 : 0 , 1.5 : 1 , 3 : 2 , 7.5 : 4 , 15 : 5 , 30 : 6 , 75 : 7 } if datarate not in datarates . keys ( ) : raise Exception ( 'Datarate of {}...
def p_try_catch ( p ) : """try _ catch : TRY stmt _ list CATCH stmt _ list END _ STMT"""
# # | TRY stmt _ list END _ STMT assert isinstance ( p [ 2 ] , node . stmt_list ) # assert isinstance ( p [ 4 ] , node . stmt _ list ) p [ 0 ] = node . try_catch ( try_stmt = p [ 2 ] , catch_stmt = p [ 4 ] , finally_stmt = node . stmt_list ( ) )
def mid_pt ( self ) : """Midpoint of this interval product ."""
midp = ( self . max_pt + self . min_pt ) / 2. midp [ ~ self . nondegen_byaxis ] = self . min_pt [ ~ self . nondegen_byaxis ] return midp
def from_json ( cls , session , photo_json ) : """https : / / vk . com / dev / objects / photo"""
photo = cls ( ) photo . id = photo_json . get ( 'id' ) photo . album_id = photo_json . get ( 'album_id' ) photo . owner_id = photo_json . get ( 'owner_id' ) photo . user_id = photo_json . get ( 'user_id' ) photo . text = photo_json . get ( 'text' ) photo . type = "photo" photo . date = photo_json . get ( 'date' ) photo...
def ToDebugString ( self ) : """Converts the path filter table into a debug string ."""
text_parts = [ 'Path segment index\tPath segments(s)' ] for index , path_segments in self . path_segments_per_index . items ( ) : text_parts . append ( '{0:d}\t\t\t[{1:s}]' . format ( index , ', ' . join ( path_segments ) ) ) text_parts . append ( '' ) return '\n' . join ( text_parts )
def start ( name ) : '''Start the specified service CLI Example : . . code - block : : bash salt ' * ' service . start < service name >'''
cmd = '/usr/sbin/svcadm enable -s -t {0}' . format ( name ) retcode = __salt__ [ 'cmd.retcode' ] ( cmd , python_shell = False ) if not retcode : return True if retcode == 3 : # Return code 3 means there was a problem with the service # A common case is being in the ' maintenance ' state # Attempt a clear and try on...
def map ( cls , function , items , multiprocess = False , file = None ) : """Does a ` map ` operation while displaying a progress bar with percentage complete . def work ( i ) : print ( i ) ProgressBar . map ( work , range ( 50 ) ) Parameters function : function Function to call for each step items ...
results = [ ] if file is None : file = _get_stdout ( ) with cls ( len ( items ) , file = file ) as bar : step_size = max ( 200 , bar . _bar_length ) steps = max ( int ( float ( len ( items ) ) / step_size ) , 1 ) if not multiprocess : for i , item in enumerate ( items ) : results . a...
def fetch_data ( files , folder ) : """Downloads files to folder and checks their md5 checksums Parameters files : dictionary For each file in ` files ` the value should be ( url , md5 ) . The file will be downloaded from url if the file does not already exist or if the file exists but the md5 checksum do...
if not os . path . exists ( folder ) : _log ( "Creating new folder %s" % ( folder ) ) os . makedirs ( folder ) all_skip = True for f in files : url , md5 = files [ f ] fullpath = pjoin ( folder , f ) if os . path . exists ( fullpath ) and ( _get_file_md5 ( fullpath ) == md5 ) : continue ...
def get_onsets ( token_tuples ) : """Parameters token _ tuples : list of ( str , unicode ) a list / generator of ( token ID , token string ) tuples Returns onset _ tuples : generator of ( str , int , int ) A list / generator of ( token ID , onset , token length ) tuples . Note that PAULA starts counting...
onset = 1 for ( token_id , token ) in token_tuples : yield ( token_id , onset , len ( token ) ) onset += ( len ( token ) + 1 )
def flatten ( l ) : """Flattens a hierarchy of nested lists into a single list containing all elements in order : param l : list of arbitrary types and lists : returns : list of arbitrary types"""
l = list ( l ) i = 0 while i < len ( l ) : while isinstance ( l [ i ] , list ) : if not l [ i ] : l . pop ( i ) i -= 1 break else : l [ i : i + 1 ] = l [ i ] i += 1 return l
def EncoderLayer ( feature_depth , feedforward_depth , num_heads , dropout , mode ) : """Transformer encoder layer . The input to the encoder is a pair ( embedded source , mask ) where the mask is created from the original source to prevent attending to the padding part of the input . Args : feature _ dep...
# The encoder block expects ( activation , mask ) as input and returns # the new activations only , we add the mask back to output next . encoder_block = layers . Serial ( layers . Residual ( # Attention block here . layers . Parallel ( layers . LayerNorm ( ) , layers . Identity ( ) ) , layers . MultiHeadedAttention ( ...
def _combine_nd ( combined_ids , concat_dims , data_vars = 'all' , coords = 'different' , compat = 'no_conflicts' ) : """Concatenates and merges an N - dimensional structure of datasets . No checks are performed on the consistency of the datasets , concat _ dims or tile _ IDs , because it is assumed that this h...
# Perform N - D dimensional concatenation # Each iteration of this loop reduces the length of the tile _ ids tuples # by one . It always combines along the first dimension , removing the first # element of the tuple for concat_dim in concat_dims : combined_ids = _auto_combine_all_along_first_dim ( combined_ids , di...
def published ( self , for_user = None , force_exchange = True ) : """Customise ` UrlNodeQuerySet . published ( ) ` to add filtering by publication date constraints and exchange of draft items for published ones ."""
qs = self . _single_site ( ) # Avoid filtering to only published items when we are in a draft # context and we know this method is triggered by Fluent ( because # the ` for _ user ` is present ) because we may actually want to find # and return draft items to priveleged users in this situation . if for_user and is_draf...
def temporary_locale ( temp_locale = None ) : '''Enable code to run in a context with a temporary locale Resets the locale back when exiting context . Can set a temporary locale if provided'''
orig_locale = locale . setlocale ( locale . LC_ALL ) if temp_locale is not None : locale . setlocale ( locale . LC_ALL , temp_locale ) yield locale . setlocale ( locale . LC_ALL , orig_locale )
def _generate_assignments ( splittable_dimensions , mesh_dimension_to_size ) : """Generates all ways to map splittable dimensions to mesh dimensions . Args : splittable _ dimensions : a frozenset of the names of splittable dimensions . mesh _ dimension _ to _ size : a dictionary from mesh dimension name to si...
assignments = [ ] for assignment_size in six . moves . xrange ( 1 + min ( len ( splittable_dimensions ) , len ( mesh_dimension_to_size ) ) ) : for s_dims_chosen in itertools . combinations ( splittable_dimensions , assignment_size ) : for m_dims_chosen in itertools . permutations ( mesh_dimension_to_size , ...
def rotate ( self ) : """Does rotating , if necessary , to balance this node , and returns the new top node ."""
self . refresh_balance ( ) if abs ( self . balance ) < 2 : return self # balance > 0 is the heavy side my_heavy = self . balance > 0 child_heavy = self [ my_heavy ] . balance > 0 if my_heavy == child_heavy or self [ my_heavy ] . balance == 0 : # # Heavy sides same # self save # save - > 1 self # # Heavy side balanc...
def get_field ( cls , model , opts , label , field ) : """Just like django . contrib . admin . validation . get _ field , but knows about translation models ."""
trans_model = model . _meta . translation_model try : ( f , lang_id ) = trans_model . _meta . translated_fields [ field ] return f except KeyError : # fall back to the old way - - see if model contains the field # directly pass try : return opts . get_field ( field ) except models . FieldDoesNotExist : ...
def add_child ( self , child ) : """Add a child FSEntry to this FSEntry . Only FSEntrys with a type of ' directory ' can have children . This does not detect cyclic parent / child relationships , but that will cause problems . : param metsrw . fsentry . FSEntry child : FSEntry to add as a child : return :...
if self . type . lower ( ) != "directory" : raise ValueError ( "Only directory objects can have children" ) if child is self : raise ValueError ( "Cannot be a child of itself!" ) if child not in self . _children : self . _children . append ( child ) child . parent = self return child
def _parse ( self , r , length ) : """Raises BitReaderError"""
def bits_left ( ) : return length * 8 - r . get_position ( ) self . audioObjectType = self . _get_audio_object_type ( r ) self . samplingFrequency = self . _get_sampling_freq ( r ) self . channelConfiguration = r . bits ( 4 ) self . sbrPresentFlag = - 1 self . psPresentFlag = - 1 if self . audioObjectType in ( 5 , ...
def set_cookie ( self , key , value , expiration = 'Infinity' , path = '/' , domain = '' , secure = False ) : """expiration ( int ) : seconds after with the cookie automatically gets deleted"""
secure = 'true' if secure else 'false' self . app_instance . execute_javascript ( """ var sKey = "%(sKey)s"; var sValue = "%(sValue)s"; var vEnd = eval("%(vEnd)s"); var sPath = "%(sPath)s"; var sDomain = "%(sDomain)s"; var bSecure = %(bSecure)s; ...
def save ( self ) : """Save the resource to the API server If the resource doesn ' t have a uuid the resource will be created . If uuid is present the resource is updated . : rtype : Resource"""
if self . path . is_collection : self . session . post_json ( self . href , { self . type : dict ( self . data ) } , cls = ResourceEncoder ) else : self . session . put_json ( self . href , { self . type : dict ( self . data ) } , cls = ResourceEncoder ) return self . fetch ( exclude_children = True , exclude_b...
def perminverse ( s ) : '''Fast inverse of a ( numpy ) permutation . * * Paramters * * * * s * * : sequence Sequence of indices giving a permutation . * * Returns * * * * inv * * : numpy array Sequence of indices giving the inverse of permutation ` s ` .'''
X = np . array ( range ( len ( s ) ) ) X [ s ] = range ( len ( s ) ) return X
def createLoanOffer ( self , currency , amount , duration , autoRenew , lendingRate ) : """Creates a loan offer for a given currency . Required POST parameters are " currency " , " amount " , " duration " , " autoRenew " ( 0 or 1 ) , and " lendingRate " ."""
return self . _private ( 'createLoanOffer' , currency = currency , amount = amount , duration = duration , autoRenew = autoRenew , lendingRate = lendingRate )
def list_pkgs ( versions_as_list = False , ** kwargs ) : '''List the packages currently installed as a dict : : { ' < package _ name > ' : ' < version > ' } CLI Example : . . code - block : : bash salt ' * ' pkg . list _ pkgs'''
versions_as_list = salt . utils . data . is_true ( versions_as_list ) # not yet implemented or not applicable if any ( [ salt . utils . data . is_true ( kwargs . get ( x ) ) for x in ( 'removed' , 'purge_desired' ) ] ) : return { } if 'pkg.list_pkgs' in __context__ : if versions_as_list : return __conte...
def combine_nt_lists ( lists , flds , dflt_null = "" ) : """Return a new list of namedtuples by zipping " lists " of namedtuples or objects ."""
combined_nt_list = [ ] # Check that all lists are the same length lens = [ len ( lst ) for lst in lists ] assert len ( set ( lens ) ) == 1 , "LIST LENGTHS MUST BE EQUAL: {Ls}" . format ( Ls = " " . join ( str ( l ) for l in lens ) ) # 1 . Instantiate namedtuple object ntobj = cx . namedtuple ( "Nt" , " " . join ( flds ...
def store_net_fw_db ( self , tenant_id , net , net_dict , subnet_dict , direc , result , os_status = None , dcnm_status = None , dev_status = None ) : """Save the entries in Network and Firewall DB . Stores the entries into Network DB and Firewall DB as well as update the result of operation into FWDB . General...
self . store_net_db ( tenant_id , net , net_dict , result ) self . store_fw_db ( tenant_id , net , subnet_dict , direc ) self . update_fw_db_result ( tenant_id , os_status = os_status , dcnm_status = dcnm_status , dev_status = dev_status )
def get_if_addr6 ( iff ) : """Returns the main global unicast address associated with provided interface , in human readable form . If no global address is found , None is returned ."""
return next ( ( x [ 0 ] for x in in6_getifaddr ( ) if x [ 2 ] == iff and x [ 1 ] == IPV6_ADDR_GLOBAL ) , None )
def Then ( self , f , * args , ** kwargs ) : """` Then ( f , . . . ) ` is equivalent to ` ThenAt ( 1 , f , . . . ) ` . Checkout ` phi . builder . Builder . ThenAt ` for more information ."""
return self . ThenAt ( 1 , f , * args , ** kwargs )
def rotate_scatter3d ( data , filename = None , elev = 30 , rotation_speed = 30 , fps = 10 , ax = None , figsize = None , dpi = None , ipython_html = "jshtml" , ** kwargs ) : """Create a rotating 3D scatter plot Builds upon ` matplotlib . pyplot . scatter ` with nice defaults and handles categorical colors / le...
warnings . warn ( "`phate.plot.rotate_scatter3d` is deprecated. " "Use `scprep.plot.rotate_scatter3d` instead." , FutureWarning ) return scprep . plot . rotate_scatter3d ( data , filename = filename , elev = elev , rotation_speed = rotation_speed , fps = fps , ax = ax , figsize = figsize , dpi = dpi , ipython_html = ip...
def convert_to_picos ( sdp , duplicate_moment_matrix = False ) : """Convert an SDP relaxation to a PICOS problem such that the exported . dat - s file is extremely sparse , there is not penalty imposed in terms of SDP variables or number of constraints . This conversion can be used for imposing extra constrai...
import picos as pic import cvxopt as cvx P = pic . Problem ( verbose = sdp . verbose ) block_size = sdp . block_struct [ 0 ] if sdp . F . dtype == np . float64 : X = P . add_variable ( 'X' , ( block_size , block_size ) , vtype = "symmetric" ) if duplicate_moment_matrix : Y = P . add_variable ( 'Y' , ( b...
def update_binary_stats ( self , label , pred ) : """Update various binary classification counts for a single ( label , pred ) pair . Parameters label : ` NDArray ` The labels of the data . pred : ` NDArray ` Predicted values ."""
pred = pred . asnumpy ( ) label = label . asnumpy ( ) . astype ( 'int32' ) pred_label = numpy . argmax ( pred , axis = 1 ) check_label_shapes ( label , pred ) if len ( numpy . unique ( label ) ) > 2 : raise ValueError ( "%s currently only supports binary classification." % self . __class__ . __name__ ) pred_true = ...
def find ( cls , * args , ** kw ) : """Query the collection this class is bound to . Additional arguments are processed according to ` _ prepare _ find ` prior to passing to PyMongo , where positional parameters are interpreted as query fragments , parametric keyword arguments combined , and other keyword arg...
Doc , collection , query , options = cls . _prepare_find ( * args , ** kw ) return collection . find ( query , ** options )
def create_shot_model ( self , ) : """Return a treemodel with the levels : project , sequence , shot and reftrack type : returns : a treemodel : rtype : : class : ` jukeboxcore . gui . treemodel . TreeModel ` : raises : None"""
rootdata = treemodel . ListItemData ( [ 'Name' ] ) rootitem = treemodel . TreeItem ( rootdata ) prjs = djadapter . projects . all ( ) for prj in prjs : prjdata = djitemdata . ProjectItemData ( prj ) prjitem = treemodel . TreeItem ( prjdata , rootitem ) for seq in prj . sequence_set . all ( ) : seqda...
def op_right ( op ) : """Returns a type instance method for the given operator , applied when the instance appears on the right side of the expression ."""
def method ( self , other ) : return op ( value_left ( self , other ) , value_right ( self , other ) ) return method
def update_collisions ( self ) : """Test player for collisions with items"""
if not self . mode [ 'items' ] or len ( self . mode [ 'items' ] ) == 0 : return # update collman # FIXME : Why update each frame ? self . collman . clear ( ) for z , node in self . children : if hasattr ( node , 'cshape' ) and type ( node . cshape ) == cm . CircleShape : self . collman . add ( node ) # ...
def get_remote_chassis_id_mac ( self , tlv_data ) : """Returns Remote Chassis ID MAC from the TLV ."""
ret , parsed_val = self . _check_common_tlv_format ( tlv_data , "MAC:" , "Chassis ID TLV" ) if not ret : return None mac = parsed_val [ 1 ] . split ( '\n' ) return mac [ 0 ] . strip ( )
def read_ncstream_err ( fobj ) : """Handle reading an NcStream error from a file - like object and raise as error ."""
err = read_proto_object ( fobj , stream . Error ) raise RuntimeError ( err . message )
def visit_importfrom ( self , node ) : """return an astroid . ImportFrom node as string"""
return "from %s import %s" % ( "." * ( node . level or 0 ) + node . modname , _import_string ( node . names ) , )
def bought_value ( self ) : """[ 已弃用 ]"""
user_system_log . warn ( _ ( u"[abandon] {} is no longer valid." ) . format ( 'stock_position.bought_value' ) ) return self . _quantity * self . _avg_price
def currency_exchange ( source , source_amount , destination , destination_amount , trading_account , fee_destination = None , fee_amount = None , date = None , description = None , ) : """Exchange funds from one currency to another Use this method to represent a real world currency transfer . Note this process...
from hordak . models import Account , Transaction , Leg if trading_account . type != Account . TYPES . trading : raise TradingAccountRequiredError ( "Account {} must be a trading account" . format ( trading_account ) ) if ( fee_destination or fee_amount ) and not ( fee_destination and fee_amount ) : raise Runti...
def strip_instructions ( text ) : """Remove instructional HTML comment tags inserted by RTV . We used to use # to annotate comments , but it conflicted with the header tag for markdown , which some people use to format their posts ."""
# Pattern can span multiple lines , allows dot to match newline chars flags = re . MULTILINE | re . DOTALL pattern = '<!--{token}(.*?){token}-->' . format ( token = TOKEN ) text = re . sub ( pattern , '' , text , flags = flags ) return re . sub ( r'\A[\s\n]*\n' , '' , text , flags = flags ) . rstrip ( )
def filter_humphrey ( mesh , alpha = 0.1 , beta = 0.5 , iterations = 10 , laplacian_operator = None ) : """Smooth a mesh in - place using laplacian smoothing and Humphrey filtering . Articles " Improved Laplacian Smoothing of Noisy Surface Meshes " J . Vollmer , R . Mencl , and H . Muller Parameters mes...
# if the laplacian operator was not passed create it here if laplacian_operator is None : laplacian_operator = laplacian_calculation ( mesh ) # get mesh vertices as vanilla numpy array vertices = mesh . vertices . copy ( ) . view ( np . ndarray ) # save original unmodified vertices original = vertices . copy ( ) # ...
def list_tags ( self ) : """Get the tags of current object : return : the tags : rtype : list"""
from highton . models . tag import Tag return fields . ListField ( name = self . ENDPOINT , init_class = Tag ) . decode ( self . element_from_string ( self . _get_request ( endpoint = self . ENDPOINT + '/' + str ( self . id ) + '/' + Tag . ENDPOINT , ) . text ) )
def block17 ( net , scale = 1.0 , activation_fn = tf . nn . relu , scope = None , reuse = None ) : """Builds the 17x17 resnet block ."""
with tf . variable_scope ( scope , 'Block17' , [ net ] , reuse = reuse ) : with tf . variable_scope ( 'Branch_0' ) : tower_conv = slim . conv2d ( net , 192 , 1 , scope = 'Conv2d_1x1' ) with tf . variable_scope ( 'Branch_1' ) : tower_conv1_0 = slim . conv2d ( net , 128 , 1 , scope = 'Conv2d_0a_1x...
def webui_schematics_assets_asset_asset_type_image_base_64_image ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) webui = ET . SubElement ( config , "webui" , xmlns = "http://tail-f.com/ns/webui" ) schematics = ET . SubElement ( webui , "schematics" ) assets = ET . SubElement ( schematics , "assets" ) asset = ET . SubElement ( assets , "asset" ) name_key = ET . SubElement ( asset , "name" ) name_...
def location_on_land ( self , coords_only = False ) : """Returns a random tuple specifying a coordinate set guaranteed to exist on land . Format is ` ( latitude , longitude , place name , two - letter country code , timezone ) ` Pass ` coords _ only ` to return coordinates without metadata ."""
place = self . random_element ( self . land_coords ) return ( place [ 0 ] , place [ 1 ] ) if coords_only else place
def save_b26 ( self , filename = None ) : """saves the script settings to a file : filename is filename is not provided , it is created from internal function"""
if filename is None : filename = self . filename ( '.b26' ) # if platform . system ( ) = = ' Windows ' : # # windows can ' t deal with long filenames so we have to use the prefix ' \ \ \ \ ? \ \ ' # if len ( filename . split ( ' \ \ \ \ ? \ \ ' ) ) = = 1: # filename = ' \ \ \ \ ? \ \ ' + filename save_b26_file ( fi...
def _ParseSystemTime ( self , byte_stream ) : """Parses a SYSTEMTIME date and time value from a byte stream . Args : byte _ stream ( bytes ) : byte stream . Returns : dfdatetime . Systemtime : SYSTEMTIME date and time value or None if no value is set . Raises : ParseError : if the SYSTEMTIME could not...
systemtime_map = self . _GetDataTypeMap ( 'systemtime' ) try : systemtime = self . _ReadStructureFromByteStream ( byte_stream , 0 , systemtime_map ) except ( ValueError , errors . ParseError ) as exception : raise errors . ParseError ( 'Unable to parse SYSTEMTIME value with error: {0!s}' . format ( exception ) ...
def build_listing ( self ) : """Builds a listing of all functions sorted A - Z , with their names and descriptions"""
def func_entry ( name , func ) : args , varargs , defaults = self . _get_arg_spec ( func ) # add regular arguments params = [ { 'name' : str ( a ) , 'optional' : a in defaults , 'vararg' : False } for a in args if a != 'ctx' ] # add possible variable argument if varargs : params += [ { 'name...
def _collect_dirty_tabs ( self , skip = None , tab_range = None ) : """Collects the list of dirty tabs : param skip : Tab to skip ( used for close _ others ) ."""
widgets = [ ] filenames = [ ] if tab_range is None : tab_range = range ( self . count ( ) ) for i in tab_range : widget = self . widget ( i ) try : if widget . dirty and widget != skip : widgets . append ( widget ) if widget . file . path : filenames . append ...
def _outer_values_update ( self , full_values ) : """Here you put the values , which were collected before in the right places . E . g . set the gradients of parameters , etc ."""
if self . has_uncertain_inputs ( ) : # gradients wrt kernel dL_dKmm = full_values [ 'dL_dKmm' ] self . kern . update_gradients_full ( dL_dKmm , self . Z , None ) kgrad = self . kern . gradient . copy ( ) self . kern . update_gradients_expectations ( variational_posterior = self . X , Z = self . Z , dL_d...
def import_ ( module , objects = None , py2 = None ) : """: param module : py3 compatiable module path : param objects : objects want to imported , it should be a list : param via : for some py2 module , you should give the import path according the objects which you want to imported : return : object or mo...
if not PY2 : mod = __import__ ( module , fromlist = [ '*' ] ) if objects : if not isinstance ( objects , ( list , tuple ) ) : objects = [ objects ] r = [ ] for x in objects : r . append ( getattr ( mod , x ) ) if len ( r ) > 1 : return tuple ( ...
def get_kernel_data ( self ) : """Get the kernel data needed for this optimization routine to work ."""
return { 'scratch_mot_float_type' : LocalMemory ( 'mot_float_type' , 8 + 2 * self . _var_replace_dict [ 'NMR_OBSERVATIONS' ] + 5 * self . _var_replace_dict [ 'NMR_PARAMS' ] + self . _var_replace_dict [ 'NMR_PARAMS' ] * self . _var_replace_dict [ 'NMR_OBSERVATIONS' ] ) , 'scratch_int' : LocalMemory ( 'int' , self . _var...
def compare_balance ( self , operator , or_equals , amount ) : """Additional step using regex matcher to compare the current balance with some number"""
amount = int ( amount ) if operator == 'less' : if or_equals : self . assertLessEqual ( self . balance , amount ) else : self . assertLess ( self . balance , amount ) elif or_equals : self . assertGreaterEqual ( self . balance , amount ) else : self . assertGreater ( self . balance , amo...
def merge ( request , obj_id ) : """Merges multiple tags into a single tag and all related objects are reassigned"""
res = Result ( ) if request . POST : tags = json . loads ( request . POST [ 'tags' ] ) else : tags = json . loads ( request . body ) [ 'body' ] [ 'tags' ] guids = [ ] images = Image . objects . filter ( tags__id__in = tags ) guids += [ _ . guid for _ in images ] videos = Video . objects . filter ( tags__id__in ...
def get_model ( name , ** kwargs ) : """Returns a pre - defined model by name Parameters name : str Name of the model . pretrained : bool Whether to load the pretrained weights for model . classes : int Number of classes for the output layer . ctx : Context , default CPU The context in which to lo...
models = { 'resnet18_v1' : resnet18_v1 , 'resnet34_v1' : resnet34_v1 , 'resnet50_v1' : resnet50_v1 , 'resnet101_v1' : resnet101_v1 , 'resnet152_v1' : resnet152_v1 , 'resnet18_v2' : resnet18_v2 , 'resnet34_v2' : resnet34_v2 , 'resnet50_v2' : resnet50_v2 , 'resnet101_v2' : resnet101_v2 , 'resnet152_v2' : resnet152_v2 , '...
def has_role_collective ( self , role_s , logical_operator = all ) : """: param role _ s : 1 . . N role identifier : type role _ s : a Set of Strings : param logical _ operator : indicates whether all or at least one permission check is true ( any ) : type : any OR all ( from python standard library ) : r...
if self . authorized : return self . security_manager . has_role_collective ( self . identifiers , role_s , logical_operator ) else : msg = 'Cannot check permission when identifiers aren\'t set!' raise ValueError ( msg )
def camel_to_snake ( s : str ) -> str : """Convert string from camel case to snake case ."""
return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( )
def deprecated ( message , exception = PendingDeprecationWarning ) : """Throw a warning when a function / method will be soon deprecated Supports passing a ` ` message ` ` and an ` ` exception ` ` class ( uses ` ` PendingDeprecationWarning ` ` by default ) . This is useful if you want to alternatively pass a ...
def decorator ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : warnings . warn ( message , exception , stacklevel = 2 ) return func ( * args , ** kwargs ) return wrapper return decorator
def _get_current_deployment_label ( self ) : '''Helper method to find the deployment label that the stage _ name is currently associated with .'''
deploymentId = self . _get_current_deployment_id ( ) deployment = __salt__ [ 'boto_apigateway.describe_api_deployment' ] ( restApiId = self . restApiId , deploymentId = deploymentId , ** self . _common_aws_args ) . get ( 'deployment' ) if deployment : return deployment . get ( 'description' ) return None
def stop ( self ) : """Stops the dependency manager ( must be called before clear ( ) ) : return : The removed bindings ( list ) or None"""
super ( SimpleDependency , self ) . stop ( ) if self . reference is not None : # Return a tuple of tuple return ( ( self . _value , self . reference ) , ) return None
def update ( self ) : """Draw the star ."""
if not self . _screen . is_visible ( self . _x , self . _y ) : self . _respawn ( ) cur_char , _ , _ , _ = self . _screen . get_from ( self . _x , self . _y ) if cur_char not in ( ord ( self . _old_char ) , 32 ) : self . _respawn ( ) self . _cycle += 1 if self . _cycle >= len ( self . _star_chars ) : self . ...
def dump_ddl ( metadata : MetaData , dialect_name : str , fileobj : TextIO = sys . stdout , checkfirst : bool = True ) -> None : """Sends schema - creating DDL from the metadata to the dump engine . This makes ` ` CREATE TABLE ` ` statements . Args : metadata : SQLAlchemy : class : ` MetaData ` dialect _ na...
# http : / / docs . sqlalchemy . org / en / rel _ 0_8 / faq . html # how - can - i - get - the - create - table - drop - table - output - as - a - string # noqa # http : / / stackoverflow . com / questions / 870925 / how - to - generate - a - file - with - ddl - in - the - engines - sql - dialect - in - sqlalchemy # no...
def generator_name ( cls ) : """: meth : ` . WHashGeneratorProto . generator _ name ` implementation"""
if cls . __generator_name__ is None : raise ValueError ( '"__generator_name__" should be override in a derived class' ) if isinstance ( cls . __generator_name__ , str ) is False : raise TypeError ( '"__generator_name__" should be a str instance' ) return cls . __generator_name__ . upper ( )
def call ( self ) : '''show a file dialog'''
from MAVProxy . modules . lib . wx_loader import wx # remap flags to wx descriptors flag_map = { 'open' : wx . FD_OPEN , 'save' : wx . FD_SAVE , 'overwrite_prompt' : wx . FD_OVERWRITE_PROMPT , } flagsMapped = map ( lambda x : flag_map [ x ] , self . flags ) # need to OR together the elements of the flagsMapped tuple if...
def get_all_comments_of_offer ( self , offer_id ) : """Get all comments of offer This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing : param offer _ id : the offer id : return : list"""
return self . _iterate_through_pages ( get_function = self . get_comments_of_offer_per_page , resource = OFFER_COMMENTS , ** { 'offer_id' : offer_id } )
def plot_lr ( self , show_moms = False , skip_start : int = 0 , skip_end : int = 0 , return_fig : bool = None ) -> Optional [ plt . Figure ] : "Plot learning rate , ` show _ moms ` to include momentum ."
lrs = self . _split_list ( self . lrs , skip_start , skip_end ) iterations = self . _split_list ( range_of ( self . lrs ) , skip_start , skip_end ) if show_moms : moms = self . _split_list ( self . moms , skip_start , skip_end ) fig , axs = plt . subplots ( 1 , 2 , figsize = ( 12 , 4 ) ) axs [ 0 ] . plot ( ...
def save_password ( url , username , password ) : """Store credentials in keyring ."""
if keyring : if ":" in username : raise RuntimeError ( "Unable to store credentials if username contains a ':' ({})." . format ( username ) ) try : # Note : we pass the url as ` username ` and username : password as ` password ` if password is None : keyring . delete_password ( "pyft...
async def request_offline_members ( self , * guilds ) : r"""| coro | Requests previously offline members from the guild to be filled up into the : attr : ` Guild . members ` cache . This function is usually not called . It should only be used if you have the ` ` fetch _ offline _ members ` ` parameter set t...
if any ( not g . large or g . unavailable for g in guilds ) : raise InvalidArgument ( 'An unavailable or non-large guild was passed.' ) _guilds = sorted ( guilds , key = lambda g : g . shard_id ) for shard_id , sub_guilds in itertools . groupby ( _guilds , key = lambda g : g . shard_id ) : sub_guilds = list ( s...
def plot ( self , figure_list ) : '''Plots a dot on top of each selected NV , with a corresponding number denoting the order in which the NVs are listed . Precondition : must have an existing image in figure _ list [ 0 ] to plot over Args : figure _ list :'''
# if there is not image data get it from the current plot if not self . data == { } and self . data [ 'image_data' ] is None : axes = figure_list [ 0 ] . axes [ 0 ] if len ( axes . images ) > 0 : self . data [ 'image_data' ] = np . array ( axes . images [ 0 ] . get_array ( ) ) self . data [ 'ext...
def start_at ( self , document_fields ) : """Start query at a cursor with this collection as parent . See : meth : ` ~ . firestore _ v1beta1 . query . Query . start _ at ` for more information on this method . Args : document _ fields ( Union [ ~ . firestore _ v1beta1 . document . DocumentSnapshot , dict ...
query = query_mod . Query ( self ) return query . start_at ( document_fields )
def write ( self , filename = None ) : """Write the PE file . This function will process all headers and components of the PE file and include all changes made ( by just assigning to attributes in the PE objects ) and write the changes back to a file whose name is provided as an argument . The filename is...
file_data = list ( self . __data__ ) for structure in self . __structures__ : struct_data = list ( structure . __pack__ ( ) ) offset = structure . get_file_offset ( ) file_data [ offset : offset + len ( struct_data ) ] = struct_data if hasattr ( self , 'VS_VERSIONINFO' ) : if hasattr ( self , 'FileInfo'...
def text_response ( self , contents , code = 200 , headers = { } ) : """shortcut to return simple plain / text messages in the response . : param contents : a string with the response contents : param code : the http status code : param headers : a dict with optional headers : returns : a : py : class : ` f...
return Response ( contents , status = code , headers = { 'Content-Type' : 'text/plain' } )
def get_mining_equipment ( ) : """Get all the mining equipment information available . Returns : This function returns two major dictionaries . The first one contains information about the coins for which mining equipment data is available . coin _ data : { symbol1 : { ' BlockNumber ' : . . . , ' BlockRew...
# load data url = build_url ( 'miningequipment' ) data = load_data ( url ) coin_data = data [ 'CoinData' ] mining_data = data [ 'MiningData' ] return coin_data , mining_data
def clear_tips ( self ) : """If reset is called with a tip attached , the tip must be removed before the poses and _ instruments members are cleared . If the tip is not removed , the effective length of the pipette remains increased by the length of the tip , and subsequent ` _ add _ tip ` calls will increase...
for instrument in self . _instruments . values ( ) : if instrument . tip_attached : instrument . _remove_tip ( instrument . _tip_length )
def is_valid ( cls , oid ) : """Checks if a ` oid ` string is valid or not . : Parameters : - ` oid ` : the object id to validate . . versionadded : : 2.3"""
if not oid : return False try : ObjectId ( oid ) return True except ( InvalidId , TypeError ) : return False
def _redshift ( distance , ** kwargs ) : r"""Uses astropy to get redshift from the given luminosity distance . Parameters distance : float The luminosity distance , in Mpc . \ * * kwargs : All other keyword args are passed to : py : func : ` get _ cosmology ` to select a cosmology . If none provided , w...
cosmology = get_cosmology ( ** kwargs ) return z_at_value ( cosmology . luminosity_distance , distance , units . Mpc )