sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def accept_operator(self, precedence): """Accept the next binary operator only if it's of higher precedence.""" match = grammar.infix(self.tokens) if not match: return if match.operator.precedence < precedence: return # The next thing is an operator that...
Accept the next binary operator only if it's of higher precedence.
entailment
def operator(self, lhs, min_precedence): """Climb operator precedence as long as there are operators. This function implements a basic precedence climbing parser to deal with binary operators in a sane fashion. The outer loop will keep spinning as long as the next token is an operator w...
Climb operator precedence as long as there are operators. This function implements a basic precedence climbing parser to deal with binary operators in a sane fashion. The outer loop will keep spinning as long as the next token is an operator with a precedence of at least 'min_precedence...
entailment
def dot_rhs(self): """Match the right-hand side of a dot (.) operator. The RHS must be a symbol token, but it is interpreted as a literal string (because that's what goes in the AST of Resolve.) """ self.tokens.expect(common_grammar.symbol) return ast.Literal(self.tokens...
Match the right-hand side of a dot (.) operator. The RHS must be a symbol token, but it is interpreted as a literal string (because that's what goes in the AST of Resolve.)
entailment
def select(self): """First part of an SQL query.""" # Try to match the asterisk, any or list of vars. if self.tokens.accept(grammar.select_any): return self.select_any() if self.tokens.accept(grammar.select_all): # The FROM after SELECT * is required. ...
First part of an SQL query.
entailment
def _guess_name_of(self, expr): """Tries to guess what variable name 'expr' ends in. This is a heuristic that roughly emulates what most SQL databases name columns, based on selected variable names or applied functions. """ if isinstance(expr, ast.Var): return expr.v...
Tries to guess what variable name 'expr' ends in. This is a heuristic that roughly emulates what most SQL databases name columns, based on selected variable names or applied functions.
entailment
def select_limit(self, source_expression): """Match LIMIT take [OFFSET drop].""" start = self.tokens.matched.start # The expression right after LIMIT is the count to take. limit_count_expression = self.expression() # Optional OFFSET follows. if self.tokens.accept(gramma...
Match LIMIT take [OFFSET drop].
entailment
def builtin(self, keyword): """Parse the pseudo-function application subgrammar.""" # The match includes the lparen token, so the keyword is just the first # token in the match, not the whole thing. keyword_start = self.tokens.matched.first.start keyword_end = self.tokens.matched...
Parse the pseudo-function application subgrammar.
entailment
def application(self, func): """Parse the function application subgrammar. Function application can, conceptually, be thought of as a mixfix operator, similar to the way array subscripting works. However, it is not clear at this point whether we want to allow it to work as such, ...
Parse the function application subgrammar. Function application can, conceptually, be thought of as a mixfix operator, similar to the way array subscripting works. However, it is not clear at this point whether we want to allow it to work as such, because doing so would permit queries t...
entailment
def list(self): """Parse a list (tuple) which can contain any combination of types.""" start = self.tokens.matched.start if self.tokens.accept(common_grammar.rbracket): return ast.Tuple(start=start, end=self.tokens.matched.end, source=self.original) ...
Parse a list (tuple) which can contain any combination of types.
entailment
def get_singleton(self): """If the row only has one column, return that value; otherwise raise. Raises: ValueError, if count of columns is not 1. """ only_value = None for value in six.itervalues(self.ordered_dict): # This loop will raise if it runs more ...
If the row only has one column, return that value; otherwise raise. Raises: ValueError, if count of columns is not 1.
entailment
def _cpu(self): """Record CPU usage.""" value = int(psutil.cpu_percent()) set_metric("cpu", value, category=self.category) gauge("cpu", value)
Record CPU usage.
entailment
def _mem(self): """Record Memory usage.""" value = int(psutil.virtual_memory().percent) set_metric("memory", value, category=self.category) gauge("memory", value)
Record Memory usage.
entailment
def _disk(self): """Record Disk usage.""" mountpoints = [ p.mountpoint for p in psutil.disk_partitions() if p.device.endswith(self.device) ] if len(mountpoints) != 1: raise CommandError("Unknown device: {0}".format(self.device)) value = int(ps...
Record Disk usage.
entailment
def _net(self): """Record Network usage.""" data = psutil.network_io_counters(pernic=True) if self.device not in data: raise CommandError("Unknown device: {0}".format(self.device)) # Network bytes sent value = data[self.device].bytes_sent metric("net-{0}-sent...
Record Network usage.
entailment
def implements(obj, protocol): """Does the object 'obj' implement the 'prococol'?""" if isinstance(obj, type): raise TypeError("First argument to implements must be an instance. " "Got %r." % obj) return isinstance(obj, protocol) or issubclass(AnyType, protocol)
Does the object 'obj' implement the 'prococol'?
entailment
def isa(cls, protocol): """Does the type 'cls' participate in the 'protocol'?""" if not isinstance(cls, type): raise TypeError("First argument to isa must be a type. Got %s." % repr(cls)) if not isinstance(protocol, type): raise TypeError(("Second argument to isa mus...
Does the type 'cls' participate in the 'protocol'?
entailment
def implemented(cls, for_type): """Assert that protocol 'cls' is implemented for type 'for_type'. This will cause 'for_type' to be registered with the protocol 'cls'. Subsequently, protocol.isa(for_type, cls) will return True, as will isinstance, issubclass and others. Raises: ...
Assert that protocol 'cls' is implemented for type 'for_type'. This will cause 'for_type' to be registered with the protocol 'cls'. Subsequently, protocol.isa(for_type, cls) will return True, as will isinstance, issubclass and others. Raises: TypeError if 'for_type' doesn't...
entailment
def __get_type_args(for_type=None, for_types=None): """Parse the arguments and return a tuple of types to implement for. Raises: ValueError or TypeError as appropriate. """ if for_type: if for_types: raise ValueError("Cannot pass both for_type and...
Parse the arguments and return a tuple of types to implement for. Raises: ValueError or TypeError as appropriate.
entailment
def implicit_static(cls, for_type=None, for_types=None): """Automatically generate implementations for a type. Implement the protocol for the 'for_type' type by dispatching each member function of the protocol to an instance method of the same name declared on the type 'for_type'. ...
Automatically generate implementations for a type. Implement the protocol for the 'for_type' type by dispatching each member function of the protocol to an instance method of the same name declared on the type 'for_type'. Arguments: for_type: The type to implictly implement...
entailment
def _build_late_dispatcher(func_name): """Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that ...
Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that takes an 'obj' parameter, followed by *args and ...
entailment
def implicit_dynamic(cls, for_type=None, for_types=None): """Automatically generate late dynamic dispatchers to type. This is similar to 'implicit_static', except instead of binding the instance methods, it generates a dispatcher that will call whatever instance method of the same name ...
Automatically generate late dynamic dispatchers to type. This is similar to 'implicit_static', except instead of binding the instance methods, it generates a dispatcher that will call whatever instance method of the same name happens to be available at time of dispatch. This ha...
entailment
def implement(cls, implementations, for_type=None, for_types=None): """Provide protocol implementation for a type. Register all implementations of multimethod functions in this protocol and add the type into the abstract base class of the protocol. Arguments: implem...
Provide protocol implementation for a type. Register all implementations of multimethod functions in this protocol and add the type into the abstract base class of the protocol. Arguments: implementations: A dict of (function, implementation), where each fun...
entailment
def _parse_query(self, source): """Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. Returns: ...
Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. Returns: The AST to represent the rule.
entailment
def _parse_tagfile(self): """Parse the tagfile and yield tuples of tag_name, list of rule ASTs.""" rules = None tag = None for line in self.original: match = self.TAG_DECL_LINE.match(line) if match: if tag and rules: yield tag, ...
Parse the tagfile and yield tuples of tag_name, list of rule ASTs.
entailment
def normalize(expr): """Normalize both sides, but don't eliminate the expression.""" lhs = normalize(expr.lhs) rhs = normalize(expr.rhs) return type(expr)(lhs, rhs, start=lhs.start, end=rhs.end)
Normalize both sides, but don't eliminate the expression.
entailment
def normalize(expr): """No elimination, but normalize arguments.""" args = [normalize(arg) for arg in expr.args] return type(expr)(expr.func, *args, start=expr.start, end=expr.end)
No elimination, but normalize arguments.
entailment
def normalize(expr): """Pass through n-ary expressions, and eliminate empty branches. Variadic and binary expressions recursively visit all their children. If all children are eliminated then the parent expression is also eliminated: (& [removed] [removed]) => [removed] If only one child is ...
Pass through n-ary expressions, and eliminate empty branches. Variadic and binary expressions recursively visit all their children. If all children are eliminated then the parent expression is also eliminated: (& [removed] [removed]) => [removed] If only one child is left, it is promoted to repl...
entailment
def dedupe(items): """Remove duplicates from a sequence (of hashable items) while maintaining order. NOTE: This only works if items in the list are hashable types. Taken from the Python Cookbook, 3rd ed. Such a great book! """ seen = set() for item in items: if item not in seen: ...
Remove duplicates from a sequence (of hashable items) while maintaining order. NOTE: This only works if items in the list are hashable types. Taken from the Python Cookbook, 3rd ed. Such a great book!
entailment
def _date_range(self, granularity, since, to=None): """Returns a generator that yields ``datetime.datetime`` objects from the ``since`` date until ``to`` (default: *now*). * ``granularity`` -- The granularity at which the generated datetime objects should be created: seconds, minutes,...
Returns a generator that yields ``datetime.datetime`` objects from the ``since`` date until ``to`` (default: *now*). * ``granularity`` -- The granularity at which the generated datetime objects should be created: seconds, minutes, hourly, daily, weekly, monthly, or yearly * ...
entailment
def _category_slugs(self, category): """Returns a set of the metric slugs for the given category""" key = self._category_key(category) slugs = self.r.smembers(key) return slugs
Returns a set of the metric slugs for the given category
entailment
def _categorize(self, slug, category): """Add the ``slug`` to the ``category``. We store category data as as set, with a key of the form:: c:<category name> The data is set of metric slugs:: "slug-a", "slug-b", ... """ key = self._category_key(category...
Add the ``slug`` to the ``category``. We store category data as as set, with a key of the form:: c:<category name> The data is set of metric slugs:: "slug-a", "slug-b", ...
entailment
def _granularities(self): """Returns a generator of all possible granularities based on the MIN_GRANULARITY and MAX_GRANULARITY settings. """ keep = False for g in GRANULARITIES: if g == app_settings.MIN_GRANULARITY and not keep: keep = True ...
Returns a generator of all possible granularities based on the MIN_GRANULARITY and MAX_GRANULARITY settings.
entailment
def _build_key_patterns(self, slug, date): """Builds an OrderedDict of metric keys and patterns for the given slug and date.""" # we want to keep the order, from smallest to largest granularity patts = OrderedDict() metric_key_patterns = self._metric_key_patterns() for g ...
Builds an OrderedDict of metric keys and patterns for the given slug and date.
entailment
def _build_keys(self, slug, date=None, granularity='all'): """Builds redis keys used to store metrics. * ``slug`` -- a slug used for a metric, e.g. "user-signups" * ``date`` -- (optional) A ``datetime.datetime`` object used to generate the time period for the metric. If omitted, the c...
Builds redis keys used to store metrics. * ``slug`` -- a slug used for a metric, e.g. "user-signups" * ``date`` -- (optional) A ``datetime.datetime`` object used to generate the time period for the metric. If omitted, the current date and time (in UTC) will be used. * ``gran...
entailment
def metric_slugs_by_category(self): """Return a dictionary of metrics data indexed by category: {<category_name>: set(<slug1>, <slug2>, ...)} """ result = OrderedDict() categories = sorted(self.r.smembers(self._categories_key)) for category in categories: ...
Return a dictionary of metrics data indexed by category: {<category_name>: set(<slug1>, <slug2>, ...)}
entailment
def delete_metric(self, slug): """Removes all keys for the given ``slug``.""" # To remove all keys for a slug, I need to retrieve them all from # the set of metric keys, This uses the redis "keys" command, which is # inefficient, but this shouldn't be used all that often. prefix...
Removes all keys for the given ``slug``.
entailment
def set_metric(self, slug, value, category=None, expire=None, date=None): """Assigns a specific value to the *current* metric. You can use this to start a metric at a value greater than 0 or to reset a metric. The given slug will be used to generate Redis keys at the following granulari...
Assigns a specific value to the *current* metric. You can use this to start a metric at a value greater than 0 or to reset a metric. The given slug will be used to generate Redis keys at the following granularities: Seconds, Minutes, Hours, Day, Week, Month, and Year. Parameters: ...
entailment
def metric(self, slug, num=1, category=None, expire=None, date=None): """Records a metric, creating it if it doesn't exist or incrementing it if it does. All metrics are prefixed with 'm', and automatically aggregate for Seconds, Minutes, Hours, Day, Week, Month, and Year. Parameters: ...
Records a metric, creating it if it doesn't exist or incrementing it if it does. All metrics are prefixed with 'm', and automatically aggregate for Seconds, Minutes, Hours, Day, Week, Month, and Year. Parameters: * ``slug`` -- a unique value to identify the metric; used in co...
entailment
def get_metric(self, slug): """Get the current values for a metric. Returns a dictionary with metric values accumulated for the seconds, minutes, hours, day, week, month, and year. """ results = OrderedDict() granularities = self._granularities() keys = self._bu...
Get the current values for a metric. Returns a dictionary with metric values accumulated for the seconds, minutes, hours, day, week, month, and year.
entailment
def get_metrics(self, slug_list): """Get the metrics for multiple slugs. Returns a list of two-tuples containing the metric slug and a dictionary like the one returned by ``get_metric``:: ( some-metric, { 'seconds': 0, 'minutes': 0, 'hours': 0, ...
Get the metrics for multiple slugs. Returns a list of two-tuples containing the metric slug and a dictionary like the one returned by ``get_metric``:: ( some-metric, { 'seconds': 0, 'minutes': 0, 'hours': 0, 'day': 0, 'week': 0, 'mont...
entailment
def get_category_metrics(self, category): """Get metrics belonging to the given category""" slug_list = self._category_slugs(category) return self.get_metrics(slug_list)
Get metrics belonging to the given category
entailment
def delete_category(self, category): """Removes the category from Redis. This doesn't touch the metrics; they simply become uncategorized.""" # Remove mapping of metrics-to-category category_key = self._category_key(category) self.r.delete(category_key) # Remove category...
Removes the category from Redis. This doesn't touch the metrics; they simply become uncategorized.
entailment
def reset_category(self, category, metric_slugs): """Resets (or creates) a category containing a list of metrics. * ``category`` -- A category name * ``metric_slugs`` -- a list of all metrics that are members of the category. """ key = self._category_key(category) ...
Resets (or creates) a category containing a list of metrics. * ``category`` -- A category name * ``metric_slugs`` -- a list of all metrics that are members of the category.
entailment
def get_metric_history(self, slugs, since=None, to=None, granularity='daily'): """Get history for one or more metrics. * ``slugs`` -- a slug OR a list of slugs * ``since`` -- the date from which we start pulling metrics * ``to`` -- the date until which we start pulling metrics *...
Get history for one or more metrics. * ``slugs`` -- a slug OR a list of slugs * ``since`` -- the date from which we start pulling metrics * ``to`` -- the date until which we start pulling metrics * ``granularity`` -- seconds, minutes, hourly, daily, weekly, ...
entailment
def get_metric_history_as_columns(self, slugs, since=None, granularity='daily'): """Provides the same data as ``get_metric_history``, but in a columnar format. If you had the following yearly history, for example:: [ ('m:bar:y:2012', '1'...
Provides the same data as ``get_metric_history``, but in a columnar format. If you had the following yearly history, for example:: [ ('m:bar:y:2012', '1'), ('m:bar:y:2013', '2'), ('m:foo:y:2012', '3'), ('m:foo:y:2013', '4') ...
entailment
def get_metric_history_chart_data(self, slugs, since=None, granularity='daily'): """Provides the same data as ``get_metric_history``, but with metrics data arranged in a format that's easy to plot with Chart.js. If you had the following yearly history, for example:: [ ...
Provides the same data as ``get_metric_history``, but with metrics data arranged in a format that's easy to plot with Chart.js. If you had the following yearly history, for example:: [ ('m:bar:y:2012', '1'), ('m:bar:y:2013', '2'), ('m:bar:y:20...
entailment
def gauge(self, slug, current_value): """Set the value for a Gauge. * ``slug`` -- the unique identifier (or key) for the Gauge * ``current_value`` -- the value that the gauge should display """ k = self._gauge_key(slug) self.r.sadd(self._gauge_slugs_key, slug) # keep t...
Set the value for a Gauge. * ``slug`` -- the unique identifier (or key) for the Gauge * ``current_value`` -- the value that the gauge should display
entailment
def delete_gauge(self, slug): """Removes all gauges with the given ``slug``.""" key = self._gauge_key(slug) self.r.delete(key) # Remove the Gauge self.r.srem(self._gauge_slugs_key, slug)
Removes all gauges with the given ``slug``.
entailment
def metrics_since(slugs, years, link_type="detail", granularity=None): """Renders a template with a menu to view a metric (or metrics) for a given number of years. * ``slugs`` -- A Slug or a set/list of slugs * ``years`` -- Number of years to show past metrics * ``link_type`` -- What type of chart ...
Renders a template with a menu to view a metric (or metrics) for a given number of years. * ``slugs`` -- A Slug or a set/list of slugs * ``years`` -- Number of years to show past metrics * ``link_type`` -- What type of chart do we want ("history" or "aggregate") * history -- use when displayin...
entailment
def gauge(slug, maximum=9000, size=200, coerce='float'): """Include a Donut Chart for the specified Gauge. * ``slug`` -- the unique slug for the Gauge. * ``maximum`` -- The maximum value for the gauge (default is 9000) * ``size`` -- The size (in pixels) of the gauge (default is 200) * ``coerce`` --...
Include a Donut Chart for the specified Gauge. * ``slug`` -- the unique slug for the Gauge. * ``maximum`` -- The maximum value for the gauge (default is 9000) * ``size`` -- The size (in pixels) of the gauge (default is 200) * ``coerce`` -- type to which gauge values should be coerced. The default ...
entailment
def metric_detail(slug, with_data_table=False): """Template Tag to display a metric's *current* detail. * ``slug`` -- the metric's unique slug * ``with_data_table`` -- if True, prints the raw data in a table. """ r = get_r() granularities = list(r._granularities()) metrics = r.get_metric(s...
Template Tag to display a metric's *current* detail. * ``slug`` -- the metric's unique slug * ``with_data_table`` -- if True, prints the raw data in a table.
entailment
def metric_history(slug, granularity="daily", since=None, to=None, with_data_table=False): """Template Tag to display a metric's history. * ``slug`` -- the metric's unique slug * ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly * ``since`` -- a datetime obje...
Template Tag to display a metric's history. * ``slug`` -- the metric's unique slug * ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly * ``since`` -- a datetime object or a string string matching one of the following patterns: "YYYY-mm-dd" for a date or "YYYY-mm-dd HH:MM:SS" ...
entailment
def aggregate_detail(slug_list, with_data_table=False): """Template Tag to display multiple metrics. * ``slug_list`` -- A list of slugs to display * ``with_data_table`` -- if True, prints the raw data in a table. """ r = get_r() metrics_data = [] granularities = r._granularities() # X...
Template Tag to display multiple metrics. * ``slug_list`` -- A list of slugs to display * ``with_data_table`` -- if True, prints the raw data in a table.
entailment
def aggregate_history(slugs, granularity="daily", since=None, with_data_table=False): """Template Tag to display history for multiple metrics. * ``slug_list`` -- A list of slugs to display * ``granularity`` -- the granularity: seconds, minutes, hourly, daily, weekly, monthly, yearl...
Template Tag to display history for multiple metrics. * ``slug_list`` -- A list of slugs to display * ``granularity`` -- the granularity: seconds, minutes, hourly, daily, weekly, monthly, yearly * ``since`` -- a datetime object or a string string matching one of the following...
entailment
def apply(query, replacements=None, vars=None, allow_io=False, libs=("stdcore", "stdmath")): """Run 'query' on 'vars' and return the result(s). Arguments: query: A query object or string with the query. replacements: Built-time parameters to the query, either as dict or as...
Run 'query' on 'vars' and return the result(s). Arguments: query: A query object or string with the query. replacements: Built-time parameters to the query, either as dict or as an array (for positional interpolation). vars: The variables to be supplied to the query solver. ...
entailment
def user_func(func, arg_types=None, return_type=None): """Create an EFILTER-callable version of function 'func'. As a security precaution, EFILTER will not execute Python callables unless they implement the IApplicative protocol. There is a perfectly good implementation of this protocol in the standard...
Create an EFILTER-callable version of function 'func'. As a security precaution, EFILTER will not execute Python callables unless they implement the IApplicative protocol. There is a perfectly good implementation of this protocol in the standard library and user functions can inherit from it. This...
entailment
def infer(query, replacements=None, root_type=None, libs=("stdcore", "stdmath")): """Determine the type of the query's output without actually running it. Arguments: query: A query object or string with the query. replacements: Built-time parameters to the query, either as dict or as ...
Determine the type of the query's output without actually running it. Arguments: query: A query object or string with the query. replacements: Built-time parameters to the query, either as dict or as an array (for positional interpolation). root_type: The types of variables to b...
entailment
def search(query, data, replacements=None): """Yield objects from 'data' that match the 'query'.""" query = q.Query(query, params=replacements) for entry in data: if solve.solve(query, entry).value: yield entry
Yield objects from 'data' that match the 'query'.
entailment
def peek(self, steps=1): """Look ahead, doesn't affect current_token and next_token.""" try: tokens = iter(self) for _ in six.moves.range(steps): next(tokens) return next(tokens) except StopIteration: return None
Look ahead, doesn't affect current_token and next_token.
entailment
def skip(self, steps=1): """Skip ahead by 'steps' tokens.""" for _ in six.moves.range(steps): self.next_token()
Skip ahead by 'steps' tokens.
entailment
def next_token(self): """Returns the next logical token, advancing the tokenizer.""" if self.lookahead: self.current_token = self.lookahead.popleft() return self.current_token self.current_token = self._parse_next_token() return self.current_token
Returns the next logical token, advancing the tokenizer.
entailment
def _parse_next_token(self): """Will parse patterns until it gets to the next token or EOF.""" while self._position < self.limit: token = self._next_pattern() if token: return token return None
Will parse patterns until it gets to the next token or EOF.
entailment
def _next_pattern(self): """Parses the next pattern by matching each in turn.""" current_state = self.state_stack[-1] position = self._position for pattern in self.patterns: if current_state not in pattern.states: continue m = pattern.regex.match(...
Parses the next pattern by matching each in turn.
entailment
def _error(self, message, start, end=None): """Raise a nice error, with the token highlighted.""" raise errors.EfilterParseError( source=self.source, start=start, end=end, message=message)
Raise a nice error, with the token highlighted.
entailment
def emit(self, string, match, pattern, **_): """Emits a token using the current pattern match and pattern label.""" return grammar.Token(name=pattern.name, value=string, start=match.start(), end=match.end())
Emits a token using the current pattern match and pattern label.
entailment
def get_pkg_version(): """Get version string by parsing PKG-INFO.""" try: with open("PKG-INFO", "r") as fp: rgx = re.compile(r"Version: (\d+)") for line in fp.readlines(): match = rgx.match(line) if match: return match.group(1) ...
Get version string by parsing PKG-INFO.
entailment
def get_version(dev_version=False): """Generates a version string. Arguments: dev_version: Generate a verbose development version from git commits. Examples: 1.1 1.1.dev43 # If 'dev_version' was passed. """ if dev_version: version = git_dev_version() if not ...
Generates a version string. Arguments: dev_version: Generate a verbose development version from git commits. Examples: 1.1 1.1.dev43 # If 'dev_version' was passed.
entailment
def _heartbeat(self): """ **Purpose**: Method to be executed in the heartbeat thread. This method sends a 'request' to the heartbeat-req queue. It expects a 'response' message from the 'heartbeart-res' queue within 10 seconds. This message should contain the same correlation id. If no me...
**Purpose**: Method to be executed in the heartbeat thread. This method sends a 'request' to the heartbeat-req queue. It expects a 'response' message from the 'heartbeart-res' queue within 10 seconds. This message should contain the same correlation id. If no message if received in 10 seconds, the tmgr ...
entailment
def _tmgr(self, uid, rmgr, logger, mq_hostname, port, pending_queue, completed_queue): """ **Purpose**: Method to be run by the tmgr process. This method receives a Task from the pending_queue and submits it to the RTS. At all state transititons, they are synced (blocking) with the AppManager ...
**Purpose**: Method to be run by the tmgr process. This method receives a Task from the pending_queue and submits it to the RTS. At all state transititons, they are synced (blocking) with the AppManager in the master process. In addition, the tmgr also receives heartbeat 'request' msgs from the...
entailment
def start_heartbeat(self): """ **Purpose**: Method to start the heartbeat thread. The heartbeat function is not to be accessed directly. The function is started in a separate thread using this method. """ if not self._hb_thread: try: self._l...
**Purpose**: Method to start the heartbeat thread. The heartbeat function is not to be accessed directly. The function is started in a separate thread using this method.
entailment
def terminate_heartbeat(self): """ **Purpose**: Method to terminate the heartbeat thread. This method is blocking as it waits for the heartbeat thread to terminate (aka join). This is the last method that is executed from the TaskManager and hence closes the profiler. "...
**Purpose**: Method to terminate the heartbeat thread. This method is blocking as it waits for the heartbeat thread to terminate (aka join). This is the last method that is executed from the TaskManager and hence closes the profiler.
entailment
def terminate_manager(self): """ **Purpose**: Method to terminate the tmgr process. This method is blocking as it waits for the tmgr process to terminate (aka join). """ try: if self._tmgr_process: if not self._tmgr_terminate.is_set(): ...
**Purpose**: Method to terminate the tmgr process. This method is blocking as it waits for the tmgr process to terminate (aka join).
entailment
def getvalues(self): """Yields all the values from 'generator_func' and type-checks. Yields: Whatever 'generator_func' yields. Raises: TypeError: if subsequent values are of a different type than first value. ValueError: if subsequent iterat...
Yields all the values from 'generator_func' and type-checks. Yields: Whatever 'generator_func' yields. Raises: TypeError: if subsequent values are of a different type than first value. ValueError: if subsequent iteration returns a different number o...
entailment
def value_eq(self, other): """Sorted comparison of values.""" self_sorted = ordered.ordered(self.getvalues()) other_sorted = ordered.ordered(repeated.getvalues(other)) return self_sorted == other_sorted
Sorted comparison of values.
entailment
def call_audit(func): """Print a detailed audit of all calls to this function.""" def audited_func(*args, **kwargs): import traceback stack = traceback.extract_stack() r = func(*args, **kwargs) func_name = func.__name__ print("@depth %d, trace %s -> %s(*%r, **%r) => %r" ...
Print a detailed audit of all calls to this function.
entailment
def _class_dispatch(args, kwargs): """See 'class_multimethod'.""" _ = kwargs if not args: raise ValueError( "Multimethods must be passed at least one positional arg.") if not isinstance(args[0], type): raise TypeError( "class_multimethod must be called with a typ...
See 'class_multimethod'.
entailment
def prefer_type(self, prefer, over): """Prefer one type over another type, all else being equivalent. With abstract base classes (Python's abc module) it is possible for a type to appear to be a subclass of another type without the supertype appearing in the subtype's MRO. As such, the ...
Prefer one type over another type, all else being equivalent. With abstract base classes (Python's abc module) it is possible for a type to appear to be a subclass of another type without the supertype appearing in the subtype's MRO. As such, the supertype has no order with respect to o...
entailment
def _find_and_cache_best_function(self, dispatch_type): """Finds the best implementation of this function given a type. This function caches the result, and uses locking for thread safety. Returns: Implementing function, in below order of preference: 1. Explicitly regis...
Finds the best implementation of this function given a type. This function caches the result, and uses locking for thread safety. Returns: Implementing function, in below order of preference: 1. Explicitly registered implementations (through multimethod.implement...
entailment
def __get_types(for_type=None, for_types=None): """Parse the arguments and return a tuple of types to implement for. Raises: ValueError or TypeError as appropriate. """ if for_type: if for_types: raise ValueError("Cannot pass both for_type and for...
Parse the arguments and return a tuple of types to implement for. Raises: ValueError or TypeError as appropriate.
entailment
def implementation(self, for_type=None, for_types=None): """Return a decorator that will register the implementation. Example: @multimethod def add(x, y): pass @add.implementation(for_type=int) def add(x, y): return x + y ...
Return a decorator that will register the implementation. Example: @multimethod def add(x, y): pass @add.implementation(for_type=int) def add(x, y): return x + y @add.implementation(for_type=SomeType) def ...
entailment
def implement(self, implementation, for_type=None, for_types=None): """Registers an implementing function for for_type. Arguments: implementation: Callable implementation for this type. for_type: The type this implementation applies to. for_types: Same as for_type, b...
Registers an implementing function for for_type. Arguments: implementation: Callable implementation for this type. for_type: The type this implementation applies to. for_types: Same as for_type, but takes a tuple of types. for_type and for_types cannot both be p...
entailment
def to_int_list(values): """Converts the given list of vlues into a list of integers. If the integer conversion fails (e.g. non-numeric strings or None-values), this filter will include a 0 instead.""" results = [] for v in values: try: results.append(int(v)) except (Type...
Converts the given list of vlues into a list of integers. If the integer conversion fails (e.g. non-numeric strings or None-values), this filter will include a 0 instead.
entailment
def _validate_resource_desc(self): """ **Purpose**: Validate the resource description provided to the ResourceManager """ self._prof.prof('validating rdesc', uid=self._uid) self._logger.debug('Validating resource description') expected_keys = ['resource', ...
**Purpose**: Validate the resource description provided to the ResourceManager
entailment
def _populate(self): """ **Purpose**: Populate the ResourceManager class with the validated resource description """ if self._validated: self._prof.prof('populating rmgr', uid=self._uid) self._logger.debug('Populating resource manager ...
**Purpose**: Populate the ResourceManager class with the validated resource description
entailment
def get_context_data(self, **kwargs): """Includes the Gauge slugs and data in the context.""" data = super(GaugesView, self).get_context_data(**kwargs) data.update({'gauges': get_r().gauge_slugs()}) return data
Includes the Gauge slugs and data in the context.
entailment
def get_context_data(self, **kwargs): """Includes the metrics slugs in the context.""" data = super(MetricsListView, self).get_context_data(**kwargs) # Metrics organized by category, like so: # { <category_name>: [ <slug1>, <slug2>, ... ]} data.update({'metrics': get_r().metric_...
Includes the metrics slugs in the context.
entailment
def get_context_data(self, **kwargs): """Includes the metrics slugs in the context.""" data = super(MetricDetailView, self).get_context_data(**kwargs) data['slug'] = kwargs['slug'] data['granularities'] = list(get_r()._granularities()) return data
Includes the metrics slugs in the context.
entailment
def get_context_data(self, **kwargs): """Includes the metrics slugs in the context.""" data = super(MetricHistoryView, self).get_context_data(**kwargs) # Accept GET query params for ``since`` since = self.request.GET.get('since', None) if since and len(since) == 10: # yyyy-mm-d...
Includes the metrics slugs in the context.
entailment
def get_success_url(self): """Reverses the ``redis_metric_aggregate_detail`` URL using ``self.metric_slugs`` as an argument.""" slugs = '+'.join(self.metric_slugs) url = reverse('redis_metric_aggregate_detail', args=[slugs]) # Django 1.6 quotes reversed URLs, which changes + into...
Reverses the ``redis_metric_aggregate_detail`` URL using ``self.metric_slugs`` as an argument.
entailment
def form_valid(self, form): """Pull the metrics from the submitted form, and store them as a list of strings in ``self.metric_slugs``. """ self.metric_slugs = [k.strip() for k in form.cleaned_data['metrics']] return super(AggregateFormView, self).form_valid(form)
Pull the metrics from the submitted form, and store them as a list of strings in ``self.metric_slugs``.
entailment
def get_context_data(self, **kwargs): """Includes the metrics slugs in the context.""" r = get_r() category = kwargs.pop('category', None) data = super(AggregateDetailView, self).get_context_data(**kwargs) if category: slug_set = r._category_slugs(category) ...
Includes the metrics slugs in the context.
entailment
def get_context_data(self, **kwargs): """Includes the metrics slugs in the context.""" r = get_r() data = super(AggregateHistoryView, self).get_context_data(**kwargs) slug_set = set(kwargs['slugs'].split('+')) granularity = kwargs.get('granularity', 'daily') # Accept GET...
Includes the metrics slugs in the context.
entailment
def get(self, *args, **kwargs): """See if this view was called with a specified category.""" self.initial = {"category_name": kwargs.get('category_name', None)} return super(CategoryFormView, self).get(*args, **kwargs)
See if this view was called with a specified category.
entailment
def form_valid(self, form): """Get the category name/metric slugs from the form, and update the category so contains the given metrics.""" form.categorize_metrics() return super(CategoryFormView, self).form_valid(form)
Get the category name/metric slugs from the form, and update the category so contains the given metrics.
entailment
def rerun(self): """ Rerun sets the state of the Pipeline to scheduling so that the Pipeline can be checked for new stages """ self._state = states.SCHEDULING self._completed_flag = threading.Event() print 'Pipeline %s in %s state'%(self._uid, self._state)
Rerun sets the state of the Pipeline to scheduling so that the Pipeline can be checked for new stages
entailment
def to_dict(self): """ Convert current Pipeline (i.e. its attributes) into a dictionary :return: python dictionary """ pipeline_desc_as_dict = { 'uid': self._uid, 'name': self._name, 'state': self._state, 'state_history': self._s...
Convert current Pipeline (i.e. its attributes) into a dictionary :return: python dictionary
entailment
def from_dict(self, d): """ Create a Pipeline from a dictionary. The change is in inplace. :argument: python dictionary :return: None """ if 'uid' in d: if d['uid']: self._uid = d['uid'] if 'name' in d: if d['name']: ...
Create a Pipeline from a dictionary. The change is in inplace. :argument: python dictionary :return: None
entailment
def _increment_stage(self): """ Purpose: Increment stage pointer. Also check if Pipeline has completed. """ try: if self._cur_stage < self._stage_count: self._cur_stage += 1 else: self._completed_flag.set() except Excepti...
Purpose: Increment stage pointer. Also check if Pipeline has completed.
entailment
def _decrement_stage(self): """ Purpose: Decrement stage pointer. Reset completed flag. """ try: if self._cur_stage > 0: self._cur_stage -= 1 self._completed_flag = threading.Event() # reset except Exception, ex: raise E...
Purpose: Decrement stage pointer. Reset completed flag.
entailment
def _validate_entities(self, stages): """ Purpose: Validate whether the argument 'stages' is of list of Stage objects :argument: list of Stage objects """ if not stages: raise TypeError(expected_type=Stage, actual_type=type(stages)) if not isinstance(stages,...
Purpose: Validate whether the argument 'stages' is of list of Stage objects :argument: list of Stage objects
entailment