idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
32,800
def create_pool ( dsn = None , * , min_size = 10 , max_size = 10 , max_queries = 50000 , max_inactive_connection_lifetime = 300.0 , setup = None , init = None , loop = None , connection_class = connection . Connection , ** connect_kwargs ) : r return Pool ( dsn , connection_class = connection_class , min_size = min_siz...
r Create a connection pool .
32,801
def _release ( self ) : if self . _in_use is None : return if not self . _in_use . done ( ) : self . _in_use . set_result ( None ) self . _in_use = None if self . _proxy is not None : self . _proxy . _detach ( ) self . _proxy = None self . _pool . _queue . put_nowait ( self )
Release this connection holder .
32,802
def set_connect_args ( self , dsn = None , ** connect_kwargs ) : r self . _connect_args = [ dsn ] self . _connect_kwargs = connect_kwargs self . _working_addr = None self . _working_config = None self . _working_params = None
r Set the new connection arguments for this pool .
32,803
async def release ( self , connection , * , timeout = None ) : if ( type ( connection ) is not PoolConnectionProxy or connection . _holder . _pool is not self ) : raise exceptions . InterfaceError ( 'Pool.release() received invalid connection: ' '{connection!r} is not a member of this pool' . format ( connection = conn...
Release a database connection back to the pool .
32,804
async def close ( self ) : if self . _closed : return self . _check_init ( ) self . _closing = True warning_callback = None try : warning_callback = self . _loop . call_later ( 60 , self . _warn_on_long_close ) release_coros = [ ch . wait_until_released ( ) for ch in self . _holders ] await asyncio . gather ( * release...
Attempt to gracefully close all connections in the pool .
32,805
def terminate ( self ) : if self . _closed : return self . _check_init ( ) for ch in self . _holders : ch . terminate ( ) self . _closed = True
Terminate all connections in the pool .
32,806
async def start ( self ) : self . __check_state_base ( 'start' ) if self . _state is TransactionState . STARTED : raise apg_errors . InterfaceError ( 'cannot start; the transaction is already started' ) con = self . _connection if con . _top_xact is None : if con . _protocol . is_in_transaction ( ) : raise apg_errors ....
Enter the transaction or savepoint block .
32,807
def get_statusmsg ( self ) -> str : if self . _last_status is None : return self . _last_status return self . _last_status . decode ( )
Return the status of the executed command .
32,808
async def explain ( self , * args , analyze = False ) : query = 'EXPLAIN (FORMAT JSON, VERBOSE' if analyze : query += ', ANALYZE) ' else : query += ') ' query += self . _state . query if analyze : tr = self . _connection . transaction ( ) await tr . start ( ) try : data = await self . _connection . fetchval ( query , *...
Return the execution plan of the statement .
32,809
async def fetchval ( self , * args , column = 0 , timeout = None ) : data = await self . __bind_execute ( args , 1 , timeout ) if not data : return None return data [ 0 ] [ column ]
Execute the statement and return a value in the first row .
32,810
async def fetchrow ( self , * args , timeout = None ) : data = await self . __bind_execute ( args , 1 , timeout ) if not data : return None return data [ 0 ]
Execute the statement and return the first row .
32,811
def _read_password_from_pgpass ( * , passfile : typing . Optional [ pathlib . Path ] , hosts : typing . List [ str ] , ports : typing . List [ int ] , database : str , user : str ) : passtab = _read_password_file ( passfile ) if not passtab : return None for host , port in zip ( hosts , ports ) : if host . startswith (...
Parse the pgpass file and return the matching password .
32,812
async def _mogrify ( conn , query , args ) : ps = await conn . prepare ( query ) paramtypes = [ ] for t in ps . get_parameters ( ) : if t . name . endswith ( '[]' ) : pname = '_' + t . name [ : - 2 ] else : pname = t . name paramtypes . append ( '{}.{}' . format ( _quote_ident ( t . schema ) , _quote_ident ( pname ) ) ...
Safely inline arguments to query text .
32,813
def aggregate ( self , val1 , val2 ) : assert val1 is not None assert val2 is not None return self . _aggregator ( val1 , val2 )
Aggregate two event values .
32,814
def stripped_name ( self ) : name = self . name while True : name , n = self . _parenthesis_re . subn ( '' , name ) if not n : break name = self . _const_re . sub ( '' , name ) while True : name , n = self . _angles_re . subn ( '' , name ) if not n : break return name
Remove extraneous information from C ++ demangled function names .
32,815
def validate ( self ) : for function in compat_itervalues ( self . functions ) : for callee_id in compat_keys ( function . calls ) : assert function . calls [ callee_id ] . callee_id == callee_id if callee_id not in self . functions : sys . stderr . write ( 'warning: call to undefined function %s from function %s\n' % ...
Validate the edges .
32,816
def find_cycles ( self ) : stack = [ ] data = { } order = 0 for function in compat_itervalues ( self . functions ) : order = self . _tarjan ( function , order , stack , data ) cycles = [ ] for function in compat_itervalues ( self . functions ) : if function . cycle is not None and function . cycle not in cycles : cycle...
Find cycles using Tarjan s strongly connected components algorithm .
32,817
def _tarjan ( self , function , order , stack , data ) : try : func_data = data [ function . id ] return order except KeyError : func_data = self . _TarjanData ( order ) data [ function . id ] = func_data order += 1 pos = len ( stack ) stack . append ( function ) func_data . onstack = True for call in compat_itervalues...
Tarjan s strongly connected components algorithm .
32,818
def integrate ( self , outevent , inevent ) : assert outevent not in self for function in compat_itervalues ( self . functions ) : assert outevent not in function assert inevent in function for call in compat_itervalues ( function . calls ) : assert outevent not in call if call . callee_id != function . id : assert cal...
Propagate function time ratio along the function calls .
32,819
def _rank_cycle_function ( self , cycle , function , ranks ) : import heapq Q = [ ] Qd = { } p = { } visited = set ( [ function ] ) ranks [ function ] = 0 for call in compat_itervalues ( function . calls ) : if call . callee_id != function . id : callee = self . functions [ call . callee_id ] if callee . cycle is cycle...
Dijkstra s shortest paths algorithm .
32,820
def aggregate ( self , event ) : total = event . null ( ) for function in compat_itervalues ( self . functions ) : try : total = event . aggregate ( total , function [ event ] ) except UndefinedEvent : return self [ event ] = total
Aggregate an event for the whole profile .
32,821
def prune ( self , node_thres , edge_thres , paths , color_nodes_by_selftime ) : for function in compat_itervalues ( self . functions ) : try : function . weight = function [ TOTAL_TIME_RATIO ] except UndefinedEvent : pass for call in compat_itervalues ( function . calls ) : callee = self . functions [ call . callee_id...
Prune the profile
32,822
def translate ( self , mo ) : attrs = { } groupdict = mo . groupdict ( ) for name , value in compat_iteritems ( groupdict ) : if value is None : value = None elif self . _int_re . match ( value ) : value = int ( value ) elif self . _float_re . match ( value ) : value = float ( value ) attrs [ name ] = ( value ) return ...
Extract a structure from a match object while translating the types in the process .
32,823
def parse_cg ( self ) : line = self . readline ( ) while self . _cg_header_re . match ( line ) : line = self . readline ( ) entry_lines = [ ] while not self . _cg_footer_re . match ( line ) : if line . isspace ( ) : self . parse_cg_entry ( entry_lines ) entry_lines = [ ] else : entry_lines . append ( line ) line = self...
Parse the call graph .
32,824
def hsl_to_rgb ( self , h , s , l ) : h = h % 1.0 s = min ( max ( s , 0.0 ) , 1.0 ) l = min ( max ( l , 0.0 ) , 1.0 ) if l <= 0.5 : m2 = l * ( s + 1.0 ) else : m2 = l + s - l * s m1 = l * 2.0 - m2 r = self . _hue_to_rgb ( m1 , m2 , h + 1.0 / 3.0 ) g = self . _hue_to_rgb ( m1 , m2 , h ) b = self . _hue_to_rgb ( m1 , m2 ...
Convert a color from HSL color - model to RGB .
32,825
def wrap_function_name ( self , name ) : if len ( name ) > 32 : ratio = 2.0 / 3.0 height = max ( int ( len ( name ) / ( 1.0 - ratio ) + 0.5 ) , 1 ) width = max ( len ( name ) / height , 32 ) name = textwrap . fill ( name , width , break_long_words = False ) name = name . replace ( ", " , "," ) name = name . replace ( "...
Split the function name on multiple lines .
32,826
def matlab_compatible ( name ) : compatible_name = [ ch if ch in ALLOWED_MATLAB_CHARS else "_" for ch in name ] compatible_name = "" . join ( compatible_name ) if compatible_name [ 0 ] not in string . ascii_letters : compatible_name = "M_" + compatible_name return compatible_name [ : 60 ]
make a channel name compatible with Matlab variable naming
32,827
def get_text_v3 ( address , stream , mapped = False ) : if address == 0 : return "" if mapped : size , = UINT16_uf ( stream , address + 2 ) text_bytes = stream [ address + 4 : address + size ] else : stream . seek ( address + 2 ) size = UINT16_u ( stream . read ( 2 ) ) [ 0 ] - 4 text_bytes = stream . read ( size ) try ...
faster way to extract strings from mdf versions 2 and 3 TextBlock
32,828
def get_text_v4 ( address , stream , mapped = False ) : if address == 0 : return "" if mapped : size , _ = TWO_UINT64_uf ( stream , address + 8 ) text_bytes = stream [ address + 24 : address + size ] else : stream . seek ( address + 8 ) size , _ = TWO_UINT64_u ( stream . read ( 16 ) ) text_bytes = stream . read ( size ...
faster way to extract strings from mdf version 4 TextBlock
32,829
def get_fmt_v3 ( data_type , size ) : if data_type in { v3c . DATA_TYPE_STRING , v3c . DATA_TYPE_BYTEARRAY } : size = size // 8 if data_type == v3c . DATA_TYPE_STRING : fmt = f"S{size}" elif data_type == v3c . DATA_TYPE_BYTEARRAY : fmt = f"({size},)u1" else : if size <= 8 : size = 1 elif size <= 16 : size = 2 elif size...
convert mdf versions 2 and 3 channel data type to numpy dtype format string
32,830
def get_fmt_v4 ( data_type , size , channel_type = v4c . CHANNEL_TYPE_VALUE ) : if data_type in v4c . NON_SCALAR_TYPES : size = size // 8 if data_type == v4c . DATA_TYPE_BYTEARRAY : if channel_type == v4c . CHANNEL_TYPE_VALUE : fmt = f"({size},)u1" else : if size == 4 : fmt = "<u4" elif size == 8 : fmt = "<u8" elif dat...
convert mdf version 4 channel data type to numpy dtype format string
32,831
def fmt_to_datatype_v3 ( fmt , shape , array = False ) : size = fmt . itemsize * 8 if not array and shape [ 1 : ] and fmt . itemsize == 1 and fmt . kind == "u" : data_type = v3c . DATA_TYPE_BYTEARRAY for dim in shape [ 1 : ] : size *= dim else : if fmt . kind == "u" : if fmt . byteorder in "=<|" : data_type = v3c . DAT...
convert numpy dtype format string to mdf versions 2 and 3 channel data type and size
32,832
def info_to_datatype_v4 ( signed , little_endian ) : if signed : if little_endian : datatype = v4c . DATA_TYPE_SIGNED_INTEL else : datatype = v4c . DATA_TYPE_SIGNED_MOTOROLA else : if little_endian : datatype = v4c . DATA_TYPE_UNSIGNED_INTEL else : datatype = v4c . DATA_TYPE_UNSIGNED_MOTOROLA return datatype
map CAN signal to MDF integer types
32,833
def fmt_to_datatype_v4 ( fmt , shape , array = False ) : size = fmt . itemsize * 8 if not array and shape [ 1 : ] and fmt . itemsize == 1 and fmt . kind == "u" : data_type = v4c . DATA_TYPE_BYTEARRAY for dim in shape [ 1 : ] : size *= dim else : if fmt . kind == "u" : if fmt . byteorder in "=<|" : data_type = v4c . DAT...
convert numpy dtype format string to mdf version 4 channel data type and size
32,834
def debug_channel ( mdf , group , channel , dependency , file = None ) : print ( "MDF" , "=" * 76 , file = file ) print ( "name:" , mdf . name , file = file ) print ( "version:" , mdf . version , file = file ) print ( "read fragment size:" , mdf . _read_fragment_size , file = file ) print ( "write fragment size:" , mdf...
use this to print debug information in case of errors
32,835
def count_channel_groups ( stream , include_channels = False ) : count = 0 ch_count = 0 stream . seek ( 64 ) blk_id = stream . read ( 2 ) if blk_id == b"HD" : version = 3 else : blk_id += stream . read ( 2 ) if blk_id == b"##HD" : version = 4 else : raise MdfException ( f'"{stream.name}" is not a valid MDF file' ) if v...
count all channel groups as fast as possible . This is used to provide reliable progress information when loading a file using the GUI
32,836
def validate_version_argument ( version , hint = 4 ) : if version not in SUPPORTED_VERSIONS : if hint == 2 : valid_version = "2.14" elif hint == 3 : valid_version = "3.30" else : valid_version = "4.10" message = ( 'Unknown mdf version "{}".' " The available versions are {};" ' automatically using version "{}"' ) messag...
validate the version argument against the supported MDF versions . The default version used depends on the hint MDF major revision
32,837
def cut_video_stream ( stream , start , end , fmt ) : with TemporaryDirectory ( ) as tmp : in_file = Path ( tmp ) / f"in{fmt}" out_file = Path ( tmp ) / f"out{fmt}" in_file . write_bytes ( stream ) try : ret = subprocess . run ( [ "ffmpeg" , "-ss" , f"{start}" , "-i" , f"{in_file}" , "-to" , f"{end}" , "-c" , "copy" , ...
cut video stream from start to end time
32,838
def components ( channel , channel_name , unique_names , prefix = "" , master = None ) : names = channel . dtype . names if names [ 0 ] == channel_name : name = names [ 0 ] if prefix : name_ = unique_names . get_unique_name ( f"{prefix}.{name}" ) else : name_ = unique_names . get_unique_name ( name ) values = channel [...
yield pandas Series and unique name based on the ndarray object
32,839
def master_using_raster ( mdf , raster , endpoint = False ) : if not raster : master = np . array ( [ ] , dtype = '<f8' ) else : t_min = [ ] t_max = [ ] for i , group in enumerate ( mdf . groups ) : cycles_nr = group . channel_group . cycles_nr if cycles_nr : master_min = mdf . get_master ( i , record_offset = 0 , reco...
get single master based on the raster
32,840
def add ( self , channel_name , entry ) : if channel_name : if channel_name not in self : self [ channel_name ] = [ entry ] else : self [ channel_name ] . append ( entry ) if "\\" in channel_name : channel_name = channel_name . split ( "\\" ) [ 0 ] if channel_name not in self : self [ channel_name ] = [ entry ] else : ...
add name to channels database and check if it contains a source path
32,841
def get_unique_name ( self , name ) : if name not in self . _db : self . _db [ name ] = 0 return name else : index = self . _db [ name ] self . _db [ name ] = index + 1 return f"{name}_{index}"
returns an available unique name
32,842
def iter_get ( self , name = None , group = None , index = None , raster = None , samples_only = False , raw = False , ) : gp_nr , ch_nr = self . _validate_channel_selection ( name , group , index ) grp = self . groups [ gp_nr ] data = self . _load_data ( grp ) for fragment in data : yield self . get ( group = gp_nr , ...
iterator over a channel
32,843
def whereis ( self , channel ) : if channel in self : return tuple ( self . channels_db [ channel ] ) else : return tuple ( )
get ocurrences of channel name in the file
32,844
def get_invalidation_bits ( self , group_index , channel , fragment ) : group = self . groups [ group_index ] dtypes = group . types data_bytes , offset , _count = fragment try : invalidation = self . _invalidation_cache [ ( group_index , offset , _count ) ] except KeyError : record = group . record if record is None :...
get invalidation indexes for the channel
32,845
def configure ( self , * , read_fragment_size = None , write_fragment_size = None , use_display_names = None , single_bit_uint_as_bool = None , integer_interpolation = None , ) : if read_fragment_size is not None : self . _read_fragment_size = int ( read_fragment_size ) if write_fragment_size : self . _write_fragment_s...
configure MDF parameters
32,846
def extract_attachment ( self , address = None , index = None ) : if address is None and index is None : return b"" , Path ( "" ) if address is not None : index = self . _attachments_map [ address ] attachment = self . attachments [ index ] current_path = Path . cwd ( ) file_path = Path ( attachment . file_name or "emb...
extract attachment data by original address or by index . If it is an embedded attachment then this method creates the new file according to the attachment file name information
32,847
def get_channel_name ( self , group , index ) : gp_nr , ch_nr = self . _validate_channel_selection ( None , group , index ) return self . groups [ gp_nr ] . channels [ ch_nr ] . name
Gets channel name .
32,848
def get_channel_unit ( self , name = None , group = None , index = None ) : gp_nr , ch_nr = self . _validate_channel_selection ( name , group , index ) grp = self . groups [ gp_nr ] channel = grp . channels [ ch_nr ] conversion = channel . conversion unit = conversion and conversion . unit or channel . unit or "" retur...
Gets channel unit .
32,849
def get_channel_comment ( self , name = None , group = None , index = None ) : gp_nr , ch_nr = self . _validate_channel_selection ( name , group , index ) grp = self . groups [ gp_nr ] channel = grp . channels [ ch_nr ] return extract_cncomment_xml ( channel . comment )
Gets channel comment .
32,850
def _cmd_line_parser ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( '--path' , help = ( 'path to test files, ' 'if not provided the script folder is used' ) ) parser . add_argument ( '--text_output' , action = 'store_true' , help = 'option to save the results to text file' ) parser . add_argument ...
return a command line parser . It is used when generating the documentation
32,851
def append ( self , item ) : print ( item ) super ( MyList , self ) . append ( item )
append item and print it to stdout
32,852
def extend ( self , items ) : print ( '\n' . join ( items ) ) super ( MyList , self ) . extend ( items )
extend items and print them to stdout using the new line separator
32,853
def extend ( self , other ) : if len ( self . timestamps ) : last_stamp = self . timestamps [ - 1 ] else : last_stamp = 0 if len ( other ) : other_first_sample = other . timestamps [ 0 ] if last_stamp >= other_first_sample : timestamps = other . timestamps + last_stamp else : timestamps = other . timestamps if self . i...
extend signal with samples from another signal
32,854
def physical ( self ) : if not self . raw or self . conversion is None : samples = self . samples . copy ( ) else : samples = self . conversion . convert ( self . samples ) return Signal ( samples , self . timestamps . copy ( ) , unit = self . unit , name = self . name , conversion = self . conversion , raw = False , m...
get the physical samples values
32,855
def extract ( self ) : if self . flags & v4c . FLAG_AT_EMBEDDED : if self . flags & v4c . FLAG_AT_COMPRESSED_EMBEDDED : data = decompress ( self . embedded_data ) else : data = self . embedded_data if self . flags & v4c . FLAG_AT_MD5_VALID : md5_worker = md5 ( ) md5_worker . update ( data ) md5_sum = md5_worker . diges...
extract attachment data
32,856
def start_time ( self ) : timestamp = self . abs_time / 10 ** 9 if self . time_flags & v4c . FLAG_HD_LOCAL_TIME : timestamp = datetime . fromtimestamp ( timestamp ) else : timestamp = datetime . fromtimestamp ( timestamp , timezone . utc ) return timestamp
getter and setter the measurement start timestamp
32,857
def _prepare_record ( self , group ) : parents , dtypes = group . parents , group . types if parents is None : if group . data_location == v23c . LOCATION_ORIGINAL_FILE : stream = self . _file else : stream = self . _tempfile grp = group record_size = grp . channel_group . samples_byte_nr << 3 next_byte_aligned_positio...
compute record dtype and parents dict for this group
32,858
def close ( self ) : if self . _tempfile is not None : self . _tempfile . close ( ) if self . _file is not None and not self . _from_filelike : self . _file . close ( )
if the MDF was created with memory = minimum and new channels have been appended then this must be called just before the object is not used anymore to clean - up the temporary file
32,859
def iter_get_triggers ( self ) : for i , gp in enumerate ( self . groups ) : trigger = gp . trigger if trigger : for j in range ( trigger [ "trigger_events_nr" ] ) : trigger_info = { "comment" : trigger . comment , "index" : j , "group" : i , "time" : trigger [ f"trigger_{j}_time" ] , "pre_time" : trigger [ f"trigger_{...
generator that yields triggers
32,860
def setLabel ( self , text = None , units = None , unitPrefix = None , ** args ) : show_label = False if text is not None : self . labelText = text show_label = True if units is not None : self . labelUnits = units show_label = True if show_label : self . showLabel ( ) if unitPrefix is not None : self . labelUnitPrefix...
overwrites pyqtgraph setLabel
32,861
def clean_tenant_url ( url_string ) : if hasattr ( settings , 'PUBLIC_SCHEMA_URLCONF' ) : if ( settings . PUBLIC_SCHEMA_URLCONF and url_string . startswith ( settings . PUBLIC_SCHEMA_URLCONF ) ) : url_string = url_string [ len ( settings . PUBLIC_SCHEMA_URLCONF ) : ] return url_string
Removes the TENANT_TOKEN from a particular string
32,862
def app_labels ( apps_list ) : if AppConfig is None : return [ app . split ( '.' ) [ - 1 ] for app in apps_list ] return [ AppConfig . create ( app ) . label for app in apps_list ]
Returns a list of app labels of the given apps_list now properly handles new Django 1 . 7 + application registry .
32,863
def path ( self , name ) : if name is None : name = '' try : location = safe_join ( self . location , connection . tenant . domain_url ) except AttributeError : location = self . location try : path = safe_join ( location , name ) except ValueError : raise SuspiciousOperation ( "Attempted access to '%s' denied." % name...
Look for files in subdirectory of MEDIA_ROOT using the tenant s domain_url value as the specifier .
32,864
def run_from_argv ( self , argv ) : try : app_name = get_commands ( ) [ argv [ 2 ] ] except KeyError : raise CommandError ( "Unknown command: %r" % argv [ 2 ] ) if isinstance ( app_name , BaseCommand ) : klass = app_name else : klass = load_command_class ( app_name , argv [ 2 ] ) del argv [ 1 ] schema_parser = argparse...
Changes the option_list to use the options from the wrapped command . Adds schema parameter to specify which schema will be used when executing the wrapped command .
32,865
def handle ( self , * args , ** options ) : if options [ 'schema_name' ] : connection . set_schema_to_public ( ) self . execute_command ( get_tenant_model ( ) . objects . get ( schema_name = options [ 'schema_name' ] ) , self . COMMAND_NAME , * args , ** options ) else : for tenant in get_tenant_model ( ) . objects . a...
Iterates a command over all registered schemata .
32,866
def _cursor ( self , name = None ) : if name : cursor = super ( DatabaseWrapper , self ) . _cursor ( name = name ) else : cursor = super ( DatabaseWrapper , self ) . _cursor ( ) if ( not get_limit_set_calls ( ) ) or not self . search_path_set : if not self . schema_name : raise ImproperlyConfigured ( "Database schema n...
Here it happens . We hope every Django db operation using PostgreSQL must go through this to get the cursor handle . We change the path .
32,867
def best_practice ( app_configs , ** kwargs ) : if app_configs is None : app_configs = apps . get_app_configs ( ) INSTALLED_APPS = [ config . name for config in app_configs ] if not hasattr ( settings , 'TENANT_APPS' ) : return [ Critical ( 'TENANT_APPS setting not set' ) ] if not hasattr ( settings , 'TENANT_MODEL' ) ...
Test for configuration recommendations . These are best practices they avoid hard to find bugs and unexpected behaviour .
32,868
def short_repr ( obj , max_len = 40 ) : obj_repr = repr ( obj ) if len ( obj_repr ) <= max_len : return obj_repr return '<{} of length {}>' . format ( type ( obj ) . __name__ , len ( obj_repr ) )
Returns a short term - friendly string representation of the object .
32,869
def measures ( * measurements , ** kwargs ) : def _maybe_make ( meas ) : if isinstance ( meas , Measurement ) : return meas elif isinstance ( meas , six . string_types ) : return Measurement ( meas , ** kwargs ) raise InvalidMeasurementType ( 'Expected Measurement or string' , meas ) if kwargs and len ( measurements ) ...
Decorator - maker used to declare measurements for phases .
32,870
def set_notification_callback ( self , notification_cb ) : self . _notification_cb = notification_cb if not notification_cb and self . dimensions : self . measured_value . notify_value_set = None return self
Set the notifier we ll call when measurements are set .
32,871
def _maybe_make_unit_desc ( self , unit_desc ) : if isinstance ( unit_desc , str ) or unit_desc is None : unit_desc = units . Unit ( unit_desc ) if not isinstance ( unit_desc , units . UnitDescriptor ) : raise TypeError ( 'Invalid units for measurement %s: %s' % ( self . name , unit_desc ) ) return unit_desc
Return the UnitDescriptor or convert a string to one .
32,872
def _maybe_make_dimension ( self , dimension ) : if isinstance ( dimension , Dimension ) : return dimension if isinstance ( dimension , units . UnitDescriptor ) : return Dimension . from_unit_descriptor ( dimension ) if isinstance ( dimension , str ) : return Dimension . from_string ( dimension ) raise TypeError ( 'Can...
Return a measurements . Dimension instance .
32,873
def with_dimensions ( self , * dimensions ) : self . dimensions = tuple ( self . _maybe_make_dimension ( dim ) for dim in dimensions ) self . _cached = None return self
Declare dimensions for this Measurement returns self for chaining .
32,874
def with_validator ( self , validator ) : if not callable ( validator ) : raise ValueError ( 'Validator must be callable' , validator ) self . validators . append ( validator ) self . _cached = None return self
Add a validator callback to this Measurement chainable .
32,875
def with_args ( self , ** kwargs ) : validators = [ validator . with_args ( ** kwargs ) if hasattr ( validator , 'with_args' ) else validator for validator in self . validators ] return mutablerecords . CopyRecord ( self , name = util . format_string ( self . name , kwargs ) , docstring = util . format_string ( self . ...
String substitution for names and docstrings .
32,876
def validate ( self ) : try : if all ( v ( self . measured_value . value ) for v in self . validators ) : self . outcome = Outcome . PASS else : self . outcome = Outcome . FAIL return self except Exception as e : _LOG . error ( 'Validation for measurement %s raised an exception %s.' , self . name , e ) self . outcome =...
Validate this measurement and update its outcome field .
32,877
def as_base_types ( self ) : if not self . _cached : self . _cached = { 'name' : self . name , 'outcome' : self . outcome . name , } if self . validators : self . _cached [ 'validators' ] = data . convert_to_base_types ( tuple ( str ( v ) for v in self . validators ) ) if self . dimensions : self . _cached [ 'dimension...
Convert this measurement to a dict of basic types .
32,878
def to_dataframe ( self , columns = None ) : if not isinstance ( self . measured_value , DimensionedMeasuredValue ) : raise TypeError ( 'Only a dimensioned measurement can be converted to a DataFrame' ) if columns is None : columns = [ d . name for d in self . dimensions ] columns += [ self . units . name if self . uni...
Convert a multi - dim to a pandas dataframe .
32,879
def set ( self , value ) : if self . is_value_set : _LOG . warning ( 'Overriding previous measurement %s value of %s with %s, the old ' 'value will be lost. Use a dimensioned measurement if you need to ' 'save multiple values.' , self . name , self . stored_value , value ) if value is None : _LOG . warning ( 'Measurem...
Set the value for this measurement with some sanity checks .
32,880
def from_string ( cls , string ) : if string in units . UNITS_BY_ALL : return cls ( description = string , unit = units . Unit ( string ) ) else : return cls ( description = string )
Convert a string into a Dimension
32,881
def value ( self ) : if not self . is_value_set : raise MeasurementNotSetError ( 'Measurement not yet set' , self . name ) return [ dimensions + ( value , ) for dimensions , value in six . iteritems ( self . value_dict ) ]
The values stored in this record .
32,882
def to_dataframe ( self , columns = None ) : if not self . is_value_set : raise ValueError ( 'Value must be set before converting to a DataFrame.' ) if not pandas : raise RuntimeError ( 'Install pandas to convert to pandas.DataFrame' ) return pandas . DataFrame . from_records ( self . value , columns = columns )
Converts to a pandas . DataFrame
32,883
def _assert_valid_key ( self , name ) : if name not in self . _measurements : raise NotAMeasurementError ( 'Not a measurement' , name , self . _measurements )
Raises if name is not a valid measurement .
32,884
def install ( self , apk_path , destination_dir = None , timeout_ms = None ) : if not destination_dir : destination_dir = '/data/local/tmp/' basename = os . path . basename ( apk_path ) destination_path = destination_dir + basename self . push ( apk_path , destination_path , timeout_ms = timeout_ms ) return self . Shel...
Install apk to device .
32,885
def push ( self , source_file , device_filename , timeout_ms = None ) : mtime = 0 if isinstance ( source_file , six . string_types ) : mtime = os . path . getmtime ( source_file ) source_file = open ( source_file ) self . filesync_service . send ( source_file , device_filename , mtime = mtime , timeout = timeouts . Pol...
Push source_file to file on device .
32,886
def pull ( self , device_filename , dest_file = None , timeout_ms = None ) : should_return_data = dest_file is None if isinstance ( dest_file , six . string_types ) : dest_file = open ( dest_file , 'w' ) elif dest_file is None : dest_file = six . StringIO ( ) self . filesync_service . recv ( device_filename , dest_file...
Pull file from device .
32,887
def list ( self , device_path , timeout_ms = None ) : return self . filesync_service . list ( device_path , timeouts . PolledTimeout . from_millis ( timeout_ms ) )
Yield filesync_service . DeviceFileStat objects for directory contents .
32,888
def _check_remote_command ( self , destination , timeout_ms , success_msgs = None ) : timeout = timeouts . PolledTimeout . from_millis ( timeout_ms ) stream = self . _adb_connection . open_stream ( destination , timeout ) if not stream : raise usb_exceptions . AdbStreamUnavailableError ( 'Service %s not supported' , de...
Open a stream to destination check for remote errors .
32,889
def send ( query , address = DEFAULT_ADDRESS , port = DEFAULT_PORT , ttl = DEFAULT_TTL , local_only = False , timeout_s = 2 ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) sock . setsockopt ( socket . IPPROTO_IP , socket . IP_MULTICAST_TTL , ttl ) if local_only : sock . setsockopt ( socket . IPPRO...
Sends a query to the given multicast socket and returns responses .
32,890
def run ( self ) : self . _live = True self . _sock . settimeout ( self . LISTEN_TIMEOUT_S ) for interface_ip in ( socket . INADDR_ANY , LOCALHOST_ADDRESS ) : self . _sock . setsockopt ( socket . IPPROTO_IP , socket . IP_ADD_MEMBERSHIP , struct . pack ( '!4sL' , socket . inet_aton ( self . address ) , interface_ip ) ) ...
Listen for pings until stopped .
32,891
def _handle_progress ( self , total , progress_callback ) : current = 0 while True : current += yield try : progress_callback ( current , total ) except Exception : _LOG . exception ( 'Progress callback raised an exception. %s' , progress_callback ) continue
Calls the callback with the current progress and total .
32,892
def _simple_command ( self , command , arg = None , ** kwargs ) : self . _protocol . send_command ( command , arg ) return self . _protocol . handle_simple_responses ( ** kwargs )
Send a simple command .
32,893
def _discover ( ** kwargs ) : query = station_server . MULTICAST_QUERY for host , response in multicast . send ( query , ** kwargs ) : try : result = json . loads ( response ) except ValueError : _LOG . warn ( 'Received bad JSON over multicast from %s: %s' , host , response ) try : yield StationInfo ( result [ 'cell' ]...
Yields info about station servers announcing themselves via multicast .
32,894
def update_stations ( cls , station_info_list ) : with cls . station_map_lock : for host_port , station_info in six . iteritems ( cls . station_map ) : cls . station_map [ host_port ] = station_info . _replace ( status = 'UNREACHABLE' ) for station_info in station_info_list : host_port = '%s:%s' % ( station_info . host...
Called by the station discovery loop to update the station map .
32,895
def publish_if_new ( cls ) : message = cls . make_message ( ) if message != cls . last_message : super ( DashboardPubSub , cls ) . publish ( message ) cls . last_message = message
If the station map has changed publish the new information .
32,896
def run_basic_group ( ) : test = htf . Test ( htf . PhaseGroup ( setup = [ setup_phase ] , main = [ main_phase ] , teardown = [ teardown_phase ] , ) ) test . execute ( )
Run the basic phase group example .
32,897
def run_setup_error_group ( ) : test = htf . Test ( htf . PhaseGroup ( setup = [ error_setup_phase ] , main = [ main_phase ] , teardown = [ teardown_phase ] , ) ) test . execute ( )
Run the phase group example where an error occurs in a setup phase .
32,898
def run_main_error_group ( ) : test = htf . Test ( htf . PhaseGroup ( setup = [ setup_phase ] , main = [ error_main_phase , main_phase ] , teardown = [ teardown_phase ] , ) ) test . execute ( )
Run the phase group example where an error occurs in a main phase .
32,899
def run_nested_groups ( ) : test = htf . Test ( htf . PhaseGroup ( main = [ main_phase , htf . PhaseGroup . with_teardown ( inner_teardown_phase ) ( inner_main_phase ) , ] , teardown = [ teardown_phase ] ) ) test . execute ( )
Run the nested groups example .