INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return a list of all the tags in the git repo matching a regex passed in pattern. If pattern is None return all the tags.
def git_tag_list(pattern=None): """ Return a list of all the tags in the git repo matching a regex passed in `pattern`. If `pattern` is None, return all the tags. """ with chdir(get_root()): result = run_command('git tag', capture=True).stdout result = result.splitlines() if not...
Return a boolean value for whether the given file is tracked by git.
def git_ls_files(filename): """ Return a boolean value for whether the given file is tracked by git. """ with chdir(get_root()): # https://stackoverflow.com/a/2406813 result = run_command('git ls-files --error-unmatch {}'.format(filename), capture=True) return result.code == 0
When handling non english versions the counters don t work quite as documented. This is because strings like Bytes Sent/ sec might appear multiple times in the english master and might not have mappings for each index.
def _make_counter_path(self, machine_name, counter_name, instance_name, counters): """ When handling non english versions, the counters don't work quite as documented. This is because strings like "Bytes Sent/sec" might appear multiple times in the english master, and might not have mapp...
Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps
def gauge(self, *args, **kwargs): """ Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps """ orig_gauge = super(Nagios, self).gauge # remove 'timestamp' arg if the base class' gauge function does not accept a 'timestamp' arg if 'times...
Parse until the end of each tailer associated with this instance. We match instance and tailers based on the path to the Nagios configuration file
def check(self, instance): """ Parse until the end of each tailer associated with this instance. We match instance and tailers based on the path to the Nagios configuration file Special case: Compatibility with the old conf when no conf file is specified but the path to the even...
Actual nagios parsing Return True if we found an event False otherwise
def _parse_line(self, line): """ Actual nagios parsing Return True if we found an event, False otherwise """ # first isolate the timestamp and the event type try: self._line_parsed = self._line_parsed + 1 m = RE_LINE_REG.match(line) if...
Factory method called by the parsers
def create_event(self, timestamp, event_type, hostname, fields, tags=None): """Factory method called by the parsers """ # Agent6 expects a specific set of fields, so we need to place all # extra fields in the msg_title and let the Datadog backend separate them # Any remaining fie...
Create a command generator to perform all the snmp query. If mibs_path is not None load the mibs present in the custom mibs folder. ( Need to be in pysnmp format )
def create_snmp_engine(self, mibs_path): ''' Create a command generator to perform all the snmp query. If mibs_path is not None, load the mibs present in the custom mibs folder. (Need to be in pysnmp format) ''' snmp_engine = hlapi.SnmpEngine() mib_builder = snmp_...
Generate a Security Parameters object based on the instance s configuration. See http:// pysnmp. sourceforge. net/ docs/ current/ security - configuration. html
def get_auth_data(cls, instance): ''' Generate a Security Parameters object based on the instance's configuration. See http://pysnmp.sourceforge.net/docs/current/security-configuration.html ''' if "community_string" in instance: # SNMP v1 - SNMP v2 ...
Generate a Context Parameters object based on the instance s configuration. We do not use the hlapi currently but the rfc3413. oneliner. cmdgen accepts Context Engine Id ( always None for now ) and Context Name parameters.
def get_context_data(cls, instance): ''' Generate a Context Parameters object based on the instance's configuration. We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen accepts Context Engine Id (always None for now) and Context Name parameters. ''' ...
Generate a Transport target object based on the instance s configuration
def get_transport_target(cls, instance, timeout, retries): ''' Generate a Transport target object based on the instance's configuration ''' if "ip_address" not in instance: raise Exception("An IP address needs to be specified") ip_address = instance["ip_address"] ...
Perform a snmpwalk on the domain specified by the oids on the device configured in instance. lookup_names is a boolean to specify whether or not to use the mibs to resolve the name and values.
def check_table( self, instance, snmp_engine, mib_view_controller, oids, lookup_names, timeout, retries, enforce_constraints=False, mibs_to_load=None, ): ''' Perform a snmpwalk on the domain specified by the oids, on the...
Perform two series of SNMP requests one for all that have MIB asociated and should be looked up and one for those specified by oids
def _check(self, instance): ''' Perform two series of SNMP requests, one for all that have MIB asociated and should be looked up and one for those specified by oids ''' ( snmp_engine, mib_view_controller, ip_address, tags, ...
For all the metrics that are specified as oid the conf oid is going to exactly match or be a prefix of the oid sent back by the device Use the instance configuration to find the name to give to the metric
def report_raw_metrics(self, metrics, results, tags): ''' For all the metrics that are specified as oid, the conf oid is going to exactly match or be a prefix of the oid sent back by the device Use the instance configuration to find the name to give to the metric Submit the resu...
For each of the metrics specified as needing to be resolved with mib gather the tags requested in the instance conf for each row.
def report_table_metrics(self, metrics, results, tags): ''' For each of the metrics specified as needing to be resolved with mib, gather the tags requested in the instance conf for each row. Submit the results to the aggregator. ''' for metric in metrics: fo...
Gather the tags for this row of the table ( index ) based on the results ( all the results from the query ). index_tags and column_tags are the tags to gather. - Those specified in index_tags contain the tag_group name and the index of the value we want to extract from the index tuple. cf. 1 for ipVersion in the IP - M...
def get_index_tags(self, index, results, index_tags, column_tags): ''' Gather the tags for this row of the table (index) based on the results (all the results from the query). index_tags and column_tags are the tags to gather. - Those specified in index_tags contain the tag_grou...
Convert the values reported as pysnmp - Managed Objects to values and report them to the aggregator
def submit_metric(self, name, snmp_value, forced_type, tags=None): ''' Convert the values reported as pysnmp-Managed Objects to values and report them to the aggregator ''' tags = [] if tags is None else tags if reply_invalid(snmp_value): # Metrics not present...
See https:// github. com/ python/ cpython/ blob/ b02774f42108aaf18eb19865472c8d5cd95b5f11/ Lib/ bdb. py#L319 - L332
def set_trace(self, frame=None): """See https://github.com/python/cpython/blob/b02774f42108aaf18eb19865472c8d5cd95b5f11/Lib/bdb.py#L319-L332""" self.reset() if frame is None: frame = sys._getframe().f_back while frame: frame.f_trace = self.trace_dispatch ...
The current average latency or None.
def round_trip_time(self): """The current average latency or None.""" # This override is for unittesting only! if self._address in self._host_to_round_trip_time: return self._host_to_round_trip_time[self._address] return self._round_trip_time
Collect stats for all reachable networks
def collect_networks_metrics(self, tags, network_ids, exclude_network_id_rules): """ Collect stats for all reachable networks """ networks = self.get_networks() filtered_networks = [] if not network_ids: # Filter out excluded networks filtered_netw...
Parse u 16: 53: 48 up 1 day 21: 34 3 users load average: 0. 04 0. 14 0. 19 \ n
def _parse_uptime_string(self, uptime): """ Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' """ uptime = uptime.strip() load_averages = uptime[uptime.find('load average:') :].split(':')[1].strip().split(',') load_averages = [float(load_avg) for load_avg in...
Submits stats for all hypervisors registered to this control plane Raises specific exceptions based on response code
def collect_hypervisors_metrics( self, servers, custom_tags=None, use_shortname=False, collect_hypervisor_metrics=True, collect_hypervisor_load=False, ): """ Submits stats for all hypervisors registered to this control plane Raises specific exc...
Guarantees a valid auth scope for this instance and returns it
def init_api(self, instance_config, custom_tags): """ Guarantees a valid auth scope for this instance, and returns it Communicates with the identity server and initializes a new scope when one is absent, or has been forcibly removed due to token expiry """ custom_tags = ...
Tries to connect to the cadvisor endpoint with given params: return: url if OK raises exception if NOK
def detect_cadvisor(kubelet_url, cadvisor_port): """ Tries to connect to the cadvisor endpoint, with given params :return: url if OK, raises exception if NOK """ if cadvisor_port == 0: raise ValueError("cAdvisor port set to 0 in configuration") kubelet_hostnam...
Scrape and submit metrics from cadvisor: param: instance: check instance object: param: cadvisor_url: valid cadvisor url as returned by detect_cadvisor (): param: pod_list: fresh podlist object from the kubelet: param: pod_list_utils: already initialised PodListUtils object
def process_cadvisor(self, instance, cadvisor_url, pod_list, pod_list_utils): """ Scrape and submit metrics from cadvisor :param: instance: check instance object :param: cadvisor_url: valid cadvisor url, as returned by detect_cadvisor() :param: pod_list: fresh podlist object from...
Recusively parses and submit metrics for a given entity until reaching self. max_depth. Nested metric names are flattened: memory/ usage - > memory. usage: param: metric: parent s metric name ( check namespace for root stat objects ): param: dat: metric dictionnary to parse: param: tags: entity tags to use when submitt...
def _publish_raw_metrics(self, metric, dat, tags, is_pod, depth=0): """ Recusively parses and submit metrics for a given entity, until reaching self.max_depth. Nested metric names are flattened: memory/usage -> memory.usage :param: metric: parent's metric name (check namespace fo...
Get the proper set of stats metrics for the specified ES version
def stats_for_version(version): """ Get the proper set of stats metrics for the specified ES version """ metrics = dict(STATS_METRICS) # JVM additional metrics if version >= [0, 90, 10]: metrics.update(JVM_METRICS_POST_0_90_10) else: metrics.update(JVM_METRICS_PRE_0_90_10) ...
Get the proper set of pshard metrics for the specified ES version
def pshard_stats_for_version(version): """ Get the proper set of pshard metrics for the specified ES version """ pshard_stats_metrics = dict(PRIMARY_SHARD_METRICS) if version >= [1, 0, 0]: pshard_stats_metrics.update(PRIMARY_SHARD_METRICS_POST_1_0) return pshard_stats_metrics
Get the proper set of health metrics for the specified ES version
def health_stats_for_version(version): """ Get the proper set of health metrics for the specified ES version """ cluster_health_metrics = dict(CLUSTER_HEALTH_METRICS) if version >= [2, 4, 0]: cluster_health_metrics.update(CLUSTER_HEALTH_METRICS_POST_2_4) return cluster_health_metrics
Show all the checks that can be released.
def ready(ctx, quiet): """Show all the checks that can be released.""" user_config = ctx.obj cached_prs = {} for target in sorted(get_valid_checks()): # get the name of the current release tag cur_version = get_version_string(target) target_tag = get_release_tag_string(target, c...
Show all the pending PRs for a given check.
def changes(ctx, check, dry_run): """Show all the pending PRs for a given check.""" if not dry_run and check not in get_valid_checks(): abort('Check `{}` is not an Agent-based Integration'.format(check)) # get the name of the current release tag cur_version = get_version_string(check) targe...
Tag the HEAD of the git repo with the current release number for a specific check. The tag is pushed to origin by default.
def tag(check, version, push, dry_run): """Tag the HEAD of the git repo with the current release number for a specific check. The tag is pushed to origin by default. You can tag everything at once by setting the check to `all`. Notice: specifying a different version than the one in __about__.py is ...
Perform a set of operations needed to release a single check:
def make(ctx, check, version, initial_release, skip_sign, sign_only): """Perform a set of operations needed to release a single check: \b * update the version in __about__.py * update the changelog * update the requirements-agent-release.txt file * update in-toto metadata * commit...
Perform the operations needed to update the changelog.
def changelog(ctx, check, version, old_version, initial, quiet, dry_run): """Perform the operations needed to update the changelog. This method is supposed to be used by other tasks and not directly. """ if check not in get_valid_checks(): abort('Check `{}` is not an Agent-based Integration'.fo...
Build a wheel for a check as it is on the repo HEAD
def build(check, sdist): """Build a wheel for a check as it is on the repo HEAD""" if check in get_valid_checks(): check_dir = os.path.join(get_root(), check) else: check_dir = resolve_path(check) if not dir_exists(check_dir): abort('`{}` is not an Agent-based Integration...
Release a specific check to PyPI as it is on the repo HEAD.
def upload(ctx, check, sdist, dry_run): """Release a specific check to PyPI as it is on the repo HEAD.""" if check in get_valid_checks(): check_dir = os.path.join(get_root(), check) else: check_dir = resolve_path(check) if not dir_exists(check_dir): abort('`{}` is not an ...
Return the metrics received under the given name
def metrics(self, name): """ Return the metrics received under the given name """ return [ MetricStub( ensure_unicode(stub.name), stub.type, stub.value, normalize_tags(stub.tags), ensure_unicode(s...
Return the service checks received under the given name
def service_checks(self, name): """ Return the service checks received under the given name """ return [ ServiceCheckStub( ensure_unicode(stub.check_id), ensure_unicode(stub.name), stub.status, normalize_tags(stu...
Return all events
def events(self): """ Return all events """ all_events = [{ensure_unicode(key): value for key, value in iteritems(ev)} for ev in self._events] for ev in all_events: to_decode = [] for key, value in iteritems(ev): if isinstance(value, binar...
Assert a metric is tagged with tag
def assert_metric_has_tag(self, metric_name, tag, count=None, at_least=1): """ Assert a metric is tagged with tag """ self._asserted.add(metric_name) candidates = [] for metric in self.metrics(metric_name): if tag in metric.tags: candidates.ap...
Assert a metric was processed by this stub
def assert_metric(self, name, value=None, tags=None, count=None, at_least=1, hostname=None, metric_type=None): """ Assert a metric was processed by this stub """ self._asserted.add(name) tags = normalize_tags(tags, sort=True) candidates = [] for metric in self.me...
Assert a service check was processed by this stub
def assert_service_check(self, name, status=None, tags=None, count=None, at_least=1, hostname=None, message=None): """ Assert a service check was processed by this stub """ tags = normalize_tags(tags, sort=True) candidates = [] for sc in self.service_checks(name): ...
Return the metrics assertion coverage
def metrics_asserted_pct(self): """ Return the metrics assertion coverage """ num_metrics = len(self._metrics) num_asserted = len(self._asserted) if num_metrics == 0: if num_asserted == 0: return 100 else: return 0 ...
Examine the response and raise an error is something is off
def _process_response(cls, response): """ Examine the response and raise an error is something is off """ if len(response) != 1: raise BadResponseError("Malformed response: {}".format(response)) stats = list(itervalues(response))[0] if not len(stats): ...
Optional metric handler for items stats
def get_items_stats(key, value): """ Optional metric handler for 'items' stats key: "items:<slab_id>:<metric_name>" format value: return untouched Like all optional metric handlers returns metric, tags, value """ itemized_key = key.split(':') slab_id = i...
Optional metric handler for items stats
def get_slabs_stats(key, value): """ Optional metric handler for 'items' stats key: "items:<slab_id>:<metric_name>" format value: return untouched Like all optional metric handlers returns metric, tags, value """ slabbed_key = key.split(':') tags = [] ...
instance: the check instance base_url: the url of the rabbitmq management api ( e. g. http:// localhost: 15672/ api ) object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE max_detailed: the limit of objects to collect for this type filters: explicit or regexes filters of specified queues or nodes ( specified in ...
def get_stats( self, instance, base_url, object_type, max_detailed, filters, limit_vhosts, custom_tags, auth=None, ssl_verify=True, ): """ instance: the check instance base_url: the url of the rabbitmq management...
Collect metrics on currently open connection per vhost.
def get_connections_stat( self, instance, base_url, object_type, vhosts, limit_vhosts, custom_tags, auth=None, ssl_verify=True ): """ Collect metrics on currently open connection per vhost. """ instance_proxy = self.get_instance_proxy(instance, base_url) grab_all_dat...
Check the aliveness API against all or a subset of vhosts. The API will return { status: ok } and a 200 response code in the case that the check passes.
def _check_aliveness(self, instance, base_url, vhosts, custom_tags, auth=None, ssl_verify=True): """ Check the aliveness API against all or a subset of vhosts. The API will return {"status": "ok"} and a 200 response code in the case that the check passes. """ for vhost i...
Create a GridIn property.
def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): """Create a GridIn property.""" def getter(self): if closed_only and not self._closed: raise AttributeError("can only get %r on a closed file" % field_name...
Create a GridOut property.
def _grid_out_property(field_name, docstring): """Create a GridOut property.""" def getter(self): self._ensure_file() # Protect against PHP-237 if field_name == 'length': return self._file.get(field_name, 0) return self._file.get(field_name, None) docstring += "...
Flush data to a chunk.
def __flush_data(self, data): """Flush `data` to a chunk. """ # Ensure the index, even if there's nothing to write, so # the filemd5 command always succeeds. self.__ensure_indexes() self._file['md5'].update(data) if not data: return assert(len...
Flush the buffer contents out to a chunk.
def __flush_buffer(self): """Flush the buffer contents out to a chunk. """ self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = StringIO()
Flush the file to the database.
def __flush(self): """Flush the file to the database. """ try: self.__flush_buffer() self._file['md5'] = self._file["md5"].hexdigest() self._file["length"] = self._position self._file["uploadDate"] = datetime.datetime.utcnow() return ...
Flush the file and close it.
def close(self): """Flush the file and close it. A closed file cannot be written any more. Calling :meth:`close` more than once is allowed. """ if not self._closed: self.__flush() object.__setattr__(self, "_closed", True)
Write data to the file. There is no return value.
def write(self, data): """Write data to the file. There is no return value. `data` can be either a string of bytes or a file-like object (implementing :meth:`read`). If the file has an :attr:`encoding` attribute, `data` can also be a :class:`unicode` (:class:`str` in python 3) i...
Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned.
def readchunk(self): """Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned. """ received = len(self.__buffer) chunk_data = EMPTY chunk_size = int(self.chunk_size) if received > 0: chunk_data = sel...
Read at most size bytes from the file ( less if there isn t enough data ).
def read(self, size=-1): """Read at most `size` bytes from the file (less if there isn't enough data). The bytes are returned as an instance of :class:`str` (:class:`bytes` in python 3). If `size` is negative or omitted all data is read. :Parameters: - `size` (optiona...
Set the current position of this file.
def seek(self, pos, whence=_SEEK_SET): """Set the current position of this file. :Parameters: - `pos`: the position (or offset if using relative positioning) to seek to - `whence` (optional): where to seek from. :attr:`os.SEEK_SET` (``0``) for absolute file ...
Validate and set a WMI provider. Default to ProviderArchitecture. DEFAULT
def provider(self, value): """ Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT` """ result = None # `None` defaults to `ProviderArchitecture.DEFAULT` defaulted_value = value or ProviderArchitecture.DEFAULT try: parsed_value ...
A property to retrieve the sampler connection information.
def connection(self): """ A property to retrieve the sampler connection information. """ return {'host': self.host, 'namespace': self.namespace, 'username': self.username, 'password': self.password}
Return an index key used to cache the sampler connection.
def connection_key(self): """ Return an index key used to cache the sampler connection. """ return "{host}:{namespace}:{username}".format(host=self.host, namespace=self.namespace, username=self.username)
Cache and return filters as a comprehensive WQL clause.
def formatted_filters(self): """ Cache and return filters as a comprehensive WQL clause. """ if not self._formatted_filters: filters = deepcopy(self.filters) self._formatted_filters = self._format_filter(filters, self._and_props) return self._formatted_fil...
Compute new samples.
def sample(self): """ Compute new samples. """ self._sampling = True try: if self.is_raw_perf_class and not self._previous_sample: self._current_sample = self._query() self._previous_sample = self._current_sample self._current...
Return the calculator for the given counter_type. Fallback with get_raw.
def _get_property_calculator(self, counter_type): """ Return the calculator for the given `counter_type`. Fallback with `get_raw`. """ calculator = get_raw try: calculator = get_calculator(counter_type) except UndefinedCalculator: self.logg...
Format WMI Object s RAW data based on the previous sample.
def _format_property_values(self, previous, current): """ Format WMI Object's RAW data based on the previous sample. Do not override the original WMI Object ! """ formatted_wmi_object = CaseInsensitiveDict() for property_name, property_raw_value in iteritems(current): ...
Create a new WMI connection
def get_connection(self): """ Create a new WMI connection """ self.logger.debug( u"Connecting to WMI server " u"(host={host}, namespace={namespace}, provider={provider}, username={username}).".format( host=self.host, namespace=self.namespace, provi...
Transform filters to a comprehensive WQL WHERE clause.
def _format_filter(filters, and_props=[]): """ Transform filters to a comprehensive WQL `WHERE` clause. Builds filter from a filter list. - filters: expects a list of dicts, typically: - [{'Property': value},...] or - [{'Property': (comparison_op, value)}...
Query WMI using WMI Query Language ( WQL ) & parse the results.
def _query(self): # pylint: disable=E0202 """ Query WMI using WMI Query Language (WQL) & parse the results. Returns: List of WMI objects or `TimeoutException`. """ formated_property_names = ",".join(self.property_names) wql = "Select {property_names} from {class_name}{f...
Parse WMI query results in a more comprehensive form.
def _parse_results(self, raw_results, includes_qualifiers): """ Parse WMI query results in a more comprehensive form. Returns: List of WMI objects ``` [ { 'freemegabytes': 19742.0, 'name': 'C:', 'avgdiskbytesperwrite': ...
Return ( IsMaster round_trip_time ).
def _check_with_socket(self, sock_info, metadata=None): """Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. """ cmd = SON([('ismaster', 1)]) if metadata is not None: cmd['client'] = metadata start = _time() request_...
Verify that the checks versions are in sync with the requirements - agent - release. txt file
def agent_reqs(): """Verify that the checks versions are in sync with the requirements-agent-release.txt file""" echo_info("Validating requirements-agent-release.txt...") agent_reqs_content = parse_agent_req_file(read_file(get_agent_release_requirements())) ok_checks = 0 unreleased_checks = 0 f...
Logs a deprecation notice at most once per AgentCheck instance for the pre - defined deprecation_key
def _log_deprecation(self, deprecation_key): """ Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key` """ if not self._deprecations[deprecation_key][0]: self.log.warning(self._deprecations[deprecation_key][1]) self....
Convert from CamelCase to camel_case And substitute illegal metric characters
def convert_to_underscore_separated(self, name): """ Convert from CamelCase to camel_case And substitute illegal metric characters """ metric_name = self.FIRST_CAP_RE.sub(br'\1_\2', ensure_bytes(name)) metric_name = self.ALL_CAP_RE.sub(br'\1_\2', metric_name).lower() ...
Normalize tags contents and type: - append device_name as device: tag - normalize tags type - doesn t mutate the passed list returns a new list
def _normalize_tags_type(self, tags, device_name=None, metric_name=None): """ Normalize tags contents and type: - append `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list """ normalized_tags = [] if ...
Turn a metric into a well - formed metric name prefix. b. c: param metric The metric name to normalize: param prefix A prefix to to add to the normalized name default None: param fix_case A boolean indicating whether to make sure that the metric name returned is in snake_case
def normalize(self, metric, prefix=None, fix_case=False): """ Turn a metric into a well-formed metric name prefix.b.c :param metric The metric name to normalize :param prefix A prefix to to add to the normalized name, default None :param fix_case A boolean, indicating whe...
Normalize tags contents and type: - append device_name as device: tag - normalize tags type - doesn t mutate the passed list returns a new list
def _normalize_tags_type(self, tags, device_name=None, metric_name=None): """ Normalize tags contents and type: - append `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list """ normalized_tags = [] if ...
Normalize a text data to bytes ( type bytes ) so that the go bindings can handle it easily.
def _to_bytes(self, data): """ Normalize a text data to bytes (type `bytes`) so that the go bindings can handle it easily. """ # TODO: On Python 3, move this `if` line to the `except` branch # as the common case will indeed no longer be bytes. if not isinstance(da...
Create a config object from an instance dictionary
def from_instance(instance): """ Create a config object from an instance dictionary """ url = instance.get('url') if not url: raise ConfigurationError("A URL must be specified in the instance") pshard_stats = is_affirmative(instance.get('pshard_stats', False)) pshard_graceful_to = i...
Download the dataset from the hosted Yellowbrick data store and save it to the location specified by get_data_home. The downloader verifies the download completed successfully and safely by comparing the expected signature with the SHA 256 signature of the downloaded archive file.
def download(self, replace=False): """ Download the dataset from the hosted Yellowbrick data store and save it to the location specified by ``get_data_home``. The downloader verifies the download completed successfully and safely by comparing the expected signature with the SHA 2...
Contents returns a list of the files in the data directory.
def contents(self): """ Contents returns a list of the files in the data directory. """ data = find_dataset_path( self.name, data_home=self.data_home, ext=None ) return os.listdir(data)
Returns the contents of the README. md file that describes the dataset in detail and contains attribution information.
def README(self): """ Returns the contents of the README.md file that describes the dataset in detail and contains attribution information. """ path = find_dataset_path( self.name, data_home=self.data_home, fname="README.md" ) with open(path, 'r') as f...
Returns the contents of the meta. json file that describes important attributes about the dataset and modifies the behavior of the loader.
def meta(self): """ Returns the contents of the meta.json file that describes important attributes about the dataset and modifies the behavior of the loader. """ path = find_dataset_path( self.name, data_home=self.data_home, fname="meta.json", raises=False ) ...
Returns the contents of the citation. bib file that describes the source and provenance of the dataset or to cite for academic work.
def citation(self): """ Returns the contents of the citation.bib file that describes the source and provenance of the dataset or to cite for academic work. """ path = find_dataset_path( self.name, data_home=self.data_home, fname="meta.json", raises=False ) ...
Returns the dataset as two numpy arrays: X and y.
def to_numpy(self): """ Returns the dataset as two numpy arrays: X and y. Returns ------- X : array-like with shape (n_instances, n_features) A numpy array describing the instance features. y : array-like with shape (n_instances,) A numpy array d...
Returns the dataset as two pandas objects: X and y.
def to_pandas(self): """ Returns the dataset as two pandas objects: X and y. Returns ------- X : DataFrame with shape (n_instances, n_features) A pandas DataFrame containing feature data and named columns. y : Series with shape (n_instances,) A p...
Returns the entire dataset as a single pandas DataFrame.
def to_dataframe(self): """ Returns the entire dataset as a single pandas DataFrame. Returns ------- df : DataFrame with shape (n_instances, n_columns) A pandas DataFrame containing the complete original data table including all targets (specified by the ...
Return the unique labels assigned to the documents.
def labels(self): """ Return the unique labels assigned to the documents. """ return [ name for name in os.listdir(self.root) if os.path.isdir(os.path.join(self.root, name)) ]
Returns the list of file names for all documents.
def files(self): """ Returns the list of file names for all documents. """ return [ os.path.join(self.root, label, name) for label in self.labels for name in os.listdir(os.path.join(self.root, label)) ]
Read all of the documents from disk into an in - memory list.
def data(self): """ Read all of the documents from disk into an in-memory list. """ def read(path): with open(path, 'r', encoding='UTF-8') as f: return f.read() return [ read(f) for f in self.files ]
Returns the label associated with each item in data.
def target(self): """ Returns the label associated with each item in data. """ return [ os.path.basename(os.path.dirname(f)) for f in self.files ]
Fits the model and generates the silhouette visualization.
def fit(self, X, y=None, **kwargs): """ Fits the model and generates the silhouette visualization. """ # TODO: decide to use this method or the score method to draw. # NOTE: Probably this would be better in score, but the standard score # is a little different and I'm not...
Draw the silhouettes for each sample and the average score.
def draw(self, labels): """ Draw the silhouettes for each sample and the average score. Parameters ---------- labels : array-like An array with the cluster label for each silhouette sample, usually computed with ``predict()``. Labels are not stored on th...
Prepare the figure for rendering by setting the title and adjusting the limits on the axes adding labels and a legend.
def finalize(self): """ Prepare the figure for rendering by setting the title and adjusting the limits on the axes, adding labels and a legend. """ # Set the title self.set_title(( "Silhouette Plot of {} Clustering for {} Samples in {} Centers" ).form...
Computes the SHA256 signature of a file to verify that the file has not been modified in transit and that it is the correct version of the data.
def sha256sum(path, blocksize=65536): """ Computes the SHA256 signature of a file to verify that the file has not been modified in transit and that it is the correct version of the data. """ sig = hashlib.sha256() with open(path, 'rb') as f: buf = f.read(blocksize) while len(buf)...
Uses Scikit - Learn to fit a model to X and y then uses the resulting model to predict the curve based on the X values. This curve is drawn to the ax ( matplotlib axis ) which must be passed as the third variable.
def draw_best_fit(X, y, ax, estimator='linear', **kwargs): """ Uses Scikit-Learn to fit a model to X and y then uses the resulting model to predict the curve based on the X values. This curve is drawn to the ax (matplotlib axis) which must be passed as the third variable. The estimator function can...
Selects the best fit of the estimators already implemented by choosing the model with the smallest mean square error metric for the trained values.
def fit_select_best(X, y): """ Selects the best fit of the estimators already implemented by choosing the model with the smallest mean square error metric for the trained values. """ models = [fit(X,y) for fit in [fit_linear, fit_quadratic]] errors = map(lambda model: mse(y, model.predict(X)), m...
Uses OLS to fit the regression.
def fit_linear(X, y): """ Uses OLS to fit the regression. """ model = linear_model.LinearRegression() model.fit(X, y) return model
Uses OLS with Polynomial order 2.
def fit_quadratic(X, y): """ Uses OLS with Polynomial order 2. """ model = make_pipeline( PolynomialFeatures(2), linear_model.LinearRegression() ) model.fit(X, y) return model
Draws a 45 degree identity line such that y = x for all points within the given axes x and y limits. This function also registeres a callback so that as the figure is modified the axes are updated and the line remains drawn correctly.
def draw_identity_line(ax=None, dynamic=True, **kwargs): """ Draws a 45 degree identity line such that y=x for all points within the given axes x and y limits. This function also registeres a callback so that as the figure is modified, the axes are updated and the line remains drawn correctly. ...