signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_route_to ( self , destination = '' , protocol = '' ) : """Return route details to a specific destination , learned from a certain protocol ."""
# Note , it should be possible to query the FIB : # " < show > < routing > < fib > < / fib > < / routing > < / show > " # To add informations to this getter routes = { } if destination : destination = "<destination>{0}</destination>" . format ( destination ) if protocol : protocol = "<type>{0}</type>" . format ...
def ParseFileObject ( self , parser_mediator , file_object ) : """Parses an ESE database file - like object . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . file _ object ( dfvfs . FileIO ) : file - like object ."""
esedb_file = pyesedb . file ( ) try : esedb_file . open_file_object ( file_object ) except IOError as exception : parser_mediator . ProduceExtractionWarning ( 'unable to open file with error: {0!s}' . format ( exception ) ) return # Compare the list of available plugin objects . cache = ESEDBCache ( ) try :...
def fast_kde ( x , y , gridsize = ( 200 , 200 ) , extents = None , nocorrelation = False , weights = None ) : """Performs a gaussian kernel density estimate over a regular grid using a convolution of the gaussian kernel with a 2D histogram of the data . This function is typically several orders of magnitude fas...
# - - - - Setup - - - - - x , y = np . asarray ( x ) , np . asarray ( y ) x , y = np . squeeze ( x ) , np . squeeze ( y ) if x . size != y . size : raise ValueError ( 'Input x & y arrays must be the same size!' ) nx , ny = gridsize n = x . size if weights is None : # Default : Weight all points equally weights ...
def cleanup ( self ) : '''a method for removing instances and images in unusual states : return : True'''
# find non - running instances self . iam . printer ( 'Cleaning up AWS region %s.' % self . iam . region_name ) response = self . connection . describe_instances ( ) instance_list = response [ 'Reservations' ] for instance in instance_list : instance_info = instance [ 'Instances' ] [ 0 ] if instance_info [ 'Sta...
def _handle_github ( self ) : """Handle exception and submit it as GitHub issue ."""
value = click . prompt ( _BUG + click . style ( '1. Open an issue by typing "open";\n' , fg = 'green' , ) + click . style ( '2. Print human-readable information by typing ' '"print";\n' , fg = 'yellow' , ) + click . style ( '3. See the full traceback without submitting details ' '(default: "ignore").\n\n' , fg = 'red' ...
def patch_python_logging_handlers ( ) : '''Patch the python logging handlers with out mixed - in classes'''
logging . StreamHandler = StreamHandler logging . FileHandler = FileHandler logging . handlers . SysLogHandler = SysLogHandler logging . handlers . WatchedFileHandler = WatchedFileHandler logging . handlers . RotatingFileHandler = RotatingFileHandler if sys . version_info >= ( 3 , 2 ) : logging . handlers . QueueHa...
def _compute_term_3 ( self , C , rhypo ) : """Compute term 3 in equation 2 page 462. Distances are clipped at 15 km ( as per Ezio Faccioli ' s personal communication . )"""
d = rhypo d [ d <= 15.0 ] = 15.0 return C [ 'a3' ] * np . log10 ( d )
def _map_player_request_to_func ( self , player_request_type ) : """Provides appropriate parameters to the on _ playback functions ."""
# calbacks for on _ playback requests are optional view_func = self . _intent_view_funcs . get ( player_request_type , lambda : None ) argspec = inspect . getargspec ( view_func ) arg_names = argspec . args arg_values = self . _map_params_to_view_args ( player_request_type , arg_names ) return partial ( view_func , * a...
def get_sites ( self , domain = None , show = True , proxy = None , timeout = 0 ) : """GET Wikimedia sites via Extension : SiteMatrix https : / / www . mediawiki . org / wiki / Extension : SiteMatrix Optional params : - [ domain ] : filter sites on this domain , e . g . ' wiktionary . org ' Optional argumen...
if domain : self . params . update ( { 'domain' : domain } ) self . params . update ( { 'wiki' : self . COMMONS } ) self . _get ( 'sitematrix' , show , proxy , timeout ) del self . params [ 'wiki' ] return self
def predict_moments ( self , X , nsamples = 200 , likelihood_args = ( ) ) : r"""Predictive moments , in particular mean and variance , of a Bayesian GLM . This function uses Monte - Carlo sampling to evaluate the predictive mean and variance of a Bayesian GLM . The exact expressions evaluated are , . . math :...
# Get latent function samples N = X . shape [ 0 ] ys = np . empty ( ( N , nsamples ) ) fsamples = self . _sample_func ( X , nsamples ) # Push samples though likelihood expected value Eyargs = tuple ( chain ( atleast_list ( self . like_hypers_ ) , likelihood_args ) ) for i , f in enumerate ( fsamples ) : ys [ : , i ...
def payload ( self ) : """Picks out the payload from the different parts of the signed / encrypted JSON Web Token . If the content type is said to be ' jwt ' deserialize the payload into a Python object otherwise return as - is . : return : The payload"""
_msg = as_unicode ( self . part [ 1 ] ) # If not JSON web token assume JSON if "cty" in self . headers and self . headers [ "cty" ] . lower ( ) != "jwt" : pass else : try : _msg = json . loads ( _msg ) except ValueError : pass return _msg
def serialize ( cls , ** properties ) : """With a Protobuf class and properties as keyword arguments , sets all the properties on a new instance of the class and serializes the resulting value ."""
obj = cls ( ) for k , v in properties . iteritems ( ) : log . debug ( "%s.%s = %r" , cls . __name__ , k , v ) setattr ( obj , k , v ) return obj . SerializeToString ( )
def chunk ( self , chunks = None , name = None , lock = False ) : """Coerce this array ' s data into a dask arrays with the given chunks . If this variable is a non - dask array , it will be converted to dask array . If it ' s a dask array , it will be rechunked to the given chunk sizes . If neither chunks ...
import dask . array as da if utils . is_dict_like ( chunks ) : chunks = dict ( ( self . get_axis_num ( dim ) , chunk ) for dim , chunk in chunks . items ( ) ) if chunks is None : chunks = self . chunks or self . shape data = self . _data if isinstance ( data , da . Array ) : data = data . rechunk ( chunks )...
def call_later ( self , time_seconds , callback , arguments ) : """Schedules a function to be run x number of seconds from now . The call _ later method is primarily used to resend messages if we haven ' t received a confirmation message from the receiving host . We can wait x number of seconds for a response...
scheduled_call = { 'ts' : time . time ( ) + time_seconds , 'callback' : callback , 'args' : arguments } self . scheduled_calls . append ( scheduled_call )
def autoescape ( filter_func ) : """Decorator to autoescape result from filters ."""
@ evalcontextfilter @ wraps ( filter_func ) def _autoescape ( eval_ctx , * args , ** kwargs ) : result = filter_func ( * args , ** kwargs ) if eval_ctx . autoescape : result = Markup ( result ) return result return _autoescape
def _prepare_defaults ( self ) : """Trigger assignment of default values ."""
for name , field in self . __fields__ . items ( ) : if field . assign : getattr ( self , name )
def start ( self ) : '''Start the worker process .'''
# metrics napalm_logs_device_messages_received = Counter ( 'napalm_logs_device_messages_received' , "Count of messages received by the device process" , [ 'device_os' ] ) napalm_logs_device_raw_published_messages = Counter ( 'napalm_logs_device_raw_published_messages' , "Count of raw type published messages" , [ 'devic...
def input_yn ( conf_mess ) : """Print Confirmation Message and Get Y / N response from user ."""
ui_erase_ln ( ) ui_print ( conf_mess ) with term . cbreak ( ) : input_flush ( ) val = input_by_key ( ) return bool ( val . lower ( ) == 'y' )
def write ( self , client ) : """Write current data to db in plc"""
assert ( isinstance ( self . _bytearray , DB ) ) assert ( self . row_size >= 0 ) db_nr = self . _bytearray . db_number offset = self . db_offset data = self . get_bytearray ( ) [ offset : offset + self . row_size ] db_offset = self . db_offset # indicate start of write only area of row ! if self . row_offset : data...
def next ( self ) : """Next point in iteration"""
if self . count < len ( self . reservoir ) : self . count += 1 return self . reservoir [ self . count - 1 ] raise StopIteration ( "Reservoir exhausted" )
def mkcols ( l , rows ) : '''Compute the size of our columns by first making them a divisible of our row height and then splitting our list into smaller lists the size of the row height .'''
cols = [ ] base = 0 while len ( l ) > rows and len ( l ) % rows != 0 : l . append ( "" ) for i in range ( rows , len ( l ) + rows , rows ) : cols . append ( l [ base : i ] ) base = i return cols
def _Kvalue ( T , gas , liquid = "H2O" ) : """Equation for the vapor - liquid distribution constant Parameters T : float Temperature , [ K ] gas : string Name of gas to calculate solubility liquid : string Name of liquid solvent , can be H20 ( default ) or D2O Returns kd : float Vapor - liquid d...
if liquid == "D2O" : gas += "(D2O)" limit = { "He" : ( 273.21 , 553.18 ) , "Ne" : ( 273.20 , 543.36 ) , "Ar" : ( 273.19 , 568.36 ) , "Kr" : ( 273.19 , 525.56 ) , "Xe" : ( 273.22 , 574.85 ) , "H2" : ( 273.15 , 636.09 ) , "N2" : ( 278.12 , 636.46 ) , "O2" : ( 274.15 , 616.52 ) , "CO" : ( 278.15 , 588.67 ) , "CO2" : (...
def _output_to_list ( cmdoutput ) : '''Convert rabbitmqctl output to a list of strings ( assuming whitespace - delimited output ) . Ignores output lines that shouldn ' t be parsed , like warnings . cmdoutput : string output of rabbitmqctl commands'''
return [ item for line in cmdoutput . splitlines ( ) if _safe_output ( line ) for item in line . split ( ) ]
def write ( self , h , txt = '' , link = '' ) : "Output text in flowing mode"
txt = self . normalize_text ( txt ) cw = self . current_font [ 'cw' ] w = self . w - self . r_margin - self . x wmax = ( w - 2 * self . c_margin ) * 1000.0 / self . font_size s = txt . replace ( "\r" , '' ) nb = len ( s ) sep = - 1 i = 0 j = 0 l = 0 nl = 1 while ( i < nb ) : # Get next character c = s [ i ] if ...
def setup_ui ( uifile , base_instance = None ) : """Load a Qt Designer . ui file and returns an instance of the user interface Args : uifile ( str ) : Absolute path to . ui file base _ instance ( QWidget ) : The widget into which UI widgets are loaded Returns : QWidget : the base instance"""
ui = QtCompat . loadUi ( uifile ) # Qt . py mapped function if not base_instance : return ui else : for member in dir ( ui ) : if not member . startswith ( '__' ) and member is not 'staticMetaObject' : setattr ( base_instance , member , getattr ( ui , member ) ) return ui
def psychrometrics ( Tdb_in , w_in , P ) : """Modified version of Psychometrics by Tea Zakula MIT Building Technology Lab Input : Tdb _ in , w _ in , P Output : Tdb , w , phi , h , Tdp , v where : Tdb _ in = [ K ] dry bulb temperature w _ in = [ kgv / kgda ] Humidity Ratio P = [ P ] Atmospheric Statio...
# Change units c_air = 1006. # [ J / kg ] air heat capacity , value from ASHRAE Fundamentals hlg = 2501000. # [ J / kg ] latent heat , value from ASHRAE Fundamentals cw = 1860. # [ J / kg ] value from ASHRAE Fundamentals P = P / 1000. # convert from Pa to kPa Tdb = Tdb_in - 273.15 w = w_in # phi ( RH ) calculation from...
def _do_POSTGET ( self , handler ) : """handle an HTTP request"""
# at first , assume that the given path is the actual path and there are # no arguments self . server . _dbg ( self . path ) self . path , self . args = _parse_url ( self . path ) # Extract POST data , if any . Clumsy syntax due to Python 2 and # 2to3 ' s lack of a byte literal . self . data = u"" . encode ( ) length =...
def cell_to_text ( self ) : """Return the text representation for the cell"""
if self . cell_type == 'code' : source = copy ( self . source ) return comment_magic ( source , self . language , self . comment_magics ) if 'cell_marker' in self . metadata : cell_marker = self . metadata . pop ( 'cell_marker' ) else : cell_marker = self . default_cell_marker if self . source == [ '' ]...
def get_all_widget_classes ( ) : """returns collected Leonardo Widgets if not declared in settings is used _ _ subclasses _ _ which not supports widget subclassing"""
from leonardo . module . web . models import Widget _widgets = getattr ( settings , 'WIDGETS' , Widget . __subclasses__ ( ) ) widgets = [ ] if isinstance ( _widgets , dict ) : for group , widget_cls in six . iteritems ( _widgets ) : widgets . extend ( widget_cls ) elif isinstance ( _widgets , list ) : w...
def complex_el_from_dict ( parent , data , key ) : """Create element from a dict definition and add it to ` ` parent ` ` . : param parent : parent element : type parent : Element : param data : dictionary with elements definitions , it can be a simple { element _ name : ' element _ value ' } or complex { elem...
el = ET . SubElement ( parent , key ) value = data [ key ] if isinstance ( value , dict ) : if '_attr' in value : for a_name , a_value in viewitems ( value [ '_attr' ] ) : el . set ( a_name , a_value ) if '_text' in value : el . text = value [ '_text' ] else : el . text = value r...
def GetMetaData ( self , request ) : """Get metadata from local metadata server . Any failed URL check will fail the whole action since our bios / service checks may not always correctly identify cloud machines . We don ' t want to wait on multiple DNS timeouts . Args : request : CloudMetadataRequest obje...
if request . timeout == 0 : raise ValueError ( "Requests library can't handle timeout of 0" ) result = requests . request ( "GET" , request . url , headers = request . headers , timeout = request . timeout ) # By default requests doesn ' t raise on HTTP error codes . result . raise_for_status ( ) # Requests does no...
def get_relay_state ( self ) : """Get the relay state ."""
self . get_status ( ) try : self . state = self . data [ 'relay' ] except TypeError : self . state = False return bool ( self . state )
def _unpack_case ( self , case ) : """Returns the contents of the case to be used in the OPF ."""
base_mva = case . base_mva b = case . connected_buses l = case . online_branches g = case . online_generators nb = len ( b ) nl = len ( l ) ng = len ( g ) return b , l , g , nb , nl , ng , base_mva
def _create_font_face_buttons ( self ) : """Creates font face buttons"""
font_face_buttons = [ ( wx . FONTFLAG_BOLD , "OnBold" , "FormatTextBold" , _ ( "Bold" ) ) , ( wx . FONTFLAG_ITALIC , "OnItalics" , "FormatTextItalic" , _ ( "Italics" ) ) , ( wx . FONTFLAG_UNDERLINED , "OnUnderline" , "FormatTextUnderline" , _ ( "Underline" ) ) , ( wx . FONTFLAG_STRIKETHROUGH , "OnStrikethrough" , "Form...
def get_catalogs ( self ) : """Gets the catalog list resulting from the search . return : ( osid . cataloging . CatalogList ) - the catalogs list raise : IllegalState - list has already been retrieved * compliance : mandatory - - This method must be implemented . *"""
if self . retrieved : raise errors . IllegalState ( 'List has already been retrieved.' ) self . retrieved = True return objects . CatalogList ( self . _results , runtime = self . _runtime )
def _set_client ( self , v , load = False ) : """Setter method for client , mapped from YANG variable / cluster / client ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ client is considered as a private method . Backends looking to populate this variable shou...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "client_name client_id" , client . client , yang_name = "client" , rest_name = "client" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'client-n...
def _SetupDatabase ( host = None , port = None , user = None , password = None , database = None , client_key_path = None , client_cert_path = None , ca_cert_path = None ) : """Connect to the given MySQL host and create a utf8mb4 _ unicode _ ci database . Args : host : The hostname to connect to . port : The ...
with contextlib . closing ( _Connect ( host = host , port = port , user = user , password = password , # No database should be specified in a connection that intends # to create a database . database = None , client_key_path = client_key_path , client_cert_path = client_cert_path , ca_cert_path = ca_cert_path ) ) as co...
def dot1x_enable ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) dot1x = ET . SubElement ( config , "dot1x" , xmlns = "urn:brocade.com:mgmt:brocade-dot1x" ) enable = ET . SubElement ( dot1x , "enable" ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config )
def sanitize_win_path ( winpath ) : '''Remove illegal path characters for windows'''
intab = '<>:|?*' if isinstance ( winpath , six . text_type ) : winpath = winpath . translate ( dict ( ( ord ( c ) , '_' ) for c in intab ) ) elif isinstance ( winpath , six . string_types ) : outtab = '_' * len ( intab ) trantab = '' . maketrans ( intab , outtab ) if six . PY3 else string . maketrans ( inta...
def upload_file ( self , file_name , file_path ) : """Upload a file to a server Attempts to upload a local file with path filepath , to the server , where it will be named filename . Args : : param file _ name : The name that the uploaded file will be called on the server . : param file _ path : The path ...
request = urllib . request . Request ( self . url + '/rest/v1/data/upload/job_input?name=' + file_name ) if self . authorization_header ( ) is not None : request . add_header ( 'Authorization' , self . authorization_header ( ) ) request . add_header ( 'User-Agent' , 'GenePatternRest' ) with open ( file_path , 'rb' ...
def insert_synapses ( self , cell , cellindex , synParams , idx = np . array ( [ ] ) , X = 'EX' , SpCell = np . array ( [ ] ) , synDelays = None ) : """Insert synapse with ` parameters ` = ` synparams ` on cell = cell , with segment indexes given by ` idx ` . ` SpCell ` and ` SpTimes ` picked from Brunel networ...
# Insert synapses in an iterative fashion try : spikes = self . networkSim . dbs [ X ] . select ( SpCell [ : idx . size ] ) except AttributeError as ae : raise ae , 'could not open CachedNetwork database objects' # apply synaptic delays if synDelays is not None and idx . size > 0 : for i , delay in enumerat...
def cycle_generator ( cycle , step = 1 , begin = ( 0 , 0 ) , end = None ) : '''Generates pairs of values representing a cycle . E . g . clock hours for a day could could be generated with : _ cycle _ generator ( cycle = ( 1 , 12 ) , step = 1 , begin = ( 0 , 1 ) , end = ( 23 , 12 ) ) = > ( 0 , 1 ) , ( 0 , 2 ) ...
( cycle_begin , cycle_end ) = cycle ( major , minor ) = begin ( end_major , end_minor ) = end if end is not None else ( None , None ) while True : if end is not None and ( major > end_major or ( major == end_major and minor > end_minor ) ) : return yield ( major , minor ) minor += step if minor ...
def tf_lanczos_smallest_eigval ( vector_prod_fn , matrix_dim , initial_vector , num_iter = 1000 , max_iter = 1000 , collapse_tol = 1e-9 , dtype = tf . float32 ) : """Computes smallest eigenvector and eigenvalue using Lanczos in pure TF . This function computes smallest eigenvector and eigenvalue of the matrix w...
# alpha will store diagonal elements alpha = tf . TensorArray ( dtype , size = 1 , dynamic_size = True , element_shape = ( ) ) # beta will store off diagonal elements beta = tf . TensorArray ( dtype , size = 0 , dynamic_size = True , element_shape = ( ) ) # q will store Krylov space basis q_vectors = tf . TensorArray (...
def tail ( records , tail ) : """Limit results to the bottom N records . Use + N to output records starting with the Nth ."""
logging . info ( 'Applying _tail generator: ' 'limiting results to top ' + tail + ' records.' ) if tail == '+0' : for record in records : yield record elif '+' in tail : tail = int ( tail ) - 1 for record in itertools . islice ( records , tail , None ) : yield record else : with _record_...
def loadDolfin ( filename , c = "gold" , alpha = 0.5 , wire = None , bc = None ) : """Reads a ` Fenics / Dolfin ` file format . Return an ` ` Actor ( vtkActor ) ` ` object ."""
if not os . path . exists ( filename ) : colors . printc ( "~noentry Error in loadDolfin: Cannot find" , filename , c = 1 ) return None import xml . etree . ElementTree as et if filename . endswith ( ".gz" ) : import gzip inF = gzip . open ( filename , "rb" ) outF = open ( "/tmp/filename.xml" , "wb"...
def rfc7033_webfinger_view ( request , * args , ** kwargs ) : """Django view to generate an RFC7033 webfinger ."""
resource = request . GET . get ( "resource" ) if not resource : return HttpResponseBadRequest ( "No resource found" ) if not resource . startswith ( "acct:" ) : return HttpResponseBadRequest ( "Invalid resource" ) handle = resource . replace ( "acct:" , "" ) . lower ( ) profile_func = get_function_from_config (...
def isostr_to_datetime ( dt_str ) : """Converts iso formated text string into a datetime object Args : dt _ str ( str ) : ISO formated text string Returns : : obj : ` datetime . datetime `"""
if len ( dt_str ) <= 20 : return datetime . datetime . strptime ( dt_str , "%Y-%m-%dT%H:%M:%SZ" ) else : dt_str = dt_str . split ( "." ) return isostr_to_datetime ( "%sZ" % dt_str [ 0 ] )
def traverse_many ( self , attribute , source_sequence , target_sequence , visitor ) : """Traverses the given source and target sequences and makes appropriate calls to : method : ` traverse _ one ` . Algorithm : 1 ) Build a map target item ID - > target data item from the target sequence ; 2 ) For each s...
target_map = { } if not target_sequence is None : for target in target_sequence : target_map [ target . get_id ( ) ] = target src_tgt_pairs = [ ] if not source_sequence is None : for source in source_sequence : source_id = source . get_id ( ) if not source_id is None : # Check if target ...
def icon ( theme_name = '' , path = '' , qta_name = '' , qta_options = None , use_qta = None ) : """Creates an icon from qtawesome , from theme or from path . : param theme _ name : icon name in the current theme ( GNU / Linux only ) : param path : path of the icon ( from file system or qrc ) : param qta _ na...
ret_val = None if use_qta is None : use_qta = USE_QTAWESOME if qta_options is None : qta_options = QTA_OPTIONS if qta is not None and use_qta is True : ret_val = qta . icon ( qta_name , ** qta_options ) else : if theme_name and path : ret_val = QtGui . QIcon . fromTheme ( theme_name , QtGui . QI...
def auto_retry ( exception_t , retries = 3 , sleepSeconds = 1 , back_of_factor = 1 , msg = '' , auto_log = 1 , raise_on_failure = True ) : """a generic auto - retry function @ wrapper - decorator : param Exception exception _ t : exception ( or tuple of exceptions ) to auto retry : param int retries : max retri...
def wrapper ( func ) : def fun_call ( * args , ** kwargs ) : tries = 0 while tries < retries : try : return func ( * args , ** kwargs ) except exception_t as e : tries += 1 sleep_seconds = sleepSeconds * tries * back_of_factor ...
def add_resourcegroup ( group , network_id , ** kwargs ) : """Add a new group to a network ."""
group_i = ResourceGroup ( ) group_i . name = group . name group_i . description = group . description group_i . status = group . status group_i . network_id = network_id db . DBSession . add ( group_i ) db . DBSession . flush ( ) return group_i
def reversed ( self ) : """returns a copy of the QuadraticBezier object with its orientation reversed ."""
new_quad = QuadraticBezier ( self . end , self . control , self . start ) if self . _length_info [ 'length' ] : new_quad . _length_info = self . _length_info new_quad . _length_info [ 'bpoints' ] = ( self . end , self . control , self . start ) return new_quad
def extract_list_from_list_of_dict ( list_of_dict , key ) : # type : ( List [ DictUpperBound ] , Any ) - > List """Extract a list by looking up key in each member of a list of dictionaries Args : list _ of _ dict ( List [ DictUpperBound ] ) : List of dictionaries key ( Any ) : Key to find in each dictionary ...
result = list ( ) for dictionary in list_of_dict : result . append ( dictionary [ key ] ) return result
def srun ( self ) : """Get path to srun executable : rtype : string"""
commands = self . campaign . process . get ( 'commands' , { } ) srun = find_executable ( commands . get ( 'srun' , 'srun' ) ) if six . PY2 : srun = srun . encode ( 'utf-8' ) return srun
def execute ( ) : """Entry point of the install helper tool to ease the download of the right version of the ANTLR v4 tool jar ."""
arg_parser = ArgumentParser ( description = 'Install helper tool to download the right version of the ANTLR v4 tool jar.' ) arg_parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s {version}' . format ( version = __version__ ) ) mode_group = arg_parser . add_mutually_exclusive_group ( ) mode_g...
def launch_check ( self , timestamp , hosts , services , timeperiods , macromodulations , checkmodulations , checks , ref_check = None , force = False , dependent = False ) : # pylint : disable = too - many - locals , too - many - arguments # pylint : disable = too - many - branches , too - many - return - statements ...
chk = None cls = self . __class__ # Look if we are in check or not self . update_in_checking ( ) # the check is being forced , so we just replace next _ chk time by now if force and self . in_checking : try : c_in_progress = checks [ self . checks_in_progress [ 0 ] ] c_in_progress . t_to_go = time ....
def _get_tag ( self , name ) : """Get the L { NodeItem } attribute name for the given C { tag } ."""
if name . endswith ( "_" ) : if name [ : - 1 ] in self . _schema . reserved : return name [ : - 1 ] return name
def get_interpolated_gap ( self , tol = 0.001 , abs_tol = False , spin = None ) : """Expects a DOS object and finds the gap Args : tol : tolerance in occupations for determining the gap abs _ tol : Set to True for an absolute tolerance and False for a relative one . spin : Possible values are None - finds...
tdos = self . y if len ( self . ydim ) == 1 else np . sum ( self . y , axis = 1 ) if not abs_tol : tol = tol * tdos . sum ( ) / tdos . shape [ 0 ] energies = self . x below_fermi = [ i for i in range ( len ( energies ) ) if energies [ i ] < self . efermi and tdos [ i ] > tol ] above_fermi = [ i for i in range ( len...
def timediff ( time ) : """Return the difference in seconds between now and the given time ."""
now = datetime . datetime . utcnow ( ) diff = now - time diff_sec = diff . total_seconds ( ) return diff_sec
def is_archive ( self ) : '''Determines if the attachment is an archive .'''
try : if zipfile . is_zipfile ( self . attachment . path ) or tarfile . is_tarfile ( self . attachment . path ) : return True except Exception : pass return False
def handle_args ( ) : """Default values are defined here ."""
default_database_name = dbconfig . testdb_corpus_url . database parser = argparse . ArgumentParser ( prog = os . path . basename ( __file__ ) , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) parser . add_argument ( 'dbname' , nargs = '?' , default = str ( default_database_name ) , help = 'Database name' ,...
def adsb_vehicle_encode ( self , ICAO_address , lat , lon , altitude_type , altitude , heading , hor_velocity , ver_velocity , callsign , emitter_type , tslc , flags , squawk ) : '''The location and information of an ADSB vehicle ICAO _ address : ICAO address ( uint32 _ t ) lat : Latitude , expressed as degrees...
return MAVLink_adsb_vehicle_message ( ICAO_address , lat , lon , altitude_type , altitude , heading , hor_velocity , ver_velocity , callsign , emitter_type , tslc , flags , squawk )
def attach_securitygroup_components ( self , group_id , component_ids ) : """Attaches network components to a security group . : param int group _ id : The ID of the security group : param list component _ ids : The IDs of the network components to attach"""
return self . security_group . attachNetworkComponents ( component_ids , id = group_id )
def select_dag_nodes ( reftrack ) : """Select all dag nodes of the given reftrack : param reftrack : The reftrack to select the dagnodes for : type reftrack : : class : ` jukeboxcore . reftrack . Reftrack ` : returns : None : rtype : None : raises : None"""
refobj = reftrack . get_refobj ( ) if not refobj : return parentns = common . get_namespace ( refobj ) ns = cmds . getAttr ( "%s.namespace" % refobj ) fullns = ":" . join ( ( parentns . rstrip ( ":" ) , ns . lstrip ( ":" ) ) ) c = cmds . namespaceInfo ( fullns , listOnlyDependencyNodes = True , dagPath = True , rec...
def check_status ( self , delay = 0 ) : """Checks the api endpoint in a loop : param delay : number of seconds to wait between api calls . Note Connection ' requests _ delay ' also apply . : return : tuple of status and percentage complete : rtype : tuple ( str , float )"""
if not self . item_id : while not self . _request_status ( ) : # wait until _ request _ status returns True yield self . status , self . completion_percentage if self . item_id is None : sleep ( delay ) else : yield self . status , self . completion_percentage
def smear ( self , sigma ) : """Apply Gaussian smearing to spectrum y value . Args : sigma : Std dev for Gaussian smear function"""
diff = [ self . x [ i + 1 ] - self . x [ i ] for i in range ( len ( self . x ) - 1 ) ] avg_x_per_step = np . sum ( diff ) / len ( diff ) if len ( self . ydim ) == 1 : self . y = gaussian_filter1d ( self . y , sigma / avg_x_per_step ) else : self . y = np . array ( [ gaussian_filter1d ( self . y [ : , k ] , sigm...
def invoke_common_options ( f ) : """Common CLI options shared by " local invoke " and " local start - api " commands : param f : Callback passed by Click"""
invoke_options = [ template_click_option ( ) , click . option ( '--env-vars' , '-n' , type = click . Path ( exists = True ) , help = "JSON file containing values for Lambda function's environment variables." ) , parameter_override_click_option ( ) , click . option ( '--debug-port' , '-d' , help = "When specified, Lambd...
def vectorize ( * args , ** kwargs ) : """Allows using ` @ vectorize ` as well as ` @ vectorize ( ) ` ."""
if args and callable ( args [ 0 ] ) : # Guessing the argument is the method . return _vectorize ( args [ 0 ] ) else : # Wait for the second call . return lambda m : _vectorize ( m , * args , ** kwargs )
def happy_birthday ( name : hug . types . text , age : hug . types . number , hug_timer = 3 ) : """Says happy birthday to a user"""
return { 'message' : 'Happy {0} Birthday {1}!' . format ( age , name ) , 'took' : float ( hug_timer ) }
def index ( self , doc , index , doc_type , id = None , parent = None , force_insert = False , op_type = None , bulk = False , version = None , querystring_args = None , ttl = None ) : """Index a typed JSON document into a specific index and make it searchable ."""
if querystring_args is None : querystring_args = { } if bulk : if op_type is None : op_type = "index" if force_insert : op_type = "create" cmd = { op_type : { "_index" : index , "_type" : doc_type } } if parent : cmd [ op_type ] [ '_parent' ] = parent if version : ...
def _get_fieldsets_post_form_or_formset ( self , request , form , obj = None ) : """Generic get _ fieldsets code , shared by TranslationAdmin and TranslationInlineModelAdmin ."""
base_fields = self . replace_orig_field ( form . base_fields . keys ( ) ) fields = base_fields + list ( self . get_readonly_fields ( request , obj ) ) return [ ( None , { 'fields' : self . replace_orig_field ( fields ) } ) ]
def doc_type ( self , * doc_type , ** kwargs ) : """Set the type to search through . You can supply a single value or multiple . Values can be strings or subclasses of ` ` Document ` ` . You can also pass in any keyword arguments , mapping a doc _ type to a callback that should be used instead of the Hit clas...
# . doc _ type ( ) resets s = self . _clone ( ) if not doc_type and not kwargs : s . _doc_type = [ ] s . _doc_type_map = { } else : s . _doc_type . extend ( doc_type ) s . _doc_type . extend ( kwargs . keys ( ) ) s . _doc_type_map . update ( kwargs ) return s
def find_datafile ( name , search_path , codecs = get_codecs ( ) ) : """find all matching data files in search _ path search _ path : path of directories to load from codecs : allow to override from list of installed returns array of tuples ( codec _ object , filename )"""
return munge . find_datafile ( name , search_path , codecs )
def _translate_div ( self , oprnd1 , oprnd2 , oprnd3 ) : """Return a formula representation of an DIV instruction ."""
assert oprnd1 . size and oprnd2 . size and oprnd3 . size assert oprnd1 . size == oprnd2 . size op1_var = self . _translate_src_oprnd ( oprnd1 ) op2_var = self . _translate_src_oprnd ( oprnd2 ) op3_var , op3_var_constrs = self . _translate_dst_oprnd ( oprnd3 ) if oprnd3 . size > oprnd1 . size : op1_var_zx = smtfunct...
def get_entry_view ( self , key ) : """Returns the EntryView for the specified key . * * Warning : This method returns a clone of original mapping , modifying the returned value does not change the actual value in the map . One should put modified value back to make changes visible to all nodes . * * * * Wa...
check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( map_get_entry_view_codec , key_data , key = key_data , thread_id = thread_id ( ) )
def format ( self , fmt ) : """Return a representation of this instance formatted with user supplied syntax"""
_fmt_params = { 'base' : self . base , 'bin' : self . bin , 'binary' : self . binary , 'bits' : self . bits , 'bytes' : self . bytes , 'power' : self . power , 'system' : self . system , 'unit' : self . unit , 'unit_plural' : self . unit_plural , 'unit_singular' : self . unit_singular , 'value' : self . value } return ...
def status_for ( self , code ) : """Returns the weather status related to the specified weather status code , if any is stored , ` ` None ` ` otherwise . : param code : the weather status code whose status is to be looked up : type code : int : returns : the weather status str or ` ` None ` ` if the code is...
is_in = lambda start , end , n : True if start <= n <= end else False for status in self . _code_ranges_dict : for _range in self . _code_ranges_dict [ status ] : if is_in ( _range [ 'start' ] , _range [ 'end' ] , code ) : return status return None
def allsec_preorder ( h ) : """Alternative to using h . allsec ( ) . This returns all sections in order from the root . Traverses the topology each neuron in " pre - order " """
# Iterate over all sections , find roots roots = root_sections ( h ) # Build list of all sections sec_list = [ ] for r in roots : add_pre ( h , sec_list , r ) return sec_list
def _viscounts2radiance ( counts , slope , offset ) : """Convert VIS counts to radiance References : [ VIS ] Args : counts : Raw detector counts slope : Slope [ W m - 2 um - 1 sr - 1] offset : Offset [ W m - 2 um - 1 sr - 1] Returns : Radiance [ W m - 2 um - 1 sr - 1]"""
rad = counts * slope + offset return rad . clip ( min = 0 )
def popen_uci ( cls , command : Union [ str , List [ str ] ] , * , timeout : Optional [ float ] = 10.0 , debug : bool = False , setpgrp : bool = False , ** popen_args : Any ) -> "SimpleEngine" : """Spawns and initializes an UCI engine . Returns a : class : ` ~ chess . engine . SimpleEngine ` instance ."""
return cls . popen ( UciProtocol , command , timeout = timeout , debug = debug , setpgrp = setpgrp , ** popen_args )
def sliding_impl ( wrap , size , step , sequence ) : """Implementation for sliding _ t : param wrap : wrap children values with this : param size : size of window : param step : step size : param sequence : sequence to create sliding windows from : return : sequence of sliding windows"""
i = 0 n = len ( sequence ) while i + size <= n or ( step != 1 and i < n ) : yield wrap ( sequence [ i : i + size ] ) i += step
async def post_entry_tags ( self , entry , tags ) : """POST / api / entries / { entry } / tags . { _ format } Add one or more tags to an entry : param entry : \ w + an integer The Entry ID : param tags : list of tags ( urlencoded ) : return result"""
params = { 'access_token' : self . token , 'tags' : [ ] } if len ( tags ) > 0 and isinstance ( tags , list ) : params [ 'tags' ] = ', ' . join ( tags ) path = '/api/entries/{entry}/tags.{ext}' . format ( entry = entry , ext = self . format ) return await self . query ( path , "post" , ** params )
def sha256sum ( filename ) : """Return SHA256 hash of file ."""
sha256 = hashlib . sha256 ( ) mem_view = memoryview ( bytearray ( 128 * 1024 ) ) with open ( filename , 'rb' , buffering = 0 ) as stream : for i in iter ( lambda : stream . readinto ( mem_view ) , 0 ) : sha256 . update ( mem_view [ : i ] ) return sha256 . hexdigest ( )
def _sum ( ctx , * number ) : """Returns the sum of all arguments"""
if len ( number ) == 0 : raise ValueError ( "Wrong number of arguments" ) result = Decimal ( 0 ) for arg in number : result += conversions . to_decimal ( arg , ctx ) return result
def get_instance ( self , payload ) : """Build an instance of AuthTypeRegistrationsInstance : param dict payload : Payload response from the API : returns : twilio . rest . api . v2010 . account . sip . domain . auth _ types . auth _ registrations _ mapping . AuthTypeRegistrationsInstance : rtype : twilio . r...
return AuthTypeRegistrationsInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , domain_sid = self . _solution [ 'domain_sid' ] , )
def start ( self ) : """Starts the connection"""
self . __stop = False self . _queue . start ( ) self . _zk . start ( )
def _generate ( self , item , * args ) : """wraps execution of specific methods ."""
if item in self . done : return # verbose output with location . if self . generate_locations and item . location : print ( "# %s:%d" % item . location , file = self . stream ) if self . generate_comments : self . print_comment ( item ) log . debug ( "generate %s, %s" , item . __class__ . __name__ , item . ...
def read_tsv ( cls , path , encoding = 'utf-8' ) : """Read a gene set database from a tab - delimited text file . Parameters path : str The path name of the the file . encoding : str The encoding of the text file . Returns None"""
gene_sets = [ ] n = 0 with open ( path , 'rb' ) as fh : reader = csv . reader ( fh , dialect = 'excel-tab' , encoding = encoding ) for l in reader : n += 1 gs = GeneSet . from_list ( l ) gene_sets . append ( gs ) logger . debug ( 'Read %d gene sets.' , n ) logger . debug ( 'Size of gene ...
def doc ( inherit = None , ** kwargs ) : """Annotate the decorated view function or class with the specified Swagger attributes . Usage : . . code - block : : python @ doc ( tags = [ ' pet ' ] , description = ' a pet store ' ) def get _ pet ( pet _ id ) : return Pet . query . filter ( Pet . id = = pet _...
def wrapper ( func ) : annotate ( func , 'docs' , [ kwargs ] , inherit = inherit ) return activate ( func ) return wrapper
def route ( regex , view , method , name ) : """Route the given view . : param regex : A string describing a regular expression to which the request path will be matched . : param view : A string describing the name of the view to delegate the request to . : param method : A string describing the HTTP method ...
return _Route ( regex , view , method , name )
def _get_existing_report ( self , mask , report ) : """Returns the aggregated report that matches report"""
for existing_report in self . _reports : if existing_report [ 'namespace' ] == report [ 'namespace' ] : if mask == existing_report [ 'queryMask' ] : return existing_report return None
def partition ( string , sep ) : """New in Python 2.5 as str . partition ( sep )"""
p = string . split ( sep , 1 ) if len ( p ) == 2 : return p [ 0 ] , sep , p [ 1 ] return string , '' , ''
def clean_params ( self ) : """Retrieves the parameter OrderedDict without the context or self parameters . Useful for inspecting signature ."""
result = self . params . copy ( ) if self . cog is not None : # first parameter is self result . popitem ( last = False ) try : # first / second parameter is context result . popitem ( last = False ) except Exception : raise ValueError ( 'Missing context parameter' ) from None return result
def write_file ( self , filename , content ) : """Write a file . This is useful when writing a file that will fit within memory : param filename : ` ` str ` ` : param content : ` ` str ` `"""
with open ( filename , 'wb' ) as f : self . log . debug ( content ) f . write ( content )
def ListDirectory ( self , pathspec , depth = 0 ) : """A recursive generator of files ."""
# Limit recursion depth if depth >= self . request . max_depth : return try : fd = vfs . VFSOpen ( pathspec , progress_callback = self . Progress ) files = fd . ListFiles ( ext_attrs = self . request . collect_ext_attrs ) except ( IOError , OSError ) as e : if depth == 0 : # We failed to open the direct...
def device_id_from_name ( device_name , nodes ) : """Get the device ID when given a device name : param str device _ name : device name : param list nodes : list of nodes from : py : meth : ` generate _ nodes ` : return : device ID : rtype : int"""
device_id = None for node in nodes : if device_name == node [ 'properties' ] [ 'name' ] : device_id = node [ 'id' ] break return device_id
def request ( self , method , url , params = None , body = None , ** kwargs ) : """Send an HTTP request . The : param : ` params ` will be properly encoded , as well as : param : ` body ` which will be wrapped with envelope the API expects and json encoded . When you get a reponse the method will try to json ...
url = "{base_url}{version}{resource}" . format ( base_url = self . config . base_url , version = self . API_VERSION , resource = url ) headers = { 'Accept' : 'application/json' , 'Authorization' : "Bearer {0}" . format ( self . config . access_token ) , 'User-Agent' : self . config . user_agent , } user_headers = { } i...
def create_data_map ( msgs_to_read ) : '''Create a data map for usage when parsing the bag'''
dmap = { } for topic in msgs_to_read . keys ( ) : base_name = get_key_name ( topic ) + '__' fields = { } for f in msgs_to_read [ topic ] : key = ( base_name + f ) . replace ( '.' , '_' ) fields [ f ] = key dmap [ topic ] = fields return dmap
def insert_or_merge_entity ( self , entity ) : '''Adds an insert or merge entity operation to the batch . See : func : ` ~ azure . storage . table . tableservice . TableService . insert _ or _ merge _ entity ` for more information on insert or merge operations . The operation will not be executed until the ba...
request = _insert_or_merge_entity ( entity , self . _require_encryption , self . _key_encryption_key ) self . _add_to_batch ( entity [ 'PartitionKey' ] , entity [ 'RowKey' ] , request )
def stage_import_from_file ( self , fd , filename = 'upload.gz' ) : """Stage an import from a file upload . : param fd : File - like object to upload . : param filename : ( optional ) Filename to use for import as string . : return : : class : ` imports . Import < imports . Import > ` object"""
schema = ImportSchema ( ) resp = self . service . post ( self . base , files = { 'file' : ( filename , fd ) } ) return self . service . decode ( schema , resp )