signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def mutate ( self , row ) : """Add a row to the batch . If the current batch meets one of the size limits , the batch is sent synchronously . For example : . . literalinclude : : snippets . py : start - after : [ START bigtable _ batcher _ mutate ] : end - before : [ END bigtable _ batcher _ mutate ] : ...
mutation_count = len ( row . _get_mutations ( ) ) if mutation_count > MAX_MUTATIONS : raise MaxMutationsError ( "The row key {} exceeds the number of mutations {}." . format ( row . row_key , mutation_count ) ) if ( self . total_mutation_count + mutation_count ) >= MAX_MUTATIONS : self . flush ( ) self . rows ....
def _raise_or_append_exception ( self ) : """The connection is presumably dead and we need to raise or append an exception . If we have a list for exceptions , append the exception and let the connection handle it , if not raise the exception here . : return :"""
message = ( 'Connection dead, no heartbeat or data received in >= ' '%ds' % ( self . _interval * 2 ) ) why = AMQPConnectionError ( message ) if self . _exceptions is None : raise why self . _exceptions . append ( why )
def register ( self , classes = [ ] ) : """Registers new plugins . The registration only creates a new entry for a plugin inside the _ classes dictionary . It does not activate or even initialise the plugin . A plugin must be a class , which inherits directly or indirectly from GwBasePattern . : param class...
if not isinstance ( classes , list ) : raise AttributeError ( "plugins must be a list, not %s." % type ( classes ) ) plugin_registered = [ ] for plugin_class in classes : plugin_name = plugin_class . __name__ self . register_class ( plugin_class , plugin_name ) self . _log . debug ( "Plugin %s registere...
def delete_posix_account ( self , name , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) : """Deletes a POSIX account . Example : > > > from google . cloud import oslogin _ v1 > > > client = oslogin _ v1 . OsLoginService...
# Wrap the transport method to add retry and timeout logic . if "delete_posix_account" not in self . _inner_api_calls : self . _inner_api_calls [ "delete_posix_account" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . delete_posix_account , default_retry = self . _method_configs [ "Delet...
def get_models ( self , columns = None ) : """Get the hydrated models without eager loading . : param columns : The columns to get : type columns : list : return : A list of models : rtype : list"""
results = self . _query . get ( columns ) connection = self . _model . get_connection_name ( ) return self . _model . hydrate ( results , connection ) . all ( )
def opened ( self , block_identifier : BlockSpecification ) -> bool : """Returns if the channel is opened ."""
return self . token_network . channel_is_opened ( participant1 = self . participant1 , participant2 = self . participant2 , block_identifier = block_identifier , channel_identifier = self . channel_identifier , )
def clear_dead_threads ( self ) : """Remove Thread objects from the snapshot referring to threads no longer running ."""
for tid in self . get_thread_ids ( ) : aThread = self . get_thread ( tid ) if not aThread . is_alive ( ) : self . _del_thread ( aThread )
def decode_iter ( data , codec_options = DEFAULT_CODEC_OPTIONS ) : """Decode BSON data to multiple documents as a generator . Works similarly to the decode _ all function , but yields one document at a time . ` data ` must be a string of concatenated , valid , BSON - encoded documents . : Parameters : -...
if not isinstance ( codec_options , CodecOptions ) : raise _CODEC_OPTIONS_TYPE_ERROR position = 0 end = len ( data ) - 1 while position < end : obj_size = _UNPACK_INT ( data [ position : position + 4 ] ) [ 0 ] elements = data [ position : position + obj_size ] position += obj_size yield _bson_to_dic...
def process_checkpoint ( self , msg : Checkpoint , sender : str ) -> bool : """Process checkpoint messages : return : whether processed ( True ) or stashed ( False )"""
self . logger . info ( '{} processing checkpoint {} from {}' . format ( self , msg , sender ) ) result , reason = self . validator . validate_checkpoint_msg ( msg ) if result == DISCARD : self . discard ( msg , "{} discard message {} from {} " "with the reason: {}" . format ( self , msg , sender , reason ) , self ....
def import_teamocil ( sconf ) : """Return tmuxp config from a ` teamocil ` _ yaml config . . . _ teamocil : https : / / github . com / remiprev / teamocil Parameters sconf : dict python dict for session configuration Notes Todos : - change ' root ' to a cd or start _ directory - width in pane - > ma...
tmuxp_config = { } if 'session' in sconf : sconf = sconf [ 'session' ] if 'name' in sconf : tmuxp_config [ 'session_name' ] = sconf [ 'name' ] else : tmuxp_config [ 'session_name' ] = None if 'root' in sconf : tmuxp_config [ 'start_directory' ] = sconf . pop ( 'root' ) tmuxp_config [ 'windows' ] = [ ] f...
def calculate_eclipses ( M1s , M2s , R1s , R2s , mag1s , mag2s , u11s = 0.394 , u21s = 0.296 , u12s = 0.394 , u22s = 0.296 , Ps = None , period = None , logperkde = RAGHAVAN_LOGPERKDE , incs = None , eccs = None , mininc = None , calc_mininc = True , maxecc = 0.97 , ecc_fn = draw_eccs , band = 'Kepler' , return_probabi...
if MAfn is None : logging . warning ( 'MAInterpolationFunction not passed, so generating one...' ) MAfn = MAInterpolationFunction ( nzs = 200 , nps = 400 , pmin = 0.007 , pmax = 1 / 0.007 ) M1s = np . atleast_1d ( M1s ) M2s = np . atleast_1d ( M2s ) R1s = np . atleast_1d ( R1s ) R2s = np . atleast_1d ( R2s ) nb...
def all ( self ) : """Returns list with vids of all indexed partitions ."""
partitions = [ ] query = text ( """ SELECT dataset_vid, vid FROM partition_index;""" ) for result in self . backend . library . database . connection . execute ( query ) : dataset_vid , vid = result partitions . append ( PartitionSearchResult ( dataset_vid = dataset_vid , vid = vid , sco...
def recordWidget ( xparent , widget ) : """Records the inputed widget to the parent profile . : param xparent | < xml . etree . Element > widget | < QWidget >"""
# record a splitter if isinstance ( widget , XSplitter ) : xwidget = ElementTree . SubElement ( xparent , 'split' ) if ( widget . orientation ( ) == Qt . Horizontal ) : xwidget . set ( 'orient' , 'horizontal' ) else : xwidget . set ( 'orient' , 'vertical' ) xwidget . set ( 'state' , nati...
def construct_time_based_gas_price_strategy ( max_wait_seconds , sample_size = 120 , probability = 98 ) : """A gas pricing strategy that uses recently mined block data to derive a gas price for which a transaction is likely to be mined within X seconds with probability P . : param max _ wait _ seconds : The d...
def time_based_gas_price_strategy ( web3 , transaction_params ) : avg_block_time = _get_avg_block_time ( web3 , sample_size = sample_size ) wait_blocks = int ( math . ceil ( max_wait_seconds / avg_block_time ) ) raw_miner_data = _get_raw_miner_data ( web3 , sample_size = sample_size ) miner_data = _aggr...
def tensor_markov ( * args ) : """Computes the product of two independent markov chains . : param m1 : a tuple containing the nodes and the transition matrix of the first chain : param m2 : a tuple containing the nodes and the transition matrix of the second chain : return : a tuple containing the nodes and t...
if len ( args ) > 2 : m1 = args [ 0 ] m2 = args [ 1 ] tail = args [ 2 : ] prod = tensor_markov ( m1 , m2 ) return tensor_markov ( prod , tail ) elif len ( args ) == 2 : m1 , m2 = args n1 , t1 = m1 n2 , t2 = m2 n1 = np . array ( n1 , dtype = float ) n2 = np . array ( n2 , dtype = ...
def reshape_1d ( df ) : """If parameter is 1D row vector then convert it into 2D matrix ."""
shape = df . shape if len ( shape ) == 1 : return df . reshape ( shape [ 0 ] , 1 ) else : return df
def get_segment_efforts ( self , segment_id , athlete_id = None , start_date_local = None , end_date_local = None , limit = None ) : """Gets all efforts on a particular segment sorted by start _ date _ local Returns an array of segment effort summary representations sorted by start _ date _ local ascending or b...
params = { "segment_id" : segment_id } if athlete_id is not None : params [ 'athlete_id' ] = athlete_id if start_date_local : if isinstance ( start_date_local , six . string_types ) : start_date_local = arrow . get ( start_date_local ) . naive params [ "start_date_local" ] = start_date_local . strft...
def get_parsed_args ( self , comp_words ) : """gets the parsed args from a patched parser"""
active_parsers = self . _patch_argument_parser ( ) parsed_args = argparse . Namespace ( ) self . completing = True if USING_PYTHON2 : # Python 2 argparse only properly works with byte strings . comp_words = [ ensure_bytes ( word ) for word in comp_words ] try : active_parsers [ 0 ] . parse_known_args ( comp_wor...
def nodeInLanguageStem ( _ : Context , n : Node , s : ShExJ . LanguageStem ) -> bool : """http : / / shex . io / shex - semantics / # values * * nodeIn * * : asserts that an RDF node n is equal to an RDF term s or is in a set defined by a : py : class : ` ShExJ . IriStem ` , : py : class : ` LiteralStem ` or : ...
return isinstance ( s , ShExJ . Wildcard ) or ( isinstance ( n , Literal ) and n . language is not None and str ( n . language ) . startswith ( str ( s ) ) )
def create_new_account ( data_dir , password , ** geth_kwargs ) : """Creates a new Ethereum account on geth . This is useful for testing when you want to stress interaction ( transfers ) between Ethereum accounts . This command communicates with ` ` geth ` ` command over terminal interaction . It creates ke...
if os . path . exists ( password ) : geth_kwargs [ 'password' ] = password command , proc = spawn_geth ( dict ( data_dir = data_dir , suffix_args = [ 'account' , 'new' ] , ** geth_kwargs ) ) if os . path . exists ( password ) : stdoutdata , stderrdata = proc . communicate ( ) else : stdoutdata , stderrdata ...
def parse_parameter ( self , tup_tree ) : """< ! ELEMENT PARAMETER ( QUALIFIER * ) > < ! ATTLIST PARAMETER % CIMName ; % CIMType ; # REQUIRED >"""
self . check_node ( tup_tree , 'PARAMETER' , ( 'NAME' , 'TYPE' ) , ( ) , ( 'QUALIFIER' , ) ) attrl = attrs ( tup_tree ) qualifiers = self . list_of_matching ( tup_tree , ( 'QUALIFIER' , ) ) return CIMParameter ( attrl [ 'NAME' ] , type = attrl [ 'TYPE' ] , is_array = False , qualifiers = qualifiers , embedded_object = ...
def filter_N_top ( self , inst_rc , N_top , rank_type = 'sum' ) : '''Filter the matrix rows or columns based on sum / variance , and only keep the top'''
inst_df = self . dat_to_df ( ) inst_df = run_filter . filter_N_top ( inst_rc , inst_df , N_top , rank_type ) self . df_to_dat ( inst_df )
def clear ( self ) : """Brutely clears the key value store for keys with THUMBNAIL _ KEY _ PREFIX prefix . Use this in emergency situations . Normally you would probably want to use the ` ` cleanup ` ` method instead ."""
all_keys = self . _find_keys_raw ( settings . THUMBNAIL_KEY_PREFIX ) if all_keys : self . _delete_raw ( * all_keys )
def total_ordering ( cls ) : # pragma : no cover """Class decorator that fills in missing ordering methods"""
convert = { '__lt__' : [ ( '__gt__' , lambda self , other : not ( self < other or self == other ) ) , ( '__le__' , lambda self , other : self < other or self == other ) , ( '__ge__' , lambda self , other : not self < other ) ] , '__le__' : [ ( '__ge__' , lambda self , other : not self <= other or self == other ) , ( '_...
def save_current_nb_as_html ( info = False ) : """Save the current notebook as html file in the same directory"""
assert in_ipynb ( ) full_path = get_notebook_name ( ) path , filename = os . path . split ( full_path ) wd_save = os . getcwd ( ) os . chdir ( path ) cmd = 'jupyter nbconvert --to html "{}"' . format ( filename ) os . system ( cmd ) os . chdir ( wd_save ) if info : print ( "target dir: " , path ) print ( "cmd: ...
def get_root_folder ( ) : """returns the home folder and program root depending on OS"""
locations = { 'linux' : { 'hme' : '/home/duncan/' , 'core_folder' : '/home/duncan/dev/src/python/AIKIF' } , 'win32' : { 'hme' : 'T:\\user\\' , 'core_folder' : 'T:\\user\\dev\\src\\python\\AIKIF' } , 'cygwin' : { 'hme' : os . getcwd ( ) + os . sep , 'core_folder' : os . getcwd ( ) } , 'darwin' : { 'hme' : os . getcwd ( ...
def _default_ising_beta_range ( h , J ) : """Determine the starting and ending beta from h J Args : h ( dict ) J ( dict ) Assume each variable in J is also in h . We use the minimum bias to give a lower bound on the minimum energy gap , such at the final sweeps we are highly likely to settle into the cu...
# Get nonzero , absolute biases abs_h = [ abs ( hh ) for hh in h . values ( ) if hh != 0 ] abs_J = [ abs ( jj ) for jj in J . values ( ) if jj != 0 ] abs_biases = abs_h + abs_J if not abs_biases : return [ 0.1 , 1.0 ] # Rough approximation of min change in energy when flipping a qubit min_delta_energy = min ( abs_b...
def describe ( self , language = DEFAULT_LANGUAGE , min_score : int = 75 ) -> dict : """Return a dictionary that describes a given language tag in a specified natural language . See ` language _ name ` and related methods for more specific versions of this . The desired ` language ` will in fact be matched ag...
names = { } if self . language : names [ 'language' ] = self . language_name ( language , min_score ) if self . script : names [ 'script' ] = self . script_name ( language , min_score ) if self . region : names [ 'region' ] = self . region_name ( language , min_score ) if self . variants : names [ 'vari...
def get_methods_by_name ( self , name ) : """generator of methods matching name . This will include any bridges present ."""
return ( m for m in self . methods if m . get_name ( ) == name )
def list_protocols ( profile , ** libcloud_kwargs ) : '''Return a list of supported protocols . : param profile : The profile key : type profile : ` ` str ` ` : param libcloud _ kwargs : Extra arguments for the driver ' s list _ protocols method : type libcloud _ kwargs : ` ` dict ` ` : return : a list of...
conn = _get_driver ( profile = profile ) libcloud_kwargs = salt . utils . args . clean_kwargs ( ** libcloud_kwargs ) return conn . list_protocols ( ** libcloud_kwargs )
def firmware_drivers ( self ) : """Gets the FirmwareDrivers API client . Returns : FirmwareDrivers :"""
if not self . __firmware_drivers : self . __firmware_drivers = FirmwareDrivers ( self . __connection ) return self . __firmware_drivers
def classorder ( self , classes ) : """Return a list of class IDs in order for presentational purposes : order is determined first and foremost by explicit ordering , else alphabetically by label or as a last resort by class ID"""
return [ classid for classid , classitem in sorted ( ( ( classid , classitem ) for classid , classitem in classes . items ( ) if 'seqnr' in classitem ) , key = lambda pair : pair [ 1 ] [ 'seqnr' ] ) ] + [ classid for classid , classitem in sorted ( ( ( classid , classitem ) for classid , classitem in classes . items ( ...
def problem_serializing ( value , e = None ) : """THROW ERROR ABOUT SERIALIZING"""
from mo_logs import Log try : typename = type ( value ) . __name__ except Exception : typename = "<error getting name>" try : rep = text_type ( repr ( value ) ) except Exception as _ : rep = None if rep == None : Log . error ( "Problem turning value of type {{type}} to json" , type = typename , caus...
def logit ( self , msg , pid , user , cname , priority = None ) : """Function for formatting content and logging to syslog"""
if self . stream : print ( msg , file = self . stream ) elif priority == logging . WARNING : self . logger . warning ( "{0}[pid:{1}] user:{2}: WARNING - {3}" . format ( cname , pid , user , msg ) ) elif priority == logging . ERROR : self . logger . error ( "{0}[pid:{1}] user:{2}: ERROR - {3}" . format ( cna...
def ReplaceStoredProcedure ( self , sproc_link , sproc , options = None ) : """Replaces a stored procedure and returns it . : param str sproc _ link : The link to the stored procedure . : param dict sproc : : param dict options : The request options for the request . : return : The replaced Stored Pro...
if options is None : options = { } CosmosClient . __ValidateResource ( sproc ) sproc = sproc . copy ( ) if sproc . get ( 'serverScript' ) : sproc [ 'body' ] = str ( sproc [ 'serverScript' ] ) elif sproc . get ( 'body' ) : sproc [ 'body' ] = str ( sproc [ 'body' ] ) path = base . GetPathFromLink ( sproc_link...
def get_contributor_sort_value ( self , obj ) : """Generate display name for contributor ."""
user = obj . contributor if user . first_name or user . last_name : contributor = user . get_full_name ( ) else : contributor = user . username return contributor . strip ( ) . lower ( )
def addNotice ( self , data ) : """Add custom notice to front - end for this NodeServers : param data : String of characters to add as a notification in the front - end ."""
LOGGER . info ( 'Sending addnotice to Polyglot: {}' . format ( data ) ) message = { 'addnotice' : data } self . send ( message )
def search ( pattern , sentence , * args , ** kwargs ) : """Returns a list of all matches found in the given sentence ."""
return compile ( pattern , * args , ** kwargs ) . search ( sentence )
def init_fftw_plan ( self , planning_effort = 'measure' , ** kwargs ) : """Initialize the FFTW plan for this transform for later use . If the implementation of this operator is not ' pyfftw ' , this method should not be called . Parameters planning _ effort : str , optional Flag for the amount of effort p...
if self . impl != 'pyfftw' : raise ValueError ( 'cannot create fftw plan without fftw backend' ) # Using available temporaries if possible inverse = isinstance ( self , FourierTransformInverse ) if inverse : rspace = self . range fspace = self . domain else : rspace = self . domain fspace = self . r...
def epoch_cb ( self ) : """Callback function after each epoch . Now it records each epoch time and append it to epoch dataframe ."""
metrics = { } metrics [ 'elapsed' ] = self . elapsed ( ) now = datetime . datetime . now ( ) metrics [ 'epoch_time' ] = now - self . last_epoch_time self . append_metrics ( metrics , 'epoch' ) self . last_epoch_time = now
def sam_readline ( sock , partial = None ) : """read a line from a sam control socket"""
response = b'' exception = None while True : try : c = sock . recv ( 1 ) if not c : raise EOFError ( 'SAM connection died. Partial response %r %r' % ( partial , response ) ) elif c == b'\n' : break else : response += c except ( BlockingIOError ...
def hacking_no_removed_module ( logical_line , noqa ) : r"""Check for removed modules in Python 3. Examples : Okay : from os import path Okay : from os import path as p Okay : from os import ( path as p ) Okay : import os . path H237 : import thread Okay : import thread # noqa H237 : import commands...
if noqa : return line = core . import_normalize ( logical_line . strip ( ) ) if line and line . split ( ) [ 0 ] == 'import' : module_name = line . split ( ) [ 1 ] . split ( '.' ) [ 0 ] if module_name in removed_modules : yield 0 , ( "H237: module %s is " "removed in Python 3" % module_name )
def must_open ( filename , mode = "r" , checkexists = False , skipcheck = False , oappend = False ) : """Accepts filename and returns filehandle . Checks on multiple files , stdin / stdout / stderr , . gz or . bz2 file ."""
if isinstance ( filename , list ) : assert "r" in mode if filename [ 0 ] . endswith ( ( ".gz" , ".bz2" ) ) : filename = " " . join ( filename ) # allow opening multiple gz / bz2 files else : import fileinput return fileinput . input ( filename ) if filename . startswith ( "s3...
def update_values ( self ) : """Update form values when detection method is selected ."""
self . method = self . idx_method . currentText ( ) sw_det = DetectSlowWave ( method = self . method ) self . index [ 'f1' ] . set_value ( sw_det . det_filt [ 'freq' ] [ 0 ] ) self . index [ 'f2' ] . set_value ( sw_det . det_filt [ 'freq' ] [ 1 ] ) self . index [ 'min_trough_dur' ] . set_value ( sw_det . trough_duratio...
def value ( self ) : """returns the class as a dictionary"""
val = { } for k in self . __allowed_keys : v = getattr ( self , "_" + k ) if v is not None : val [ k ] = v return val
def obo ( self ) : """str : the ontology serialized in obo format ."""
meta = self . _obo_meta ( ) meta = [ meta ] if meta else [ ] newline = "\n\n" if six . PY3 else "\n\n" . encode ( 'utf-8' ) try : # if ' namespace ' in self . meta : return newline . join ( meta + [ r . obo for r in self . typedefs ] + [ t . obo for t in self if t . id . startswith ( self . meta [ 'namespace' ] [ 0...
def stop ( self ) -> None : """Stops the running simulation once the current event is done executing ."""
if self . is_running : if _logger is not None : self . _log ( INFO , "stop" , __now = self . now ( ) ) self . _is_running = False
def render_template ( self , plain , rich = None , ** context ) : '''Render the body of the message from a template . The plain body will be rendered from a template named ` ` plain ` ` or ` ` plain + ' . txt ' ` ` ( in that order of preference ) . The rich body will be rendered from ` ` rich ` ` if given , o...
self . plain = render_template ( [ plain , plain + '.txt' ] , ** context ) if rich is not None : self . rich = render_template ( rich , ** context ) else : try : self . rich = render_template ( plain + '.html' , ** context ) except TemplateNotFound : pass
def result ( self , r = None , ** kwargs ) : '''Validates a result , stores it in self . results and prints it . Accepts the same kwargs as the binwalk . core . module . Result class . @ r - An existing instance of binwalk . core . module . Result . Returns an instance of binwalk . core . module . Result .'''
if r is None : r = Result ( ** kwargs ) # Add the name of the current module to the result r . module = self . __class__ . __name__ # Any module that is reporting results , valid or not , should be marked # as enabled if not self . enabled : self . enabled = True self . validate ( r ) self . _plugins_result ( r...
def _wait_for_reader ( self ) : """Checks for backpressure by the downstream reader ."""
if self . max_size <= 0 : # Unlimited queue return if self . write_item_offset - self . cached_remote_offset <= self . max_size : return # Hasn ' t reached max size remote_offset = internal_kv . _internal_kv_get ( self . read_ack_key ) if remote_offset is None : # logger . debug ( " [ writer ] Waiting for r...
def hexdiff ( x , y ) : """Show differences between 2 binary strings"""
x = bytes_encode ( x ) [ : : - 1 ] y = bytes_encode ( y ) [ : : - 1 ] SUBST = 1 INSERT = 1 d = { ( - 1 , - 1 ) : ( 0 , ( - 1 , - 1 ) ) } for j in range ( len ( y ) ) : d [ - 1 , j ] = d [ - 1 , j - 1 ] [ 0 ] + INSERT , ( - 1 , j - 1 ) for i in range ( len ( x ) ) : d [ i , - 1 ] = d [ i - 1 , - 1 ] [ 0 ] + INSE...
def setColor ( self , color ) : """Convenience method to set the border , fill and highlight colors based on the inputed color . : param color | < QColor >"""
# sets the border color as the full value self . setBorderColor ( color ) # set the highlight color as the color with a 140 % alpha clr = QColor ( color ) clr . setAlpha ( 150 ) self . setHighlightColor ( clr ) # set the fill color as the color with a 50 % alpha clr = QColor ( color ) clr . setAlpha ( 80 ) self . setFi...
def _internal_write ( out_stream , arr ) : """Writes numpy . ndarray arr to a file - like object ( with write ( ) method ) in IDX format ."""
if arr . size == 0 : raise FormatError ( 'Cannot encode empty array.' ) try : type_byte , struct_lib_type = _DATA_TYPES_NUMPY [ str ( arr . dtype ) ] except KeyError : raise FormatError ( 'numpy ndarray type not supported by IDX format.' ) if arr . ndim > _MAX_IDX_DIMENSIONS : raise FormatError ( 'IDX f...
def get_object ( self , identifier , mask = None ) : """Get a Reserved Capacity Group : param int identifier : Id of the SoftLayer _ Virtual _ ReservedCapacityGroup : param string mask : override default object Mask"""
if mask is None : mask = "mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]" result = self . client . call ( self . rcg_service , 'getObject' , id = identifier , mask = mask ) return result
def fetch_file_handler ( unused_build_context , target , fetch , package_dir , tar ) : """Handle remote downloadable file URI . Download the file and cache it under the private builer workspace ( unless already downloaded ) , and add it to the package tar . TODO ( itamar ) : Support re - downloading if remote...
dl_dir = join ( package_dir , fetch . name ) if fetch . name else package_dir fetch_url ( fetch . uri , join ( dl_dir , basename ( urlparse ( fetch . uri ) . path ) ) , dl_dir ) tar . add ( package_dir , arcname = split_name ( target . name ) )
def merge_upwards_if_smaller_than ( self , small_size , a_or_u ) : """After prune _ if _ smaller _ than is run , we may still have excess nodes . For example , with a small _ size of 609710690: 28815419 / data / * 32 / data / srv / * 925746 / data / srv / docker . bak / * 12 / data / srv / docker . bak ...
# Assert that we ' re not messing things up . prev_app_size = self . app_size ( ) prev_use_size = self . use_size ( ) small_nodes = self . _find_small_nodes ( small_size , ( ) , a_or_u ) for node , parents in small_nodes : # Check immediate grandparent for isdir = None and if it # exists , move this there . The isdir =...
def add_cron ( self , name , command , minute = "*" , hour = "*" , mday = "*" , month = "*" , wday = "*" , who = "root" , env = None ) : """Write a file to / etc / cron . d to schedule a command env is a dict containing environment variables you want to set in the file name will be used as the name of the file"...
if minute == 'random' : minute = str ( random . randrange ( 60 ) ) if hour == 'random' : hour = str ( random . randrange ( 24 ) ) fp = open ( '/etc/cron.d/%s' % name , "w" ) if env : for key , value in env . items ( ) : fp . write ( '%s=%s\n' % ( key , value ) ) fp . write ( '%s %s %s %s %s %s %s\n'...
def as_set ( obj ) : """Convert obj into a set , returns None if obj is None . > > > assert as _ set ( None ) is None and as _ set ( 1 ) = = set ( [ 1 ] ) and as _ set ( range ( 1,3 ) ) = = set ( [ 1 , 2 ] )"""
if obj is None or isinstance ( obj , collections . Set ) : return obj if not isinstance ( obj , collections . Iterable ) : return set ( ( obj , ) ) else : return set ( obj )
def fire ( self , * args , ** kwargs ) : """Fire event and call all handler functions You can call EventHandler object itself like e ( * args , * * kwargs ) instead of e . fire ( * args , * * kwargs ) ."""
for func in self . _getfunctionlist ( ) : if type ( func ) == EventHandler : func . fire ( * args , ** kwargs ) else : func ( self . obj , * args , ** kwargs )
def find_by_organization ( self , organization , params = { } , ** options ) : """Returns the compact records for all teams in the organization visible to the authorized user . Parameters organization : { Id } Globally unique identifier for the workspace or organization . [ params ] : { Object } Parameters ...
path = "/organizations/%s/teams" % ( organization ) return self . client . get_collection ( path , params , ** options )
def get_by_username ( cls , username ) : """Return a User by email address"""
return cls . query ( ) . filter ( cls . username == username ) . first ( )
def _split_sequences_multitraj ( dtrajs , lag ) : """splits the discrete trajectories into conditional sequences by starting state Parameters dtrajs : list of int - iterables discrete trajectories nstates : int total number of discrete states lag : int lag time"""
n = number_of_states ( dtrajs ) res = [ ] for i in range ( n ) : res . append ( [ ] ) for dtraj in dtrajs : states , seqs = _split_sequences_singletraj ( dtraj , n , lag ) for i in range ( len ( states ) ) : res [ states [ i ] ] . append ( seqs [ i ] ) return res
def load_config ( self , config ) : """Load the outputs section of the configuration file ."""
# Limit the number of processes to display in the WebUI if config is not None and config . has_section ( 'outputs' ) : logger . debug ( 'Read number of processes to display in the WebUI' ) n = config . get_value ( 'outputs' , 'max_processes_display' , default = None ) logger . debug ( 'Number of processes t...
def trimLeft ( self , amount ) : """Trim this fastqSequence in - place by removing < amount > nucleotides from the 5 ' end ( left end ) . : param amount : the number of nucleotides to trim from the left - side of this sequence ."""
if amount == 0 : return self . sequenceData = self . sequenceData [ amount : ] self . sequenceQual = self . sequenceQual [ amount : ]
def function_call ( self , function , arguments ) : """Generates code for a function call function - function index in symbol table arguments - list of arguments ( indexes in symbol table )"""
# push each argument to stack for arg in arguments : self . push ( self . symbol ( arg ) ) self . free_if_register ( arg ) self . newline_text ( "CALL\t" + self . symtab . get_name ( function ) , True ) args = self . symtab . get_attribute ( function ) # generates stack cleanup if function has arguments if args...
def divide ( n , iterable ) : """split an iterable into n groups , per https : / / more - itertools . readthedocs . io / en / latest / api . html # grouping : param int n : Number of unique groups : param iter iterable : An iterable to split up : return : a list of new iterables derived from the original iter...
seq = tuple ( iterable ) q , r = divmod ( len ( seq ) , n ) ret = [ ] for i in range ( n ) : start = ( i * q ) + ( i if i < r else r ) stop = ( ( i + 1 ) * q ) + ( i + 1 if i + 1 < r else r ) ret . append ( iter ( seq [ start : stop ] ) ) return ret
def from_content ( cls , content ) : """Parses a Tibia . com response into a House object . Parameters content : : class : ` str ` HTML content of the page . Returns : class : ` House ` The house contained in the page , or None if the house doesn ' t exist . Raises InvalidContent If the content is...
parsed_content = parse_tibiacom_content ( content ) image_column , desc_column , * _ = parsed_content . find_all ( 'td' ) if "Error" in image_column . text : return None image = image_column . find ( 'img' ) for br in desc_column . find_all ( "br" ) : br . replace_with ( "\n" ) description = desc_column . text ...
def reset ( self ) : '''Reset the state of the container and its internal fields'''
super ( Container , self ) . reset ( ) for field in self . _fields : field . reset ( ) self . _field_idx = 0
def __create_remote_webdriver_from_config ( self , testname = None ) : '''Reads the config value for browser type .'''
desired_capabilities = self . _generate_desired_capabilities ( testname ) remote_url = self . _config_reader . get ( WebDriverFactory . REMOTE_URL_CONFIG ) # Instantiate remote webdriver . driver = webdriver . Remote ( desired_capabilities = desired_capabilities , command_executor = remote_url ) # Log IP Address of nod...
def dbnsfp ( self ) : """dbnsfp"""
tstart = datetime . now ( ) # python . . / scripts / annotate _ vcfs . py - i mm13173_14 . ug . target1 . vcf - r 1000genomes dbsnp138 clinvar esp6500 - a . . / data / 1000genomes / ALL . wgs . integrated _ phase1 _ v3.20101123 . snps _ indels _ sv . sites . vcf . gz . . / data / dbsnp138/00 - All . vcf . gz . . / data...
def diff_json_files ( left_files , right_files ) : '''Compute the difference between two sets of basis set JSON files The output is a set of files that correspond to each file in ` left _ files ` . Each resulting dictionary will contain only the elements / shells that exist in that entry and not in any of the...
left_data = [ fileio . read_json_basis ( x ) for x in left_files ] right_data = [ fileio . read_json_basis ( x ) for x in right_files ] d = diff_basis_dict ( left_data , right_data ) for idx , diff_bs in enumerate ( d ) : fpath = left_files [ idx ] fileio . write_json_basis ( fpath + '.diff' , diff_bs )
def confd_state_rest_listen_tcp_port ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" ) rest = ET . SubElement ( confd_state , "rest" ) listen = ET . SubElement ( rest , "listen" ) tcp = ET . SubElement ( listen , "tcp" ) port = ET . SubElement ( tcp , "port" ) po...
def on_before_transform_template ( self , template_dict ) : """Hook method that gets called before the SAM template is processed . The template has pass the validation and is guaranteed to contain a non - empty " Resources " section . : param dict template _ dict : Dictionary of the SAM template : return : No...
template = SamTemplate ( template_dict ) # Temporarily add Serverless : : Api resource corresponding to Implicit API to the template . # This will allow the processing code to work the same way for both Implicit & Explicit APIs # If there are no implicit APIs , we will remove from the template later . # If the customer...
def _clean_dic ( self , dic ) : """Clean recursively all empty or None values inside a dict ."""
aux_dic = dic . copy ( ) for key , value in iter ( dic . items ( ) ) : if value is None or value == '' : del aux_dic [ key ] elif type ( value ) is dict : cleaned_dict = self . _clean_dic ( value ) if not cleaned_dict : del aux_dic [ key ] continue aux_dic...
def linear_insert ( self , item , priority ) : """Linear search . Performance is O ( n ^ 2 ) ."""
with self . lock : self_data = self . data rotate = self_data . rotate maxlen = self . _maxlen length = len ( self_data ) count = length # in practice , this is better than doing a rotate ( - 1 ) every # loop and getting self . data [ 0 ] each time only because deque # implements a very ...
def _evaluate_sql_query_subprocess ( self , predicted_query : str , sql_query_labels : List [ str ] ) -> int : """We evaluate here whether the predicted query and the query label evaluate to the exact same table . This method is only called by the subprocess , so we just exit with 1 if it is correct and 0 other...
postprocessed_predicted_query = self . postprocess_query_sqlite ( predicted_query ) try : self . _cursor . execute ( postprocessed_predicted_query ) predicted_rows = self . _cursor . fetchall ( ) except sqlite3 . Error as error : logger . warning ( f'Error executing predicted: {error}' ) exit ( 0 ) # If...
def running_window ( iterable , size ) : """Generate n - size running window . Example : : > > > for i in running _ windows ( [ 1 , 2 , 3 , 4 , 5 ] , size = 3 ) : . . . print ( i ) [1 , 2 , 3] [2 , 3 , 4] [3 , 4 , 5] * * 中文文档 * * 简单滑窗函数 。"""
if size > len ( iterable ) : raise ValueError ( "size can not be greater than length of iterable." ) fifo = collections . deque ( maxlen = size ) for i in iterable : fifo . append ( i ) if len ( fifo ) == size : yield list ( fifo )
def add_domain_to_toctree ( app , doctree , docname ) : """Add domain objects to the toctree dynamically . This should be attached to the ` ` doctree - resolved ` ` event . This works by : * Finding each domain node ( addnodes . desc ) * Figuring out it ' s parent that will be in the toctree ( nodes . sec...
toc = app . env . tocs [ docname ] for desc_node in doctree . traverse ( addnodes . desc ) : try : ref_id = desc_node . children [ 0 ] . attributes [ "ids" ] [ 0 ] except ( KeyError , IndexError ) as e : LOGGER . warning ( "Invalid desc node: %s" % e ) continue try : # Python domain ...
def is_blocked ( self , ip ) : """Determine if an IP address should be considered blocked ."""
blocked = True if ip in self . allowed_admin_ips : blocked = False for allowed_range in self . allowed_admin_ip_ranges : if ipaddress . ip_address ( ip ) in ipaddress . ip_network ( allowed_range ) : blocked = False return blocked
def wait ( self , log_file ) : "Wait until the process is ready ."
lines = map ( self . log_line , self . filter_lines ( self . get_lines ( log_file ) ) ) return any ( std . re . search ( self . pattern , line ) for line in lines )
def set_config_for_routing_entity ( self , routing_entity : Union [ web . Resource , web . StaticResource , web . ResourceRoute ] , config ) : """Record configuration for resource or it ' s route ."""
if isinstance ( routing_entity , ( web . Resource , web . StaticResource ) ) : resource = routing_entity # Add resource configuration or fail if it ' s already added . if resource in self . _resource_config : raise ValueError ( "CORS is already configured for {!r} resource." . format ( resource ) ) ...
def space_labels ( document ) : """Ensure space around bold compound labels ."""
for label in document . xpath ( './/bold' ) : # TODO : Make this more permissive to match chemical _ label in parser if not label . text or not re . match ( '^\(L?\d\d?[a-z]?\):?$' , label . text , re . I ) : continue parent = label . getparent ( ) previous = label . getprevious ( ) if previous ...
def add_case ( self , case_obj ) : """Add a case obj with individuals to adapter Args : case _ obj ( puzzle . models . Case )"""
for ind_obj in case_obj . individuals : self . _add_individual ( ind_obj ) logger . debug ( "Adding case {0} to plugin" . format ( case_obj . case_id ) ) self . case_objs . append ( case_obj ) if case_obj . tabix_index : logger . debug ( "Setting filters.can_filter_range to True" ) self . filters . can_filt...
def save_object ( collection , obj ) : """Save an object ` ` obj ` ` to the given ` ` collection ` ` . ` ` obj . id ` ` must be unique across all other existing objects in the given collection . If ` ` id ` ` is not present in the object , a * UUID * is assigned as the object ' s ` ` id ` ` . Indexes alread...
if 'id' not in obj : obj . id = uuid ( ) id = obj . id path = object_path ( collection , id ) temp_path = '%s.temp' % path with open ( temp_path , 'w' ) as f : data = _serialize ( obj ) f . write ( data ) shutil . move ( temp_path , path ) if id in _db [ collection ] . cache : _db [ collection ] . cache...
def update_http_rules ( rules , content_type = 'text/plain' ) : """Adds rules to global http mock . It permits to set mock in a more global way than decorators , cf . : https : / / github . com / openstack / requests - mock Here we assume urls in the passed dict are regex we recompile before adding a rule ....
for kw in deepcopy ( rules ) : kw [ 'url' ] = re . compile ( kw [ 'url' ] ) # ensure headers dict for at least have a default content type if 'Content-Type' not in kw . get ( 'headers' , { } ) : kw [ 'headers' ] = dict ( kw . get ( 'headers' , { } ) , ** { 'Content-Type' : content_type , } ) met...
def dallinger_package_path ( ) : """Return the absolute path of the root directory of the installed Dallinger package : > > > utils . dallinger _ package _ location ( ) ' / Users / janedoe / projects / Dallinger3 / dallinger '"""
dist = get_distribution ( "dallinger" ) src_base = os . path . join ( dist . location , dist . project_name ) return src_base
def getmeths ( method_type ) : """returns MagIC method codes available for a given type"""
meths = [ ] if method_type == 'GM' : meths . append ( 'GM-PMAG-APWP' ) meths . append ( 'GM-ARAR' ) meths . append ( 'GM-ARAR-AP' ) meths . append ( 'GM-ARAR-II' ) meths . append ( 'GM-ARAR-NI' ) meths . append ( 'GM-ARAR-TF' ) meths . append ( 'GM-CC-ARCH' ) meths . append ( 'GM-CC-ARCH...
def _setup_appium ( self ) : """Setup Appium webdriver : returns : a new remote Appium driver"""
self . config . set ( 'Server' , 'host' , '127.0.0.1' ) self . config . set ( 'Server' , 'port' , '4723' ) return self . _create_remote_driver ( )
def rdann ( record_name , extension , sampfrom = 0 , sampto = None , shift_samps = False , pb_dir = None , return_label_elements = [ 'symbol' ] , summarize_labels = False ) : """Read a WFDB annotation file record _ name . extension and return an Annotation object . Parameters record _ name : str The record ...
return_label_elements = check_read_inputs ( sampfrom , sampto , return_label_elements ) # Read the file in byte pairs filebytes = load_byte_pairs ( record_name , extension , pb_dir ) # Get wfdb annotation fields from the file bytes ( sample , label_store , subtype , chan , num , aux_note ) = proc_ann_bytes ( filebytes ...
def create ( self , image = None ) : """Create content and return url . In case of images add the image ."""
container = self . context new = api . content . create ( container = container , type = self . portal_type , title = self . title , safe_id = True , ) if image : namedblobimage = NamedBlobImage ( data = image . read ( ) , filename = safe_unicode ( image . filename ) ) new . image = namedblobimage if new : ...
def server_identity_is_verified ( self ) : """GPGAuth stage0"""
# Encrypt a uuid token for the server server_verify_token = self . gpg . encrypt ( self . _nonce0 , self . server_fingerprint , always_trust = True ) if not server_verify_token . ok : raise GPGAuthStage0Exception ( 'Encryption of the nonce0 (%s) ' 'to the server fingerprint (%s) failed.' % ( self . _nonce0 , self ....
def run ( self , workflow_input , * args , ** kwargs ) : ''': param workflow _ input : Dictionary of the workflow ' s input arguments ; see below for more details : type workflow _ input : dict : param instance _ type : Instance type on which all stages ' jobs will be run , or a dict mapping function names to i...
return super ( DXWorkflow , self ) . run ( workflow_input , * args , ** kwargs )
def comment ( self , s , ** args ) : """Write DOT comment ."""
self . write ( u"// " ) self . writeln ( s = s , ** args )
def blacklistNode ( self , nodeName : str , reason : str = None , code : int = None ) : """Add the node specified by ` nodeName ` to this node ' s blacklist"""
msg = "{} blacklisting node {}" . format ( self , nodeName ) if reason : msg += " for reason {}" . format ( reason ) if code : msg += " for code {}" . format ( code ) logger . display ( msg ) self . nodeBlacklister . blacklist ( nodeName )
def write_file ( content , * path ) : """Simply write some content to a file , overriding the file if necessary ."""
with open ( os . path . join ( * path ) , "w" ) as file : return file . write ( content )
def recurse_tree ( path , excludes , opts ) : """Look for every file in the directory tree and create the corresponding ReST files ."""
# use absolute path for root , as relative paths like ' . . / . . / foo ' cause # ' if " / . " in root . . . ' to filter out * all * modules otherwise path = os . path . abspath ( path ) # check if the base directory is a package and get is name if INIT in os . listdir ( path ) : package_name = path . split ( os . ...
def rename ( self , dn : str , new_rdn : str , new_base_dn : Optional [ str ] = None ) -> None : """rename a dn in the ldap database ; see ldap module . doesn ' t return a result if transactions enabled ."""
_debug ( "rename" , self , dn , new_rdn , new_base_dn ) # split up the parameters split_dn = tldap . dn . str2dn ( dn ) split_newrdn = tldap . dn . str2dn ( new_rdn ) assert ( len ( split_newrdn ) == 1 ) # make dn unqualified rdn = tldap . dn . dn2str ( split_dn [ 0 : 1 ] ) # make newrdn fully qualified dn tmplist = [ ...
def _pick_unused_port_without_server ( ) : # Protected . pylint : disable = invalid - name """Pick an available network port without the help of a port server . This code ensures that the port is available on both TCP and UDP . This function is an implementation detail of PickUnusedPort ( ) , and should not b...
# Try random ports first . rng = random . Random ( ) for _ in range ( 10 ) : port = int ( rng . randrange ( 15000 , 25000 ) ) if is_port_free ( port ) : _random_ports . add ( port ) return port # Next , try a few times to get an OS - assigned port . # Ambrose discovered that on the 2.6 kernel , ...
def findPolymorphisms ( self , strSeq , strict = False ) : """Compares strSeq with self . sequence . If not ' strict ' , this function ignores the cases of matching heterozygocity ( ex : for a given position i , strSeq [ i ] = A and self . sequence [ i ] = ' A / G ' ) . If ' strict ' it returns all positions wher...
arr = self . encode ( strSeq ) [ 0 ] res = [ ] if not strict : for i in range ( len ( arr ) + len ( self ) ) : if i >= len ( arr ) or i > len ( self ) : break if arr [ i ] & self [ i ] == 0 : res . append ( i ) else : for i in range ( len ( arr ) + len ( self ) ) : ...
def get_editor_nodes ( self , editor , node = None ) : """Returns the : class : ` umbra . components . factory . script _ editor . nodes . EditorNode ` class Nodes with given editor . : param node : Node to start walking from . : type node : AbstractNode or AbstractCompositeNode or Object : param editor : Edi...
return [ editor_node for editor_node in self . list_editor_nodes ( node ) if editor_node . editor == editor ]