signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def encrypt_item ( table_name , rsa_wrapping_private_key_bytes , rsa_signing_private_key_bytes ) : """Demonstrate use of EncryptedTable to transparently encrypt an item ."""
index_key = { "partition_attribute" : "is this" , "sort_attribute" : 55 } plaintext_item = { "example" : "data" , "some numbers" : 99 , "and some binary" : Binary ( b"\x00\x01\x02" ) , "leave me" : "alone" , # We want to ignore this attribute } # Collect all of the attributes that will be encrypted ( used later ) . enc...
def create_script ( create = None ) : # noqa : E501 """Create a new script Create a new script # noqa : E501 : param create : The data needed to create this script : type create : dict | bytes : rtype : Response"""
if connexion . request . is_json : create = Create . from_dict ( connexion . request . get_json ( ) ) # noqa : E501 return 'do some magic!'
def db_is_indexing ( cls , impl , working_dir ) : """Is the system indexing ? Return True if so , False if not ."""
indexing_lockfile_path = config . get_lockfile_filename ( impl , working_dir ) return os . path . exists ( indexing_lockfile_path )
def gettrace ( self , burn = 0 , thin = 1 , chain = - 1 , slicing = None ) : """Return the trace ( last by default ) . Input : - burn ( int ) : The number of transient steps to skip . - thin ( int ) : Keep one in thin . - chain ( int ) : The index of the chain to fetch . If None , return all chains . By d...
# warnings . warn ( ' Use Sampler . trace method instead . ' , # DeprecationWarning ) if not slicing : slicing = slice ( burn , None , thin ) # If chain is None , get the data from all chains . if chain is None : self . db . cur . execute ( 'SELECT * FROM [%s]' % self . name ) trace = self . db . cur . fetc...
def get_by_model ( self , model ) : """Gets all object by a specific model ."""
content_type = ContentType . objects . get_for_model ( model ) return self . filter ( content_type = content_type )
def create_issue ( self , title , content , priority = None , milestone = None , tags = None , assignee = None , private = None ) : """Create a new issue . : param title : the title of the issue : param content : the description of the issue : param priority : the priority of the ticket : param milestone : ...
request_url = "{}new_issue" . format ( self . create_basic_url ( ) ) payload = { 'title' : title , 'issue_content' : content } if priority is not None : payload [ 'priority' ] = priority if milestone is not None : payload [ 'milestone' ] = milestone if tags is not None : payload [ 'tag' ] = tags if assignee...
def fetch ( self ) : """Fetch a CompositionSettingsInstance : returns : Fetched CompositionSettingsInstance : rtype : twilio . rest . video . v1 . composition _ settings . CompositionSettingsInstance"""
params = values . of ( { } ) payload = self . _version . fetch ( 'GET' , self . _uri , params = params , ) return CompositionSettingsInstance ( self . _version , payload , )
def hybrid_forward ( self , F , words1 , words2 , weight ) : # pylint : disable = arguments - differ """Predict the similarity of words1 and words2. Parameters words1 : Symbol or NDArray The indices of the words the we wish to compare to the words in words2. words2 : Symbol or NDArray The indices of the w...
embeddings_words1 = F . Embedding ( words1 , weight , input_dim = self . _vocab_size , output_dim = self . _embed_size ) embeddings_words2 = F . Embedding ( words2 , weight , input_dim = self . _vocab_size , output_dim = self . _embed_size ) similarity = self . similarity ( embeddings_words1 , embeddings_words2 ) retur...
def fix_ticks ( ax ) : """Center ticklabels and hide any outside axes limits . By Joe Kington"""
plt . setp ( ax . get_yticklabels ( ) , ha = 'center' , x = 0.5 , transform = ax . _yaxis_transform ) # We ' ll still wind up with some tick labels beyond axes limits for reasons # I don ' t fully understand . . . limits = ax . get_ylim ( ) for label , loc in zip ( ax . yaxis . get_ticklabels ( ) , ax . yaxis . get_tic...
def time_annotated ( func , * args , ** kwargs ) : """Annotate the decorated function or method with the total execution time . The result is annotated with a ` time ` attribute ."""
start = time ( ) result = func ( * args , ** kwargs ) end = time ( ) result . time = round ( end - start , config . PRECISION ) return result
def _get_filename ( table ) : """Get the filename from a data table . If it doesn ' t exist , create a new one based on table hierarchy in metadata file . format : < dataSetName > . < section > < idx > < table > < idx > . csv example : ODP1098B . Chron1 . ChronMeasurementTable . csv : param dict table : Table...
try : filename = table [ "filename" ] except KeyError : logger_csvs . info ( "get_filename: KeyError: missing filename for a table" ) print ( "Error: Missing filename for a table" ) filename = "" except Exception as e : logger_csvs . error ( "get_filename: {}" . format ( e ) ) filename = "" retu...
def junos_cli ( command , format = None , dev_timeout = None , dest = None , ** kwargs ) : '''. . versionadded : : 2019.2.0 Execute a CLI command and return the output in the specified format . command The command to execute on the Junos CLI . format : ` ` text ` ` Format in which to get the CLI output ( ...
prep = _junos_prep_fun ( napalm_device ) # pylint : disable = undefined - variable if not prep [ 'result' ] : return prep return __salt__ [ 'junos.cli' ] ( command , format = format , dev_timeout = dev_timeout , dest = dest , ** kwargs )
def autocorrelation ( x , lag ) : """Calculates the autocorrelation of the specified lag , according to the formula [ 1] . . math : : \\ frac { 1 } { ( n - l ) \ sigma ^ { 2 } } \\ sum _ { t = 1 } ^ { n - l } ( X _ { t } - \\ mu ) ( X _ { t + l } - \\ mu ) where : math : ` n ` is the length of the time series...
# This is important : If a series is passed , the product below is calculated # based on the index , which corresponds to squaring the series . if type ( x ) is pd . Series : x = x . values if len ( x ) < lag : return np . nan # Slice the relevant subseries based on the lag y1 = x [ : ( len ( x ) - lag ) ] y2 =...
def getCmd ( snmpEngine , authData , transportTarget , contextData , * varBinds , ** options ) : """Performs SNMP GET query . Based on passed parameters , prepares SNMP GET packet ( : RFC : ` 1905 # section - 4.2.1 ` ) and schedules its transmission by : mod : ` twisted ` I / O framework at a later point of t...
def __cbFun ( snmpEngine , sendRequestHandle , errorIndication , errorStatus , errorIndex , varBinds , cbCtx ) : lookupMib , deferred = cbCtx if errorIndication : deferred . errback ( Failure ( errorIndication ) ) else : try : varBinds = VB_PROCESSOR . unmakeVarBinds ( snmpEngine...
def sign_execute_cancellation ( cancellation_params , key_pair ) : """Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange . Execution of this function is as follows : : sign _ execute _ cancellation ( cancellation _ params = signable _ params , key _ pair = key _ ...
signature = sign_transaction ( transaction = cancellation_params [ 'transaction' ] , private_key_hex = private_key_to_hex ( key_pair = key_pair ) ) return { 'signature' : signature }
def cluster_coincs ( stat , time1 , time2 , timeslide_id , slide , window , argmax = numpy . argmax ) : """Cluster coincident events for each timeslide separately , across templates , based on the ranking statistic Parameters stat : numpy . ndarray vector of ranking values to maximize time1 : numpy . ndar...
logging . info ( 'clustering coinc triggers over %ss window' % window ) if len ( time1 ) == 0 or len ( time2 ) == 0 : logging . info ( 'No coinc triggers in one, or both, ifos.' ) return numpy . array ( [ ] ) if numpy . isfinite ( slide ) : # for a time shifted coinc , time1 is greater than time2 by approximate...
def vdm_b ( vdm , lat ) : """Converts a virtual dipole moment ( VDM ) or a virtual axial dipole moment ( VADM ; input in units of Am ^ 2 ) to a local magnetic field value ( output in units of tesla ) Parameters vdm : V ( A ) DM in units of Am ^ 2 lat : latitude of site in degrees Returns B : local mag...
rad = old_div ( np . pi , 180. ) # changed radius of the earth from 3.367e6 3/12/2010 fact = ( ( 6.371e6 ) ** 3 ) * 1e7 colat = ( 90. - lat ) * rad return vdm * ( np . sqrt ( 1 + 3 * ( np . cos ( colat ) ** 2 ) ) ) / fact
def _family_notes_path ( family , data_dir ) : '''Form a path to the notes for a family'''
data_dir = fix_data_dir ( data_dir ) family = family . lower ( ) if not family in get_families ( data_dir ) : raise RuntimeError ( "Family '{}' does not exist" . format ( family ) ) file_name = 'NOTES.' + family . lower ( ) file_path = os . path . join ( data_dir , file_name ) return file_path
def parse_rich_header ( self ) : """Parses the rich header see http : / / www . ntcore . com / files / richsign . htm for more information Structure : 00 DanS ^ checksum , checksum , checksum , checksum 10 Symbol RVA ^ checksum , Symbol size ^ checksum . . . XX Rich , checksum , 0 , 0 , . . ."""
# Rich Header constants DANS = 0x536E6144 # ' DanS ' as dword RICH = 0x68636952 # ' Rich ' as dword rich_index = self . __data__ . find ( b'Rich' , 0x80 , self . OPTIONAL_HEADER . get_file_offset ( ) ) if rich_index == - 1 : return None # Read a block of data try : # The end of the structure is 8 bytes after the st...
def apply ( self , X , ntree_limit = 0 ) : """Return the predicted leaf every tree for each sample . Parameters X : array _ like , shape = [ n _ samples , n _ features ] Input features matrix . ntree _ limit : int Limit number of trees in the prediction ; defaults to 0 ( use all trees ) . Returns X _ ...
test_dmatrix = DMatrix ( X , missing = self . missing , nthread = self . n_jobs ) return self . get_booster ( ) . predict ( test_dmatrix , pred_leaf = True , ntree_limit = ntree_limit )
def grant_sudo_privileges ( request , max_age = COOKIE_AGE ) : """Assigns a random token to the user ' s session that allows them to have elevated permissions"""
user = getattr ( request , 'user' , None ) # If there ' s not a user on the request , just noop if user is None : return if not user . is_authenticated ( ) : raise ValueError ( 'User needs to be logged in to be elevated to sudo' ) # Token doesn ' t need to be unique , # just needs to be unpredictable and match ...
def assertFileSizeLessEqual ( self , filename , size , msg = None ) : '''Fail if ` ` filename ` ` ' s size is not less than or equal to ` ` size ` ` as determined by the ' < = ' operator . Parameters filename : str , bytes , file - like size : int , float msg : str If not provided , the : mod : ` marble...
fsize = self . _get_file_size ( filename ) self . assertLessEqual ( fsize , size , msg = msg )
def set_meta ( self , _props ) : """Set metadata values for collection ."""
if self . is_fake : return props = { } for key , value in _props . items ( ) : key , value = self . meta_mappings . map_set ( key , value ) props [ key ] = value # Pop out tag which we don ' t want props . pop ( "tag" , None ) self . journal . update_info ( { } ) self . journal . update_info ( props ) self ...
def list ( self ) : """Return a list of bots . : return : all of your bots : rtype : : class : ` list `"""
response = self . session . get ( self . url ) return [ Bot ( self , ** bot ) for bot in response . data ]
def l_system ( axiom , transformations , iterations = 1 , angle = 45 , resolution = 1 ) : """Generates a texture by running transformations on a turtle program . First , the given transformations are applied to the axiom . This is repeated ` iterations ` times . Then , the output is run as a turtle program to...
turtle_program = transform_multiple ( axiom , transformations , iterations ) return turtle_to_texture ( turtle_program , angle , resolution = resolution )
def path_wo_ns ( obj ) : """Return path of an instance or instance path without host or namespace . Creates copy of the object so the original is not changed ."""
if isinstance ( obj , pywbem . CIMInstance ) : path = obj . path . copy ( ) elif isinstance ( obj , pywbem . CIMInstanceName ) : path = obj . copy ( ) else : assert False path . host = None path . namespace = None return path
def segs ( self , word ) : """Returns a list of segments from a word Args : word ( unicode ) : input word as Unicode IPA string Returns : list : list of strings corresponding to segments found in ` word `"""
return [ m . group ( 'all' ) for m in self . seg_regex . finditer ( word ) ]
def validate_marked_location ( location ) : """Validate that a Location object is safe for marking , and not at a field ."""
if not isinstance ( location , ( Location , FoldScopeLocation ) ) : raise TypeError ( u'Expected Location or FoldScopeLocation location, got: {} {}' . format ( type ( location ) . __name__ , location ) ) if location . field is not None : raise GraphQLCompilationError ( u'Cannot mark location at a field: {}' . f...
def invalidate ( self ) : """Clear out cached properties"""
if hasattr ( self , '_avail_backups' ) : del self . _avail_backups if hasattr ( self , '_ips' ) : del self . _ips Base . invalidate ( self )
def get_atoms ( self , ligands = True , inc_alt_states = False ) : """Flat list of all the Atoms in the Polymer . Parameters inc _ alt _ states : bool If true atoms from alternate conformations are included rather than only the " active " states . Returns atoms : itertools . chain Returns an iterator ...
if ligands and self . ligands : monomers = self . _monomers + self . ligands . _monomers else : monomers = self . _monomers atoms = itertools . chain ( * ( list ( m . get_atoms ( inc_alt_states = inc_alt_states ) ) for m in monomers ) ) return atoms
def validate ( self , instance , value ) : """Checks that the value is a valid file open in the correct mode If value is a string , it attempts to open it with the given mode ."""
if isinstance ( value , string_types ) and self . mode is not None : try : value = open ( value , self . mode ) except ( IOError , TypeError ) : self . error ( instance , value , extra = 'Cannot open file: {}' . format ( value ) ) if not all ( [ hasattr ( value , attr ) for attr in ( 'read' , 's...
def moving_hfs_rank ( h , size , start = 0 , stop = None ) : """Helper function for plotting haplotype frequencies in moving windows . Parameters h : array _ like , int , shape ( n _ variants , n _ haplotypes ) Haplotype array . size : int The window size ( number of variants ) . start : int , optional ...
# determine windows windows = np . asarray ( list ( index_windows ( h , size = size , start = start , stop = stop , step = None ) ) ) # setup output hr = np . zeros ( ( windows . shape [ 0 ] , h . shape [ 1 ] ) , dtype = 'i4' ) # iterate over windows for i , ( window_start , window_stop ) in enumerate ( windows ) : # e...
def node_to_ini ( node , output = sys . stdout ) : """Convert a Node object with the right structure into a . ini file . : params node : a Node object : params output : a file - like object opened in write mode"""
for subnode in node : output . write ( u'\n[%s]\n' % subnode . tag ) for name , value in sorted ( subnode . attrib . items ( ) ) : output . write ( u'%s=%s\n' % ( name , value ) ) output . flush ( )
def matrix_height ( self , zoom ) : """Tile matrix height ( number of rows ) at zoom level . - zoom : zoom level"""
validate_zoom ( zoom ) height = int ( math . ceil ( self . grid . shape . height * 2 ** ( zoom ) / self . metatiling ) ) return 1 if height < 1 else height
def write ( self , path ) : """Write RSS content to file ."""
with open ( path , 'wb' ) as f : f . write ( self . getXML ( ) )
def member_command ( self , repl_id , member_id , command ) : """apply command ( start , stop , restart ) to the member of replica set Args : repl _ id - replica set identity member _ id - member index command - command : start , stop , restart return True if operation success otherwise False"""
repl = self [ repl_id ] result = repl . member_command ( member_id , command ) self [ repl_id ] = repl return result
def ycbcr2rgb ( y__ , cb_ , cr_ ) : """Convert the three YCbCr channels to RGB channels ."""
kb_ = 0.114 kr_ = 0.299 r__ = 2 * cr_ / ( 1 - kr_ ) + y__ b__ = 2 * cb_ / ( 1 - kb_ ) + y__ g__ = ( y__ - kr_ * r__ - kb_ * b__ ) / ( 1 - kr_ - kb_ ) return r__ , g__ , b__
def get_queryset ( self , request ) : """Limit to Tenants that this user can access ."""
qs = super ( TenantAdmin , self ) . get_queryset ( request ) if not request . user . is_superuser : tenants_by_group_manager_role = qs . filter ( group__tenantrole__user = request . user , group__tenantrole__role = TenantRole . ROLE_GROUP_MANAGER ) tenants_by_tenant_manager_role = qs . filter ( tenantrole__user...
def factorial ( n , mod = None ) : """Calculates factorial iteratively . If mod is not None , then return ( n ! % mod ) Time Complexity - O ( n )"""
if not ( isinstance ( n , int ) and n >= 0 ) : raise ValueError ( "'n' must be a non-negative integer." ) if mod is not None and not ( isinstance ( mod , int ) and mod > 0 ) : raise ValueError ( "'mod' must be a positive integer" ) result = 1 if n == 0 : return 1 for i in range ( 2 , n + 1 ) : result *=...
def get_rate ( self , currency , date ) : """Get the exchange rate for ` ` currency ` ` against ` ` _ INTERNAL _ CURRENCY ` ` If implementing your own backend , you should probably override : meth : ` _ get _ rate ( ) ` rather than this ."""
if str ( currency ) == defaults . INTERNAL_CURRENCY : return Decimal ( 1 ) cached = cache . get ( _cache_key ( currency , date ) ) if cached : return Decimal ( cached ) else : # Expect self . _ get _ rate ( ) to implement caching return Decimal ( self . _get_rate ( currency , date ) )
def _publish_actor_class_to_key ( self , key , actor_class_info ) : """Push an actor class definition to Redis . The is factored out as a separate function because it is also called on cached actor class definitions when a worker connects for the first time . Args : key : The key to store the actor class ...
# We set the driver ID here because it may not have been available when # the actor class was defined . self . _worker . redis_client . hmset ( key , actor_class_info ) self . _worker . redis_client . rpush ( "Exports" , key )
def logger_focus ( self , i , focus_shift = 16 ) : """focuses the logger on an index 12 entries below i @ param : i - > index to focus on"""
if self . logger . GetItemCount ( ) - 1 > i + focus_shift : i += focus_shift else : i = self . logger . GetItemCount ( ) - 1 self . logger . Focus ( i )
def createPlotDataItem ( self ) : """Creates a PyQtGraph PlotDataItem from the config values"""
antialias = self . antiAliasCti . configValue color = self . penColor if self . lineCti . configValue : pen = QtGui . QPen ( ) pen . setCosmetic ( True ) pen . setColor ( color ) pen . setWidthF ( self . lineWidthCti . configValue ) pen . setStyle ( self . lineStyleCti . configValue ) shadowCti ...
def CallFunction ( self ) : """Calls the function via RPC ."""
if self . _xmlrpc_proxy is None : return None rpc_call = getattr ( self . _xmlrpc_proxy , self . _RPC_FUNCTION_NAME , None ) if rpc_call is None : return None try : return rpc_call ( ) # pylint : disable = not - callable except ( expat . ExpatError , SocketServer . socket . error , xmlrpclib . Fault ) a...
def add_summary_page ( self ) : """Build a table which is shown on the first page which gives an overview of the portfolios"""
s = PortfolioSummary ( ) s . include_long_short ( ) pieces = [ ] for r in self . results : tmp = s ( r . port , PortfolioSummary . analyze_returns ) tmp [ 'desc' ] = r . desc tmp [ 'sid' ] = r . sid tmp = tmp . set_index ( [ 'sid' , 'desc' ] , append = 1 ) . reorder_levels ( [ 2 , 1 , 0 ] ) pieces ....
def bind ( self , server , net = None , address = None ) : """Create a network adapter object and bind ."""
if _debug : NetworkServiceAccessPoint . _debug ( "bind %r net=%r address=%r" , server , net , address ) # make sure this hasn ' t already been called with this network if net in self . adapters : raise RuntimeError ( "already bound" ) # create an adapter object , add it to our map adapter = NetworkAdapter ( sel...
def on_any_event ( self , event ) : """On any event method"""
for delegate in self . delegates : if hasattr ( delegate , "on_any_event" ) : delegate . on_any_event ( event )
def pca_loadings ( adata , components = None , show = None , save = None ) : """Rank genes according to contributions to PCs . Parameters adata : : class : ` ~ anndata . AnnData ` Annotated data matrix . components : str or list of integers , optional For example , ` ` ' 1,2,3 ' ` ` means ` ` [ 1 , 2 , 3 ...
if components is None : components = [ 1 , 2 , 3 ] elif isinstance ( components , str ) : components = components . split ( ',' ) components = np . array ( components ) - 1 ranking ( adata , 'varm' , 'PCs' , indices = components ) utils . savefig_or_show ( 'pca_loadings' , show = show , save = save )
def resample ( df , rule , time_index , groupby = None , aggregation = 'mean' ) : """pd . DataFrame . resample adapter . Call the ` df . resample ` method on the given time _ index and afterwards call the indicated aggregation . Optionally group the dataframe by the indicated columns before performing the r...
if groupby : df = df . groupby ( groupby ) df = df . resample ( rule , on = time_index ) df = getattr ( df , aggregation ) ( ) for column in groupby : del df [ column ] return df
def symlink ( target , link , target_is_directory = False ) : """An implementation of os . symlink for Windows ( Vista and greater )"""
target_is_directory = ( target_is_directory or _is_target_a_directory ( link , target ) ) # normalize the target ( MS symlinks don ' t respect forward slashes ) target = os . path . normpath ( target ) handle_nonzero_success ( api . CreateSymbolicLink ( link , target , target_is_directory ) )
def schedule_snapshot ( self ) : """Trigger snapshot to be uploaded to AWS . Return success state ."""
# Notes : # - Snapshots are not immediate . # - Snapshots will be cached for predefined amount # of time . # - Snapshots are not balanced . To get a better # image , it must be taken from the stream , a few # seconds after stream start . url = SNAPSHOTS_ENDPOINT params = SNAPSHOTS_BODY params [ 'from' ] = "{0}_web" . f...
def _dict_seq_locus ( list_c , loci_obj , seq_obj ) : """return dict with sequences = [ cluster1 , cluster2 . . . ]"""
seqs = defaultdict ( set ) # n = len ( list _ c . keys ( ) ) for c in list_c . values ( ) : for l in c . loci2seq : [ seqs [ s ] . add ( c . id ) for s in c . loci2seq [ l ] ] common = [ s for s in seqs if len ( seqs [ s ] ) > 1 ] seqs_in_c = defaultdict ( float ) for c in list_c . values ( ) : for l in...
def run ( self ) : """Run the configured method and write the HTTP response status and text to the output stream ."""
region = AWSServiceRegion ( access_key = self . key , secret_key = self . secret , uri = self . endpoint ) query = self . query_factory ( action = self . action , creds = region . creds , endpoint = region . ec2_endpoint , other_params = self . parameters ) def write_response ( response ) : print >> self . output ,...
def to_bytes ( value ) : """Get a byte array representing the value"""
if isinstance ( value , unicode ) : return value . encode ( 'utf8' ) elif not isinstance ( value , str ) : return str ( value ) return value
def publish_date ( self , publish_date ) : """Set Report publish date"""
self . _group_data [ 'publishDate' ] = self . _utils . format_datetime ( publish_date , date_format = '%Y-%m-%dT%H:%M:%SZ' )
def restart ( self ) : """Restart all the processes"""
Global . LOGGER . info ( "restarting the flow manager" ) self . _stop_actions ( ) # stop the old actions self . actions = [ ] # clear the action list self . _start_actions ( ) # start the configured actions Global . LOGGER . debug ( "flow manager restarted" )
def post ( self ) : """Create a new config item"""
self . reqparse . add_argument ( 'namespacePrefix' , type = str , required = True ) self . reqparse . add_argument ( 'description' , type = str , required = True ) self . reqparse . add_argument ( 'key' , type = str , required = True ) self . reqparse . add_argument ( 'value' , required = True ) self . reqparse . add_a...
def dump_orm_object_as_insert_sql ( engine : Engine , obj : object , fileobj : TextIO ) -> None : """Takes a SQLAlchemy ORM object , and writes ` ` INSERT ` ` SQL to replicate it to the output file - like object . Args : engine : SQLAlchemy : class : ` Engine ` obj : SQLAlchemy ORM object to write fileobj...
# literal _ query = make _ literal _ query _ fn ( engine . dialect ) insp = inspect ( obj ) # insp : an InstanceState # http : / / docs . sqlalchemy . org / en / latest / orm / internals . html # sqlalchemy . orm . state . InstanceState # noqa # insp . mapper : a Mapper # http : / / docs . sqlalchemy . org / en / lates...
def expanduser ( path ) : """Expand ~ and ~ user constructs . If user or $ HOME is unknown , do nothing ."""
if path [ : 1 ] != '~' : return path i , n = 1 , len ( path ) while i < n and path [ i ] not in '/\\' : i = i + 1 if 'HOME' in os . environ : userhome = os . environ [ 'HOME' ] elif 'USERPROFILE' in os . environ : userhome = os . environ [ 'USERPROFILE' ] elif not 'HOMEPATH' in os . environ : return...
def click ( self , x , y , button , press ) : '''Print Fibonacci numbers when the left click is pressed .'''
if button == 1 : if press : print ( self . fibo . next ( ) ) else : # Exit if any other mouse button used self . stop ( )
def barycenter ( A , M , weights = None , verbose = False , log = False , solver = 'interior-point' ) : """Compute the Wasserstein barycenter of distributions A The function solves the following optimization problem [ 16 ] : . . math : : \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{1}(\mathbf{a},\mathbf{a}_i) ...
if weights is None : weights = np . ones ( A . shape [ 1 ] ) / A . shape [ 1 ] else : assert ( len ( weights ) == A . shape [ 1 ] ) n_distributions = A . shape [ 1 ] n = A . shape [ 0 ] n2 = n * n c = np . zeros ( ( 0 ) ) b_eq1 = np . zeros ( ( 0 ) ) for i in range ( n_distributions ) : c = np . concatenate...
def traceroute6 ( target , dport = 80 , minttl = 1 , maxttl = 30 , sport = RandShort ( ) , l4 = None , timeout = 2 , verbose = None , ** kargs ) : """Instant TCP traceroute using IPv6 : traceroute6 ( target , [ maxttl = 30 ] , [ dport = 80 ] , [ sport = 80 ] ) - > None"""
if verbose is None : verbose = conf . verb if l4 is None : a , b = sr ( IPv6 ( dst = target , hlim = ( minttl , maxttl ) ) / TCP ( seq = RandInt ( ) , sport = sport , dport = dport ) , timeout = timeout , filter = "icmp6 or tcp" , verbose = verbose , ** kargs ) else : a , b = sr ( IPv6 ( dst = target , hlim...
def load ( self , value ) : """enforce env > value when loading from file"""
self . reset ( value , validator = self . __dict__ . get ( 'validator' ) , env = self . __dict__ . get ( 'env' ) , )
def run ( self , * , # Force keyword args . program : Union [ circuits . Circuit , Schedule ] , job_config : Optional [ JobConfig ] = None , param_resolver : ParamResolver = ParamResolver ( { } ) , repetitions : int = 1 , priority : int = 50 , processor_ids : Sequence [ str ] = ( 'xmonsim' , ) ) -> TrialResult : ""...
return list ( self . run_sweep ( program = program , job_config = job_config , params = [ param_resolver ] , repetitions = repetitions , priority = priority , processor_ids = processor_ids ) ) [ 0 ]
def _from_java ( cls , java_stage ) : """Given a Java OneVsRestModel , create and return a Python wrapper of it . Used for ML persistence ."""
featuresCol = java_stage . getFeaturesCol ( ) labelCol = java_stage . getLabelCol ( ) predictionCol = java_stage . getPredictionCol ( ) classifier = JavaParams . _from_java ( java_stage . getClassifier ( ) ) models = [ JavaParams . _from_java ( model ) for model in java_stage . models ( ) ] py_stage = cls ( models = mo...
def rule ( self ) : """The ( partial ) url rule for this route ."""
if self . _rule : return self . _rule return self . _make_rule ( member_param = self . _member_param , unique_member_param = self . _unique_member_param )
def make_path ( * path_or_str_or_segments ) : """: param path _ or _ str _ or _ segments : : return : : rtype : cifparser . path . Path"""
if len ( path_or_str_or_segments ) == 0 : return ROOT_PATH elif len ( path_or_str_or_segments ) == 1 : single_item = path_or_str_or_segments [ 0 ] if isinstance ( single_item , Path ) : return single_item if isinstance ( single_item , str ) : try : return path_parser . parseS...
def get_full_xml_representation ( entity , private_key ) : """Get full XML representation of an entity . This contains the < XML > < post > . . < / post > < / XML > wrapper . Accepts either a Base entity or a Diaspora entity . Author ` private _ key ` must be given so that certain entities can be signed ."""
from federation . entities . diaspora . mappers import get_outbound_entity diaspora_entity = get_outbound_entity ( entity , private_key ) xml = diaspora_entity . to_xml ( ) return "<XML><post>%s</post></XML>" % etree . tostring ( xml ) . decode ( "utf-8" )
def atomic_open_for_write ( target , binary = False , newline = None , encoding = None ) : """Atomically open ` target ` for writing . This is based on Lektor ' s ` atomic _ open ( ) ` utility , but simplified a lot to handle only writing , and skip many multi - process / thread edge cases handled by Werkzeug...
mode = "w+b" if binary else "w" f = NamedTemporaryFile ( dir = os . path . dirname ( target ) , prefix = ".__atomic-write" , mode = mode , encoding = encoding , newline = newline , delete = False , ) # set permissions to 0644 os . chmod ( f . name , stat . S_IWUSR | stat . S_IRUSR | stat . S_IRGRP | stat . S_IROTH ) tr...
def is_sw_writable ( self ) : """Field is writable by software"""
sw = self . get_property ( 'sw' ) return sw in ( rdltypes . AccessType . rw , rdltypes . AccessType . rw1 , rdltypes . AccessType . w , rdltypes . AccessType . w1 )
def match ( self , subject : Union [ Expression , FlatTerm ] ) -> Iterator [ Tuple [ T , Substitution ] ] : """Match the given subject against all patterns in the net . Args : subject : The subject that is matched . Must be constant . Yields : A tuple : code : ` ( final label , substitution ) ` , where th...
for index in self . _match ( subject ) : pattern , label = self . _patterns [ index ] subst = Substitution ( ) if subst . extract_substitution ( subject , pattern . expression ) : for constraint in pattern . constraints : if not constraint ( subst ) : break else :...
def store ( self , name = None ) : """Get a cache store instance by name . : param name : The cache store name : type name : str : rtype : Repository"""
if name is None : name = self . get_default_driver ( ) self . _stores [ name ] = self . _get ( name ) return self . _stores [ name ]
def reduction ( input_type , output_type ) : """Define a user - defined reduction function that takes N pandas Series or scalar values as inputs and produces one row of output . Parameters input _ type : List [ ibis . expr . datatypes . DataType ] A list of the types found in : mod : ` ~ ibis . expr . datat...
return udf . _grouped ( input_type , output_type , base_class = ops . Reduction , output_type_method = operator . attrgetter ( 'scalar_type' ) , )
def search ( self , read_cache = True , ** kwparams ) : """Returns records corresponding to the given search query . See docstring of invenio . legacy . search _ engine . perform _ request _ search ( ) for an overview of available parameters . @ raise InvenioConnectorAuthError : if authentication fails"""
parse_results = False of = kwparams . get ( 'of' , "" ) if of == "" : parse_results = True of = "xm" kwparams [ 'of' ] = of params = urllib . urlencode ( kwparams , doseq = 1 ) # Are we running locally ? If so , better directly access the # search engine directly if self . local and of != 't' : # See if use...
def MIS ( G , weights , maxiter = None ) : """Compute a maximal independent set of a graph in parallel . Parameters G : csr _ matrix Matrix graph , G [ i , j ] ! = 0 indicates an edge weights : ndarray Array of weights for each vertex in the graph G maxiter : int Maximum number of iterations ( default...
if not isspmatrix_csr ( G ) : raise TypeError ( 'expected csr_matrix' ) G = remove_diagonal ( G ) mis = np . empty ( G . shape [ 0 ] , dtype = 'intc' ) mis [ : ] = - 1 fn = amg_core . maximal_independent_set_parallel if maxiter is None : fn ( G . shape [ 0 ] , G . indptr , G . indices , - 1 , 1 , 0 , mis , weig...
def sendMessage ( self , data ) : """Send websocket data frame to the client . If data is a unicode object then the frame is sent as Text . If the data is a bytearray object then the frame is sent as Binary ."""
opcode = BINARY if isinstance ( data , unicode ) : opcode = TEXT self . _sendMessage ( False , opcode , data )
def retrieve ( self , request , _id ) : """Returns the document containing the given _ id or 404"""
_id = deserialize ( _id ) retrieved = self . collection . find_one ( { '_id' : _id } ) if retrieved : return Response ( serialize ( retrieved ) ) else : return Response ( response = serialize ( DocumentNotFoundError ( self . collection . __name__ , _id ) ) , status = 400 )
def simple_periodic_send ( bus ) : """Sends a message every 20ms with no explicit timeout Sleeps for 2 seconds then stops the task ."""
print ( "Starting to send a message every 200ms for 2s" ) msg = can . Message ( arbitration_id = 0x123 , data = [ 1 , 2 , 3 , 4 , 5 , 6 ] , is_extended_id = False ) task = bus . send_periodic ( msg , 0.20 ) assert isinstance ( task , can . CyclicSendTaskABC ) time . sleep ( 2 ) task . stop ( ) print ( "stopped cyclic s...
def read ( self ) -> None : """Call method | NetCDFFile . read | of all handled | NetCDFFile | objects ."""
for folder in self . folders . values ( ) : for file_ in folder . values ( ) : file_ . read ( )
def from_locus_read ( cls , locus_read , n_ref ) : """Given a single LocusRead object , return either an AlleleRead or None Parameters locus _ read : LocusRead Read which overlaps a variant locus but doesn ' t necessarily contain the alternate nucleotides n _ ref : int Number of reference positions we a...
sequence = locus_read . sequence reference_positions = locus_read . reference_positions # positions of the nucleotides before and after the variant within # the read sequence read_pos_before = locus_read . base0_read_position_before_variant read_pos_after = locus_read . base0_read_position_after_variant # positions of ...
def plot ( self , skip_start : int = 10 , skip_end : int = 5 , suggestion : bool = False , return_fig : bool = None , ** kwargs ) -> Optional [ plt . Figure ] : "Plot learning rate and losses , trimmed between ` skip _ start ` and ` skip _ end ` . Optionally plot and return min gradient"
lrs = self . _split_list ( self . lrs , skip_start , skip_end ) losses = self . _split_list ( self . losses , skip_start , skip_end ) losses = [ x . item ( ) for x in losses ] if 'k' in kwargs : losses = self . smoothen_by_spline ( lrs , losses , ** kwargs ) fig , ax = plt . subplots ( 1 , 1 ) ax . plot ( lrs , los...
def require ( * requirements , ** kwargs ) : """Decorator that can be used to require requirements . : param requirements : List of requirements that should be verified : param none _ on _ failure : If true , does not raise a PrerequisiteFailedError , but instead returns None"""
# TODO : require ( * requirements , none _ on _ failure = False ) is not supported by Python 2 none_on_failure = kwargs . get ( 'none_on_failure' , False ) def inner ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : for req in requirements : if none_on_failure : ...
def netconf_config_change_changed_by_server_or_user_server_server ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) netconf_config_change = ET . SubElement ( config , "netconf-config-change" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-notifications" ) changed_by = ET . SubElement ( netconf_config_change , "changed-by" ) server_or_user = ET . SubElement ( changed_by , "server-or-user" ) serv...
def dataset_upload_file ( self , path , quiet ) : """upload a dataset file Parameters path : the complete path to upload quiet : suppress verbose output ( default is False )"""
file_name = os . path . basename ( path ) content_length = os . path . getsize ( path ) last_modified_date_utc = int ( os . path . getmtime ( path ) ) result = FileUploadInfo ( self . process_response ( self . datasets_upload_file_with_http_info ( file_name , content_length , last_modified_date_utc ) ) ) success = self...
def get_array ( self ) : """Returns an numpy array containing the values from start ( inclusive ) to stop ( exclusive ) in step steps . Returns array : ndarray Array of values from start ( inclusive ) to stop ( exclusive ) in step steps ."""
s = self . slice array = _np . arange ( s . start , s . stop , s . step ) return array
def process_waypoint_request ( self , m , master ) : '''process a waypoint request from the master'''
if ( not self . loading_waypoints or time . time ( ) > self . loading_waypoint_lasttime + 10.0 ) : self . loading_waypoints = False self . console . error ( "not loading waypoints" ) return if m . seq >= self . wploader . count ( ) : self . console . error ( "Request for bad waypoint %u (max %u)" % ( m ...
def options ( self , section ) : """Return a list of option names for the given section name ."""
try : opts = self . _sections [ section ] . copy ( ) except KeyError : raise from_none ( NoSectionError ( section ) ) opts . update ( self . _defaults ) return list ( opts . keys ( ) )
def debug_consec_list ( list_ ) : """Returns : tuple of ( missing _ items , missing _ indices , duplicate _ items )"""
if not issorted ( list_ ) : print ( 'warning list is not sorted. indices will not match' ) sortedlist = sorted ( list_ ) start = sortedlist [ 0 ] last = start - 1 missing_vals = [ ] missing_indices = [ ] duplicate_items = [ ] for count , item in enumerate ( sortedlist ) : diff = item - last if diff > 1 : ...
def get_files_with_extensions ( folder , extensions ) : """walk dir and return . * files as a list Note : directories are walked recursively"""
out = [ ] for root , dirs , files in os . walk ( folder ) : for file in files : filename , file_extension = os . path . splitext ( file ) if file_extension . replace ( "." , "" ) in extensions : out += [ os . path . join ( root , file ) ] # break return out
def push_repository ( self , repository , docker_executable = 'docker' , shutit_pexpect_child = None , expect = None , note = None , loglevel = logging . INFO ) : """Pushes the repository . @ param repository : Repository to push . @ param docker _ executable : Defaults to ' docker ' @ param expect : See send...
shutit_global . shutit_global_object . yield_to_draw ( ) self . handle_note ( note ) shutit_pexpect_child = shutit_pexpect_child or self . get_shutit_pexpect_session_from_id ( 'host_child' ) . pexpect_child expect = expect or self . expect_prompts [ 'ORIGIN_ENV' ] send = docker_executable + ' push ' + self . repository...
def _multiline_convert ( config , start = "banner login" , end = "EOF" , depth = 1 ) : """Converts running - config HEREDOC into EAPI JSON dict"""
ret = list ( config ) # Don ' t modify list in - place try : s = ret . index ( start ) e = s while depth : e = ret . index ( end , e + 1 ) depth = depth - 1 except ValueError : # Couldn ' t find end , abort return ret ret [ s ] = { "cmd" : ret [ s ] , "input" : "\n" . join ( ret [ s + 1 ...
def setup_recovery ( working_dir ) : """Set up the recovery metadata so we can fully recover secondary state , like subdomains ."""
db = get_db_state ( working_dir ) bitcoind_session = get_bitcoind ( new = True ) assert bitcoind_session is not None _ , current_block = virtualchain . get_index_range ( 'bitcoin' , bitcoind_session , virtualchain_hooks , working_dir ) assert current_block , 'Failed to connect to bitcoind' set_recovery_range ( working_...
def get_version ( self , as_tuple = False ) : """Returns uWSGI version string or tuple . : param bool as _ tuple : : rtype : str | tuple"""
if as_tuple : return uwsgi . version_info return decode ( uwsgi . version )
def attributes_in_restriction ( self ) : """: return : list of attributes that are probably used in the restriction . The function errs on the side of false positives . For example , if the restriction is " val = ' id ' " , then the attribute ' id ' would be flagged . This is used internally for optimizing SQ...
return set ( name for name in self . heading . names if re . search ( r'\b' + name + r'\b' , self . where_clause ) )
def _process_response ( self , msg ) : '''处理响应消息'''
status , headers , body = self . _parse_response ( msg ) rsp_cseq = int ( headers [ 'cseq' ] ) if self . _cseq_map [ rsp_cseq ] != 'GET_PARAMETER' : PRINT ( self . _get_time_str ( ) + '\n' + msg ) if status == 302 : self . location = headers [ 'location' ] if status != 200 : self . do_teardown ( ) if self ....
def get_namespace_by_keyword_pattern ( self , keyword : str , pattern : str ) -> Optional [ Namespace ] : """Get a namespace with a given keyword and pattern ."""
filt = and_ ( Namespace . keyword == keyword , Namespace . pattern == pattern ) return self . session . query ( Namespace ) . filter ( filt ) . one_or_none ( )
def is_choked_turbulent_l ( dP , P1 , Psat , FF , FL = None , FLP = None , FP = None ) : r'''Calculates if a liquid flow in IEC 60534 calculations is critical or not , for use in IEC 60534 liquid valve sizing calculations . Either FL may be provided or FLP and FP , depending on the calculation process . . ....
if FLP and FP : return dP >= ( FLP / FP ) ** 2 * ( P1 - FF * Psat ) elif FL : return dP >= FL ** 2 * ( P1 - FF * Psat ) else : raise Exception ( 'Either (FLP and FP) or FL is needed' )
def align_seqs ( found_seqs , sequence , locus , start_pos , missing , annotated , cutoff = 0.90 , verbose = False , verbosity = 0 ) : """align _ seqs - Aligns sequences with clustalo : param found _ seqs : List of the reference sequences : type found _ seqs : ` ` List ` ` : param sequence : The input consens...
logger = logging . getLogger ( "Logger." + __name__ ) seqs = [ found_seqs , sequence ] if verbose and verbosity > 0 : logger . info ( "found_seqs length = " + str ( len ( found_seqs ) ) ) logger . info ( "sequence length = " + str ( len ( sequence ) ) ) seqs = [ ] seqs . append ( found_seqs ) seqs . append ( se...
def ParseAccountInformation ( self , parser_mediator , query , row , ** unused_kwargs ) : """Parses account information . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . query ( str ) : query that created the row . row ...
query_hash = hash ( query ) display_name = self . _GetRowValue ( query_hash , row , 'given_displayname' ) fullname = self . _GetRowValue ( query_hash , row , 'fullname' ) # TODO : Move this to the formatter , and ensure username is rendered # properly when fullname and / or display _ name is None . username = '{0!s} <{...
def _config_win32_domain ( self , domain ) : """Configure a Domain registry entry ."""
# we call str ( ) on domain to convert it from unicode to ascii self . domain = dns . name . from_text ( str ( domain ) )