idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
28,400
def collect ( self ) : cmd = [ self . config [ 'bin' ] , "list" ] if str_to_bool ( self . config [ 'reset' ] ) : cmd . append ( "reset" ) if str_to_bool ( self . config [ 'use_sudo' ] ) : cmd . insert ( 0 , self . config [ 'sudo_cmd' ] ) matcher = re . compile ( "{ pkts = (.*), bytes = (.*) } = (.*);" ) lines = Popen (...
Collect and publish netfilter counters
28,401
def parse_url ( self , uri ) : parsed = urlparse . urlparse ( uri ) if 'scheme' not in parsed : class Object ( object ) : pass newparsed = Object ( ) newparsed . scheme = parsed [ 0 ] newparsed . netloc = parsed [ 1 ] newparsed . path = parsed [ 2 ] newparsed . params = parsed [ 3 ] newparsed . query = parsed [ 4 ] new...
Convert urlparse from a python 2 . 4 layout to a python 2 . 7 layout
28,402
def sanitize_word ( s ) : s = re . sub ( '[^\w-]+' , '_' , s ) s = re . sub ( '__+' , '_' , s ) return s . strip ( '_' )
Remove non - alphanumerical characters from metric word . And trim excessive underscores .
28,403
def _add_cpu_usage ( self , cur_read ) : for executor_id , cur_data in cur_read . items ( ) : if executor_id in self . executors_prev_read : prev_data = self . executors_prev_read [ executor_id ] prev_stats = prev_data [ 'statistics' ] cur_stats = cur_data [ 'statistics' ] cpus_time_diff_s = cur_stats [ 'cpus_user_time...
Compute cpu usage based on cpu time spent compared to elapsed time
28,404
def _add_cpu_percent ( self , cur_read ) : for executor_id , cur_data in cur_read . items ( ) : stats = cur_data [ 'statistics' ] cpus_limit = stats . get ( 'cpus_limit' ) cpus_utilisation = stats . get ( 'cpus_utilisation' ) if cpus_utilisation and cpus_limit != 0 : stats [ 'cpus_percent' ] = cpus_utilisation / cpus_l...
Compute cpu percent basing on the provided utilisation
28,405
def _add_mem_percent ( self , cur_read ) : for executor_id , cur_data in cur_read . items ( ) : stats = cur_data [ 'statistics' ] mem_rss_bytes = stats . get ( 'mem_rss_bytes' ) mem_limit_bytes = stats . get ( 'mem_limit_bytes' ) if mem_rss_bytes and mem_limit_bytes != 0 : stats [ 'mem_percent' ] = mem_rss_bytes / floa...
Compute memory percent utilisation based on the mem_rss_bytes and mem_limit_bytes
28,406
def _group_and_publish_tasks_statistics ( self , result ) : for i in result : executor_id = i [ 'executor_id' ] i [ 'executor_id' ] = executor_id [ : executor_id . rfind ( '.' ) ] i [ 'statistics' ] [ 'instances_count' ] = 1 r = { } for i in result : executor_id = i [ 'executor_id' ] r [ executor_id ] = r . get ( execu...
This function group statistics of same tasks by adding them . It also add instances_count statistic to get information about how many instances is running on the server
28,407
def _get ( self , path ) : url = self . _get_url ( path ) try : response = urllib2 . urlopen ( url ) except Exception as err : self . log . error ( "%s: %s" , url , err ) return False try : doc = json . load ( response ) except ( TypeError , ValueError ) : self . log . error ( "Unable to parse response from Mesos as a"...
Execute a Mesos API call .
28,408
def get_default_config_help ( self ) : config_help = super ( PostgresqlCollector , self ) . get_default_config_help ( ) config_help . update ( { 'host' : 'Hostname' , 'dbname' : 'DB to connect to in order to get list of DBs in PgSQL' , 'user' : 'Username' , 'password' : 'Password' , 'port' : 'Port number' , 'password_p...
Return help text for collector
28,409
def collect ( self ) : if psycopg2 is None : self . log . error ( 'Unable to import module psycopg2' ) return { } dbs = self . _get_db_names ( ) if len ( dbs ) == 0 : self . log . error ( "I have 0 databases!" ) return { } if self . config [ 'metrics' ] : metrics = self . config [ 'metrics' ] elif str_to_bool ( self . ...
Do pre - flight checks get list of db names collect metrics publish
28,410
def _get_db_names ( self ) : query = conn = self . _connect ( self . config [ 'dbname' ] ) cursor = conn . cursor ( cursor_factory = psycopg2 . extras . DictCursor ) cursor . execute ( query ) datnames = [ d [ 'datname' ] for d in cursor . fetchall ( ) ] conn . close ( ) if not datnames : datnames = [ 'postgres' ] retu...
Try to get a list of db names
28,411
def _connect ( self , database = None ) : conn_args = { 'host' : self . config [ 'host' ] , 'user' : self . config [ 'user' ] , 'password' : self . config [ 'password' ] , 'port' : self . config [ 'port' ] , 'sslmode' : self . config [ 'sslmode' ] , } if database : conn_args [ 'database' ] = database else : conn_args [...
Connect to given database
28,412
def get_string_index_oid ( self , s ) : return ( len ( self . get_bytes ( s ) ) , ) + self . get_bytes ( s )
Turns a string into an oid format is length of name followed by name chars in ascii
28,413
def collect_snmp ( self , device , host , port , community ) : timestamp = time . time ( ) for k , v in self . IODRIVE_STATS . items ( ) : metricName = '.' . join ( [ k ] ) metricValue = int ( self . get ( v , host , port , community ) [ v ] ) metricPath = '.' . join ( [ 'servers' , host , device , metricName ] ) metri...
Collect Fusion IO Drive SNMP stats from device host and device are from the conf file . In the future device should be changed to be what IODRive device it being checked . i . e . fioa fiob .
28,414
def _send_data ( self , data ) : try : self . socket . sendall ( data ) self . _reset_errors ( ) except : self . _close ( ) self . _throttle_error ( "GraphiteHandler: Socket error, " "trying reconnect." ) self . _connect ( ) try : self . socket . sendall ( data ) except : return self . _reset_errors ( )
Try to send all data in buffer .
28,415
def _send ( self ) : try : try : if self . socket is None : self . log . debug ( "GraphiteHandler: Socket is not connected. " "Reconnecting." ) self . _connect ( ) if self . socket is None : self . log . debug ( "GraphiteHandler: Reconnect failed." ) else : self . _send_data ( '' . join ( self . metrics ) ) self . metr...
Send data to graphite . Data that can not be sent will be queued .
28,416
def _connect ( self ) : if ( self . proto == 'udp' ) : stream = socket . SOCK_DGRAM else : stream = socket . SOCK_STREAM if ( self . proto [ - 1 ] == '4' ) : family = socket . AF_INET connection_struct = ( self . host , self . port ) elif ( self . proto [ - 1 ] == '6' ) : family = socket . AF_INET6 connection_struct = ...
Connect to the graphite server
28,417
def process ( self , metric ) : self . log . debug ( "Metric: %s" , str ( metric ) . rstrip ( ) . replace ( ' ' , '\t' ) )
Process a metric by doing nothing
28,418
def load_config ( self , configfile = None , override_config = None ) : self . config = configobj . ConfigObj ( ) if self . get_default_config ( ) is not None : self . config . merge ( self . get_default_config ( ) ) if configfile is not None : self . configfile = os . path . abspath ( configfile ) if self . configfile...
Process a configfile or reload if previously given one .
28,419
def process_config ( self ) : if 'byte_unit' in self . config : if isinstance ( self . config [ 'byte_unit' ] , basestring ) : self . config [ 'byte_unit' ] = self . config [ 'byte_unit' ] . split ( ) if 'enabled' in self . config : self . config [ 'enabled' ] = str_to_bool ( self . config [ 'enabled' ] ) if 'measure_c...
Intended to put any code that should be run after any config reload event
28,420
def get_metric_path ( self , name , instance = None ) : if 'path' in self . config : path = self . config [ 'path' ] else : path = self . __class__ . __name__ if instance is not None : if 'instance_prefix' in self . config : prefix = self . config [ 'instance_prefix' ] else : prefix = 'instances' if path == '.' : retur...
Get metric path . Instance indicates that this is a metric for a virtual machine and should have a different root prefix .
28,421
def publish ( self , name , value , raw_value = None , precision = 0 , metric_type = 'GAUGE' , instance = None ) : if self . config [ 'metrics_whitelist' ] : if not self . config [ 'metrics_whitelist' ] . match ( name ) : return elif self . config [ 'metrics_blacklist' ] : if self . config [ 'metrics_blacklist' ] . mat...
Publish a metric with the given name
28,422
def derivative ( self , name , new , max_value = 0 , time_delta = True , interval = None , allow_negative = False , instance = None ) : path = self . get_metric_path ( name , instance = instance ) if path in self . last_values : old = self . last_values [ path ] if new < old : old = old - max_value derivative_x = new -...
Calculate the derivative of the metric .
28,423
def _run ( self ) : try : start_time = time . time ( ) self . collect ( ) end_time = time . time ( ) collector_time = int ( ( end_time - start_time ) * 1000 ) self . log . debug ( 'Collection took %s ms' , collector_time ) if 'measure_collector_time' in self . config : if self . config [ 'measure_collector_time' ] : me...
Run the collector unless it s already running
28,424
def find_binary ( self , binary ) : if os . path . exists ( binary ) : return binary binary_name = os . path . basename ( binary ) search_paths = os . environ [ 'PATH' ] . split ( ':' ) default_paths = [ '/usr/bin' , '/bin' '/usr/local/bin' , '/usr/sbin' , '/sbin' '/usr/local/sbin' , ] for path in default_paths : if pa...
Scan and return the first path to a binary that we can find
28,425
def parse_slab_stats ( slab_stats ) : stats_dict = { 'slabs' : defaultdict ( lambda : { } ) } for line in slab_stats . splitlines ( ) : if line == 'END' : break cmd , key , value = line . split ( ' ' ) if cmd != 'STAT' : continue if ":" not in key : stats_dict [ key ] = int ( value ) continue slab , key = key . split (...
Convert output from memcached s stats slabs into a Python dict .
28,426
def dict_to_paths ( dict_ ) : metrics = { } for k , v in dict_ . iteritems ( ) : if isinstance ( v , dict ) : submetrics = dict_to_paths ( v ) for subk , subv in submetrics . iteritems ( ) : metrics [ '.' . join ( [ str ( k ) , str ( subk ) ] ) ] = subv else : metrics [ k ] = v return metrics
Convert a dict to metric paths .
28,427
def get_slab_stats ( self ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . connect ( ( self . host , self . port ) ) s . send ( "stats slabs\n" ) try : data = "" while True : data += s . recv ( 4096 ) if data . endswith ( 'END\r\n' ) : break return data finally : s . close ( )
Retrieve slab stats from memcached .
28,428
def push ( self , metric_name = None , metric_value = None , volume = None ) : graphite_path = self . path_prefix graphite_path += '.' + self . device + '.' + 'volume' graphite_path += '.' + volume + '.' + metric_name metric = Metric ( graphite_path , metric_value , precision = 4 , host = self . device ) self . publish...
Ship that shit off to graphite broski
28,429
def get_netapp_data ( self ) : netapp_data = self . server . invoke ( 'volume-list-info' ) if netapp_data . results_status ( ) == 'failed' : self . log . error ( 'While using netapp API failed to retrieve ' 'volume-list-info for netapp filer %s' % self . device ) return netapp_xml = ET . fromstring ( netapp_data . spri...
Retrieve netapp volume information
28,430
def verbose_message ( self ) : if self . threshold is None : return 'No threshold' return '%.1f is %s than %.1f' % ( self . value , self . adjective , self . threshold )
return more complete message
28,431
def process ( self , metric , handler ) : match = self . regexp . match ( metric . path ) if match : minimum = Minimum ( metric . value , self . min ) maximum = Maximum ( metric . value , self . max ) if minimum . is_error or maximum . is_error : self . counter_errors += 1 message = "%s Warning on %s: %.1f" % ( self . ...
process a single diamond metric
28,432
def compile_rules ( self ) : output = [ ] for key_name , section in self . config . items ( ) : rule = self . compile_section ( section ) if rule is not None : output . append ( rule ) return output
Compile alert rules
28,433
def compile_section ( self , section ) : if section . __class__ != Section : return keys = section . keys ( ) for key in ( 'name' , 'path' ) : if key not in keys : self . log . warning ( "section %s miss key '%s' ignore" , key , section . name ) return for key in keys : if key not in self . VALID_RULES_KEYS : self . lo...
Validate if a section is a valid rule
28,434
def configure_sentry_errors ( self ) : sentry_errors_logger = logging . getLogger ( 'sentry.errors' ) root_logger = logging . getLogger ( ) for handler in root_logger . handlers : sentry_errors_logger . addHandler ( handler )
Configure sentry . errors to use the same loggers as the root handler
28,435
def process ( self , metric ) : for rule in self . rules : rule . process ( metric , self )
process a single metric
28,436
def collect ( self ) : results = { } if os . access ( self . PROC , os . R_OK ) : file = open ( self . PROC ) greed = '' if str_to_bool ( self . config [ 'greedy' ] ) : greed = '\S*' exp = ( ( '^(?:\s*)((?:%s)%s):(?:\s*)' + '(?P<rx_bytes>\d+)(?:\s*)' + '(?P<rx_packets>\w+)(?:\s*)' + '(?P<rx_errors>\d+)(?:\s*)' + '(?P<r...
Collect network interface stats .
28,437
def get_default_config_help ( self ) : config_help = super ( ConnTrackCollector , self ) . get_default_config_help ( ) config_help . update ( { "dir" : "Directories with files of interest, comma seperated" , "files" : "List of files to collect statistics from" , } ) return config_help
Return help text for collector configuration
28,438
def _replace_and_publish ( self , path , prettyname , value , device ) : if value is None : return newpath = path newpath = "." . join ( [ "." . join ( path . split ( "." ) [ : - 1 ] ) , prettyname ] ) metric = Metric ( newpath , value , precision = 4 , host = device ) self . publish_metric ( metric )
Inputs a complete path for a metric and a value . Replace the metric name and publish .
28,439
def _gen_delta_depend ( self , path , derivative , multiplier , prettyname , device ) : primary_delta = derivative [ path ] shortpath = "." . join ( path . split ( "." ) [ : - 1 ] ) basename = path . split ( "." ) [ - 1 ] secondary_delta = None if basename in self . DIVIDERS . keys ( ) : mateKey = "." . join ( [ shortp...
For some metrics we need to divide the delta for one metric with the delta of another . Publishes a metric if the convertion goes well .
28,440
def _gen_delta_per_sec ( self , path , value_delta , time_delta , multiplier , prettyname , device ) : if time_delta < 0 : return value = ( value_delta / time_delta ) * multiplier if value > 0.0 : self . _replace_and_publish ( path , prettyname , value , device )
Calulates the difference between to point and scales is to per second .
28,441
def _send ( self ) : while len ( self . queue ) > 0 : metric = self . queue . popleft ( ) path = '%s.%s.%s' % ( metric . getPathPrefix ( ) , metric . getCollectorPath ( ) , metric . getMetricPath ( ) ) topic , value , timestamp = str ( metric ) . split ( ) logging . debug ( "Sending.. topic[%s], value[%s], timestamp[%s...
Take metrics from queue and send it to Datadog API
28,442
def get_version ( ) : try : f = open ( 'version.txt' ) except IOError : os . system ( "./version.sh > version.txt" ) f = open ( 'version.txt' ) version = '' . join ( f . readlines ( ) ) . rstrip ( ) f . close ( ) return version
Read the version . txt file to get the new version string Generate it if version . txt is not available . Generation is required for pip installs
28,443
def pkgPath ( root , path , rpath = "/" ) : global data_files if not os . path . exists ( path ) : return files = [ ] for spath in os . listdir ( path ) : if spath == 'test' : continue subpath = os . path . join ( path , spath ) spath = os . path . join ( rpath , spath ) if os . path . isfile ( subpath ) : files . appe...
Package up a path recursively
28,444
def _send ( self , data ) : retry = self . RETRY while retry > 0 : if not self . socket : self . log . error ( "StatsiteHandler: Socket unavailable." ) self . _connect ( ) retry -= 1 continue try : data = data . split ( ) data = data [ 0 ] + ":" + data [ 1 ] + "|kv\n" self . socket . sendall ( data ) break except socke...
Send data to statsite . Data that can not be sent will be queued .
28,445
def _connect ( self ) : if self . udpport > 0 : self . socket = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) self . port = self . udpport elif self . tcpport > 0 : self . socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) self . port = self . tcpport if socket is None : self . log . erro...
Connect to the statsite server
28,446
def load_include_path ( paths ) : for path in paths : if not os . path . isdir ( path ) : continue if path not in sys . path : sys . path . insert ( 1 , path ) for f in os . listdir ( path ) : fpath = os . path . join ( path , f ) if os . path . isdir ( fpath ) : load_include_path ( [ fpath ] )
Scan for and add paths to the include path
28,447
def load_dynamic_class ( fqn , subclass ) : if not isinstance ( fqn , basestring ) : return fqn cls = load_class_from_name ( fqn ) if cls == subclass or not issubclass ( cls , subclass ) : raise TypeError ( "%s is not a valid %s" % ( fqn , subclass . __name__ ) ) return cls
Dynamically load fqn class and verify it s a subclass of subclass
28,448
def load_collectors_from_paths ( paths ) : collectors = { } if paths is None : return if isinstance ( paths , basestring ) : paths = paths . split ( ',' ) paths = map ( str . strip , paths ) load_include_path ( paths ) for path in paths : if not os . path . exists ( path ) : raise OSError ( "Directory does not exist: %...
Scan for collectors to load from path
28,449
def load_collectors_from_entry_point ( path ) : collectors = { } for ep in pkg_resources . iter_entry_points ( path ) : try : mod = ep . load ( ) except Exception : logger . error ( 'Failed to import entry_point: %s. %s' , ep . name , traceback . format_exc ( ) ) else : collectors . update ( get_collectors_from_module ...
Load collectors that were installed into an entry_point .
28,450
def get_collectors_from_module ( mod ) : for attrname in dir ( mod ) : attr = getattr ( mod , attrname ) if ( ( inspect . isclass ( attr ) and issubclass ( attr , Collector ) and attr != Collector ) ) : if attrname . startswith ( 'parent_' ) : continue fqcn = '.' . join ( [ mod . __name__ , attrname ] ) try : cls = loa...
Locate all of the collector classes within a given module
28,451
def _send ( self , data ) : data = data . strip ( ) . split ( ' ' ) try : cursor = self . conn . cursor ( ) cursor . execute ( "INSERT INTO %s (%s, %s, %s) VALUES(%%s, %%s, %%s)" % ( self . table , self . col_metric , self . col_time , self . col_value ) , ( data [ 0 ] , data [ 2 ] , data [ 1 ] ) ) cursor . close ( ) s...
Insert the data
28,452
def _connect ( self ) : self . _close ( ) self . conn = MySQLdb . Connect ( host = self . hostname , port = self . port , user = self . username , passwd = self . password , db = self . database )
Connect to the MySQL server
28,453
def collect ( self ) : stats_config = self . config [ 'stats' ] if USE_PYTHON_BINDING : collect_metrics = self . collect_via_pynvml else : collect_metrics = self . collect_via_nvidia_smi collect_metrics ( stats_config )
Collector GPU stats
28,454
def decode_network_values ( ptype , plen , buf ) : nvalues = short . unpack_from ( buf , header . size ) [ 0 ] off = header . size + short . size + nvalues valskip = double . size assert ( ( valskip + 1 ) * nvalues + short . size + header . size ) == plen assert double . size == number . size result = [ ] for dstype in...
Decodes a list of DS values in collectd network format
28,455
def decode_network_packet ( buf ) : off = 0 blen = len ( buf ) while off < blen : ptype , plen = header . unpack_from ( buf , off ) if plen > blen - off : raise ValueError ( "Packet longer than amount of data in buffer" ) if ptype not in _decoders : raise ValueError ( "Message type %i not recognized" % ptype ) yield pt...
Decodes a network packet in collectd format .
28,456
def receive ( self , poll_interval ) : readable , writeable , errored = select . select ( self . _readlist , [ ] , [ ] , poll_interval ) for s in readable : data , addr = s . recvfrom ( self . BUFFER_SIZE ) if data : return data return None
Receives a single raw collect network packet .
28,457
def decode ( self , poll_interval , buf = None ) : if buf is None : buf = self . receive ( poll_interval ) if buf is None : return None return decode_network_packet ( buf )
Decodes a given buffer or the next received packet .
28,458
def interpret ( self , iterable = None , poll_interval = 0.2 ) : if iterable is None : iterable = self . decode ( poll_interval ) if iterable is None : return None if isinstance ( iterable , basestring ) : iterable = self . decode ( poll_interval , iterable ) return interpret_opcodes ( iterable )
Interprets a sequence
28,459
def make_device_handler ( device_params ) : if device_params is None : device_params = { } handler = device_params . get ( 'handler' , None ) if handler : return handler ( device_params ) device_name = device_params . get ( "name" , "default" ) class_name = "%sDeviceHandler" % device_name . capitalize ( ) devices_modul...
Create a device handler object that provides device specific parameters and functions which are called in various places throughout our code .
28,460
def take_notification ( self , block = True , timeout = None ) : return self . _session . take_notification ( block , timeout )
Attempt to retrieve one notification from the queue of received notifications .
28,461
def request ( self , cmds ) : if isinstance ( cmds , list ) : cmd = '\n' . join ( cmds ) elif isinstance ( cmds , str ) or isinstance ( cmds , unicode ) : cmd = cmds node = etree . Element ( qualify ( 'CLI' , BASE_NS_1_0 ) ) etree . SubElement ( node , qualify ( 'Execution' , BASE_NS_1_0 ) ) . text = cmd return self . ...
Single Execution element is permitted . cmds can be a list or single command
28,462
def validated_element ( x , tags = None , attrs = None ) : ele = to_ele ( x ) if tags : if isinstance ( tags , ( str , bytes ) ) : tags = [ tags ] if ele . tag not in tags : raise XMLError ( "Element [%s] does not meet requirement" % ele . tag ) if attrs : for req in attrs : if isinstance ( req , ( str , bytes ) ) : re...
Checks if the root element of an XML document or Element meets the supplied criteria .
28,463
def tostring ( self ) : parser = etree . XMLParser ( remove_blank_text = True ) outputtree = etree . XML ( etree . tostring ( self . __doc ) , parser ) return etree . tostring ( outputtree , pretty_print = True )
return a pretty - printed string output for rpc reply
28,464
def remove_namespaces ( self , rpc_reply ) : self . __xslt = self . __transform_reply self . __parser = etree . XMLParser ( remove_blank_text = True ) self . __xslt_doc = etree . parse ( io . BytesIO ( self . __xslt ) , self . __parser ) self . __transform = etree . XSLT ( self . __xslt_doc ) self . __root = etree . fr...
remove xmlns attributes from rpc reply
28,465
def request ( self , identifier , version = None , format = None ) : node = etree . Element ( qualify ( "get-schema" , NETCONF_MONITORING_NS ) ) if identifier is not None : elem = etree . Element ( qualify ( "identifier" , NETCONF_MONITORING_NS ) ) elem . text = identifier node . append ( elem ) if version is not None ...
Retrieve a named schema with optional revision and type .
28,466
def is_rpc_error_exempt ( self , error_text ) : if error_text is not None : error_text = error_text . lower ( ) . strip ( ) else : error_text = 'no error given' for ex in self . _exempt_errors_exact_match : if error_text == ex : return True for ex in self . _exempt_errors_startwith_wildcard_match : if error_text . ends...
Check whether an RPC error message is excempt thus NOT causing an exception .
28,467
def get_ssh_subsystem_names ( self ) : preferred_ssh_subsystem = self . device_params . get ( "ssh_subsystem_name" ) name_list = [ "netconf" , "xmlagent" ] if preferred_ssh_subsystem : return [ preferred_ssh_subsystem ] + [ n for n in name_list if n != preferred_ssh_subsystem ] else : return name_list
Return a list of possible SSH subsystem names .
28,468
def add_listener ( self , listener ) : self . logger . debug ( 'installing listener %r' , listener ) if not isinstance ( listener , SessionListener ) : raise SessionError ( "Listener must be a SessionListener type" ) with self . _lock : self . _listeners . add ( listener )
Register a listener that will be notified of incoming messages and errors .
28,469
def remove_listener ( self , listener ) : self . logger . debug ( 'discarding listener %r' , listener ) with self . _lock : self . _listeners . discard ( listener )
Unregister some listener ; ignore if the listener was never registered .
28,470
def get_listener_instance ( self , cls ) : with self . _lock : for listener in self . _listeners : if isinstance ( listener , cls ) : return listener
If a listener of the specified type is registered returns the instance .
28,471
def request ( self , filter = None , stream_name = None , start_time = None , stop_time = None ) : node = new_ele_ns ( "create-subscription" , NETCONF_NOTIFICATION_NS ) if filter is not None : node . append ( util . build_filter ( filter ) ) if stream_name is not None : sub_ele ( node , "stream" ) . text = stream_name ...
Creates a subscription for notifications from the server .
28,472
def request ( self , target ) : node = new_ele ( "delete-config" ) node . append ( util . datastore_or_url ( "target" , target , self . _assert ) ) return self . _request ( node )
Delete a configuration datastore .
28,473
def request ( self , source , target ) : node = new_ele ( "copy-config" ) node . append ( util . datastore_or_url ( "target" , target , self . _assert ) ) try : node . append ( util . datastore_or_url ( "source" , source , self . _assert ) ) except Exception : node . append ( validated_element ( source , ( "source" , q...
Create or replace an entire configuration datastore with the contents of another complete configuration datastore .
28,474
def request ( self , source = "candidate" ) : node = new_ele ( "validate" ) if type ( source ) is str : src = util . datastore_or_url ( "source" , source , self . _assert ) else : validated_element ( source , ( "config" , qualify ( "config" ) ) ) src = new_ele ( "source" ) src . append ( source ) node . append ( src ) ...
Validate the contents of the specified configuration .
28,475
def request ( self , target = "candidate" ) : node = new_ele ( "lock" ) sub_ele ( sub_ele ( node , "target" ) , target ) return self . _request ( node )
Allows the client to lock the configuration system of a device .
28,476
def _parse10 ( self ) : self . logger . debug ( "parsing netconf v1.0" ) buf = self . _buffer buf . seek ( self . _parsing_pos10 ) if MSG_DELIM in buf . read ( ) . decode ( 'UTF-8' ) : buf . seek ( 0 ) msg , _ , remaining = buf . read ( ) . decode ( 'UTF-8' ) . partition ( MSG_DELIM ) msg = msg . strip ( ) if sys . ver...
Messages are delimited by MSG_DELIM . The buffer could have grown by a maximum of BUF_SIZE bytes everytime this method is called . Retains state across method calls and if a chunk has been read it will not be considered again .
28,477
def one_of ( * args ) : "Verifies that only one of the arguments is not None" for i , arg in enumerate ( args ) : if arg is not None : for argh in args [ i + 1 : ] : if argh is not None : raise OperationError ( "Too many parameters" ) else : return raise OperationError ( "Insufficient parameters" )
Verifies that only one of the arguments is not None
28,478
def _get_scale_and_shape ( self , transformed_lvs ) : if self . scale is True : if self . shape is True : model_shape = transformed_lvs [ - 1 ] model_scale = transformed_lvs [ - 2 ] else : model_shape = 0 model_scale = transformed_lvs [ - 1 ] else : model_scale = 0 model_shape = 0 if self . skewness is True : model_ske...
Obtains model scale shape and skewness latent variables
28,479
def _get_scale_and_shape_sim ( self , transformed_lvs ) : if self . scale is True : if self . shape is True : model_shape = self . latent_variables . z_list [ - 1 ] . prior . transform ( transformed_lvs [ - 1 , : ] ) model_scale = self . latent_variables . z_list [ - 2 ] . prior . transform ( transformed_lvs [ - 2 , : ...
Obtains model scale shape skewness latent variables for a 2d array of simulations .
28,480
def _summarize_simulations ( self , mean_values , sim_vector , date_index , h , past_values ) : error_bars = [ ] for pre in range ( 5 , 100 , 5 ) : error_bars . append ( np . insert ( [ np . percentile ( i , pre ) for i in sim_vector ] , 0 , mean_values [ - h - 1 ] ) ) if self . latent_variables . estimation_method in ...
Produces forecasted values to plot along with prediction intervals
28,481
def normal_neg_loglik ( self , beta ) : mu , Y = self . _model ( beta ) return - np . sum ( ss . norm . logpdf ( Y , loc = mu , scale = self . latent_variables . z_list [ - 1 ] . prior . transform ( beta [ - 1 ] ) ) )
Calculates the negative log - likelihood of the model for Normal family
28,482
def normal_mb_neg_loglik ( self , beta , mini_batch ) : mu , Y = self . _mb_model ( beta , mini_batch ) return - np . sum ( ss . norm . logpdf ( Y , loc = mu , scale = self . latent_variables . z_list [ - 1 ] . prior . transform ( beta [ - 1 ] ) ) )
Calculates the negative log - likelihood of the Normal model for a minibatch
28,483
def draw_variable ( loc , scale , shape , skewness , nsims ) : return loc + scale * Skewt . rvs ( shape , skewness , nsims )
Draws random variables from Skew t distribution
28,484
def first_order_score ( y , mean , scale , shape , skewness ) : m1 = ( np . sqrt ( shape ) * sp . gamma ( ( shape - 1.0 ) / 2.0 ) ) / ( np . sqrt ( np . pi ) * sp . gamma ( shape / 2.0 ) ) mean = mean + ( skewness - ( 1.0 / skewness ) ) * scale * m1 if ( y - mean ) >= 0 : return ( ( shape + 1 ) / shape ) * ( y - mean )...
GAS Skew t Update term using gradient only - native Python function
28,485
def rvs ( df , gamma , n ) : if type ( n ) == list : u = np . random . uniform ( size = n [ 0 ] * n [ 1 ] ) result = Skewt . ppf ( q = u , df = df , gamma = gamma ) result = np . split ( result , n [ 0 ] ) return np . array ( result ) else : u = np . random . uniform ( size = n ) if isinstance ( df , np . ndarray ) or ...
Generates random variables from a Skew t distribution
28,486
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return self . logpdf_internal_prior ( mu , df = self . df0 , loc = self . loc0 , scale = self . scale0 , gamma = self . gamma0 )
Log PDF for Skew t prior
28,487
def markov_blanket ( y , mean , scale , shape , skewness ) : m1 = ( np . sqrt ( shape ) * sp . gamma ( ( shape - 1.0 ) / 2.0 ) ) / ( np . sqrt ( np . pi ) * sp . gamma ( shape / 2.0 ) ) mean = mean + ( skewness - ( 1.0 / skewness ) ) * scale * m1 return Skewt . logpdf_internal ( x = y , df = shape , loc = mean , gamma ...
Markov blanket for each likelihood term
28,488
def pdf_internal ( x , df , loc = 0.0 , scale = 1.0 , gamma = 1.0 ) : result = np . zeros ( x . shape [ 0 ] ) result [ x < 0 ] = 2.0 / ( gamma + 1.0 / gamma ) * stats . t . pdf ( x = gamma * x [ ( x - loc ) < 0 ] , loc = loc [ ( x - loc ) < 0 ] * gamma , df = df , scale = scale ) result [ x >= 0 ] = 2.0 / ( gamma + 1.0...
Raw PDF function for the Skew t distribution
28,489
def pdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return self . pdf_internal ( mu , df = self . df0 , loc = self . loc0 , scale = self . scale0 , gamma = self . gamma0 )
PDF for Skew t prior
28,490
def cdf ( x , df , loc = 0.0 , scale = 1.0 , gamma = 1.0 ) : result = np . zeros ( x . shape [ 0 ] ) result [ x < 0 ] = 2.0 / ( np . power ( gamma , 2 ) + 1.0 ) * ss . t . cdf ( gamma * ( x [ x - loc < 0 ] - loc [ x - loc < 0 ] ) / scale , df = df ) result [ x >= 0 ] = 1.0 / ( np . power ( gamma , 2 ) + 1.0 ) + 2.0 / (...
CDF function for Skew t distribution
28,491
def ppf ( q , df , loc = 0.0 , scale = 1.0 , gamma = 1.0 ) : result = np . zeros ( q . shape [ 0 ] ) probzero = Skewt . cdf ( x = np . zeros ( 1 ) , loc = np . zeros ( 1 ) , df = df , gamma = gamma ) result [ q < probzero ] = 1.0 / gamma * ss . t . ppf ( ( ( np . power ( gamma , 2 ) + 1.0 ) * q [ q < probzero ] ) / 2.0...
PPF function for Skew t distribution
28,492
def transform_define ( transform ) : if transform == 'tanh' : return np . tanh elif transform == 'exp' : return np . exp elif transform == 'logit' : return Family . ilogit elif transform is None : return np . array else : return None
This function links the user s choice of transformation with the associated numpy function
28,493
def itransform_define ( transform ) : if transform == 'tanh' : return np . arctanh elif transform == 'exp' : return np . log elif transform == 'logit' : return Family . logit elif transform is None : return np . array else : return None
This function links the user s choice of transformation with its inverse
28,494
def _L ( self , parm ) : return np . linalg . cholesky ( self . kernel . K ( parm ) + np . identity ( self . X ( ) . shape [ 1 ] ) * parm [ 0 ] )
Creates cholesky decomposition of covariance matrix
28,495
def plot_fit ( self , intervals = True , ** kwargs ) : import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) date_index = self . index [ self . max_lag : ] expectation = self . expected_values ( self . latent_variables . get_z_values ( ) ) variance = self . variance_v...
Plots the fit of the Gaussian process model to the data
28,496
def _get_scale_and_shape ( self , parm ) : if self . scale is True : if self . shape is True : model_shape = parm [ - 1 ] model_scale = parm [ - 2 ] else : model_shape = 0 model_scale = parm [ - 1 ] else : model_scale = 0 model_shape = 0 if self . skewness is True : model_skewness = parm [ - 3 ] else : model_skewness =...
Obtains appropriate model scale and shape latent variables
28,497
def plot_sample ( self , nsims = 10 , plot_data = True , ** kwargs ) : if self . latent_variables . estimation_method not in [ 'BBVI' , 'M-H' ] : raise Exception ( "No latent variables estimated!" ) else : import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) plt . fi...
Plots draws from the posterior predictive density against the data
28,498
def _ar_matrix ( self ) : X = np . ones ( self . data_length - self . max_lag ) if self . ar != 0 : for i in range ( 0 , self . ar ) : X = np . vstack ( ( X , self . data [ ( self . max_lag - i - 1 ) : - i - 1 ] ) ) return X
Creates the Autoregressive matrix for the model
28,499
def logpdf ( self , X ) : return invwishart . logpdf ( X , df = self . v , scale = self . Psi )
Log PDF for Inverse Wishart prior