INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Change ( x not in y ) to not ( x in y ). | def ComplementMembership(*args, **kwargs):
"""Change (x not in y) to not(x in y)."""
return ast.Complement(
ast.Membership(*args, **kwargs), **kwargs) |
Change ( x doesn t contain y ) to not ( y in x ). | def ReverseComplementMembership(x, y, **kwargs):
"""Change (x doesn't contain y) to not(y in x)."""
return ast.Complement(
ast.Membership(y, x, **kwargs), **kwargs) |
Helper: solve expr always returning an IRepeated. | def __solve_for_repeated(expr, vars):
"""Helper: solve 'expr' always returning an IRepeated.
If the result of solving 'expr' is a list or a tuple of IStructured objects
then treat is as a repeated value of IStructured objects because that's
what the called meant to do. This is a convenience helper so u... |
Helper: solve expr always returning a scalar ( not IRepeated ). | def __solve_for_scalar(expr, vars):
"""Helper: solve 'expr' always returning a scalar (not IRepeated).
If the output of 'expr' is a single value or a single RowTuple with a single
column then return the value in that column. Otherwise raise.
Arguments:
expr: Expression to solve.
vars: ... |
Helper: solve expr always returning a list of scalars. | def __solve_and_destructure_repeated(expr, vars):
"""Helper: solve 'expr' always returning a list of scalars.
If the output of 'expr' is one or more row tuples with only a single column
then return a repeated value of values in that column. If there are more
than one column per row then raise.
Thi... |
Returns the value of the var named in the expression. | def solve_var(expr, vars):
"""Returns the value of the var named in the expression."""
try:
return Result(structured.resolve(vars, expr.value), ())
except (KeyError, AttributeError) as e:
# Raise a better exception for accessing a non-existent member.
raise errors.EfilterKeyError(roo... |
Use IAssociative. select to get key ( rhs ) from the data ( lhs ). | def solve_select(expr, vars):
"""Use IAssociative.select to get key (rhs) from the data (lhs).
This operation supports both scalars and repeated values on the LHS -
selecting from a repeated value implies a map-like operation and returns a
new repeated value.
"""
data, _ = __solve_for_repeated(... |
Use IStructured. resolve to get member ( rhs ) from the object ( lhs ). | def solve_resolve(expr, vars):
"""Use IStructured.resolve to get member (rhs) from the object (lhs).
This operation supports both scalars and repeated values on the LHS -
resolving from a repeated value implies a map-like operation and returns a
new repeated values.
"""
objs, _ = __solve_for_re... |
Returns the result of applying function ( lhs ) to its arguments ( rest ). | def solve_apply(expr, vars):
"""Returns the result of applying function (lhs) to its arguments (rest).
We use IApplicative to apply the function, because that gives the host
application an opportunity to compare the function being called against
a whitelist. EFILTER will never directly call a function ... |
Build a RowTuple from key/ value pairs under the bind. | def solve_bind(expr, vars):
"""Build a RowTuple from key/value pairs under the bind.
The Bind subtree is arranged as follows:
Bind
| First KV Pair
| | First Key Expression
| | First Value Expression
| Second KV Pair
| | Second Key Expression
| | Second Value Expression
Etc...
... |
Build a repeated value from subexpressions. | def solve_repeat(expr, vars):
"""Build a repeated value from subexpressions."""
try:
result = repeated.meld(*[solve(x, vars).value for x in expr.children])
return Result(result, ())
except TypeError:
raise errors.EfilterTypeError(
root=expr, query=expr.source,
... |
Build a tuple from subexpressions. | def solve_tuple(expr, vars):
"""Build a tuple from subexpressions."""
result = tuple(solve(x, vars).value for x in expr.children)
return Result(result, ()) |
Evaluate conditions and return the one that matches. | def solve_ifelse(expr, vars):
"""Evaluate conditions and return the one that matches."""
for condition, result in expr.conditions():
if boolean.asbool(solve(condition, vars).value):
return solve(result, vars)
return solve(expr.default(), vars) |
Solves the map - form by recursively calling its RHS with new vars. | def solve_map(expr, vars):
"""Solves the map-form, by recursively calling its RHS with new vars.
let-forms are binary expressions. The LHS should evaluate to an IAssociative
that can be used as new vars with which to solve a new query, of which
the RHS is the root. In most cases, the LHS will be a Var ... |
Solves a let - form by calling RHS with nested scope. | def solve_let(expr, vars):
"""Solves a let-form by calling RHS with nested scope."""
lhs_value = solve(expr.lhs, vars).value
if not isinstance(lhs_value, structured.IStructured):
raise errors.EfilterTypeError(
root=expr.lhs, query=expr.original,
message="The LHS of 'let' must... |
Filter values on the LHS by evaluating RHS with each value. | def solve_filter(expr, vars):
"""Filter values on the LHS by evaluating RHS with each value.
Returns any LHS values for which RHS evaluates to a true value.
"""
lhs_values, _ = __solve_for_repeated(expr.lhs, vars)
def lazy_filter():
for lhs_value in repeated.getvalues(lhs_values):
... |
Sort values on the LHS by the value they yield when passed to RHS. | def solve_sort(expr, vars):
"""Sort values on the LHS by the value they yield when passed to RHS."""
lhs_values = repeated.getvalues(__solve_for_repeated(expr.lhs, vars)[0])
sort_expression = expr.rhs
def _key_func(x):
return solve(sort_expression, __nest_scope(expr.lhs, vars, x)).value
r... |
Return True if RHS evaluates to a true value with each state of LHS. | def solve_each(expr, vars):
"""Return True if RHS evaluates to a true value with each state of LHS.
If LHS evaluates to a normal IAssociative object then this is the same as
a regular let-form, except the return value is always a boolean. If LHS
evaluates to a repeared var (see efilter.protocols.repeat... |
Get cast LHS to RHS. | def solve_cast(expr, vars):
"""Get cast LHS to RHS."""
lhs = solve(expr.lhs, vars).value
t = solve(expr.rhs, vars).value
if t is None:
raise errors.EfilterTypeError(
root=expr, query=expr.source,
message="Cannot find type named %r." % expr.rhs.value)
if not isinstan... |
Typecheck whether LHS is type on the RHS. | def solve_isinstance(expr, vars):
"""Typecheck whether LHS is type on the RHS."""
lhs = solve(expr.lhs, vars)
try:
t = solve(expr.rhs, vars).value
except errors.EfilterKeyError:
t = None
if t is None:
raise errors.EfilterTypeError(
root=expr.rhs, query=expr.sour... |
mod_root a VERSION file containes the version strings is created in mod_root during installation. That file is used at runtime to get the version information. | def set_version(mod_root):
"""
mod_root
a VERSION file containes the version strings is created in mod_root,
during installation. That file is used at runtime to get the version
information.
"""
try:
version_base = None
version_detail = None
# ge... |
Create distutils data_files structure from dir distutil will copy all file rooted under dir into prefix excluding dir itself just like ditto src dst works and unlike cp - r src dst which copy src into dst. Typical usage: # install the contents of wiki under sys. prefix + share/ moin data_files = makeDataFiles ( share/ ... | def makeDataFiles(prefix, dir):
""" Create distutils data_files structure from dir
distutil will copy all file rooted under dir into prefix, excluding
dir itself, just like 'ditto src dst' works, and unlike 'cp -r src
dst, which copy src into dst'.
Typical usage:
# install the contents of 'w... |
Visit directory create distutil tuple Add distutil tuple for each directory using this format: ( destination [ dirname/ file1 dirname/ file2... ] ) distutil will copy later file1 file2... info destination. | def visit((prefix, strip, found), dirname, names):
""" Visit directory, create distutil tuple
Add distutil tuple for each directory using this format:
(destination, [dirname/file1, dirname/file2, ...])
distutil will copy later file1, file2, ... info destination.
"""
files = []
# Iterate ... |
Whether name should be installed | def isgood(name):
""" Whether name should be installed """
if not isbad(name):
if name.endswith('.py') or name.endswith('.json') or name.endswith('.tar'):
return True
return False |
** Purpose **: Initialize the PST of the workflow with a uid and type checks | def _initialize_workflow(self):
"""
**Purpose**: Initialize the PST of the workflow with a uid and type checks
"""
try:
self._prof.prof('initializing workflow', uid=self._uid)
for p in self._workflow:
p._assign_uid(self._sid)
self._... |
** Purpose **: This is the function that is run in the enqueue thread. This function extracts Tasks from the copy of workflow that exists in the WFprocessor object and pushes them to the queues in the pending_q list. Since this thread works on the copy of the workflow every state update to the Task Stage and Pipeline i... | def _enqueue(self, local_prof):
"""
**Purpose**: This is the function that is run in the enqueue thread. This function extracts Tasks from the
copy of workflow that exists in the WFprocessor object and pushes them to the queues in the pending_q list.
Since this thread works on the copy o... |
** Purpose **: This is the function that is run in the dequeue thread. This function extracts Tasks from the completed queus and updates the copy of workflow that exists in the WFprocessor object. Since this thread works on the copy of the workflow every state update to the Task Stage and Pipeline is communicated back ... | def _dequeue(self, local_prof):
"""
**Purpose**: This is the function that is run in the dequeue thread. This function extracts Tasks from the
completed queus and updates the copy of workflow that exists in the WFprocessor object.
Since this thread works on the copy of the workflow, ever... |
** Purpose **: This is the function executed in the wfp process. The function is used to simply create and spawn two threads: enqueue dequeue. The enqueue thread pushes ready tasks to the queues in the pending_q slow list whereas the dequeue thread pulls completed tasks from the queues in the completed_q. This function... | def _wfp(self):
"""
**Purpose**: This is the function executed in the wfp process. The function is used to simply create
and spawn two threads: enqueue, dequeue. The enqueue thread pushes ready tasks to the queues in the pending_q slow
list whereas the dequeue thread pulls completed task... |
** Purpose **: Method to start the wfp process. The wfp function is not to be accessed directly. The function is started in a separate process using this method. | def start_processor(self):
"""
**Purpose**: Method to start the wfp process. The wfp function
is not to be accessed directly. The function is started in a separate
process using this method.
"""
if not self._wfp_process:
try:
self._prof.prof... |
** Purpose **: Method to terminate the wfp process. This method is blocking as it waits for the wfp process to terminate ( aka join ). | def terminate_processor(self):
"""
**Purpose**: Method to terminate the wfp process. This method is
blocking as it waits for the wfp process to terminate (aka join).
"""
try:
if self.check_processor():
self._logger.debug(
'Attempt... |
** Purpose **: Method to check if the workflow execution is incomplete. | def workflow_incomplete(self):
"""
**Purpose**: Method to check if the workflow execution is incomplete.
"""
try:
for pipe in self._workflow:
with pipe.lock:
if pipe.completed:
pass
else:
... |
Return the repeated value or the first value if there s only one. | def meld(*values):
"""Return the repeated value, or the first value if there's only one.
This is a convenience function, equivalent to calling
getvalue(repeated(x)) to get x.
This function skips over instances of None in values (None is not allowed
in repeated variables).
Examples:
me... |
Return the single value of x or raise TypError if more than one value. | def getvalue(x):
"""Return the single value of x or raise TypError if more than one value."""
if isrepeating(x):
raise TypeError(
"Ambiguous call to getvalue for %r which has more than one value."
% x)
for value in getvalues(x):
return value |
Unique ID of the current task ( fully qualified ). | def luid(self):
"""
Unique ID of the current task (fully qualified).
example:
>>> task.luid
pipe.0001.stage.0004.task.0234
:getter: Returns the fully qualified uid of the current task
:type: String
"""
p_elem = self.parent_pipeline.get('n... |
Convert current Task into a dictionary | def to_dict(self):
"""
Convert current Task into a dictionary
:return: python dictionary
"""
task_desc_as_dict = {
'uid': self._uid,
'name': self._name,
'state': self._state,
'state_history': self._state_history,
'pre... |
Create a Task from a dictionary. The change is in inplace. | def from_dict(self, d):
"""
Create a Task 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']:
... |
Purpose: Assign a uid to the current object based on the sid passed | def _assign_uid(self, sid):
"""
Purpose: Assign a uid to the current object based on the sid passed
"""
self._uid = ru.generate_id(
'task.%(item_counter)04d', ru.ID_CUSTOM, namespace=sid) |
Purpose: Validate that the state of the task is DESCRIBED and that an executable has been specified for the task. | def _validate(self):
"""
Purpose: Validate that the state of the task is 'DESCRIBED' and that an executable has been specified for the
task.
"""
if self._state is not states.INITIAL:
raise ValueError(obj=self._uid,
attribute='state',
... |
** Purpose **: The new thread that gets spawned by the main tmgr process invokes this function. This function receives tasks from task_queue and submits them to the RADICAL Pilot RTS. | def _process_tasks(self, task_queue, rmgr, logger, mq_hostname, port, local_prof, sid):
'''
**Purpose**: The new thread that gets spawned by the main tmgr process invokes this function. This
function receives tasks from 'task_queue' and submits them to the RADICAL Pilot RTS.
'''
... |
Try to infer the type of x [ y ] if y is a known value ( literal ). | def infer_type(expr, scope):
"""Try to infer the type of x[y] if y is a known value (literal)."""
# Do we know what the key even is?
if isinstance(expr.key, ast.Literal):
key = expr.key.value
else:
return protocol.AnyType
container_type = infer_type(expr.value, scope)
try:
... |
Try to infer the type of x. y if y is a known value ( literal ). | def infer_type(expr, scope):
"""Try to infer the type of x.y if y is a known value (literal)."""
# Do we know what the member is?
if isinstance(expr.member, ast.Literal):
member = expr.member.value
else:
return protocol.AnyType
container_type = infer_type(expr.obj, scope)
try:
... |
** Purpose **: Method to be run by the tmgr process. This method receives a Task from the pending_queue and submits it to the RTS. Currently it also converts Tasks into CUDs and CUs into ( partially described ) Tasks. This conversion is necessary since the current RTS is RADICAL Pilot. Once Tasks are recovered from a C... | 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. Currently, it also converts Tasks into CUDs and CUs into (partially describe... |
** Purpose **: Method to start the tmgr process. The tmgr function is not to be accessed directly. The function is started in a separate thread using this method. | def start_manager(self):
"""
**Purpose**: Method to start the tmgr process. The tmgr function
is not to be accessed directly. The function is started in a separate
thread using this method.
"""
if not self._tmgr_process:
try:
self._prof.prof... |
Case - insensitive keyword match. | def keyword(tokens, expected):
"""Case-insensitive keyword match."""
try:
token = next(iter(tokens))
except StopIteration:
return
if token and token.name == "symbol" and token.value.lower() == expected:
return TokenMatch(None, token.value, (token,)) |
Match a case - insensitive keyword consisting of multiple tokens. | def multi_keyword(tokens, keyword_parts):
"""Match a case-insensitive keyword consisting of multiple tokens."""
tokens = iter(tokens)
matched_tokens = []
limit = len(keyword_parts)
for idx in six.moves.range(limit):
try:
token = next(tokens)
except StopIteration:
... |
Match a prefix of an operator. | def prefix(tokens, operator_table):
"""Match a prefix of an operator."""
operator, matched_tokens = operator_table.prefix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) |
Match an infix of an operator. | def infix(tokens, operator_table):
"""Match an infix of an operator."""
operator, matched_tokens = operator_table.infix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) |
Match a suffix of an operator. | def suffix(tokens, operator_table):
"""Match a suffix of an operator."""
operator, matched_tokens = operator_table.suffix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) |
Match a token name ( type ). | def token_name(tokens, expected):
"""Match a token name (type)."""
try:
token = next(iter(tokens))
except StopIteration:
return
if token and token.name == expected:
return TokenMatch(None, token.value, (token,)) |
Generate a grammar function that will match expected_tokens only. | def match_tokens(expected_tokens):
"""Generate a grammar function that will match 'expected_tokens' only."""
if isinstance(expected_tokens, Token):
# Match a single token.
def _grammar_func(tokens):
try:
next_token = next(iter(tokens))
except StopIteration... |
Create/ Increment a metric. | def set_metric(slug, value, category=None, expire=None, date=None):
"""Create/Increment a metric."""
get_r().set_metric(slug, value, category=category, expire=expire, date=date) |
Create/ Increment a metric. | def metric(slug, num=1, category=None, expire=None, date=None):
"""Create/Increment a metric."""
get_r().metric(slug, num=num, category=category, expire=expire, date=date) |
An expression is an atom or an infix expression. | def expression(self, previous_precedence=0):
"""An expression is an atom or an infix expression.
Grammar (sort of, actually a precedence-climbing parser):
expression = atom [ binary_operator expression ] .
Args:
previous_precedence: What operator precedence should we st... |
Parse an atom which is most things. | def atom(self):
"""Parse an atom, which is most things.
Grammar:
atom =
[ prefix ]
( select_expression
| any_expression
| func_application
| let_expr
| var
| literal
... |
Accept the next binary operator only if it s of higher precedence. | 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... |
Climb operator precedence as long as there are operators. | 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... |
Match the right - hand side of a dot (. ) operator. | 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... |
First part of an SQL query. | 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.
... |
Tries to guess what variable name expr ends in. | 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... |
Match LIMIT take [ OFFSET drop ]. | 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... |
Parse the pseudo - function application subgrammar. | 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 function application subgrammar. | 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 a list ( tuple ) which can contain any combination of types. | 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)
... |
If the row only has one column return that value ; otherwise raise. | 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 ... |
Record CPU usage. | def _cpu(self):
"""Record CPU usage."""
value = int(psutil.cpu_percent())
set_metric("cpu", value, category=self.category)
gauge("cpu", value) |
Record Memory usage. | def _mem(self):
"""Record Memory usage."""
value = int(psutil.virtual_memory().percent)
set_metric("memory", value, category=self.category)
gauge("memory", value) |
Record Disk usage. | 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 Network usage. | 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... |
Does the object obj implement the prococol ? | 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 type cls participate in the protocol ? | 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... |
Assert that protocol cls is implemented for type for_type. | 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:
... |
Parse the arguments and return a tuple of types to implement for. | 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... |
Automatically generate implementations for a type. | 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'.
... |
Return a function that calls method func_name on objects. | 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 ... |
Automatically generate late dynamic dispatchers to type. | 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 ... |
Provide protocol implementation for a type. | 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... |
Parse one of the rules as either objectfilter or dottysql. | 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 the tagfile and yield tuples of tag_name list of rule ASTs. | 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, ... |
Normalize both sides but don t eliminate the expression. | 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) |
No elimination but normalize arguments. | 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) |
Pass through n - ary expressions and eliminate empty branches. | 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 ... |
Remove duplicates from a sequence ( of hashable items ) while maintaining order. NOTE: This only works if items in the list are hashable types. | 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:
... |
Returns a generator that yields datetime. datetime objects from the since date until to ( default: * now * ). | 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 set of the metric slugs for the given category | 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 |
Add the slug to the category. We store category data as as set with a key of the form:: | 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... |
Returns a generator of all possible granularities based on the MIN_GRANULARITY and MAX_GRANULARITY settings. | 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
... |
Builds an OrderedDict of metric keys and patterns for the given slug and date. | 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 redis keys used to store metrics. | 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... |
Return a dictionary of metrics data indexed by category: | 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:
... |
Removes all keys for the given slug. | 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... |
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. | 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... |
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. | 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:
... |
Get the current values for a metric. | 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 metrics for multiple slugs. | 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 metrics belonging to the given category | 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) |
Removes the category from Redis. This doesn t touch the metrics ; they simply become uncategorized. | 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... |
Resets ( or creates ) a category containing a list of metrics. | 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)
... |
Get history for one or more metrics. | 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
*... |
Provides the same data as get_metric_history but in a columnar format. If you had the following yearly history for example:: | 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 with metrics data arranged in a format that s easy to plot with Chart. js. If you had the following yearly history for example:: | 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::
[
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.