repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
google/dotty
|
sample_projects/tagging/tag.py
|
TagFile._parse_query
|
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:
The AST to represent the rule.
"""
if self.OBJECTFILTER_WORDS.search(source):
syntax_ = "objectfilter"
else:
syntax_ = None # Default it is.
return query.Query(source, syntax=syntax_)
|
python
|
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:
The AST to represent the rule.
"""
if self.OBJECTFILTER_WORDS.search(source):
syntax_ = "objectfilter"
else:
syntax_ = None # Default it is.
return query.Query(source, syntax=syntax_)
|
[
"def",
"_parse_query",
"(",
"self",
",",
"source",
")",
":",
"if",
"self",
".",
"OBJECTFILTER_WORDS",
".",
"search",
"(",
"source",
")",
":",
"syntax_",
"=",
"\"objectfilter\"",
"else",
":",
"syntax_",
"=",
"None",
"# Default it is.",
"return",
"query",
".",
"Query",
"(",
"source",
",",
"syntax",
"=",
"syntax_",
")"
] |
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.
|
[
"Parse",
"one",
"of",
"the",
"rules",
"as",
"either",
"objectfilter",
"or",
"dottysql",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/sample_projects/tagging/tag.py#L96-L114
|
train
|
google/dotty
|
sample_projects/tagging/tag.py
|
TagFile._parse_tagfile
|
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, rules
rules = []
tag = match.group(1)
continue
match = self.TAG_RULE_LINE.match(line)
if match:
source = match.group(1)
rules.append(self._parse_query(source))
|
python
|
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, rules
rules = []
tag = match.group(1)
continue
match = self.TAG_RULE_LINE.match(line)
if match:
source = match.group(1)
rules.append(self._parse_query(source))
|
[
"def",
"_parse_tagfile",
"(",
"self",
")",
":",
"rules",
"=",
"None",
"tag",
"=",
"None",
"for",
"line",
"in",
"self",
".",
"original",
":",
"match",
"=",
"self",
".",
"TAG_DECL_LINE",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"if",
"tag",
"and",
"rules",
":",
"yield",
"tag",
",",
"rules",
"rules",
"=",
"[",
"]",
"tag",
"=",
"match",
".",
"group",
"(",
"1",
")",
"continue",
"match",
"=",
"self",
".",
"TAG_RULE_LINE",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"source",
"=",
"match",
".",
"group",
"(",
"1",
")",
"rules",
".",
"append",
"(",
"self",
".",
"_parse_query",
"(",
"source",
")",
")"
] |
Parse the tagfile and yield tuples of tag_name, list of rule ASTs.
|
[
"Parse",
"the",
"tagfile",
"and",
"yield",
"tuples",
"of",
"tag_name",
"list",
"of",
"rule",
"ASTs",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/sample_projects/tagging/tag.py#L116-L132
|
train
|
google/dotty
|
efilter/transforms/normalize.py
|
normalize
|
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)
|
python
|
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)
|
[
"def",
"normalize",
"(",
"expr",
")",
":",
"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.
|
[
"Normalize",
"both",
"sides",
"but",
"don",
"t",
"eliminate",
"the",
"expression",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/transforms/normalize.py#L64-L68
|
train
|
google/dotty
|
efilter/transforms/normalize.py
|
normalize
|
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)
|
python
|
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)
|
[
"def",
"normalize",
"(",
"expr",
")",
":",
"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.
|
[
"No",
"elimination",
"but",
"normalize",
"arguments",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/transforms/normalize.py#L72-L76
|
train
|
google/dotty
|
efilter/transforms/normalize.py
|
normalize
|
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 left, it is promoted to replace the parent node:
(& True) => True
"""
children = []
for child in expr.children:
branch = normalize(child)
if branch is None:
continue
if type(branch) is type(expr):
children.extend(branch.children)
else:
children.append(branch)
if len(children) == 0:
return None
if len(children) == 1:
return children[0]
return type(expr)(*children, start=children[0].start,
end=children[-1].end)
|
python
|
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 left, it is promoted to replace the parent node:
(& True) => True
"""
children = []
for child in expr.children:
branch = normalize(child)
if branch is None:
continue
if type(branch) is type(expr):
children.extend(branch.children)
else:
children.append(branch)
if len(children) == 0:
return None
if len(children) == 1:
return children[0]
return type(expr)(*children, start=children[0].start,
end=children[-1].end)
|
[
"def",
"normalize",
"(",
"expr",
")",
":",
"children",
"=",
"[",
"]",
"for",
"child",
"in",
"expr",
".",
"children",
":",
"branch",
"=",
"normalize",
"(",
"child",
")",
"if",
"branch",
"is",
"None",
":",
"continue",
"if",
"type",
"(",
"branch",
")",
"is",
"type",
"(",
"expr",
")",
":",
"children",
".",
"extend",
"(",
"branch",
".",
"children",
")",
"else",
":",
"children",
".",
"append",
"(",
"branch",
")",
"if",
"len",
"(",
"children",
")",
"==",
"0",
":",
"return",
"None",
"if",
"len",
"(",
"children",
")",
"==",
"1",
":",
"return",
"children",
"[",
"0",
"]",
"return",
"type",
"(",
"expr",
")",
"(",
"*",
"children",
",",
"start",
"=",
"children",
"[",
"0",
"]",
".",
"start",
",",
"end",
"=",
"children",
"[",
"-",
"1",
"]",
".",
"end",
")"
] |
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 replace the parent node:
(& True) => True
|
[
"Pass",
"through",
"n",
"-",
"ary",
"expressions",
"and",
"eliminate",
"empty",
"branches",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/transforms/normalize.py#L80-L112
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
dedupe
|
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:
yield item
seen.add(item)
|
python
|
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:
yield item
seen.add(item)
|
[
"def",
"dedupe",
"(",
"items",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"not",
"in",
"seen",
":",
"yield",
"item",
"seen",
".",
"add",
"(",
"item",
")"
] |
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!
|
[
"Remove",
"duplicates",
"from",
"a",
"sequence",
"(",
"of",
"hashable",
"items",
")",
"while",
"maintaining",
"order",
".",
"NOTE",
":",
"This",
"only",
"works",
"if",
"items",
"in",
"the",
"list",
"are",
"hashable",
"types",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L18-L29
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R._date_range
|
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, hourly, daily, weekly,
monthly, or yearly
* ``since`` -- a ``datetime.datetime`` object, from which we start
generating periods of time. This can also be ``None``, and will
default to the past 7 days if that's the case.
* ``to`` -- a ``datetime.datetime`` object, from which we start
generating periods of time. This can also be ``None``, and will
default to now if that's the case.
If ``granularity`` is one of daily, weekly, monthly, or yearly, this
function gives objects at the daily level.
If ``granularity`` is one of the following, the number of datetime
objects returned is capped, otherwise this code is really slow and
probably generates more data than we want:
* hourly: returns at most 720 values (~30 days)
* minutes: returns at most 480 values (8 hours)
* second: returns at most 300 values (5 minutes)
For example, if granularity is "seconds", we'll receive datetime
objects that differ by 1 second each.
"""
if since is None:
since = datetime.utcnow() - timedelta(days=7) # Default to 7 days
if to is None:
to = datetime.utcnow()
elapsed = (to - since)
# Figure out how many units to generate for the elapsed time.
# I'm going to use `granularity` as a keyword parameter to timedelta,
# so I need to change the wording for hours and anything > days.
if granularity == "seconds":
units = elapsed.total_seconds()
units = 300 if units > 300 else units
elif granularity == "minutes":
units = elapsed.total_seconds() / 60
units = 480 if units > 480 else units
elif granularity == "hourly":
granularity = "hours"
units = elapsed.total_seconds() / 3600
units = 720 if units > 720 else units
else:
granularity = "days"
units = elapsed.days + 1
return (to - timedelta(**{granularity: u}) for u in range(int(units)))
|
python
|
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, hourly, daily, weekly,
monthly, or yearly
* ``since`` -- a ``datetime.datetime`` object, from which we start
generating periods of time. This can also be ``None``, and will
default to the past 7 days if that's the case.
* ``to`` -- a ``datetime.datetime`` object, from which we start
generating periods of time. This can also be ``None``, and will
default to now if that's the case.
If ``granularity`` is one of daily, weekly, monthly, or yearly, this
function gives objects at the daily level.
If ``granularity`` is one of the following, the number of datetime
objects returned is capped, otherwise this code is really slow and
probably generates more data than we want:
* hourly: returns at most 720 values (~30 days)
* minutes: returns at most 480 values (8 hours)
* second: returns at most 300 values (5 minutes)
For example, if granularity is "seconds", we'll receive datetime
objects that differ by 1 second each.
"""
if since is None:
since = datetime.utcnow() - timedelta(days=7) # Default to 7 days
if to is None:
to = datetime.utcnow()
elapsed = (to - since)
# Figure out how many units to generate for the elapsed time.
# I'm going to use `granularity` as a keyword parameter to timedelta,
# so I need to change the wording for hours and anything > days.
if granularity == "seconds":
units = elapsed.total_seconds()
units = 300 if units > 300 else units
elif granularity == "minutes":
units = elapsed.total_seconds() / 60
units = 480 if units > 480 else units
elif granularity == "hourly":
granularity = "hours"
units = elapsed.total_seconds() / 3600
units = 720 if units > 720 else units
else:
granularity = "days"
units = elapsed.days + 1
return (to - timedelta(**{granularity: u}) for u in range(int(units)))
|
[
"def",
"_date_range",
"(",
"self",
",",
"granularity",
",",
"since",
",",
"to",
"=",
"None",
")",
":",
"if",
"since",
"is",
"None",
":",
"since",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"7",
")",
"# Default to 7 days",
"if",
"to",
"is",
"None",
":",
"to",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"elapsed",
"=",
"(",
"to",
"-",
"since",
")",
"# Figure out how many units to generate for the elapsed time.",
"# I'm going to use `granularity` as a keyword parameter to timedelta,",
"# so I need to change the wording for hours and anything > days.",
"if",
"granularity",
"==",
"\"seconds\"",
":",
"units",
"=",
"elapsed",
".",
"total_seconds",
"(",
")",
"units",
"=",
"300",
"if",
"units",
">",
"300",
"else",
"units",
"elif",
"granularity",
"==",
"\"minutes\"",
":",
"units",
"=",
"elapsed",
".",
"total_seconds",
"(",
")",
"/",
"60",
"units",
"=",
"480",
"if",
"units",
">",
"480",
"else",
"units",
"elif",
"granularity",
"==",
"\"hourly\"",
":",
"granularity",
"=",
"\"hours\"",
"units",
"=",
"elapsed",
".",
"total_seconds",
"(",
")",
"/",
"3600",
"units",
"=",
"720",
"if",
"units",
">",
"720",
"else",
"units",
"else",
":",
"granularity",
"=",
"\"days\"",
"units",
"=",
"elapsed",
".",
"days",
"+",
"1",
"return",
"(",
"to",
"-",
"timedelta",
"(",
"*",
"*",
"{",
"granularity",
":",
"u",
"}",
")",
"for",
"u",
"in",
"range",
"(",
"int",
"(",
"units",
")",
")",
")"
] |
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
* ``since`` -- a ``datetime.datetime`` object, from which we start
generating periods of time. This can also be ``None``, and will
default to the past 7 days if that's the case.
* ``to`` -- a ``datetime.datetime`` object, from which we start
generating periods of time. This can also be ``None``, and will
default to now if that's the case.
If ``granularity`` is one of daily, weekly, monthly, or yearly, this
function gives objects at the daily level.
If ``granularity`` is one of the following, the number of datetime
objects returned is capped, otherwise this code is really slow and
probably generates more data than we want:
* hourly: returns at most 720 values (~30 days)
* minutes: returns at most 480 values (8 hours)
* second: returns at most 300 values (5 minutes)
For example, if granularity is "seconds", we'll receive datetime
objects that differ by 1 second each.
|
[
"Returns",
"a",
"generator",
"that",
"yields",
"datetime",
".",
"datetime",
"objects",
"from",
"the",
"since",
"date",
"until",
"to",
"(",
"default",
":",
"*",
"now",
"*",
")",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L91-L144
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R._category_slugs
|
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
|
python
|
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
|
[
"def",
"_category_slugs",
"(",
"self",
",",
"category",
")",
":",
"key",
"=",
"self",
".",
"_category_key",
"(",
"category",
")",
"slugs",
"=",
"self",
".",
"r",
".",
"smembers",
"(",
"key",
")",
"return",
"slugs"
] |
Returns a set of the metric slugs for the given category
|
[
"Returns",
"a",
"set",
"of",
"the",
"metric",
"slugs",
"for",
"the",
"given",
"category"
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L154-L158
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R._categorize
|
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)
self.r.sadd(key, slug)
# Store all category names in a Redis set, for easy retrieval
self.r.sadd(self._categories_key, category)
|
python
|
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)
self.r.sadd(key, slug)
# Store all category names in a Redis set, for easy retrieval
self.r.sadd(self._categories_key, category)
|
[
"def",
"_categorize",
"(",
"self",
",",
"slug",
",",
"category",
")",
":",
"key",
"=",
"self",
".",
"_category_key",
"(",
"category",
")",
"self",
".",
"r",
".",
"sadd",
"(",
"key",
",",
"slug",
")",
"# Store all category names in a Redis set, for easy retrieval",
"self",
".",
"r",
".",
"sadd",
"(",
"self",
".",
"_categories_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", ...
|
[
"Add",
"the",
"slug",
"to",
"the",
"category",
".",
"We",
"store",
"category",
"data",
"as",
"as",
"set",
"with",
"a",
"key",
"of",
"the",
"form",
"::"
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L160-L175
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R._granularities
|
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
elif g == app_settings.MAX_GRANULARITY and keep:
keep = False
yield g
if keep:
yield g
|
python
|
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
elif g == app_settings.MAX_GRANULARITY and keep:
keep = False
yield g
if keep:
yield g
|
[
"def",
"_granularities",
"(",
"self",
")",
":",
"keep",
"=",
"False",
"for",
"g",
"in",
"GRANULARITIES",
":",
"if",
"g",
"==",
"app_settings",
".",
"MIN_GRANULARITY",
"and",
"not",
"keep",
":",
"keep",
"=",
"True",
"elif",
"g",
"==",
"app_settings",
".",
"MAX_GRANULARITY",
"and",
"keep",
":",
"keep",
"=",
"False",
"yield",
"g",
"if",
"keep",
":",
"yield",
"g"
] |
Returns a generator of all possible granularities based on the
MIN_GRANULARITY and MAX_GRANULARITY settings.
|
[
"Returns",
"a",
"generator",
"of",
"all",
"possible",
"granularities",
"based",
"on",
"the",
"MIN_GRANULARITY",
"and",
"MAX_GRANULARITY",
"settings",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L177-L189
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R._build_key_patterns
|
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 in self._granularities():
date_string = date.strftime(metric_key_patterns[g]["date_format"])
patts[g] = metric_key_patterns[g]["key"].format(slug, date_string)
return patts
|
python
|
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 in self._granularities():
date_string = date.strftime(metric_key_patterns[g]["date_format"])
patts[g] = metric_key_patterns[g]["key"].format(slug, date_string)
return patts
|
[
"def",
"_build_key_patterns",
"(",
"self",
",",
"slug",
",",
"date",
")",
":",
"# we want to keep the order, from smallest to largest granularity",
"patts",
"=",
"OrderedDict",
"(",
")",
"metric_key_patterns",
"=",
"self",
".",
"_metric_key_patterns",
"(",
")",
"for",
"g",
"in",
"self",
".",
"_granularities",
"(",
")",
":",
"date_string",
"=",
"date",
".",
"strftime",
"(",
"metric_key_patterns",
"[",
"g",
"]",
"[",
"\"date_format\"",
"]",
")",
"patts",
"[",
"g",
"]",
"=",
"metric_key_patterns",
"[",
"g",
"]",
"[",
"\"key\"",
"]",
".",
"format",
"(",
"slug",
",",
"date_string",
")",
"return",
"patts"
] |
Builds an OrderedDict of metric keys and patterns for the given slug
and date.
|
[
"Builds",
"an",
"OrderedDict",
"of",
"metric",
"keys",
"and",
"patterns",
"for",
"the",
"given",
"slug",
"and",
"date",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L206-L215
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R._build_keys
|
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 current date
and time (in UTC) will be used.
* ``granularity`` -- Must be one of: "all" (default), "yearly",
"monthly", "weekly", "daily", "hourly", "minutes", or "seconds".
Returns a list of strings.
"""
slug = slugify(slug) # Ensure slugs have a consistent format
if date is None:
date = datetime.utcnow()
patts = self._build_key_patterns(slug, date)
if granularity == "all":
return list(patts.values())
return [patts[granularity]]
|
python
|
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 current date
and time (in UTC) will be used.
* ``granularity`` -- Must be one of: "all" (default), "yearly",
"monthly", "weekly", "daily", "hourly", "minutes", or "seconds".
Returns a list of strings.
"""
slug = slugify(slug) # Ensure slugs have a consistent format
if date is None:
date = datetime.utcnow()
patts = self._build_key_patterns(slug, date)
if granularity == "all":
return list(patts.values())
return [patts[granularity]]
|
[
"def",
"_build_keys",
"(",
"self",
",",
"slug",
",",
"date",
"=",
"None",
",",
"granularity",
"=",
"'all'",
")",
":",
"slug",
"=",
"slugify",
"(",
"slug",
")",
"# Ensure slugs have a consistent format",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"patts",
"=",
"self",
".",
"_build_key_patterns",
"(",
"slug",
",",
"date",
")",
"if",
"granularity",
"==",
"\"all\"",
":",
"return",
"list",
"(",
"patts",
".",
"values",
"(",
")",
")",
"return",
"[",
"patts",
"[",
"granularity",
"]",
"]"
] |
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.
* ``granularity`` -- Must be one of: "all" (default), "yearly",
"monthly", "weekly", "daily", "hourly", "minutes", or "seconds".
Returns a list of strings.
|
[
"Builds",
"redis",
"keys",
"used",
"to",
"store",
"metrics",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L217-L236
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.metric_slugs_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:
result[category] = self._category_slugs(category)
# We also need to see the uncategorized metric slugs, so need some way
# to check which slugs are not already stored.
categorized_metrics = set([ # Flatten the list of metrics
slug for sublist in result.values() for slug in sublist
])
f = lambda slug: slug not in categorized_metrics
uncategorized = list(set(filter(f, self.metric_slugs())))
if len(uncategorized) > 0:
result['Uncategorized'] = uncategorized
return result
|
python
|
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:
result[category] = self._category_slugs(category)
# We also need to see the uncategorized metric slugs, so need some way
# to check which slugs are not already stored.
categorized_metrics = set([ # Flatten the list of metrics
slug for sublist in result.values() for slug in sublist
])
f = lambda slug: slug not in categorized_metrics
uncategorized = list(set(filter(f, self.metric_slugs())))
if len(uncategorized) > 0:
result['Uncategorized'] = uncategorized
return result
|
[
"def",
"metric_slugs_by_category",
"(",
"self",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"categories",
"=",
"sorted",
"(",
"self",
".",
"r",
".",
"smembers",
"(",
"self",
".",
"_categories_key",
")",
")",
"for",
"category",
"in",
"categories",
":",
"result",
"[",
"category",
"]",
"=",
"self",
".",
"_category_slugs",
"(",
"category",
")",
"# We also need to see the uncategorized metric slugs, so need some way",
"# to check which slugs are not already stored.",
"categorized_metrics",
"=",
"set",
"(",
"[",
"# Flatten the list of metrics",
"slug",
"for",
"sublist",
"in",
"result",
".",
"values",
"(",
")",
"for",
"slug",
"in",
"sublist",
"]",
")",
"f",
"=",
"lambda",
"slug",
":",
"slug",
"not",
"in",
"categorized_metrics",
"uncategorized",
"=",
"list",
"(",
"set",
"(",
"filter",
"(",
"f",
",",
"self",
".",
"metric_slugs",
"(",
")",
")",
")",
")",
"if",
"len",
"(",
"uncategorized",
")",
">",
"0",
":",
"result",
"[",
"'Uncategorized'",
"]",
"=",
"uncategorized",
"return",
"result"
] |
Return a dictionary of metrics data indexed by category:
{<category_name>: set(<slug1>, <slug2>, ...)}
|
[
"Return",
"a",
"dictionary",
"of",
"metrics",
"data",
"indexed",
"by",
"category",
":"
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L243-L263
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.delete_metric
|
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 = "m:{0}:*".format(slug)
keys = self.r.keys(prefix)
self.r.delete(*keys) # Remove the metric data
# Finally, remove the slug from the set
self.r.srem(self._metric_slugs_key, slug)
|
python
|
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 = "m:{0}:*".format(slug)
keys = self.r.keys(prefix)
self.r.delete(*keys) # Remove the metric data
# Finally, remove the slug from the set
self.r.srem(self._metric_slugs_key, slug)
|
[
"def",
"delete_metric",
"(",
"self",
",",
"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",
"=",
"\"m:{0}:*\"",
".",
"format",
"(",
"slug",
")",
"keys",
"=",
"self",
".",
"r",
".",
"keys",
"(",
"prefix",
")",
"self",
".",
"r",
".",
"delete",
"(",
"*",
"keys",
")",
"# Remove the metric data",
"# Finally, remove the slug from the set",
"self",
".",
"r",
".",
"srem",
"(",
"self",
".",
"_metric_slugs_key",
",",
"slug",
")"
] |
Removes all keys for the given ``slug``.
|
[
"Removes",
"all",
"keys",
"for",
"the",
"given",
"slug",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L265-L276
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.set_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
granularities: Seconds, Minutes, Hours, Day, Week, Month, and Year.
Parameters:
* ``slug`` -- a unique value to identify the metric; used in
construction of redis keys (see below).
* ``value`` -- The value of the metric.
* ``category`` -- (optional) Assign the metric to a Category (a string)
* ``expire`` -- (optional) Specify the number of seconds in which the
metric will expire.
* ``date`` -- (optional) Specify the timestamp for the metric; default
used to build the keys will be the current date and time in UTC form.
Redis keys for each metric (slug) take the form:
m:<slug>:s:<yyyy-mm-dd-hh-mm-ss> # Second
m:<slug>:i:<yyyy-mm-dd-hh-mm> # Minute
m:<slug>:h:<yyyy-mm-dd-hh> # Hour
m:<slug>:<yyyy-mm-dd> # Day
m:<slug>:w:<yyyy-num> # Week (year - week number)
m:<slug>:m:<yyyy-mm> # Month
m:<slug>:y:<yyyy> # Year
"""
keys = self._build_keys(slug, date=date)
# Add the slug to the set of metric slugs
self.r.sadd(self._metric_slugs_key, slug)
# Construct a dictionary of key/values for use with mset
data = {}
for k in keys:
data[k] = value
self.r.mset(data)
# Add the category if applicable.
if category:
self._categorize(slug, category)
# Expire the Metric in ``expire`` seconds if applicable.
if expire:
for k in keys:
self.r.expire(k, expire)
|
python
|
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
granularities: Seconds, Minutes, Hours, Day, Week, Month, and Year.
Parameters:
* ``slug`` -- a unique value to identify the metric; used in
construction of redis keys (see below).
* ``value`` -- The value of the metric.
* ``category`` -- (optional) Assign the metric to a Category (a string)
* ``expire`` -- (optional) Specify the number of seconds in which the
metric will expire.
* ``date`` -- (optional) Specify the timestamp for the metric; default
used to build the keys will be the current date and time in UTC form.
Redis keys for each metric (slug) take the form:
m:<slug>:s:<yyyy-mm-dd-hh-mm-ss> # Second
m:<slug>:i:<yyyy-mm-dd-hh-mm> # Minute
m:<slug>:h:<yyyy-mm-dd-hh> # Hour
m:<slug>:<yyyy-mm-dd> # Day
m:<slug>:w:<yyyy-num> # Week (year - week number)
m:<slug>:m:<yyyy-mm> # Month
m:<slug>:y:<yyyy> # Year
"""
keys = self._build_keys(slug, date=date)
# Add the slug to the set of metric slugs
self.r.sadd(self._metric_slugs_key, slug)
# Construct a dictionary of key/values for use with mset
data = {}
for k in keys:
data[k] = value
self.r.mset(data)
# Add the category if applicable.
if category:
self._categorize(slug, category)
# Expire the Metric in ``expire`` seconds if applicable.
if expire:
for k in keys:
self.r.expire(k, expire)
|
[
"def",
"set_metric",
"(",
"self",
",",
"slug",
",",
"value",
",",
"category",
"=",
"None",
",",
"expire",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"keys",
"=",
"self",
".",
"_build_keys",
"(",
"slug",
",",
"date",
"=",
"date",
")",
"# Add the slug to the set of metric slugs",
"self",
".",
"r",
".",
"sadd",
"(",
"self",
".",
"_metric_slugs_key",
",",
"slug",
")",
"# Construct a dictionary of key/values for use with mset",
"data",
"=",
"{",
"}",
"for",
"k",
"in",
"keys",
":",
"data",
"[",
"k",
"]",
"=",
"value",
"self",
".",
"r",
".",
"mset",
"(",
"data",
")",
"# Add the category if applicable.",
"if",
"category",
":",
"self",
".",
"_categorize",
"(",
"slug",
",",
"category",
")",
"# Expire the Metric in ``expire`` seconds if applicable.",
"if",
"expire",
":",
"for",
"k",
"in",
"keys",
":",
"self",
".",
"r",
".",
"expire",
"(",
"k",
",",
"expire",
")"
] |
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:
* ``slug`` -- a unique value to identify the metric; used in
construction of redis keys (see below).
* ``value`` -- The value of the metric.
* ``category`` -- (optional) Assign the metric to a Category (a string)
* ``expire`` -- (optional) Specify the number of seconds in which the
metric will expire.
* ``date`` -- (optional) Specify the timestamp for the metric; default
used to build the keys will be the current date and time in UTC form.
Redis keys for each metric (slug) take the form:
m:<slug>:s:<yyyy-mm-dd-hh-mm-ss> # Second
m:<slug>:i:<yyyy-mm-dd-hh-mm> # Minute
m:<slug>:h:<yyyy-mm-dd-hh> # Hour
m:<slug>:<yyyy-mm-dd> # Day
m:<slug>:w:<yyyy-num> # Week (year - week number)
m:<slug>:m:<yyyy-mm> # Month
m:<slug>:y:<yyyy> # Year
|
[
"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",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L278-L325
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.metric
|
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:
* ``slug`` -- a unique value to identify the metric; used in
construction of redis keys (see below).
* ``num`` -- Set or Increment the metric by this number; default is 1.
* ``category`` -- (optional) Assign the metric to a Category (a string)
* ``expire`` -- (optional) Specify the number of seconds in which the
metric will expire.
* ``date`` -- (optional) Specify the timestamp for the metric; default
used to build the keys will be the current date and time in UTC form.
Redis keys for each metric (slug) take the form:
m:<slug>:s:<yyyy-mm-dd-hh-mm-ss> # Second
m:<slug>:i:<yyyy-mm-dd-hh-mm> # Minute
m:<slug>:h:<yyyy-mm-dd-hh> # Hour
m:<slug>:<yyyy-mm-dd> # Day
m:<slug>:w:<yyyy-num> # Week (year - week number)
m:<slug>:m:<yyyy-mm> # Month
m:<slug>:y:<yyyy> # Year
"""
# Add the slug to the set of metric slugs
self.r.sadd(self._metric_slugs_key, slug)
if category:
self._categorize(slug, category)
# Increment keys. NOTE: current redis-py (2.7.2) doesn't include an
# incrby method; .incr accepts a second ``amount`` parameter.
keys = self._build_keys(slug, date=date)
# Use a pipeline to speed up incrementing multiple keys
pipe = self.r.pipeline()
for key in keys:
pipe.incr(key, num)
if expire:
pipe.expire(key, expire)
pipe.execute()
|
python
|
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:
* ``slug`` -- a unique value to identify the metric; used in
construction of redis keys (see below).
* ``num`` -- Set or Increment the metric by this number; default is 1.
* ``category`` -- (optional) Assign the metric to a Category (a string)
* ``expire`` -- (optional) Specify the number of seconds in which the
metric will expire.
* ``date`` -- (optional) Specify the timestamp for the metric; default
used to build the keys will be the current date and time in UTC form.
Redis keys for each metric (slug) take the form:
m:<slug>:s:<yyyy-mm-dd-hh-mm-ss> # Second
m:<slug>:i:<yyyy-mm-dd-hh-mm> # Minute
m:<slug>:h:<yyyy-mm-dd-hh> # Hour
m:<slug>:<yyyy-mm-dd> # Day
m:<slug>:w:<yyyy-num> # Week (year - week number)
m:<slug>:m:<yyyy-mm> # Month
m:<slug>:y:<yyyy> # Year
"""
# Add the slug to the set of metric slugs
self.r.sadd(self._metric_slugs_key, slug)
if category:
self._categorize(slug, category)
# Increment keys. NOTE: current redis-py (2.7.2) doesn't include an
# incrby method; .incr accepts a second ``amount`` parameter.
keys = self._build_keys(slug, date=date)
# Use a pipeline to speed up incrementing multiple keys
pipe = self.r.pipeline()
for key in keys:
pipe.incr(key, num)
if expire:
pipe.expire(key, expire)
pipe.execute()
|
[
"def",
"metric",
"(",
"self",
",",
"slug",
",",
"num",
"=",
"1",
",",
"category",
"=",
"None",
",",
"expire",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"# Add the slug to the set of metric slugs",
"self",
".",
"r",
".",
"sadd",
"(",
"self",
".",
"_metric_slugs_key",
",",
"slug",
")",
"if",
"category",
":",
"self",
".",
"_categorize",
"(",
"slug",
",",
"category",
")",
"# Increment keys. NOTE: current redis-py (2.7.2) doesn't include an",
"# incrby method; .incr accepts a second ``amount`` parameter.",
"keys",
"=",
"self",
".",
"_build_keys",
"(",
"slug",
",",
"date",
"=",
"date",
")",
"# Use a pipeline to speed up incrementing multiple keys",
"pipe",
"=",
"self",
".",
"r",
".",
"pipeline",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"pipe",
".",
"incr",
"(",
"key",
",",
"num",
")",
"if",
"expire",
":",
"pipe",
".",
"expire",
"(",
"key",
",",
"expire",
")",
"pipe",
".",
"execute",
"(",
")"
] |
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
construction of redis keys (see below).
* ``num`` -- Set or Increment the metric by this number; default is 1.
* ``category`` -- (optional) Assign the metric to a Category (a string)
* ``expire`` -- (optional) Specify the number of seconds in which the
metric will expire.
* ``date`` -- (optional) Specify the timestamp for the metric; default
used to build the keys will be the current date and time in UTC form.
Redis keys for each metric (slug) take the form:
m:<slug>:s:<yyyy-mm-dd-hh-mm-ss> # Second
m:<slug>:i:<yyyy-mm-dd-hh-mm> # Minute
m:<slug>:h:<yyyy-mm-dd-hh> # Hour
m:<slug>:<yyyy-mm-dd> # Day
m:<slug>:w:<yyyy-num> # Week (year - week number)
m:<slug>:m:<yyyy-mm> # Month
m:<slug>:y:<yyyy> # Year
|
[
"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",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L327-L370
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.get_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._build_keys(slug)
for granularity, key in zip(granularities, keys):
results[granularity] = self.r.get(key)
return results
|
python
|
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._build_keys(slug)
for granularity, key in zip(granularities, keys):
results[granularity] = self.r.get(key)
return results
|
[
"def",
"get_metric",
"(",
"self",
",",
"slug",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"granularities",
"=",
"self",
".",
"_granularities",
"(",
")",
"keys",
"=",
"self",
".",
"_build_keys",
"(",
"slug",
")",
"for",
"granularity",
",",
"key",
"in",
"zip",
"(",
"granularities",
",",
"keys",
")",
":",
"results",
"[",
"granularity",
"]",
"=",
"self",
".",
"r",
".",
"get",
"(",
"key",
")",
"return",
"results"
] |
Get the current values for a metric.
Returns a dictionary with metric values accumulated for the seconds,
minutes, hours, day, week, month, and year.
|
[
"Get",
"the",
"current",
"values",
"for",
"a",
"metric",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L372-L384
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.get_metrics
|
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,
'day': 0, 'week': 0, 'month': 0, 'year': 0
}
)
"""
# meh. I should have been consistent here, but I'm lazy, so support these
# value names instead of granularity names, but respect the min/max
# granularity settings.
keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']
key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)}
keys = [key_mapping[gran] for gran in self._granularities()]
results = []
for slug in slug_list:
metrics = self.r.mget(*self._build_keys(slug))
if any(metrics): # Only if we have data.
results.append((slug, dict(zip(keys, metrics))))
return results
|
python
|
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,
'day': 0, 'week': 0, 'month': 0, 'year': 0
}
)
"""
# meh. I should have been consistent here, but I'm lazy, so support these
# value names instead of granularity names, but respect the min/max
# granularity settings.
keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']
key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)}
keys = [key_mapping[gran] for gran in self._granularities()]
results = []
for slug in slug_list:
metrics = self.r.mget(*self._build_keys(slug))
if any(metrics): # Only if we have data.
results.append((slug, dict(zip(keys, metrics))))
return results
|
[
"def",
"get_metrics",
"(",
"self",
",",
"slug_list",
")",
":",
"# meh. I should have been consistent here, but I'm lazy, so support these",
"# value names instead of granularity names, but respect the min/max",
"# granularity settings.",
"keys",
"=",
"[",
"'seconds'",
",",
"'minutes'",
",",
"'hours'",
",",
"'day'",
",",
"'week'",
",",
"'month'",
",",
"'year'",
"]",
"key_mapping",
"=",
"{",
"gran",
":",
"key",
"for",
"gran",
",",
"key",
"in",
"zip",
"(",
"GRANULARITIES",
",",
"keys",
")",
"}",
"keys",
"=",
"[",
"key_mapping",
"[",
"gran",
"]",
"for",
"gran",
"in",
"self",
".",
"_granularities",
"(",
")",
"]",
"results",
"=",
"[",
"]",
"for",
"slug",
"in",
"slug_list",
":",
"metrics",
"=",
"self",
".",
"r",
".",
"mget",
"(",
"*",
"self",
".",
"_build_keys",
"(",
"slug",
")",
")",
"if",
"any",
"(",
"metrics",
")",
":",
"# Only if we have data.",
"results",
".",
"append",
"(",
"(",
"slug",
",",
"dict",
"(",
"zip",
"(",
"keys",
",",
"metrics",
")",
")",
")",
")",
"return",
"results"
] |
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, 'month': 0, 'year': 0
}
)
|
[
"Get",
"the",
"metrics",
"for",
"multiple",
"slugs",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L386-L412
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.get_category_metrics
|
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)
|
python
|
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)
|
[
"def",
"get_category_metrics",
"(",
"self",
",",
"category",
")",
":",
"slug_list",
"=",
"self",
".",
"_category_slugs",
"(",
"category",
")",
"return",
"self",
".",
"get_metrics",
"(",
"slug_list",
")"
] |
Get metrics belonging to the given category
|
[
"Get",
"metrics",
"belonging",
"to",
"the",
"given",
"category"
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L414-L417
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.delete_category
|
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 from Set
self.r.srem(self._categories_key, category)
|
python
|
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 from Set
self.r.srem(self._categories_key, category)
|
[
"def",
"delete_category",
"(",
"self",
",",
"category",
")",
":",
"# Remove mapping of metrics-to-category",
"category_key",
"=",
"self",
".",
"_category_key",
"(",
"category",
")",
"self",
".",
"r",
".",
"delete",
"(",
"category_key",
")",
"# Remove category from Set",
"self",
".",
"r",
".",
"srem",
"(",
"self",
".",
"_categories_key",
",",
"category",
")"
] |
Removes the category from Redis. This doesn't touch the metrics;
they simply become uncategorized.
|
[
"Removes",
"the",
"category",
"from",
"Redis",
".",
"This",
"doesn",
"t",
"touch",
"the",
"metrics",
";",
"they",
"simply",
"become",
"uncategorized",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L419-L427
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.reset_category
|
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)
if len(metric_slugs) == 0:
# If there are no metrics, just remove the category
self.delete_category(category)
else:
# Save all the slugs in the category, and save the category name
self.r.sadd(key, *metric_slugs)
self.r.sadd(self._categories_key, category)
|
python
|
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)
if len(metric_slugs) == 0:
# If there are no metrics, just remove the category
self.delete_category(category)
else:
# Save all the slugs in the category, and save the category name
self.r.sadd(key, *metric_slugs)
self.r.sadd(self._categories_key, category)
|
[
"def",
"reset_category",
"(",
"self",
",",
"category",
",",
"metric_slugs",
")",
":",
"key",
"=",
"self",
".",
"_category_key",
"(",
"category",
")",
"if",
"len",
"(",
"metric_slugs",
")",
"==",
"0",
":",
"# If there are no metrics, just remove the category",
"self",
".",
"delete_category",
"(",
"category",
")",
"else",
":",
"# Save all the slugs in the category, and save the category name",
"self",
".",
"r",
".",
"sadd",
"(",
"key",
",",
"*",
"metric_slugs",
")",
"self",
".",
"r",
".",
"sadd",
"(",
"self",
".",
"_categories_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.
|
[
"Resets",
"(",
"or",
"creates",
")",
"a",
"category",
"containing",
"a",
"list",
"of",
"metrics",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L429-L444
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.get_metric_history
|
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
* ``granularity`` -- seconds, minutes, hourly,
daily, weekly, monthly, yearly
Returns a list of tuples containing the Redis key and the associated
metric::
r = R()
r.get_metric_history('test', granularity='weekly')
[
('m:test:w:2012-52', '15'),
]
To get history for multiple metrics, just provide a list of slugs::
metrics = ['test', 'other']
r.get_metric_history(metrics, granularity='weekly')
[
('m:test:w:2012-52', '15'),
('m:other:w:2012-52', '42'),
]
"""
if not type(slugs) == list:
slugs = [slugs]
# Build the set of Redis keys that we need to get.
keys = []
for slug in slugs:
for date in self._date_range(granularity, since, to):
keys += self._build_keys(slug, date, granularity)
keys = list(dedupe(keys))
# Fetch our data, replacing any None-values with zeros
results = [0 if v is None else v for v in self.r.mget(keys)]
results = zip(keys, results)
return sorted(results, key=lambda t: t[0])
|
python
|
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
* ``granularity`` -- seconds, minutes, hourly,
daily, weekly, monthly, yearly
Returns a list of tuples containing the Redis key and the associated
metric::
r = R()
r.get_metric_history('test', granularity='weekly')
[
('m:test:w:2012-52', '15'),
]
To get history for multiple metrics, just provide a list of slugs::
metrics = ['test', 'other']
r.get_metric_history(metrics, granularity='weekly')
[
('m:test:w:2012-52', '15'),
('m:other:w:2012-52', '42'),
]
"""
if not type(slugs) == list:
slugs = [slugs]
# Build the set of Redis keys that we need to get.
keys = []
for slug in slugs:
for date in self._date_range(granularity, since, to):
keys += self._build_keys(slug, date, granularity)
keys = list(dedupe(keys))
# Fetch our data, replacing any None-values with zeros
results = [0 if v is None else v for v in self.r.mget(keys)]
results = zip(keys, results)
return sorted(results, key=lambda t: t[0])
|
[
"def",
"get_metric_history",
"(",
"self",
",",
"slugs",
",",
"since",
"=",
"None",
",",
"to",
"=",
"None",
",",
"granularity",
"=",
"'daily'",
")",
":",
"if",
"not",
"type",
"(",
"slugs",
")",
"==",
"list",
":",
"slugs",
"=",
"[",
"slugs",
"]",
"# Build the set of Redis keys that we need to get.",
"keys",
"=",
"[",
"]",
"for",
"slug",
"in",
"slugs",
":",
"for",
"date",
"in",
"self",
".",
"_date_range",
"(",
"granularity",
",",
"since",
",",
"to",
")",
":",
"keys",
"+=",
"self",
".",
"_build_keys",
"(",
"slug",
",",
"date",
",",
"granularity",
")",
"keys",
"=",
"list",
"(",
"dedupe",
"(",
"keys",
")",
")",
"# Fetch our data, replacing any None-values with zeros",
"results",
"=",
"[",
"0",
"if",
"v",
"is",
"None",
"else",
"v",
"for",
"v",
"in",
"self",
".",
"r",
".",
"mget",
"(",
"keys",
")",
"]",
"results",
"=",
"zip",
"(",
"keys",
",",
"results",
")",
"return",
"sorted",
"(",
"results",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
"[",
"0",
"]",
")"
] |
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, monthly, yearly
Returns a list of tuples containing the Redis key and the associated
metric::
r = R()
r.get_metric_history('test', granularity='weekly')
[
('m:test:w:2012-52', '15'),
]
To get history for multiple metrics, just provide a list of slugs::
metrics = ['test', 'other']
r.get_metric_history(metrics, granularity='weekly')
[
('m:test:w:2012-52', '15'),
('m:other:w:2012-52', '42'),
]
|
[
"Get",
"history",
"for",
"one",
"or",
"more",
"metrics",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L446-L487
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.get_metric_history_as_columns
|
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'),
('m:bar:y:2013', '2'),
('m:foo:y:2012', '3'),
('m:foo:y:2013', '4')
]
this method would provide you with the following data structure::
[
['Period', 'bar', 'foo']
['y:2012', '1', '3'],
['y:2013', '2', '4'],
]
Note that this also includes a header column. Data in this format may
be useful for certain graphing libraries (I'm looking at you Google
Charts LineChart).
"""
history = self.get_metric_history(slugs, since, granularity=granularity)
_history = [] # new, columnar history
periods = ['Period'] # A separate, single column for the time period
for s in slugs:
column = [s] # story all the data for a single slug
for key, value in history:
# ``metric_slug`` extracts the slug from the Redis Key
if template_tags.metric_slug(key) == s:
column.append(value)
# Get time period value as first column; This value is
# duplicated in the Redis key for each value, so this is a bit
# inefficient, but... oh well.
period = template_tags.strip_metric_prefix(key)
if period not in periods:
periods.append(period)
_history.append(column) # Remember that slug's column of data
# Finally, stick the time periods in the first column.
_history.insert(0, periods)
return list(zip(*_history))
|
python
|
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'),
('m:bar:y:2013', '2'),
('m:foo:y:2012', '3'),
('m:foo:y:2013', '4')
]
this method would provide you with the following data structure::
[
['Period', 'bar', 'foo']
['y:2012', '1', '3'],
['y:2013', '2', '4'],
]
Note that this also includes a header column. Data in this format may
be useful for certain graphing libraries (I'm looking at you Google
Charts LineChart).
"""
history = self.get_metric_history(slugs, since, granularity=granularity)
_history = [] # new, columnar history
periods = ['Period'] # A separate, single column for the time period
for s in slugs:
column = [s] # story all the data for a single slug
for key, value in history:
# ``metric_slug`` extracts the slug from the Redis Key
if template_tags.metric_slug(key) == s:
column.append(value)
# Get time period value as first column; This value is
# duplicated in the Redis key for each value, so this is a bit
# inefficient, but... oh well.
period = template_tags.strip_metric_prefix(key)
if period not in periods:
periods.append(period)
_history.append(column) # Remember that slug's column of data
# Finally, stick the time periods in the first column.
_history.insert(0, periods)
return list(zip(*_history))
|
[
"def",
"get_metric_history_as_columns",
"(",
"self",
",",
"slugs",
",",
"since",
"=",
"None",
",",
"granularity",
"=",
"'daily'",
")",
":",
"history",
"=",
"self",
".",
"get_metric_history",
"(",
"slugs",
",",
"since",
",",
"granularity",
"=",
"granularity",
")",
"_history",
"=",
"[",
"]",
"# new, columnar history",
"periods",
"=",
"[",
"'Period'",
"]",
"# A separate, single column for the time period",
"for",
"s",
"in",
"slugs",
":",
"column",
"=",
"[",
"s",
"]",
"# story all the data for a single slug",
"for",
"key",
",",
"value",
"in",
"history",
":",
"# ``metric_slug`` extracts the slug from the Redis Key",
"if",
"template_tags",
".",
"metric_slug",
"(",
"key",
")",
"==",
"s",
":",
"column",
".",
"append",
"(",
"value",
")",
"# Get time period value as first column; This value is",
"# duplicated in the Redis key for each value, so this is a bit",
"# inefficient, but... oh well.",
"period",
"=",
"template_tags",
".",
"strip_metric_prefix",
"(",
"key",
")",
"if",
"period",
"not",
"in",
"periods",
":",
"periods",
".",
"append",
"(",
"period",
")",
"_history",
".",
"append",
"(",
"column",
")",
"# Remember that slug's column of data",
"# Finally, stick the time periods in the first column.",
"_history",
".",
"insert",
"(",
"0",
",",
"periods",
")",
"return",
"list",
"(",
"zip",
"(",
"*",
"_history",
")",
")"
] |
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')
]
this method would provide you with the following data structure::
[
['Period', 'bar', 'foo']
['y:2012', '1', '3'],
['y:2013', '2', '4'],
]
Note that this also includes a header column. Data in this format may
be useful for certain graphing libraries (I'm looking at you Google
Charts LineChart).
|
[
"Provides",
"the",
"same",
"data",
"as",
"get_metric_history",
"but",
"in",
"a",
"columnar",
"format",
".",
"If",
"you",
"had",
"the",
"following",
"yearly",
"history",
"for",
"example",
"::"
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L489-L535
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.get_metric_history_chart_data
|
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::
[
('m:bar:y:2012', '1'),
('m:bar:y:2013', '2'),
('m:bar:y:2014', '3'),
('m:foo:y:2012', '4'),
('m:foo:y:2013', '5')
('m:foo:y:2014', '6')
]
this method would provide you with the following data structure::
'periods': ['y:2012', 'y:2013', 'y:2014']
'data': [
{
'slug': 'bar',
'values': [1, 2, 3]
},
{
'slug': 'foo',
'values': [4, 5, 6]
},
]
"""
slugs = sorted(slugs)
history = self.get_metric_history(slugs, since, granularity=granularity)
# Convert the history into an intermediate data structure organized
# by periods. Since the history is sorted by key (which includes both
# the slug and the date, the values should be ordered correctly.
periods = []
data = OrderedDict()
for k, v in history:
period = template_tags.strip_metric_prefix(k)
if period not in periods:
periods.append(period)
slug = template_tags.metric_slug(k)
if slug not in data:
data[slug] = []
data[slug].append(v)
# Now, reorganize data for our end result.
metrics = {'periods': periods, 'data': []}
for slug, values in data.items():
metrics['data'].append({
'slug': slug,
'values': values
})
return metrics
|
python
|
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::
[
('m:bar:y:2012', '1'),
('m:bar:y:2013', '2'),
('m:bar:y:2014', '3'),
('m:foo:y:2012', '4'),
('m:foo:y:2013', '5')
('m:foo:y:2014', '6')
]
this method would provide you with the following data structure::
'periods': ['y:2012', 'y:2013', 'y:2014']
'data': [
{
'slug': 'bar',
'values': [1, 2, 3]
},
{
'slug': 'foo',
'values': [4, 5, 6]
},
]
"""
slugs = sorted(slugs)
history = self.get_metric_history(slugs, since, granularity=granularity)
# Convert the history into an intermediate data structure organized
# by periods. Since the history is sorted by key (which includes both
# the slug and the date, the values should be ordered correctly.
periods = []
data = OrderedDict()
for k, v in history:
period = template_tags.strip_metric_prefix(k)
if period not in periods:
periods.append(period)
slug = template_tags.metric_slug(k)
if slug not in data:
data[slug] = []
data[slug].append(v)
# Now, reorganize data for our end result.
metrics = {'periods': periods, 'data': []}
for slug, values in data.items():
metrics['data'].append({
'slug': slug,
'values': values
})
return metrics
|
[
"def",
"get_metric_history_chart_data",
"(",
"self",
",",
"slugs",
",",
"since",
"=",
"None",
",",
"granularity",
"=",
"'daily'",
")",
":",
"slugs",
"=",
"sorted",
"(",
"slugs",
")",
"history",
"=",
"self",
".",
"get_metric_history",
"(",
"slugs",
",",
"since",
",",
"granularity",
"=",
"granularity",
")",
"# Convert the history into an intermediate data structure organized",
"# by periods. Since the history is sorted by key (which includes both",
"# the slug and the date, the values should be ordered correctly.",
"periods",
"=",
"[",
"]",
"data",
"=",
"OrderedDict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"history",
":",
"period",
"=",
"template_tags",
".",
"strip_metric_prefix",
"(",
"k",
")",
"if",
"period",
"not",
"in",
"periods",
":",
"periods",
".",
"append",
"(",
"period",
")",
"slug",
"=",
"template_tags",
".",
"metric_slug",
"(",
"k",
")",
"if",
"slug",
"not",
"in",
"data",
":",
"data",
"[",
"slug",
"]",
"=",
"[",
"]",
"data",
"[",
"slug",
"]",
".",
"append",
"(",
"v",
")",
"# Now, reorganize data for our end result.",
"metrics",
"=",
"{",
"'periods'",
":",
"periods",
",",
"'data'",
":",
"[",
"]",
"}",
"for",
"slug",
",",
"values",
"in",
"data",
".",
"items",
"(",
")",
":",
"metrics",
"[",
"'data'",
"]",
".",
"append",
"(",
"{",
"'slug'",
":",
"slug",
",",
"'values'",
":",
"values",
"}",
")",
"return",
"metrics"
] |
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:2014', '3'),
('m:foo:y:2012', '4'),
('m:foo:y:2013', '5')
('m:foo:y:2014', '6')
]
this method would provide you with the following data structure::
'periods': ['y:2012', 'y:2013', 'y:2014']
'data': [
{
'slug': 'bar',
'values': [1, 2, 3]
},
{
'slug': 'foo',
'values': [4, 5, 6]
},
]
|
[
"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",
"::"
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L537-L592
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.gauge
|
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 track of all Gauges
self.r.set(k, current_value)
|
python
|
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 track of all Gauges
self.r.set(k, current_value)
|
[
"def",
"gauge",
"(",
"self",
",",
"slug",
",",
"current_value",
")",
":",
"k",
"=",
"self",
".",
"_gauge_key",
"(",
"slug",
")",
"self",
".",
"r",
".",
"sadd",
"(",
"self",
".",
"_gauge_slugs_key",
",",
"slug",
")",
"# keep track of all Gauges",
"self",
".",
"r",
".",
"set",
"(",
"k",
",",
"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
|
[
"Set",
"the",
"value",
"for",
"a",
"Gauge",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L605-L614
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/models.py
|
R.delete_gauge
|
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)
|
python
|
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)
|
[
"def",
"delete_gauge",
"(",
"self",
",",
"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``.
|
[
"Removes",
"all",
"gauges",
"with",
"the",
"given",
"slug",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/models.py#L620-L624
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/templatetags/redis_metric_tags.py
|
metrics_since
|
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 do we want ("history" or "aggregate")
* history -- use when displaying a single metric's history
* aggregate -- use when displaying aggregate metric history
* ``granularity`` -- For "history" only; show the metric's granularity;
default is "daily"
"""
now = datetime.utcnow()
# Determine if we're looking at one slug or multiple slugs
if type(slugs) in [list, set]:
slugs = "+".join(s.lower().strip() for s in slugs)
# Set the default granularity if it's omitted
granularity = granularity.lower().strip() if granularity else "daily"
# Each item is: (slug, since, text, granularity)
# Always include values for Today, 1 week, 30 days, 60 days, 90 days...
slug_values = [
(slugs, now - timedelta(days=1), "Today", granularity),
(slugs, now - timedelta(days=7), "1 Week", granularity),
(slugs, now - timedelta(days=30), "30 Days", granularity),
(slugs, now - timedelta(days=60), "60 Days", granularity),
(slugs, now - timedelta(days=90), "90 Days", granularity),
]
# Then an additional number of years
for y in range(1, years + 1):
t = now - timedelta(days=365 * y)
text = "{0} Years".format(y)
slug_values.append((slugs, t, text, granularity))
return {'slug_values': slug_values, 'link_type': link_type.lower().strip()}
|
python
|
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 do we want ("history" or "aggregate")
* history -- use when displaying a single metric's history
* aggregate -- use when displaying aggregate metric history
* ``granularity`` -- For "history" only; show the metric's granularity;
default is "daily"
"""
now = datetime.utcnow()
# Determine if we're looking at one slug or multiple slugs
if type(slugs) in [list, set]:
slugs = "+".join(s.lower().strip() for s in slugs)
# Set the default granularity if it's omitted
granularity = granularity.lower().strip() if granularity else "daily"
# Each item is: (slug, since, text, granularity)
# Always include values for Today, 1 week, 30 days, 60 days, 90 days...
slug_values = [
(slugs, now - timedelta(days=1), "Today", granularity),
(slugs, now - timedelta(days=7), "1 Week", granularity),
(slugs, now - timedelta(days=30), "30 Days", granularity),
(slugs, now - timedelta(days=60), "60 Days", granularity),
(slugs, now - timedelta(days=90), "90 Days", granularity),
]
# Then an additional number of years
for y in range(1, years + 1):
t = now - timedelta(days=365 * y)
text = "{0} Years".format(y)
slug_values.append((slugs, t, text, granularity))
return {'slug_values': slug_values, 'link_type': link_type.lower().strip()}
|
[
"def",
"metrics_since",
"(",
"slugs",
",",
"years",
",",
"link_type",
"=",
"\"detail\"",
",",
"granularity",
"=",
"None",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# Determine if we're looking at one slug or multiple slugs",
"if",
"type",
"(",
"slugs",
")",
"in",
"[",
"list",
",",
"set",
"]",
":",
"slugs",
"=",
"\"+\"",
".",
"join",
"(",
"s",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"slugs",
")",
"# Set the default granularity if it's omitted",
"granularity",
"=",
"granularity",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"granularity",
"else",
"\"daily\"",
"# Each item is: (slug, since, text, granularity)",
"# Always include values for Today, 1 week, 30 days, 60 days, 90 days...",
"slug_values",
"=",
"[",
"(",
"slugs",
",",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"\"Today\"",
",",
"granularity",
")",
",",
"(",
"slugs",
",",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"7",
")",
",",
"\"1 Week\"",
",",
"granularity",
")",
",",
"(",
"slugs",
",",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"30",
")",
",",
"\"30 Days\"",
",",
"granularity",
")",
",",
"(",
"slugs",
",",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"60",
")",
",",
"\"60 Days\"",
",",
"granularity",
")",
",",
"(",
"slugs",
",",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"90",
")",
",",
"\"90 Days\"",
",",
"granularity",
")",
",",
"]",
"# Then an additional number of years",
"for",
"y",
"in",
"range",
"(",
"1",
",",
"years",
"+",
"1",
")",
":",
"t",
"=",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"365",
"*",
"y",
")",
"text",
"=",
"\"{0} Years\"",
".",
"format",
"(",
"y",
")",
"slug_values",
".",
"append",
"(",
"(",
"slugs",
",",
"t",
",",
"text",
",",
"granularity",
")",
")",
"return",
"{",
"'slug_values'",
":",
"slug_values",
",",
"'link_type'",
":",
"link_type",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"}"
] |
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 displaying a single metric's history
* aggregate -- use when displaying aggregate metric history
* ``granularity`` -- For "history" only; show the metric's granularity;
default is "daily"
|
[
"Renders",
"a",
"template",
"with",
"a",
"menu",
"to",
"view",
"a",
"metric",
"(",
"or",
"metrics",
")",
"for",
"a",
"given",
"number",
"of",
"years",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metric_tags.py#L12-L49
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/templatetags/redis_metric_tags.py
|
gauge
|
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`` -- type to which gauge values should be coerced. The default
is float. Use ``{% gauge some_slug coerce='int' %}`` to coerce to integer
"""
coerce_options = {'float': float, 'int': int, 'str': str}
coerce = coerce_options.get(coerce, float)
redis = get_r()
value = coerce(redis.get_gauge(slug))
if value < maximum and coerce == float:
diff = round(maximum - value, 2)
elif value < maximum:
diff = maximum - value
else:
diff = 0
return {
'slug': slug,
'current_value': value,
'max_value': maximum,
'size': size,
'diff': diff,
}
|
python
|
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`` -- type to which gauge values should be coerced. The default
is float. Use ``{% gauge some_slug coerce='int' %}`` to coerce to integer
"""
coerce_options = {'float': float, 'int': int, 'str': str}
coerce = coerce_options.get(coerce, float)
redis = get_r()
value = coerce(redis.get_gauge(slug))
if value < maximum and coerce == float:
diff = round(maximum - value, 2)
elif value < maximum:
diff = maximum - value
else:
diff = 0
return {
'slug': slug,
'current_value': value,
'max_value': maximum,
'size': size,
'diff': diff,
}
|
[
"def",
"gauge",
"(",
"slug",
",",
"maximum",
"=",
"9000",
",",
"size",
"=",
"200",
",",
"coerce",
"=",
"'float'",
")",
":",
"coerce_options",
"=",
"{",
"'float'",
":",
"float",
",",
"'int'",
":",
"int",
",",
"'str'",
":",
"str",
"}",
"coerce",
"=",
"coerce_options",
".",
"get",
"(",
"coerce",
",",
"float",
")",
"redis",
"=",
"get_r",
"(",
")",
"value",
"=",
"coerce",
"(",
"redis",
".",
"get_gauge",
"(",
"slug",
")",
")",
"if",
"value",
"<",
"maximum",
"and",
"coerce",
"==",
"float",
":",
"diff",
"=",
"round",
"(",
"maximum",
"-",
"value",
",",
"2",
")",
"elif",
"value",
"<",
"maximum",
":",
"diff",
"=",
"maximum",
"-",
"value",
"else",
":",
"diff",
"=",
"0",
"return",
"{",
"'slug'",
":",
"slug",
",",
"'current_value'",
":",
"value",
",",
"'max_value'",
":",
"maximum",
",",
"'size'",
":",
"size",
",",
"'diff'",
":",
"diff",
",",
"}"
] |
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
is float. Use ``{% gauge some_slug coerce='int' %}`` to coerce to integer
|
[
"Include",
"a",
"Donut",
"Chart",
"for",
"the",
"specified",
"Gauge",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metric_tags.py#L53-L81
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/templatetags/redis_metric_tags.py
|
metric_detail
|
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(slug)
metrics_data = []
for g in granularities:
metrics_data.append((g, metrics[g]))
return {
'granularities': [g.title() for g in granularities],
'slug': slug,
'metrics': metrics_data,
'with_data_table': with_data_table,
}
|
python
|
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(slug)
metrics_data = []
for g in granularities:
metrics_data.append((g, metrics[g]))
return {
'granularities': [g.title() for g in granularities],
'slug': slug,
'metrics': metrics_data,
'with_data_table': with_data_table,
}
|
[
"def",
"metric_detail",
"(",
"slug",
",",
"with_data_table",
"=",
"False",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"granularities",
"=",
"list",
"(",
"r",
".",
"_granularities",
"(",
")",
")",
"metrics",
"=",
"r",
".",
"get_metric",
"(",
"slug",
")",
"metrics_data",
"=",
"[",
"]",
"for",
"g",
"in",
"granularities",
":",
"metrics_data",
".",
"append",
"(",
"(",
"g",
",",
"metrics",
"[",
"g",
"]",
")",
")",
"return",
"{",
"'granularities'",
":",
"[",
"g",
".",
"title",
"(",
")",
"for",
"g",
"in",
"granularities",
"]",
",",
"'slug'",
":",
"slug",
",",
"'metrics'",
":",
"metrics_data",
",",
"'with_data_table'",
":",
"with_data_table",
",",
"}"
] |
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.
|
[
"Template",
"Tag",
"to",
"display",
"a",
"metric",
"s",
"*",
"current",
"*",
"detail",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metric_tags.py#L93-L112
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/templatetags/redis_metric_tags.py
|
metric_history
|
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 object or a string string matching one of the
following patterns: "YYYY-mm-dd" for a date or "YYYY-mm-dd HH:MM:SS" for
a date & time.
* ``to`` -- the date until which we start pulling metrics
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
try:
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
if to and len(to) == 10: # yyyy-mm-dd
to = datetime.strptime(since, "%Y-%m-%d")
elif to and len(to) == 19: # yyyy-mm-dd HH:MM:ss
to = datetime.strptime(to, "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
# assume we got a datetime object or leave since = None
pass
metric_history = r.get_metric_history(
slugs=slug,
since=since,
to=to,
granularity=granularity
)
return {
'since': since,
'to': to,
'slug': slug,
'granularity': granularity,
'metric_history': metric_history,
'with_data_table': with_data_table,
}
|
python
|
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 object or a string string matching one of the
following patterns: "YYYY-mm-dd" for a date or "YYYY-mm-dd HH:MM:SS" for
a date & time.
* ``to`` -- the date until which we start pulling metrics
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
try:
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
if to and len(to) == 10: # yyyy-mm-dd
to = datetime.strptime(since, "%Y-%m-%d")
elif to and len(to) == 19: # yyyy-mm-dd HH:MM:ss
to = datetime.strptime(to, "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
# assume we got a datetime object or leave since = None
pass
metric_history = r.get_metric_history(
slugs=slug,
since=since,
to=to,
granularity=granularity
)
return {
'since': since,
'to': to,
'slug': slug,
'granularity': granularity,
'metric_history': metric_history,
'with_data_table': with_data_table,
}
|
[
"def",
"metric_history",
"(",
"slug",
",",
"granularity",
"=",
"\"daily\"",
",",
"since",
"=",
"None",
",",
"to",
"=",
"None",
",",
"with_data_table",
"=",
"False",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"try",
":",
"if",
"since",
"and",
"len",
"(",
"since",
")",
"==",
"10",
":",
"# yyyy-mm-dd",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d\"",
")",
"elif",
"since",
"and",
"len",
"(",
"since",
")",
"==",
"19",
":",
"# yyyy-mm-dd HH:MM:ss",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"if",
"to",
"and",
"len",
"(",
"to",
")",
"==",
"10",
":",
"# yyyy-mm-dd",
"to",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d\"",
")",
"elif",
"to",
"and",
"len",
"(",
"to",
")",
"==",
"19",
":",
"# yyyy-mm-dd HH:MM:ss",
"to",
"=",
"datetime",
".",
"strptime",
"(",
"to",
",",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"# assume we got a datetime object or leave since = None",
"pass",
"metric_history",
"=",
"r",
".",
"get_metric_history",
"(",
"slugs",
"=",
"slug",
",",
"since",
"=",
"since",
",",
"to",
"=",
"to",
",",
"granularity",
"=",
"granularity",
")",
"return",
"{",
"'since'",
":",
"since",
",",
"'to'",
":",
"to",
",",
"'slug'",
":",
"slug",
",",
"'granularity'",
":",
"granularity",
",",
"'metric_history'",
":",
"metric_history",
",",
"'with_data_table'",
":",
"with_data_table",
",",
"}"
] |
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" for
a date & time.
* ``to`` -- the date until which we start pulling metrics
* ``with_data_table`` -- if True, prints the raw data in a table.
|
[
"Template",
"Tag",
"to",
"display",
"a",
"metric",
"s",
"history",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metric_tags.py#L116-L159
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/templatetags/redis_metric_tags.py
|
aggregate_detail
|
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()
# XXX converting granularties into their key-name for metrics.
keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']
key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)}
keys = [key_mapping[gran] for gran in granularities]
# Our metrics data is of the form:
#
# (slug, {time_period: value, ... }).
#
# Let's convert this to (slug, list_of_values) so that the list of
# values is in the same order as the granularties
for slug, data in r.get_metrics(slug_list):
values = [data[t] for t in keys]
metrics_data.append((slug, values))
return {
'chart_id': "metric-aggregate-{0}".format("-".join(slug_list)),
'slugs': slug_list,
'metrics': metrics_data,
'with_data_table': with_data_table,
'granularities': [g.title() for g in keys],
}
|
python
|
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()
# XXX converting granularties into their key-name for metrics.
keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']
key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)}
keys = [key_mapping[gran] for gran in granularities]
# Our metrics data is of the form:
#
# (slug, {time_period: value, ... }).
#
# Let's convert this to (slug, list_of_values) so that the list of
# values is in the same order as the granularties
for slug, data in r.get_metrics(slug_list):
values = [data[t] for t in keys]
metrics_data.append((slug, values))
return {
'chart_id': "metric-aggregate-{0}".format("-".join(slug_list)),
'slugs': slug_list,
'metrics': metrics_data,
'with_data_table': with_data_table,
'granularities': [g.title() for g in keys],
}
|
[
"def",
"aggregate_detail",
"(",
"slug_list",
",",
"with_data_table",
"=",
"False",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"metrics_data",
"=",
"[",
"]",
"granularities",
"=",
"r",
".",
"_granularities",
"(",
")",
"# XXX converting granularties into their key-name for metrics.",
"keys",
"=",
"[",
"'seconds'",
",",
"'minutes'",
",",
"'hours'",
",",
"'day'",
",",
"'week'",
",",
"'month'",
",",
"'year'",
"]",
"key_mapping",
"=",
"{",
"gran",
":",
"key",
"for",
"gran",
",",
"key",
"in",
"zip",
"(",
"GRANULARITIES",
",",
"keys",
")",
"}",
"keys",
"=",
"[",
"key_mapping",
"[",
"gran",
"]",
"for",
"gran",
"in",
"granularities",
"]",
"# Our metrics data is of the form:",
"#",
"# (slug, {time_period: value, ... }).",
"#",
"# Let's convert this to (slug, list_of_values) so that the list of",
"# values is in the same order as the granularties",
"for",
"slug",
",",
"data",
"in",
"r",
".",
"get_metrics",
"(",
"slug_list",
")",
":",
"values",
"=",
"[",
"data",
"[",
"t",
"]",
"for",
"t",
"in",
"keys",
"]",
"metrics_data",
".",
"append",
"(",
"(",
"slug",
",",
"values",
")",
")",
"return",
"{",
"'chart_id'",
":",
"\"metric-aggregate-{0}\"",
".",
"format",
"(",
"\"-\"",
".",
"join",
"(",
"slug_list",
")",
")",
",",
"'slugs'",
":",
"slug_list",
",",
"'metrics'",
":",
"metrics_data",
",",
"'with_data_table'",
":",
"with_data_table",
",",
"'granularities'",
":",
"[",
"g",
".",
"title",
"(",
")",
"for",
"g",
"in",
"keys",
"]",
",",
"}"
] |
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.
|
[
"Template",
"Tag",
"to",
"display",
"multiple",
"metrics",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metric_tags.py#L163-L195
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/templatetags/redis_metric_tags.py
|
aggregate_history
|
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, 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" for
a date & time.
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
slugs = list(slugs)
try:
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
# assume we got a datetime object or leave since = None
pass
history = r.get_metric_history_chart_data(
slugs=slugs,
since=since,
granularity=granularity
)
return {
'chart_id': "metric-aggregate-history-{0}".format("-".join(slugs)),
'slugs': slugs,
'since': since,
'granularity': granularity,
'metric_history': history,
'with_data_table': with_data_table,
}
|
python
|
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, 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" for
a date & time.
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
slugs = list(slugs)
try:
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
# assume we got a datetime object or leave since = None
pass
history = r.get_metric_history_chart_data(
slugs=slugs,
since=since,
granularity=granularity
)
return {
'chart_id': "metric-aggregate-history-{0}".format("-".join(slugs)),
'slugs': slugs,
'since': since,
'granularity': granularity,
'metric_history': history,
'with_data_table': with_data_table,
}
|
[
"def",
"aggregate_history",
"(",
"slugs",
",",
"granularity",
"=",
"\"daily\"",
",",
"since",
"=",
"None",
",",
"with_data_table",
"=",
"False",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"slugs",
"=",
"list",
"(",
"slugs",
")",
"try",
":",
"if",
"since",
"and",
"len",
"(",
"since",
")",
"==",
"10",
":",
"# yyyy-mm-dd",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d\"",
")",
"elif",
"since",
"and",
"len",
"(",
"since",
")",
"==",
"19",
":",
"# yyyy-mm-dd HH:MM:ss",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"# assume we got a datetime object or leave since = None",
"pass",
"history",
"=",
"r",
".",
"get_metric_history_chart_data",
"(",
"slugs",
"=",
"slugs",
",",
"since",
"=",
"since",
",",
"granularity",
"=",
"granularity",
")",
"return",
"{",
"'chart_id'",
":",
"\"metric-aggregate-history-{0}\"",
".",
"format",
"(",
"\"-\"",
".",
"join",
"(",
"slugs",
")",
")",
",",
"'slugs'",
":",
"slugs",
",",
"'since'",
":",
"since",
",",
"'granularity'",
":",
"granularity",
",",
"'metric_history'",
":",
"history",
",",
"'with_data_table'",
":",
"with_data_table",
",",
"}"
] |
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 patterns: "YYYY-mm-dd" for a date or "YYYY-mm-dd HH:MM:SS" for
a date & time.
* ``with_data_table`` -- if True, prints the raw data in a table.
|
[
"Template",
"Tag",
"to",
"display",
"history",
"for",
"multiple",
"metrics",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metric_tags.py#L199-L236
|
train
|
google/dotty
|
efilter/api.py
|
apply
|
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 an array (for positional interpolation).
vars: The variables to be supplied to the query solver.
allow_io: (Default: False) Include 'stdio' and allow IO functions.
libs: Iterable of library modules to include, given as strings.
Default: ('stdcore', 'stdmath')
For full list of bundled libraries, see efilter.stdlib.
Note: 'stdcore' must always be included.
WARNING: Including 'stdio' must be done in conjunction with
'allow_io'. This is to make enabling IO explicit. 'allow_io'
implies that 'stdio' should be included and so adding it to
libs is actually not required.
Notes on IO: If allow_io is set to True then 'stdio' will be included and
the EFILTER query will be allowed to read files from disk. Use this with
caution.
If the query returns a lazily-evaluated result that depends on reading
from a file (for example, filtering a CSV file) then the file
descriptor will remain open until the returned result is deallocated.
The caller is responsible for releasing the result when it's no longer
needed.
Returns:
The result of evaluating the query. The type of the output will depend
on the query, and can be predicted using 'infer' (provided reflection
callbacks are implemented). In the common case of a SELECT query the
return value will be an iterable of filtered data (actually an object
implementing IRepeated, as well as __iter__.)
A word on cardinality of the return value:
Types in EFILTER always refer to a scalar. If apply returns more than
one value, the type returned by 'infer' will refer to the type of
the value inside the returned container.
If you're unsure whether your query returns one or more values (rows),
use the 'getvalues' function.
Raises:
efilter.errors.EfilterError if there are issues with the query.
Examples:
apply("5 + 5") # -> 10
apply("SELECT * FROM people WHERE age > 10",
vars={"people":({"age": 10, "name": "Bob"},
{"age": 20, "name": "Alice"},
{"age": 30, "name": "Eve"}))
# This will replace the question mark (?) with the string "Bob" in a
# safe manner, preventing SQL injection.
apply("SELECT * FROM people WHERE name = ?", replacements=["Bob"], ...)
"""
if vars is None:
vars = {}
if allow_io:
libs = list(libs)
libs.append("stdio")
query = q.Query(query, params=replacements)
stdcore_included = False
for lib in libs:
if lib == "stdcore":
stdcore_included = True
# 'solve' always includes this automatically - we don't have a say
# in the matter.
continue
if lib == "stdio" and not allow_io:
raise ValueError("Attempting to include 'stdio' but IO not "
"enabled. Pass allow_io=True.")
module = std_core.LibraryModule.ALL_MODULES.get(lib)
if not lib:
raise ValueError("There is no standard library module %r." % lib)
vars = scope.ScopeStack(module, vars)
if not stdcore_included:
raise ValueError("EFILTER cannot work without standard lib 'stdcore'.")
results = solve.solve(query, vars).value
return results
|
python
|
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 an array (for positional interpolation).
vars: The variables to be supplied to the query solver.
allow_io: (Default: False) Include 'stdio' and allow IO functions.
libs: Iterable of library modules to include, given as strings.
Default: ('stdcore', 'stdmath')
For full list of bundled libraries, see efilter.stdlib.
Note: 'stdcore' must always be included.
WARNING: Including 'stdio' must be done in conjunction with
'allow_io'. This is to make enabling IO explicit. 'allow_io'
implies that 'stdio' should be included and so adding it to
libs is actually not required.
Notes on IO: If allow_io is set to True then 'stdio' will be included and
the EFILTER query will be allowed to read files from disk. Use this with
caution.
If the query returns a lazily-evaluated result that depends on reading
from a file (for example, filtering a CSV file) then the file
descriptor will remain open until the returned result is deallocated.
The caller is responsible for releasing the result when it's no longer
needed.
Returns:
The result of evaluating the query. The type of the output will depend
on the query, and can be predicted using 'infer' (provided reflection
callbacks are implemented). In the common case of a SELECT query the
return value will be an iterable of filtered data (actually an object
implementing IRepeated, as well as __iter__.)
A word on cardinality of the return value:
Types in EFILTER always refer to a scalar. If apply returns more than
one value, the type returned by 'infer' will refer to the type of
the value inside the returned container.
If you're unsure whether your query returns one or more values (rows),
use the 'getvalues' function.
Raises:
efilter.errors.EfilterError if there are issues with the query.
Examples:
apply("5 + 5") # -> 10
apply("SELECT * FROM people WHERE age > 10",
vars={"people":({"age": 10, "name": "Bob"},
{"age": 20, "name": "Alice"},
{"age": 30, "name": "Eve"}))
# This will replace the question mark (?) with the string "Bob" in a
# safe manner, preventing SQL injection.
apply("SELECT * FROM people WHERE name = ?", replacements=["Bob"], ...)
"""
if vars is None:
vars = {}
if allow_io:
libs = list(libs)
libs.append("stdio")
query = q.Query(query, params=replacements)
stdcore_included = False
for lib in libs:
if lib == "stdcore":
stdcore_included = True
# 'solve' always includes this automatically - we don't have a say
# in the matter.
continue
if lib == "stdio" and not allow_io:
raise ValueError("Attempting to include 'stdio' but IO not "
"enabled. Pass allow_io=True.")
module = std_core.LibraryModule.ALL_MODULES.get(lib)
if not lib:
raise ValueError("There is no standard library module %r." % lib)
vars = scope.ScopeStack(module, vars)
if not stdcore_included:
raise ValueError("EFILTER cannot work without standard lib 'stdcore'.")
results = solve.solve(query, vars).value
return results
|
[
"def",
"apply",
"(",
"query",
",",
"replacements",
"=",
"None",
",",
"vars",
"=",
"None",
",",
"allow_io",
"=",
"False",
",",
"libs",
"=",
"(",
"\"stdcore\"",
",",
"\"stdmath\"",
")",
")",
":",
"if",
"vars",
"is",
"None",
":",
"vars",
"=",
"{",
"}",
"if",
"allow_io",
":",
"libs",
"=",
"list",
"(",
"libs",
")",
"libs",
".",
"append",
"(",
"\"stdio\"",
")",
"query",
"=",
"q",
".",
"Query",
"(",
"query",
",",
"params",
"=",
"replacements",
")",
"stdcore_included",
"=",
"False",
"for",
"lib",
"in",
"libs",
":",
"if",
"lib",
"==",
"\"stdcore\"",
":",
"stdcore_included",
"=",
"True",
"# 'solve' always includes this automatically - we don't have a say",
"# in the matter.",
"continue",
"if",
"lib",
"==",
"\"stdio\"",
"and",
"not",
"allow_io",
":",
"raise",
"ValueError",
"(",
"\"Attempting to include 'stdio' but IO not \"",
"\"enabled. Pass allow_io=True.\"",
")",
"module",
"=",
"std_core",
".",
"LibraryModule",
".",
"ALL_MODULES",
".",
"get",
"(",
"lib",
")",
"if",
"not",
"lib",
":",
"raise",
"ValueError",
"(",
"\"There is no standard library module %r.\"",
"%",
"lib",
")",
"vars",
"=",
"scope",
".",
"ScopeStack",
"(",
"module",
",",
"vars",
")",
"if",
"not",
"stdcore_included",
":",
"raise",
"ValueError",
"(",
"\"EFILTER cannot work without standard lib 'stdcore'.\"",
")",
"results",
"=",
"solve",
".",
"solve",
"(",
"query",
",",
"vars",
")",
".",
"value",
"return",
"results"
] |
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.
allow_io: (Default: False) Include 'stdio' and allow IO functions.
libs: Iterable of library modules to include, given as strings.
Default: ('stdcore', 'stdmath')
For full list of bundled libraries, see efilter.stdlib.
Note: 'stdcore' must always be included.
WARNING: Including 'stdio' must be done in conjunction with
'allow_io'. This is to make enabling IO explicit. 'allow_io'
implies that 'stdio' should be included and so adding it to
libs is actually not required.
Notes on IO: If allow_io is set to True then 'stdio' will be included and
the EFILTER query will be allowed to read files from disk. Use this with
caution.
If the query returns a lazily-evaluated result that depends on reading
from a file (for example, filtering a CSV file) then the file
descriptor will remain open until the returned result is deallocated.
The caller is responsible for releasing the result when it's no longer
needed.
Returns:
The result of evaluating the query. The type of the output will depend
on the query, and can be predicted using 'infer' (provided reflection
callbacks are implemented). In the common case of a SELECT query the
return value will be an iterable of filtered data (actually an object
implementing IRepeated, as well as __iter__.)
A word on cardinality of the return value:
Types in EFILTER always refer to a scalar. If apply returns more than
one value, the type returned by 'infer' will refer to the type of
the value inside the returned container.
If you're unsure whether your query returns one or more values (rows),
use the 'getvalues' function.
Raises:
efilter.errors.EfilterError if there are issues with the query.
Examples:
apply("5 + 5") # -> 10
apply("SELECT * FROM people WHERE age > 10",
vars={"people":({"age": 10, "name": "Bob"},
{"age": 20, "name": "Alice"},
{"age": 30, "name": "Eve"}))
# This will replace the question mark (?) with the string "Bob" in a
# safe manner, preventing SQL injection.
apply("SELECT * FROM people WHERE name = ?", replacements=["Bob"], ...)
|
[
"Run",
"query",
"on",
"vars",
"and",
"return",
"the",
"result",
"(",
"s",
")",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/api.py#L35-L127
|
train
|
google/dotty
|
efilter/api.py
|
user_func
|
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 library and user functions
can inherit from it.
This will declare a subclass of the standard library TypedFunction and
return an instance of it that EFILTER will happily call.
Arguments:
func: A Python callable that will serve as the implementation.
arg_types (optional): A tuple of argument types. If the function takes
keyword arguments, they must still have a defined order.
return_type (optional): The type the function returns.
Returns:
An instance of a custom subclass of efilter.stdlib.core.TypedFunction.
Examples:
def my_callback(tag):
print("I got %r" % tag)
api.apply("if True then my_callback('Hello World!')",
vars={
"my_callback": api.user_func(my_callback)
})
# This should print "I got 'Hello World!'".
"""
class UserFunction(std_core.TypedFunction):
name = func.__name__
def __call__(self, *args, **kwargs):
return func(*args, **kwargs)
@classmethod
def reflect_static_args(cls):
return arg_types
@classmethod
def reflect_static_return(cls):
return return_type
return UserFunction()
|
python
|
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 library and user functions
can inherit from it.
This will declare a subclass of the standard library TypedFunction and
return an instance of it that EFILTER will happily call.
Arguments:
func: A Python callable that will serve as the implementation.
arg_types (optional): A tuple of argument types. If the function takes
keyword arguments, they must still have a defined order.
return_type (optional): The type the function returns.
Returns:
An instance of a custom subclass of efilter.stdlib.core.TypedFunction.
Examples:
def my_callback(tag):
print("I got %r" % tag)
api.apply("if True then my_callback('Hello World!')",
vars={
"my_callback": api.user_func(my_callback)
})
# This should print "I got 'Hello World!'".
"""
class UserFunction(std_core.TypedFunction):
name = func.__name__
def __call__(self, *args, **kwargs):
return func(*args, **kwargs)
@classmethod
def reflect_static_args(cls):
return arg_types
@classmethod
def reflect_static_return(cls):
return return_type
return UserFunction()
|
[
"def",
"user_func",
"(",
"func",
",",
"arg_types",
"=",
"None",
",",
"return_type",
"=",
"None",
")",
":",
"class",
"UserFunction",
"(",
"std_core",
".",
"TypedFunction",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"@",
"classmethod",
"def",
"reflect_static_args",
"(",
"cls",
")",
":",
"return",
"arg_types",
"@",
"classmethod",
"def",
"reflect_static_return",
"(",
"cls",
")",
":",
"return",
"return_type",
"return",
"UserFunction",
"(",
")"
] |
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 will declare a subclass of the standard library TypedFunction and
return an instance of it that EFILTER will happily call.
Arguments:
func: A Python callable that will serve as the implementation.
arg_types (optional): A tuple of argument types. If the function takes
keyword arguments, they must still have a defined order.
return_type (optional): The type the function returns.
Returns:
An instance of a custom subclass of efilter.stdlib.core.TypedFunction.
Examples:
def my_callback(tag):
print("I got %r" % tag)
api.apply("if True then my_callback('Hello World!')",
vars={
"my_callback": api.user_func(my_callback)
})
# This should print "I got 'Hello World!'".
|
[
"Create",
"an",
"EFILTER",
"-",
"callable",
"version",
"of",
"function",
"func",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/api.py#L148-L193
|
train
|
google/dotty
|
efilter/api.py
|
infer
|
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
an array (for positional interpolation).
root_type: The types of variables to be supplied to the query inference.
libs: What standard libraries should be taken into account for the
inference.
Returns:
The type of the query's output, if it can be determined. If undecidable,
returns efilter.protocol.AnyType.
NOTE: The inference returns the type of a row in the results, not of the
actual Python object returned by 'apply'. For example, if a query
returns multiple rows, each one of which is an integer, the type of the
output is considered to be int, not a collection of rows.
Examples:
infer("5 + 5") # -> INumber
infer("SELECT * FROM people WHERE age > 10") # -> AnyType
# If root_type implements the IStructured reflection API:
infer("SELECT * FROM people WHERE age > 10", root_type=...) # -> dict
"""
# Always make the scope stack start with stdcore.
if root_type:
type_scope = scope.ScopeStack(std_core.MODULE, root_type)
else:
type_scope = scope.ScopeStack(std_core.MODULE)
stdcore_included = False
for lib in libs:
if lib == "stdcore":
stdcore_included = True
continue
module = std_core.LibraryModule.ALL_MODULES.get(lib)
if not module:
raise TypeError("No standard library module %r." % lib)
type_scope = scope.ScopeStack(module, type_scope)
if not stdcore_included:
raise TypeError("'stdcore' must always be included.")
query = q.Query(query, params=replacements)
return infer_type.infer_type(query, type_scope)
|
python
|
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
an array (for positional interpolation).
root_type: The types of variables to be supplied to the query inference.
libs: What standard libraries should be taken into account for the
inference.
Returns:
The type of the query's output, if it can be determined. If undecidable,
returns efilter.protocol.AnyType.
NOTE: The inference returns the type of a row in the results, not of the
actual Python object returned by 'apply'. For example, if a query
returns multiple rows, each one of which is an integer, the type of the
output is considered to be int, not a collection of rows.
Examples:
infer("5 + 5") # -> INumber
infer("SELECT * FROM people WHERE age > 10") # -> AnyType
# If root_type implements the IStructured reflection API:
infer("SELECT * FROM people WHERE age > 10", root_type=...) # -> dict
"""
# Always make the scope stack start with stdcore.
if root_type:
type_scope = scope.ScopeStack(std_core.MODULE, root_type)
else:
type_scope = scope.ScopeStack(std_core.MODULE)
stdcore_included = False
for lib in libs:
if lib == "stdcore":
stdcore_included = True
continue
module = std_core.LibraryModule.ALL_MODULES.get(lib)
if not module:
raise TypeError("No standard library module %r." % lib)
type_scope = scope.ScopeStack(module, type_scope)
if not stdcore_included:
raise TypeError("'stdcore' must always be included.")
query = q.Query(query, params=replacements)
return infer_type.infer_type(query, type_scope)
|
[
"def",
"infer",
"(",
"query",
",",
"replacements",
"=",
"None",
",",
"root_type",
"=",
"None",
",",
"libs",
"=",
"(",
"\"stdcore\"",
",",
"\"stdmath\"",
")",
")",
":",
"# Always make the scope stack start with stdcore.",
"if",
"root_type",
":",
"type_scope",
"=",
"scope",
".",
"ScopeStack",
"(",
"std_core",
".",
"MODULE",
",",
"root_type",
")",
"else",
":",
"type_scope",
"=",
"scope",
".",
"ScopeStack",
"(",
"std_core",
".",
"MODULE",
")",
"stdcore_included",
"=",
"False",
"for",
"lib",
"in",
"libs",
":",
"if",
"lib",
"==",
"\"stdcore\"",
":",
"stdcore_included",
"=",
"True",
"continue",
"module",
"=",
"std_core",
".",
"LibraryModule",
".",
"ALL_MODULES",
".",
"get",
"(",
"lib",
")",
"if",
"not",
"module",
":",
"raise",
"TypeError",
"(",
"\"No standard library module %r.\"",
"%",
"lib",
")",
"type_scope",
"=",
"scope",
".",
"ScopeStack",
"(",
"module",
",",
"type_scope",
")",
"if",
"not",
"stdcore_included",
":",
"raise",
"TypeError",
"(",
"\"'stdcore' must always be included.\"",
")",
"query",
"=",
"q",
".",
"Query",
"(",
"query",
",",
"params",
"=",
"replacements",
")",
"return",
"infer_type",
".",
"infer_type",
"(",
"query",
",",
"type_scope",
")"
] |
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 be supplied to the query inference.
libs: What standard libraries should be taken into account for the
inference.
Returns:
The type of the query's output, if it can be determined. If undecidable,
returns efilter.protocol.AnyType.
NOTE: The inference returns the type of a row in the results, not of the
actual Python object returned by 'apply'. For example, if a query
returns multiple rows, each one of which is an integer, the type of the
output is considered to be int, not a collection of rows.
Examples:
infer("5 + 5") # -> INumber
infer("SELECT * FROM people WHERE age > 10") # -> AnyType
# If root_type implements the IStructured reflection API:
infer("SELECT * FROM people WHERE age > 10", root_type=...) # -> dict
|
[
"Determine",
"the",
"type",
"of",
"the",
"query",
"s",
"output",
"without",
"actually",
"running",
"it",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/api.py#L196-L247
|
train
|
google/dotty
|
efilter/api.py
|
search
|
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
|
python
|
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
|
[
"def",
"search",
"(",
"query",
",",
"data",
",",
"replacements",
"=",
"None",
")",
":",
"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'.
|
[
"Yield",
"objects",
"from",
"data",
"that",
"match",
"the",
"query",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/api.py#L250-L255
|
train
|
google/dotty
|
efilter/parsers/common/tokenizer.py
|
LazyTokenizer.peek
|
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
|
python
|
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
|
[
"def",
"peek",
"(",
"self",
",",
"steps",
"=",
"1",
")",
":",
"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.
|
[
"Look",
"ahead",
"doesn",
"t",
"affect",
"current_token",
"and",
"next_token",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L226-L235
|
train
|
google/dotty
|
efilter/parsers/common/tokenizer.py
|
LazyTokenizer.skip
|
def skip(self, steps=1):
"""Skip ahead by 'steps' tokens."""
for _ in six.moves.range(steps):
self.next_token()
|
python
|
def skip(self, steps=1):
"""Skip ahead by 'steps' tokens."""
for _ in six.moves.range(steps):
self.next_token()
|
[
"def",
"skip",
"(",
"self",
",",
"steps",
"=",
"1",
")",
":",
"for",
"_",
"in",
"six",
".",
"moves",
".",
"range",
"(",
"steps",
")",
":",
"self",
".",
"next_token",
"(",
")"
] |
Skip ahead by 'steps' tokens.
|
[
"Skip",
"ahead",
"by",
"steps",
"tokens",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L237-L240
|
train
|
google/dotty
|
efilter/parsers/common/tokenizer.py
|
LazyTokenizer.next_token
|
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
|
python
|
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
|
[
"def",
"next_token",
"(",
"self",
")",
":",
"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.
|
[
"Returns",
"the",
"next",
"logical",
"token",
"advancing",
"the",
"tokenizer",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L242-L249
|
train
|
google/dotty
|
efilter/parsers/common/tokenizer.py
|
LazyTokenizer._parse_next_token
|
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
|
python
|
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
|
[
"def",
"_parse_next_token",
"(",
"self",
")",
":",
"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.
|
[
"Will",
"parse",
"patterns",
"until",
"it",
"gets",
"to",
"the",
"next",
"token",
"or",
"EOF",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L259-L266
|
train
|
google/dotty
|
efilter/parsers/common/tokenizer.py
|
LazyTokenizer._next_pattern
|
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(self.source, position)
if not m:
continue
position = m.end()
token = None
if pattern.next_state:
self.state_stack.append(pattern.next_state)
if pattern.action:
callback = getattr(self, pattern.action, None)
if callback is None:
raise RuntimeError(
"No method defined for pattern action %s!" %
pattern.action)
if "token" in m.groups():
value = m.group("token")
else:
value = m.group(0)
token = callback(string=value, match=m,
pattern=pattern)
self._position = position
return token
self._error("Don't know how to match next. Did you forget quotes?",
start=self._position, end=self._position + 1)
|
python
|
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(self.source, position)
if not m:
continue
position = m.end()
token = None
if pattern.next_state:
self.state_stack.append(pattern.next_state)
if pattern.action:
callback = getattr(self, pattern.action, None)
if callback is None:
raise RuntimeError(
"No method defined for pattern action %s!" %
pattern.action)
if "token" in m.groups():
value = m.group("token")
else:
value = m.group(0)
token = callback(string=value, match=m,
pattern=pattern)
self._position = position
return token
self._error("Don't know how to match next. Did you forget quotes?",
start=self._position, end=self._position + 1)
|
[
"def",
"_next_pattern",
"(",
"self",
")",
":",
"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",
"(",
"self",
".",
"source",
",",
"position",
")",
"if",
"not",
"m",
":",
"continue",
"position",
"=",
"m",
".",
"end",
"(",
")",
"token",
"=",
"None",
"if",
"pattern",
".",
"next_state",
":",
"self",
".",
"state_stack",
".",
"append",
"(",
"pattern",
".",
"next_state",
")",
"if",
"pattern",
".",
"action",
":",
"callback",
"=",
"getattr",
"(",
"self",
",",
"pattern",
".",
"action",
",",
"None",
")",
"if",
"callback",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"No method defined for pattern action %s!\"",
"%",
"pattern",
".",
"action",
")",
"if",
"\"token\"",
"in",
"m",
".",
"groups",
"(",
")",
":",
"value",
"=",
"m",
".",
"group",
"(",
"\"token\"",
")",
"else",
":",
"value",
"=",
"m",
".",
"group",
"(",
"0",
")",
"token",
"=",
"callback",
"(",
"string",
"=",
"value",
",",
"match",
"=",
"m",
",",
"pattern",
"=",
"pattern",
")",
"self",
".",
"_position",
"=",
"position",
"return",
"token",
"self",
".",
"_error",
"(",
"\"Don't know how to match next. Did you forget quotes?\"",
",",
"start",
"=",
"self",
".",
"_position",
",",
"end",
"=",
"self",
".",
"_position",
"+",
"1",
")"
] |
Parses the next pattern by matching each in turn.
|
[
"Parses",
"the",
"next",
"pattern",
"by",
"matching",
"each",
"in",
"turn",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L268-L305
|
train
|
google/dotty
|
efilter/parsers/common/tokenizer.py
|
LazyTokenizer._error
|
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)
|
python
|
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)
|
[
"def",
"_error",
"(",
"self",
",",
"message",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"raise",
"errors",
".",
"EfilterParseError",
"(",
"source",
"=",
"self",
".",
"source",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
",",
"message",
"=",
"message",
")"
] |
Raise a nice error, with the token highlighted.
|
[
"Raise",
"a",
"nice",
"error",
"with",
"the",
"token",
"highlighted",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L307-L310
|
train
|
google/dotty
|
efilter/parsers/common/tokenizer.py
|
LazyTokenizer.emit
|
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())
|
python
|
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())
|
[
"def",
"emit",
"(",
"self",
",",
"string",
",",
"match",
",",
"pattern",
",",
"*",
"*",
"_",
")",
":",
"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.
|
[
"Emits",
"a",
"token",
"using",
"the",
"current",
"pattern",
"match",
"and",
"pattern",
"label",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/tokenizer.py#L314-L317
|
train
|
google/dotty
|
efilter/version.py
|
get_pkg_version
|
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)
except IOError:
return None
|
python
|
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)
except IOError:
return None
|
[
"def",
"get_pkg_version",
"(",
")",
":",
"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",
")",
"except",
"IOError",
":",
"return",
"None"
] |
Get version string by parsing PKG-INFO.
|
[
"Get",
"version",
"string",
"by",
"parsing",
"PKG",
"-",
"INFO",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/version.py#L78-L88
|
train
|
google/dotty
|
efilter/version.py
|
get_version
|
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 version:
raise RuntimeError("Could not generate dev version from git.")
return version
return "1!%d.%d" % (MAJOR, MINOR)
|
python
|
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 version:
raise RuntimeError("Could not generate dev version from git.")
return version
return "1!%d.%d" % (MAJOR, MINOR)
|
[
"def",
"get_version",
"(",
"dev_version",
"=",
"False",
")",
":",
"if",
"dev_version",
":",
"version",
"=",
"git_dev_version",
"(",
")",
"if",
"not",
"version",
":",
"raise",
"RuntimeError",
"(",
"\"Could not generate dev version from git.\"",
")",
"return",
"version",
"return",
"\"1!%d.%d\"",
"%",
"(",
"MAJOR",
",",
"MINOR",
")"
] |
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.
|
[
"Generates",
"a",
"version",
"string",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/version.py#L100-L117
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/execman/base/task_manager.py
|
Base_TaskManager._heartbeat
|
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 message if received in 10 seconds, the tmgr is assumed
dead. The end_manager() is called to cleanly terminate tmgr process and the heartbeat thread is also
terminated.
**Details**: The AppManager can re-invoke both if the execution is still not complete.
"""
try:
self._prof.prof('heartbeat thread started', uid=self._uid)
mq_connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._mq_hostname, port=self._port))
mq_channel = mq_connection.channel()
response = True
while (response and (not self._hb_terminate.is_set())):
response = False
corr_id = str(uuid.uuid4())
# Heartbeat request signal sent to task manager via rpc-queue
mq_channel.basic_publish(exchange='',
routing_key=self._hb_request_q,
properties=pika.BasicProperties(
reply_to=self._hb_response_q,
correlation_id=corr_id),
body='request')
self._logger.info('Sent heartbeat request')
# mq_connection.close()
# Sleep for hb_interval and then check if tmgr responded
mq_connection.sleep(self._hb_interval)
# mq_connection = pika.BlockingConnection(
# pika.ConnectionParameters(host=self._mq_hostname, port=self._port))
# mq_channel = mq_connection.channel()
method_frame, props, body = mq_channel.basic_get(queue=self._hb_response_q)
if body:
if corr_id == props.correlation_id:
self._logger.info('Received heartbeat response')
response = True
mq_channel.basic_ack(delivery_tag=method_frame.delivery_tag)
# Appease pika cos it thinks the connection is dead
# mq_connection.close()
except KeyboardInterrupt:
self._logger.exception('Execution interrupted by user (you probably hit Ctrl+C), ' +
'trying to cancel tmgr process gracefully...')
raise KeyboardInterrupt
except Exception as ex:
self._logger.exception('Heartbeat failed with error: %s' % ex)
raise
finally:
try:
mq_connection.close()
except:
self._logger.warning('mq_connection not created')
self._prof.prof('terminating heartbeat thread', uid=self._uid)
|
python
|
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 message if received in 10 seconds, the tmgr is assumed
dead. The end_manager() is called to cleanly terminate tmgr process and the heartbeat thread is also
terminated.
**Details**: The AppManager can re-invoke both if the execution is still not complete.
"""
try:
self._prof.prof('heartbeat thread started', uid=self._uid)
mq_connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._mq_hostname, port=self._port))
mq_channel = mq_connection.channel()
response = True
while (response and (not self._hb_terminate.is_set())):
response = False
corr_id = str(uuid.uuid4())
# Heartbeat request signal sent to task manager via rpc-queue
mq_channel.basic_publish(exchange='',
routing_key=self._hb_request_q,
properties=pika.BasicProperties(
reply_to=self._hb_response_q,
correlation_id=corr_id),
body='request')
self._logger.info('Sent heartbeat request')
# mq_connection.close()
# Sleep for hb_interval and then check if tmgr responded
mq_connection.sleep(self._hb_interval)
# mq_connection = pika.BlockingConnection(
# pika.ConnectionParameters(host=self._mq_hostname, port=self._port))
# mq_channel = mq_connection.channel()
method_frame, props, body = mq_channel.basic_get(queue=self._hb_response_q)
if body:
if corr_id == props.correlation_id:
self._logger.info('Received heartbeat response')
response = True
mq_channel.basic_ack(delivery_tag=method_frame.delivery_tag)
# Appease pika cos it thinks the connection is dead
# mq_connection.close()
except KeyboardInterrupt:
self._logger.exception('Execution interrupted by user (you probably hit Ctrl+C), ' +
'trying to cancel tmgr process gracefully...')
raise KeyboardInterrupt
except Exception as ex:
self._logger.exception('Heartbeat failed with error: %s' % ex)
raise
finally:
try:
mq_connection.close()
except:
self._logger.warning('mq_connection not created')
self._prof.prof('terminating heartbeat thread', uid=self._uid)
|
[
"def",
"_heartbeat",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_prof",
".",
"prof",
"(",
"'heartbeat thread started'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"mq_connection",
"=",
"pika",
".",
"BlockingConnection",
"(",
"pika",
".",
"ConnectionParameters",
"(",
"host",
"=",
"self",
".",
"_mq_hostname",
",",
"port",
"=",
"self",
".",
"_port",
")",
")",
"mq_channel",
"=",
"mq_connection",
".",
"channel",
"(",
")",
"response",
"=",
"True",
"while",
"(",
"response",
"and",
"(",
"not",
"self",
".",
"_hb_terminate",
".",
"is_set",
"(",
")",
")",
")",
":",
"response",
"=",
"False",
"corr_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"# Heartbeat request signal sent to task manager via rpc-queue",
"mq_channel",
".",
"basic_publish",
"(",
"exchange",
"=",
"''",
",",
"routing_key",
"=",
"self",
".",
"_hb_request_q",
",",
"properties",
"=",
"pika",
".",
"BasicProperties",
"(",
"reply_to",
"=",
"self",
".",
"_hb_response_q",
",",
"correlation_id",
"=",
"corr_id",
")",
",",
"body",
"=",
"'request'",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Sent heartbeat request'",
")",
"# mq_connection.close()",
"# Sleep for hb_interval and then check if tmgr responded",
"mq_connection",
".",
"sleep",
"(",
"self",
".",
"_hb_interval",
")",
"# mq_connection = pika.BlockingConnection(",
"# pika.ConnectionParameters(host=self._mq_hostname, port=self._port))",
"# mq_channel = mq_connection.channel()",
"method_frame",
",",
"props",
",",
"body",
"=",
"mq_channel",
".",
"basic_get",
"(",
"queue",
"=",
"self",
".",
"_hb_response_q",
")",
"if",
"body",
":",
"if",
"corr_id",
"==",
"props",
".",
"correlation_id",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Received heartbeat response'",
")",
"response",
"=",
"True",
"mq_channel",
".",
"basic_ack",
"(",
"delivery_tag",
"=",
"method_frame",
".",
"delivery_tag",
")",
"# Appease pika cos it thinks the connection is dead",
"# mq_connection.close()",
"except",
"KeyboardInterrupt",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Execution interrupted by user (you probably hit Ctrl+C), '",
"+",
"'trying to cancel tmgr process gracefully...'",
")",
"raise",
"KeyboardInterrupt",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Heartbeat failed with error: %s'",
"%",
"ex",
")",
"raise",
"finally",
":",
"try",
":",
"mq_connection",
".",
"close",
"(",
")",
"except",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"'mq_connection not created'",
")",
"self",
".",
"_prof",
".",
"prof",
"(",
"'terminating heartbeat thread'",
",",
"uid",
"=",
"self",
".",
"_uid",
")"
] |
**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 is assumed
dead. The end_manager() is called to cleanly terminate tmgr process and the heartbeat thread is also
terminated.
**Details**: The AppManager can re-invoke both if the execution is still not complete.
|
[
"**",
"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",
"is",
"assumed",
"dead",
".",
"The",
"end_manager",
"()",
"is",
"called",
"to",
"cleanly",
"terminate",
"tmgr",
"process",
"and",
"the",
"heartbeat",
"thread",
"is",
"also",
"terminated",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/task_manager.py#L110-L179
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/execman/base/task_manager.py
|
Base_TaskManager._tmgr
|
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
in the master process.
In addition, the tmgr also receives heartbeat 'request' msgs from the heartbeat-req queue. It responds with a
'response' message to the 'heartbeart-res' queue.
**Details**: The AppManager can re-invoke the tmgr process with this function if the execution of the workflow is
still incomplete. There is also population of a dictionary, placeholder_dict, which stores the path of each of
the tasks on the remote machine.
"""
raise NotImplementedError('_tmgr() method ' +
'not implemented in TaskManager for %s' % self._rts)
|
python
|
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
in the master process.
In addition, the tmgr also receives heartbeat 'request' msgs from the heartbeat-req queue. It responds with a
'response' message to the 'heartbeart-res' queue.
**Details**: The AppManager can re-invoke the tmgr process with this function if the execution of the workflow is
still incomplete. There is also population of a dictionary, placeholder_dict, which stores the path of each of
the tasks on the remote machine.
"""
raise NotImplementedError('_tmgr() method ' +
'not implemented in TaskManager for %s' % self._rts)
|
[
"def",
"_tmgr",
"(",
"self",
",",
"uid",
",",
"rmgr",
",",
"logger",
",",
"mq_hostname",
",",
"port",
",",
"pending_queue",
",",
"completed_queue",
")",
":",
"raise",
"NotImplementedError",
"(",
"'_tmgr() method '",
"+",
"'not implemented in TaskManager for %s'",
"%",
"self",
".",
"_rts",
")"
] |
**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 heartbeat-req queue. It responds with a
'response' message to the 'heartbeart-res' queue.
**Details**: The AppManager can re-invoke the tmgr process with this function if the execution of the workflow is
still incomplete. There is also population of a dictionary, placeholder_dict, which stores the path of each of
the tasks on the remote machine.
|
[
"**",
"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",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/task_manager.py#L181-L196
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/execman/base/task_manager.py
|
Base_TaskManager.start_heartbeat
|
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._logger.info('Starting heartbeat thread')
self._prof.prof('creating heartbeat thread', uid=self._uid)
self._hb_terminate = threading.Event()
self._hb_thread = threading.Thread(target=self._heartbeat, name='heartbeat')
self._prof.prof('starting heartbeat thread', uid=self._uid)
self._hb_thread.start()
return True
except Exception, ex:
self._logger.exception('Heartbeat not started, error: %s' % ex)
self.terminate_heartbeat()
raise
else:
self._logger.warn('Heartbeat thread already running, but attempted to restart!')
|
python
|
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._logger.info('Starting heartbeat thread')
self._prof.prof('creating heartbeat thread', uid=self._uid)
self._hb_terminate = threading.Event()
self._hb_thread = threading.Thread(target=self._heartbeat, name='heartbeat')
self._prof.prof('starting heartbeat thread', uid=self._uid)
self._hb_thread.start()
return True
except Exception, ex:
self._logger.exception('Heartbeat not started, error: %s' % ex)
self.terminate_heartbeat()
raise
else:
self._logger.warn('Heartbeat thread already running, but attempted to restart!')
|
[
"def",
"start_heartbeat",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_hb_thread",
":",
"try",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Starting heartbeat thread'",
")",
"self",
".",
"_prof",
".",
"prof",
"(",
"'creating heartbeat thread'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"self",
".",
"_hb_terminate",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"_hb_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_heartbeat",
",",
"name",
"=",
"'heartbeat'",
")",
"self",
".",
"_prof",
".",
"prof",
"(",
"'starting heartbeat thread'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"self",
".",
"_hb_thread",
".",
"start",
"(",
")",
"return",
"True",
"except",
"Exception",
",",
"ex",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Heartbeat not started, error: %s'",
"%",
"ex",
")",
"self",
".",
"terminate_heartbeat",
"(",
")",
"raise",
"else",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"'Heartbeat thread already running, but attempted to restart!'",
")"
] |
**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.
|
[
"**",
"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",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/task_manager.py#L202-L230
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/execman/base/task_manager.py
|
Base_TaskManager.terminate_heartbeat
|
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.
"""
try:
if self._hb_thread:
self._hb_terminate.set()
if self.check_heartbeat():
self._hb_thread.join()
self._hb_thread = None
self._logger.info('Hearbeat thread terminated')
self._prof.prof('heartbeat thread terminated', uid=self._uid)
# We close in the heartbeat because it ends after the tmgr process
self._prof.close()
except Exception, ex:
self._logger.exception('Could not terminate heartbeat thread')
raise
finally:
if not (self.check_heartbeat() or self.check_manager()):
mq_connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._mq_hostname, port=self._port))
mq_channel = mq_connection.channel()
# To respond to heartbeat - get request from rpc_queue
mq_channel.queue_delete(queue=self._hb_response_q)
mq_channel.queue_delete(queue=self._hb_request_q)
mq_connection.close()
|
python
|
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.
"""
try:
if self._hb_thread:
self._hb_terminate.set()
if self.check_heartbeat():
self._hb_thread.join()
self._hb_thread = None
self._logger.info('Hearbeat thread terminated')
self._prof.prof('heartbeat thread terminated', uid=self._uid)
# We close in the heartbeat because it ends after the tmgr process
self._prof.close()
except Exception, ex:
self._logger.exception('Could not terminate heartbeat thread')
raise
finally:
if not (self.check_heartbeat() or self.check_manager()):
mq_connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._mq_hostname, port=self._port))
mq_channel = mq_connection.channel()
# To respond to heartbeat - get request from rpc_queue
mq_channel.queue_delete(queue=self._hb_response_q)
mq_channel.queue_delete(queue=self._hb_request_q)
mq_connection.close()
|
[
"def",
"terminate_heartbeat",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_hb_thread",
":",
"self",
".",
"_hb_terminate",
".",
"set",
"(",
")",
"if",
"self",
".",
"check_heartbeat",
"(",
")",
":",
"self",
".",
"_hb_thread",
".",
"join",
"(",
")",
"self",
".",
"_hb_thread",
"=",
"None",
"self",
".",
"_logger",
".",
"info",
"(",
"'Hearbeat thread terminated'",
")",
"self",
".",
"_prof",
".",
"prof",
"(",
"'heartbeat thread terminated'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"# We close in the heartbeat because it ends after the tmgr process",
"self",
".",
"_prof",
".",
"close",
"(",
")",
"except",
"Exception",
",",
"ex",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Could not terminate heartbeat thread'",
")",
"raise",
"finally",
":",
"if",
"not",
"(",
"self",
".",
"check_heartbeat",
"(",
")",
"or",
"self",
".",
"check_manager",
"(",
")",
")",
":",
"mq_connection",
"=",
"pika",
".",
"BlockingConnection",
"(",
"pika",
".",
"ConnectionParameters",
"(",
"host",
"=",
"self",
".",
"_mq_hostname",
",",
"port",
"=",
"self",
".",
"_port",
")",
")",
"mq_channel",
"=",
"mq_connection",
".",
"channel",
"(",
")",
"# To respond to heartbeat - get request from rpc_queue",
"mq_channel",
".",
"queue_delete",
"(",
"queue",
"=",
"self",
".",
"_hb_response_q",
")",
"mq_channel",
".",
"queue_delete",
"(",
"queue",
"=",
"self",
".",
"_hb_request_q",
")",
"mq_connection",
".",
"close",
"(",
")"
] |
**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",
")",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/task_manager.py#L232-L274
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/execman/base/task_manager.py
|
Base_TaskManager.terminate_manager
|
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():
self._tmgr_terminate.set()
if self.check_manager():
self._tmgr_process.join()
self._tmgr_process = None
self._logger.info('Task manager process closed')
self._prof.prof('tmgr process terminated', uid=self._uid)
except Exception, ex:
self._logger.exception('Could not terminate task manager process')
raise
|
python
|
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():
self._tmgr_terminate.set()
if self.check_manager():
self._tmgr_process.join()
self._tmgr_process = None
self._logger.info('Task manager process closed')
self._prof.prof('tmgr process terminated', uid=self._uid)
except Exception, ex:
self._logger.exception('Could not terminate task manager process')
raise
|
[
"def",
"terminate_manager",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_tmgr_process",
":",
"if",
"not",
"self",
".",
"_tmgr_terminate",
".",
"is_set",
"(",
")",
":",
"self",
".",
"_tmgr_terminate",
".",
"set",
"(",
")",
"if",
"self",
".",
"check_manager",
"(",
")",
":",
"self",
".",
"_tmgr_process",
".",
"join",
"(",
")",
"self",
".",
"_tmgr_process",
"=",
"None",
"self",
".",
"_logger",
".",
"info",
"(",
"'Task manager process closed'",
")",
"self",
".",
"_prof",
".",
"prof",
"(",
"'tmgr process terminated'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"except",
"Exception",
",",
"ex",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Could not terminate task manager process'",
")",
"raise"
] |
**Purpose**: Method to terminate the tmgr process. This method is
blocking as it waits for the tmgr process to terminate (aka join).
|
[
"**",
"Purpose",
"**",
":",
"Method",
"to",
"terminate",
"the",
"tmgr",
"process",
".",
"This",
"method",
"is",
"blocking",
"as",
"it",
"waits",
"for",
"the",
"tmgr",
"process",
"to",
"terminate",
"(",
"aka",
"join",
")",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/task_manager.py#L286-L309
|
train
|
google/dotty
|
efilter/ext/lazy_repetition.py
|
LazyRepetition.getvalues
|
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 iteration returns a different number of
values than the first iteration over the generator. (This would
mean 'generator_func' is not stable.)
"""
idx = 0
generator = self._generator_func()
first_value = next(generator)
self._value_type = type(first_value)
yield first_value
for idx, value in enumerate(generator):
if not isinstance(value, self._value_type):
raise TypeError(
"All values of a repeated var must be of the same type."
" First argument was of type %r, but argument %r is of"
" type %r." %
(self._value_type, value, repeated.value_type(value)))
self._watermark = max(self._watermark, idx + 1)
yield value
# Iteration stopped - check if we're at the previous watermark and raise
# if not.
if idx + 1 < self._watermark:
raise ValueError(
"LazyRepetition %r was previously able to iterate its"
" generator up to idx %d, but this time iteration stopped after"
" idx %d! Generator function %r is not stable." %
(self, self._watermark, idx + 1, self._generator_func))
# Watermark is higher than previous count! Generator function returned
# more values this time than last time.
if self._count is not None and self._watermark >= self._count:
raise ValueError(
"LazyRepetition %r previously iterated only up to idx %d but"
" was now able to reach idx %d! Generator function %r is not"
" stable." %
(self, self._count - 1, idx + 1, self._generator_func))
# We've finished iteration - cache count. After this the count will be
# watermark + 1 forever.
self._count = self._watermark + 1
|
python
|
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 iteration returns a different number of
values than the first iteration over the generator. (This would
mean 'generator_func' is not stable.)
"""
idx = 0
generator = self._generator_func()
first_value = next(generator)
self._value_type = type(first_value)
yield first_value
for idx, value in enumerate(generator):
if not isinstance(value, self._value_type):
raise TypeError(
"All values of a repeated var must be of the same type."
" First argument was of type %r, but argument %r is of"
" type %r." %
(self._value_type, value, repeated.value_type(value)))
self._watermark = max(self._watermark, idx + 1)
yield value
# Iteration stopped - check if we're at the previous watermark and raise
# if not.
if idx + 1 < self._watermark:
raise ValueError(
"LazyRepetition %r was previously able to iterate its"
" generator up to idx %d, but this time iteration stopped after"
" idx %d! Generator function %r is not stable." %
(self, self._watermark, idx + 1, self._generator_func))
# Watermark is higher than previous count! Generator function returned
# more values this time than last time.
if self._count is not None and self._watermark >= self._count:
raise ValueError(
"LazyRepetition %r previously iterated only up to idx %d but"
" was now able to reach idx %d! Generator function %r is not"
" stable." %
(self, self._count - 1, idx + 1, self._generator_func))
# We've finished iteration - cache count. After this the count will be
# watermark + 1 forever.
self._count = self._watermark + 1
|
[
"def",
"getvalues",
"(",
"self",
")",
":",
"idx",
"=",
"0",
"generator",
"=",
"self",
".",
"_generator_func",
"(",
")",
"first_value",
"=",
"next",
"(",
"generator",
")",
"self",
".",
"_value_type",
"=",
"type",
"(",
"first_value",
")",
"yield",
"first_value",
"for",
"idx",
",",
"value",
"in",
"enumerate",
"(",
"generator",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"_value_type",
")",
":",
"raise",
"TypeError",
"(",
"\"All values of a repeated var must be of the same type.\"",
"\" First argument was of type %r, but argument %r is of\"",
"\" type %r.\"",
"%",
"(",
"self",
".",
"_value_type",
",",
"value",
",",
"repeated",
".",
"value_type",
"(",
"value",
")",
")",
")",
"self",
".",
"_watermark",
"=",
"max",
"(",
"self",
".",
"_watermark",
",",
"idx",
"+",
"1",
")",
"yield",
"value",
"# Iteration stopped - check if we're at the previous watermark and raise",
"# if not.",
"if",
"idx",
"+",
"1",
"<",
"self",
".",
"_watermark",
":",
"raise",
"ValueError",
"(",
"\"LazyRepetition %r was previously able to iterate its\"",
"\" generator up to idx %d, but this time iteration stopped after\"",
"\" idx %d! Generator function %r is not stable.\"",
"%",
"(",
"self",
",",
"self",
".",
"_watermark",
",",
"idx",
"+",
"1",
",",
"self",
".",
"_generator_func",
")",
")",
"# Watermark is higher than previous count! Generator function returned",
"# more values this time than last time.",
"if",
"self",
".",
"_count",
"is",
"not",
"None",
"and",
"self",
".",
"_watermark",
">=",
"self",
".",
"_count",
":",
"raise",
"ValueError",
"(",
"\"LazyRepetition %r previously iterated only up to idx %d but\"",
"\" was now able to reach idx %d! Generator function %r is not\"",
"\" stable.\"",
"%",
"(",
"self",
",",
"self",
".",
"_count",
"-",
"1",
",",
"idx",
"+",
"1",
",",
"self",
".",
"_generator_func",
")",
")",
"# We've finished iteration - cache count. After this the count will be",
"# watermark + 1 forever.",
"self",
".",
"_count",
"=",
"self",
".",
"_watermark",
"+",
"1"
] |
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 of
values than the first iteration over the generator. (This would
mean 'generator_func' is not stable.)
|
[
"Yields",
"all",
"the",
"values",
"from",
"generator_func",
"and",
"type",
"-",
"checks",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/ext/lazy_repetition.py#L66-L117
|
train
|
google/dotty
|
efilter/ext/lazy_repetition.py
|
LazyRepetition.value_eq
|
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
|
python
|
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
|
[
"def",
"value_eq",
"(",
"self",
",",
"other",
")",
":",
"self_sorted",
"=",
"ordered",
".",
"ordered",
"(",
"self",
".",
"getvalues",
"(",
")",
")",
"other_sorted",
"=",
"ordered",
".",
"ordered",
"(",
"repeated",
".",
"getvalues",
"(",
"other",
")",
")",
"return",
"self_sorted",
"==",
"other_sorted"
] |
Sorted comparison of values.
|
[
"Sorted",
"comparison",
"of",
"values",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/ext/lazy_repetition.py#L127-L131
|
train
|
google/dotty
|
efilter/dispatch.py
|
call_audit
|
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" % (
len(stack),
" -> ".join("%s:%d:%s" % x[0:3] for x in stack[-5:-2]),
func_name,
args,
kwargs,
r))
return r
return audited_func
|
python
|
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" % (
len(stack),
" -> ".join("%s:%d:%s" % x[0:3] for x in stack[-5:-2]),
func_name,
args,
kwargs,
r))
return r
return audited_func
|
[
"def",
"call_audit",
"(",
"func",
")",
":",
"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\"",
"%",
"(",
"len",
"(",
"stack",
")",
",",
"\" -> \"",
".",
"join",
"(",
"\"%s:%d:%s\"",
"%",
"x",
"[",
"0",
":",
"3",
"]",
"for",
"x",
"in",
"stack",
"[",
"-",
"5",
":",
"-",
"2",
"]",
")",
",",
"func_name",
",",
"args",
",",
"kwargs",
",",
"r",
")",
")",
"return",
"r",
"return",
"audited_func"
] |
Print a detailed audit of all calls to this function.
|
[
"Print",
"a",
"detailed",
"audit",
"of",
"all",
"calls",
"to",
"this",
"function",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L51-L68
|
train
|
google/dotty
|
efilter/dispatch.py
|
_class_dispatch
|
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 type, not instance.")
return args[0]
|
python
|
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 type, not instance.")
return args[0]
|
[
"def",
"_class_dispatch",
"(",
"args",
",",
"kwargs",
")",
":",
"_",
"=",
"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 type, not instance.\"",
")",
"return",
"args",
"[",
"0",
"]"
] |
See 'class_multimethod'.
|
[
"See",
"class_multimethod",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L71-L82
|
train
|
google/dotty
|
efilter/dispatch.py
|
multimethod.prefer_type
|
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 supertype has no order
with respect to other supertypes, and this may lead to amguity if two
implementations are provided for unrelated abstract types.
In such cases, it is possible to disambiguate by explictly telling the
function to prefer one type over the other.
Arguments:
prefer: Preferred type (class).
over: The type we don't like (class).
Raises:
ValueError: In case of logical conflicts.
"""
self._write_lock.acquire()
try:
if self._preferred(preferred=over, over=prefer):
raise ValueError(
"Type %r is already preferred over %r." % (over, prefer))
prefs = self._prefer_table.setdefault(prefer, set())
prefs.add(over)
finally:
self._write_lock.release()
|
python
|
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 supertype has no order
with respect to other supertypes, and this may lead to amguity if two
implementations are provided for unrelated abstract types.
In such cases, it is possible to disambiguate by explictly telling the
function to prefer one type over the other.
Arguments:
prefer: Preferred type (class).
over: The type we don't like (class).
Raises:
ValueError: In case of logical conflicts.
"""
self._write_lock.acquire()
try:
if self._preferred(preferred=over, over=prefer):
raise ValueError(
"Type %r is already preferred over %r." % (over, prefer))
prefs = self._prefer_table.setdefault(prefer, set())
prefs.add(over)
finally:
self._write_lock.release()
|
[
"def",
"prefer_type",
"(",
"self",
",",
"prefer",
",",
"over",
")",
":",
"self",
".",
"_write_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"_preferred",
"(",
"preferred",
"=",
"over",
",",
"over",
"=",
"prefer",
")",
":",
"raise",
"ValueError",
"(",
"\"Type %r is already preferred over %r.\"",
"%",
"(",
"over",
",",
"prefer",
")",
")",
"prefs",
"=",
"self",
".",
"_prefer_table",
".",
"setdefault",
"(",
"prefer",
",",
"set",
"(",
")",
")",
"prefs",
".",
"add",
"(",
"over",
")",
"finally",
":",
"self",
".",
"_write_lock",
".",
"release",
"(",
")"
] |
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 other supertypes, and this may lead to amguity if two
implementations are provided for unrelated abstract types.
In such cases, it is possible to disambiguate by explictly telling the
function to prefer one type over the other.
Arguments:
prefer: Preferred type (class).
over: The type we don't like (class).
Raises:
ValueError: In case of logical conflicts.
|
[
"Prefer",
"one",
"type",
"over",
"another",
"type",
"all",
"else",
"being",
"equivalent",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L225-L252
|
train
|
google/dotty
|
efilter/dispatch.py
|
multimethod._find_and_cache_best_function
|
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 registered implementations (through
multimethod.implement) for types that 'dispatch_type' either is
or inherits from directly.
2. Explicitly registered implementations accepting an abstract type
(interface) in which dispatch_type participates (through
abstract_type.register() or the convenience methods).
3. Default behavior of the multimethod function. This will usually
raise a NotImplementedError, by convention.
Raises:
TypeError: If two implementing functions are registered for
different abstract types, and 'dispatch_type' participates in
both, and no order of preference was specified using
prefer_type.
"""
result = self._dispatch_table.get(dispatch_type)
if result:
return result
# The outer try ensures the lock is always released.
with self._write_lock:
try:
dispatch_mro = dispatch_type.mro()
except TypeError:
# Not every type has an MRO.
dispatch_mro = ()
best_match = None
result_type = None
for candidate_type, candidate_func in self.implementations:
if not issubclass(dispatch_type, candidate_type):
# Skip implementations that are obviously unrelated.
continue
try:
# The candidate implementation may be for a type that's
# actually in the MRO, or it may be for an abstract type.
match = dispatch_mro.index(candidate_type)
except ValueError:
# This means we have an implementation for an abstract
# type, which ranks below all concrete types.
match = None
if best_match is None:
if result and match is None:
# Already have a result, and no order of preference.
# This is probably because the type is a member of two
# abstract types and we have separate implementations
# for those two abstract types.
if self._preferred(candidate_type, over=result_type):
result = candidate_func
result_type = candidate_type
elif self._preferred(result_type, over=candidate_type):
# No need to update anything.
pass
else:
raise TypeError(
"Two candidate implementations found for "
"multimethod function %s (dispatch type %s) "
"and neither is preferred." %
(self.func_name, dispatch_type))
else:
result = candidate_func
result_type = candidate_type
best_match = match
if (match or 0) < (best_match or 0):
result = candidate_func
result_type = candidate_type
best_match = match
self._dispatch_table[dispatch_type] = result
return result
|
python
|
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 registered implementations (through
multimethod.implement) for types that 'dispatch_type' either is
or inherits from directly.
2. Explicitly registered implementations accepting an abstract type
(interface) in which dispatch_type participates (through
abstract_type.register() or the convenience methods).
3. Default behavior of the multimethod function. This will usually
raise a NotImplementedError, by convention.
Raises:
TypeError: If two implementing functions are registered for
different abstract types, and 'dispatch_type' participates in
both, and no order of preference was specified using
prefer_type.
"""
result = self._dispatch_table.get(dispatch_type)
if result:
return result
# The outer try ensures the lock is always released.
with self._write_lock:
try:
dispatch_mro = dispatch_type.mro()
except TypeError:
# Not every type has an MRO.
dispatch_mro = ()
best_match = None
result_type = None
for candidate_type, candidate_func in self.implementations:
if not issubclass(dispatch_type, candidate_type):
# Skip implementations that are obviously unrelated.
continue
try:
# The candidate implementation may be for a type that's
# actually in the MRO, or it may be for an abstract type.
match = dispatch_mro.index(candidate_type)
except ValueError:
# This means we have an implementation for an abstract
# type, which ranks below all concrete types.
match = None
if best_match is None:
if result and match is None:
# Already have a result, and no order of preference.
# This is probably because the type is a member of two
# abstract types and we have separate implementations
# for those two abstract types.
if self._preferred(candidate_type, over=result_type):
result = candidate_func
result_type = candidate_type
elif self._preferred(result_type, over=candidate_type):
# No need to update anything.
pass
else:
raise TypeError(
"Two candidate implementations found for "
"multimethod function %s (dispatch type %s) "
"and neither is preferred." %
(self.func_name, dispatch_type))
else:
result = candidate_func
result_type = candidate_type
best_match = match
if (match or 0) < (best_match or 0):
result = candidate_func
result_type = candidate_type
best_match = match
self._dispatch_table[dispatch_type] = result
return result
|
[
"def",
"_find_and_cache_best_function",
"(",
"self",
",",
"dispatch_type",
")",
":",
"result",
"=",
"self",
".",
"_dispatch_table",
".",
"get",
"(",
"dispatch_type",
")",
"if",
"result",
":",
"return",
"result",
"# The outer try ensures the lock is always released.",
"with",
"self",
".",
"_write_lock",
":",
"try",
":",
"dispatch_mro",
"=",
"dispatch_type",
".",
"mro",
"(",
")",
"except",
"TypeError",
":",
"# Not every type has an MRO.",
"dispatch_mro",
"=",
"(",
")",
"best_match",
"=",
"None",
"result_type",
"=",
"None",
"for",
"candidate_type",
",",
"candidate_func",
"in",
"self",
".",
"implementations",
":",
"if",
"not",
"issubclass",
"(",
"dispatch_type",
",",
"candidate_type",
")",
":",
"# Skip implementations that are obviously unrelated.",
"continue",
"try",
":",
"# The candidate implementation may be for a type that's",
"# actually in the MRO, or it may be for an abstract type.",
"match",
"=",
"dispatch_mro",
".",
"index",
"(",
"candidate_type",
")",
"except",
"ValueError",
":",
"# This means we have an implementation for an abstract",
"# type, which ranks below all concrete types.",
"match",
"=",
"None",
"if",
"best_match",
"is",
"None",
":",
"if",
"result",
"and",
"match",
"is",
"None",
":",
"# Already have a result, and no order of preference.",
"# This is probably because the type is a member of two",
"# abstract types and we have separate implementations",
"# for those two abstract types.",
"if",
"self",
".",
"_preferred",
"(",
"candidate_type",
",",
"over",
"=",
"result_type",
")",
":",
"result",
"=",
"candidate_func",
"result_type",
"=",
"candidate_type",
"elif",
"self",
".",
"_preferred",
"(",
"result_type",
",",
"over",
"=",
"candidate_type",
")",
":",
"# No need to update anything.",
"pass",
"else",
":",
"raise",
"TypeError",
"(",
"\"Two candidate implementations found for \"",
"\"multimethod function %s (dispatch type %s) \"",
"\"and neither is preferred.\"",
"%",
"(",
"self",
".",
"func_name",
",",
"dispatch_type",
")",
")",
"else",
":",
"result",
"=",
"candidate_func",
"result_type",
"=",
"candidate_type",
"best_match",
"=",
"match",
"if",
"(",
"match",
"or",
"0",
")",
"<",
"(",
"best_match",
"or",
"0",
")",
":",
"result",
"=",
"candidate_func",
"result_type",
"=",
"candidate_type",
"best_match",
"=",
"match",
"self",
".",
"_dispatch_table",
"[",
"dispatch_type",
"]",
"=",
"result",
"return",
"result"
] |
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) for types that 'dispatch_type' either is
or inherits from directly.
2. Explicitly registered implementations accepting an abstract type
(interface) in which dispatch_type participates (through
abstract_type.register() or the convenience methods).
3. Default behavior of the multimethod function. This will usually
raise a NotImplementedError, by convention.
Raises:
TypeError: If two implementing functions are registered for
different abstract types, and 'dispatch_type' participates in
both, and no order of preference was specified using
prefer_type.
|
[
"Finds",
"the",
"best",
"implementation",
"of",
"this",
"function",
"given",
"a",
"type",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L254-L335
|
train
|
google/dotty
|
efilter/dispatch.py
|
multimethod.__get_types
|
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_types.")
for_types = (for_type,)
elif for_types:
if not isinstance(for_types, tuple):
raise TypeError("for_types must be passed as a tuple of "
"types (classes).")
else:
raise ValueError("Must pass either for_type or for_types.")
return for_types
|
python
|
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_types.")
for_types = (for_type,)
elif for_types:
if not isinstance(for_types, tuple):
raise TypeError("for_types must be passed as a tuple of "
"types (classes).")
else:
raise ValueError("Must pass either for_type or for_types.")
return for_types
|
[
"def",
"__get_types",
"(",
"for_type",
"=",
"None",
",",
"for_types",
"=",
"None",
")",
":",
"if",
"for_type",
":",
"if",
"for_types",
":",
"raise",
"ValueError",
"(",
"\"Cannot pass both for_type and for_types.\"",
")",
"for_types",
"=",
"(",
"for_type",
",",
")",
"elif",
"for_types",
":",
"if",
"not",
"isinstance",
"(",
"for_types",
",",
"tuple",
")",
":",
"raise",
"TypeError",
"(",
"\"for_types must be passed as a tuple of \"",
"\"types (classes).\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Must pass either for_type or for_types.\"",
")",
"return",
"for_types"
] |
Parse the arguments and return a tuple of types to implement for.
Raises:
ValueError or TypeError as appropriate.
|
[
"Parse",
"the",
"arguments",
"and",
"return",
"a",
"tuple",
"of",
"types",
"to",
"implement",
"for",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L338-L355
|
train
|
google/dotty
|
efilter/dispatch.py
|
multimethod.implementation
|
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
@add.implementation(for_type=SomeType)
def add(x, y):
return int(x) + int(y)
"""
for_types = self.__get_types(for_type, for_types)
def _decorator(implementation):
self.implement(implementation, for_types=for_types)
return self
return _decorator
|
python
|
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
@add.implementation(for_type=SomeType)
def add(x, y):
return int(x) + int(y)
"""
for_types = self.__get_types(for_type, for_types)
def _decorator(implementation):
self.implement(implementation, for_types=for_types)
return self
return _decorator
|
[
"def",
"implementation",
"(",
"self",
",",
"for_type",
"=",
"None",
",",
"for_types",
"=",
"None",
")",
":",
"for_types",
"=",
"self",
".",
"__get_types",
"(",
"for_type",
",",
"for_types",
")",
"def",
"_decorator",
"(",
"implementation",
")",
":",
"self",
".",
"implement",
"(",
"implementation",
",",
"for_types",
"=",
"for_types",
")",
"return",
"self",
"return",
"_decorator"
] |
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 add(x, y):
return int(x) + int(y)
|
[
"Return",
"a",
"decorator",
"that",
"will",
"register",
"the",
"implementation",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L357-L379
|
train
|
google/dotty
|
efilter/dispatch.py
|
multimethod.implement
|
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, but takes a tuple of types.
for_type and for_types cannot both be passed (for obvious reasons.)
Raises:
ValueError
"""
unbound_implementation = self.__get_unbound_function(implementation)
for_types = self.__get_types(for_type, for_types)
for t in for_types:
self._write_lock.acquire()
try:
self.implementations.append((t, unbound_implementation))
finally:
self._write_lock.release()
|
python
|
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, but takes a tuple of types.
for_type and for_types cannot both be passed (for obvious reasons.)
Raises:
ValueError
"""
unbound_implementation = self.__get_unbound_function(implementation)
for_types = self.__get_types(for_type, for_types)
for t in for_types:
self._write_lock.acquire()
try:
self.implementations.append((t, unbound_implementation))
finally:
self._write_lock.release()
|
[
"def",
"implement",
"(",
"self",
",",
"implementation",
",",
"for_type",
"=",
"None",
",",
"for_types",
"=",
"None",
")",
":",
"unbound_implementation",
"=",
"self",
".",
"__get_unbound_function",
"(",
"implementation",
")",
"for_types",
"=",
"self",
".",
"__get_types",
"(",
"for_type",
",",
"for_types",
")",
"for",
"t",
"in",
"for_types",
":",
"self",
".",
"_write_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"implementations",
".",
"append",
"(",
"(",
"t",
",",
"unbound_implementation",
")",
")",
"finally",
":",
"self",
".",
"_write_lock",
".",
"release",
"(",
")"
] |
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 passed (for obvious reasons.)
Raises:
ValueError
|
[
"Registers",
"an",
"implementing",
"function",
"for",
"for_type",
"."
] |
b145131499be0c4b755fc2e2ac19be11a50bce6a
|
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L388-L409
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/templatetags/redis_metrics_filters.py
|
to_int_list
|
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 (TypeError, ValueError):
results.append(0)
return results
|
python
|
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 (TypeError, ValueError):
results.append(0)
return results
|
[
"def",
"to_int_list",
"(",
"values",
")",
":",
"results",
"=",
"[",
"]",
"for",
"v",
"in",
"values",
":",
"try",
":",
"results",
".",
"append",
"(",
"int",
"(",
"v",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"results",
".",
"append",
"(",
"0",
")",
"return",
"results"
] |
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.
|
[
"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",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metrics_filters.py#L15-L25
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/execman/base/resource_manager.py
|
Base_ResourceManager._validate_resource_desc
|
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',
'walltime',
'cpus']
for key in expected_keys:
if key not in self._resource_desc:
raise MissingError(obj='resource description', missing_attribute=key)
if not isinstance(self._resource_desc['resource'], str):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['resource']))
if not isinstance(self._resource_desc['walltime'], int):
raise TypeError(expected_type=int, actual_type=type(self._resource_desc['walltime']))
if not isinstance(self._resource_desc['cpus'], int):
raise TypeError(expected_type=int, actual_type=type(self._resource_desc['cpus']))
if 'gpus' in self._resource_desc:
if (not isinstance(self._resource_desc['gpus'], int)):
raise TypeError(expected_type=int, actual_type=type(self._resource_desc['project']))
if 'project' in self._resource_desc:
if (not isinstance(self._resource_desc['project'], str)) and (not self._resource_desc['project']):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['project']))
if 'access_schema' in self._resource_desc:
if not isinstance(self._resource_desc['access_schema'], str):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['access_schema']))
if 'queue' in self._resource_desc:
if not isinstance(self._resource_desc['queue'], str):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['queue']))
if not isinstance(self._rts_config, dict):
raise TypeError(expected_type=dict, actual_type=type(self._rts_config))
self._validated = True
self._logger.info('Resource description validated')
self._prof.prof('rdesc validated', uid=self._uid)
return self._validated
|
python
|
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',
'walltime',
'cpus']
for key in expected_keys:
if key not in self._resource_desc:
raise MissingError(obj='resource description', missing_attribute=key)
if not isinstance(self._resource_desc['resource'], str):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['resource']))
if not isinstance(self._resource_desc['walltime'], int):
raise TypeError(expected_type=int, actual_type=type(self._resource_desc['walltime']))
if not isinstance(self._resource_desc['cpus'], int):
raise TypeError(expected_type=int, actual_type=type(self._resource_desc['cpus']))
if 'gpus' in self._resource_desc:
if (not isinstance(self._resource_desc['gpus'], int)):
raise TypeError(expected_type=int, actual_type=type(self._resource_desc['project']))
if 'project' in self._resource_desc:
if (not isinstance(self._resource_desc['project'], str)) and (not self._resource_desc['project']):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['project']))
if 'access_schema' in self._resource_desc:
if not isinstance(self._resource_desc['access_schema'], str):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['access_schema']))
if 'queue' in self._resource_desc:
if not isinstance(self._resource_desc['queue'], str):
raise TypeError(expected_type=str, actual_type=type(self._resource_desc['queue']))
if not isinstance(self._rts_config, dict):
raise TypeError(expected_type=dict, actual_type=type(self._rts_config))
self._validated = True
self._logger.info('Resource description validated')
self._prof.prof('rdesc validated', uid=self._uid)
return self._validated
|
[
"def",
"_validate_resource_desc",
"(",
"self",
")",
":",
"self",
".",
"_prof",
".",
"prof",
"(",
"'validating rdesc'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Validating resource description'",
")",
"expected_keys",
"=",
"[",
"'resource'",
",",
"'walltime'",
",",
"'cpus'",
"]",
"for",
"key",
"in",
"expected_keys",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_resource_desc",
":",
"raise",
"MissingError",
"(",
"obj",
"=",
"'resource description'",
",",
"missing_attribute",
"=",
"key",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_resource_desc",
"[",
"'resource'",
"]",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"str",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_resource_desc",
"[",
"'resource'",
"]",
")",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_resource_desc",
"[",
"'walltime'",
"]",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"int",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_resource_desc",
"[",
"'walltime'",
"]",
")",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_resource_desc",
"[",
"'cpus'",
"]",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"int",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_resource_desc",
"[",
"'cpus'",
"]",
")",
")",
"if",
"'gpus'",
"in",
"self",
".",
"_resource_desc",
":",
"if",
"(",
"not",
"isinstance",
"(",
"self",
".",
"_resource_desc",
"[",
"'gpus'",
"]",
",",
"int",
")",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"int",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_resource_desc",
"[",
"'project'",
"]",
")",
")",
"if",
"'project'",
"in",
"self",
".",
"_resource_desc",
":",
"if",
"(",
"not",
"isinstance",
"(",
"self",
".",
"_resource_desc",
"[",
"'project'",
"]",
",",
"str",
")",
")",
"and",
"(",
"not",
"self",
".",
"_resource_desc",
"[",
"'project'",
"]",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"str",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_resource_desc",
"[",
"'project'",
"]",
")",
")",
"if",
"'access_schema'",
"in",
"self",
".",
"_resource_desc",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_resource_desc",
"[",
"'access_schema'",
"]",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"str",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_resource_desc",
"[",
"'access_schema'",
"]",
")",
")",
"if",
"'queue'",
"in",
"self",
".",
"_resource_desc",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_resource_desc",
"[",
"'queue'",
"]",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"str",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_resource_desc",
"[",
"'queue'",
"]",
")",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_rts_config",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"dict",
",",
"actual_type",
"=",
"type",
"(",
"self",
".",
"_rts_config",
")",
")",
"self",
".",
"_validated",
"=",
"True",
"self",
".",
"_logger",
".",
"info",
"(",
"'Resource description validated'",
")",
"self",
".",
"_prof",
".",
"prof",
"(",
"'rdesc validated'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"return",
"self",
".",
"_validated"
] |
**Purpose**: Validate the resource description provided to the ResourceManager
|
[
"**",
"Purpose",
"**",
":",
"Validate",
"the",
"resource",
"description",
"provided",
"to",
"the",
"ResourceManager"
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/resource_manager.py#L147-L196
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/execman/base/resource_manager.py
|
Base_ResourceManager._populate
|
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 object')
self._resource = self._resource_desc['resource']
self._walltime = self._resource_desc['walltime']
self._cpus = self._resource_desc['cpus']
self._gpus = self._resource_desc.get('gpus', 0)
self._project = self._resource_desc.get('project', None)
self._access_schema = self._resource_desc.get('access_schema', None)
self._queue = self._resource_desc.get('queue', None)
self._logger.debug('Resource manager population successful')
self._prof.prof('rmgr populated', uid=self._uid)
else:
raise EnTKError('Resource description not validated')
|
python
|
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 object')
self._resource = self._resource_desc['resource']
self._walltime = self._resource_desc['walltime']
self._cpus = self._resource_desc['cpus']
self._gpus = self._resource_desc.get('gpus', 0)
self._project = self._resource_desc.get('project', None)
self._access_schema = self._resource_desc.get('access_schema', None)
self._queue = self._resource_desc.get('queue', None)
self._logger.debug('Resource manager population successful')
self._prof.prof('rmgr populated', uid=self._uid)
else:
raise EnTKError('Resource description not validated')
|
[
"def",
"_populate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_validated",
":",
"self",
".",
"_prof",
".",
"prof",
"(",
"'populating rmgr'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Populating resource manager object'",
")",
"self",
".",
"_resource",
"=",
"self",
".",
"_resource_desc",
"[",
"'resource'",
"]",
"self",
".",
"_walltime",
"=",
"self",
".",
"_resource_desc",
"[",
"'walltime'",
"]",
"self",
".",
"_cpus",
"=",
"self",
".",
"_resource_desc",
"[",
"'cpus'",
"]",
"self",
".",
"_gpus",
"=",
"self",
".",
"_resource_desc",
".",
"get",
"(",
"'gpus'",
",",
"0",
")",
"self",
".",
"_project",
"=",
"self",
".",
"_resource_desc",
".",
"get",
"(",
"'project'",
",",
"None",
")",
"self",
".",
"_access_schema",
"=",
"self",
".",
"_resource_desc",
".",
"get",
"(",
"'access_schema'",
",",
"None",
")",
"self",
".",
"_queue",
"=",
"self",
".",
"_resource_desc",
".",
"get",
"(",
"'queue'",
",",
"None",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Resource manager population successful'",
")",
"self",
".",
"_prof",
".",
"prof",
"(",
"'rmgr populated'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"else",
":",
"raise",
"EnTKError",
"(",
"'Resource description not validated'",
")"
] |
**Purpose**: Populate the ResourceManager class with the validated
resource description
|
[
"**",
"Purpose",
"**",
":",
"Populate",
"the",
"ResourceManager",
"class",
"with",
"the",
"validated",
"resource",
"description"
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/resource_manager.py#L198-L221
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
GaugesView.get_context_data
|
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
|
python
|
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
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"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.
|
[
"Includes",
"the",
"Gauge",
"slugs",
"and",
"data",
"in",
"the",
"context",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L51-L55
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
MetricsListView.get_context_data
|
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_slugs_by_category()})
return data
|
python
|
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_slugs_by_category()})
return data
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"super",
"(",
"MetricsListView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"# Metrics organized by category, like so:",
"# { <category_name>: [ <slug1>, <slug2>, ... ]}",
"data",
".",
"update",
"(",
"{",
"'metrics'",
":",
"get_r",
"(",
")",
".",
"metric_slugs_by_category",
"(",
")",
"}",
")",
"return",
"data"
] |
Includes the metrics slugs in the context.
|
[
"Includes",
"the",
"metrics",
"slugs",
"in",
"the",
"context",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L61-L68
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
MetricDetailView.get_context_data
|
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
|
python
|
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
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"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.
|
[
"Includes",
"the",
"metrics",
"slugs",
"in",
"the",
"context",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L74-L79
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
MetricHistoryView.get_context_data
|
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-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
data.update({
'since': since,
'slug': kwargs['slug'],
'granularity': kwargs['granularity'],
'granularities': list(get_r()._granularities()),
})
return data
|
python
|
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-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
data.update({
'since': since,
'slug': kwargs['slug'],
'granularity': kwargs['granularity'],
'granularities': list(get_r()._granularities()),
})
return data
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"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-dd",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d\"",
")",
"elif",
"since",
"and",
"len",
"(",
"since",
")",
"==",
"19",
":",
"# yyyy-mm-dd HH:MM:ss",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"data",
".",
"update",
"(",
"{",
"'since'",
":",
"since",
",",
"'slug'",
":",
"kwargs",
"[",
"'slug'",
"]",
",",
"'granularity'",
":",
"kwargs",
"[",
"'granularity'",
"]",
",",
"'granularities'",
":",
"list",
"(",
"get_r",
"(",
")",
".",
"_granularities",
"(",
")",
")",
",",
"}",
")",
"return",
"data"
] |
Includes the metrics slugs in the context.
|
[
"Includes",
"the",
"metrics",
"slugs",
"in",
"the",
"context",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L85-L102
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
AggregateFormView.get_success_url
|
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 %2B. We want
# want to keep the + in the url (it's ok according to RFC 1738)
# https://docs.djangoproject.com/en/1.6/releases/1.6/#quoting-in-reverse
return url.replace("%2B", "+")
|
python
|
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 %2B. We want
# want to keep the + in the url (it's ok according to RFC 1738)
# https://docs.djangoproject.com/en/1.6/releases/1.6/#quoting-in-reverse
return url.replace("%2B", "+")
|
[
"def",
"get_success_url",
"(",
"self",
")",
":",
"slugs",
"=",
"'+'",
".",
"join",
"(",
"self",
".",
"metric_slugs",
")",
"url",
"=",
"reverse",
"(",
"'redis_metric_aggregate_detail'",
",",
"args",
"=",
"[",
"slugs",
"]",
")",
"# Django 1.6 quotes reversed URLs, which changes + into %2B. We want",
"# want to keep the + in the url (it's ok according to RFC 1738)",
"# https://docs.djangoproject.com/en/1.6/releases/1.6/#quoting-in-reverse",
"return",
"url",
".",
"replace",
"(",
"\"%2B\"",
",",
"\"+\"",
")"
] |
Reverses the ``redis_metric_aggregate_detail`` URL using
``self.metric_slugs`` as an argument.
|
[
"Reverses",
"the",
"redis_metric_aggregate_detail",
"URL",
"using",
"self",
".",
"metric_slugs",
"as",
"an",
"argument",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L111-L119
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
AggregateFormView.form_valid
|
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)
|
python
|
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)
|
[
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"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``.
|
[
"Pull",
"the",
"metrics",
"from",
"the",
"submitted",
"form",
"and",
"store",
"them",
"as",
"a",
"list",
"of",
"strings",
"in",
"self",
".",
"metric_slugs",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L121-L126
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
AggregateDetailView.get_context_data
|
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)
else:
slug_set = set(kwargs['slugs'].split('+'))
data['granularities'] = list(r._granularities())
data['slugs'] = slug_set
data['category'] = category
return data
|
python
|
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)
else:
slug_set = set(kwargs['slugs'].split('+'))
data['granularities'] = list(r._granularities())
data['slugs'] = slug_set
data['category'] = category
return data
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"category",
"=",
"kwargs",
".",
"pop",
"(",
"'category'",
",",
"None",
")",
"data",
"=",
"super",
"(",
"AggregateDetailView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"if",
"category",
":",
"slug_set",
"=",
"r",
".",
"_category_slugs",
"(",
"category",
")",
"else",
":",
"slug_set",
"=",
"set",
"(",
"kwargs",
"[",
"'slugs'",
"]",
".",
"split",
"(",
"'+'",
")",
")",
"data",
"[",
"'granularities'",
"]",
"=",
"list",
"(",
"r",
".",
"_granularities",
"(",
")",
")",
"data",
"[",
"'slugs'",
"]",
"=",
"slug_set",
"data",
"[",
"'category'",
"]",
"=",
"category",
"return",
"data"
] |
Includes the metrics slugs in the context.
|
[
"Includes",
"the",
"metrics",
"slugs",
"in",
"the",
"context",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L132-L146
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
AggregateHistoryView.get_context_data
|
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 query params for ``since``
since = self.request.GET.get('since', None)
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
data.update({
'slugs': slug_set,
'granularity': granularity,
'since': since,
'granularities': list(r._granularities())
})
return data
|
python
|
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 query params for ``since``
since = self.request.GET.get('since', None)
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
data.update({
'slugs': slug_set,
'granularity': granularity,
'since': since,
'granularities': list(r._granularities())
})
return data
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"data",
"=",
"super",
"(",
"AggregateHistoryView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"slug_set",
"=",
"set",
"(",
"kwargs",
"[",
"'slugs'",
"]",
".",
"split",
"(",
"'+'",
")",
")",
"granularity",
"=",
"kwargs",
".",
"get",
"(",
"'granularity'",
",",
"'daily'",
")",
"# Accept GET query params for ``since``",
"since",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"'since'",
",",
"None",
")",
"if",
"since",
"and",
"len",
"(",
"since",
")",
"==",
"10",
":",
"# yyyy-mm-dd",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d\"",
")",
"elif",
"since",
"and",
"len",
"(",
"since",
")",
"==",
"19",
":",
"# yyyy-mm-dd HH:MM:ss",
"since",
"=",
"datetime",
".",
"strptime",
"(",
"since",
",",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"data",
".",
"update",
"(",
"{",
"'slugs'",
":",
"slug_set",
",",
"'granularity'",
":",
"granularity",
",",
"'since'",
":",
"since",
",",
"'granularities'",
":",
"list",
"(",
"r",
".",
"_granularities",
"(",
")",
")",
"}",
")",
"return",
"data"
] |
Includes the metrics slugs in the context.
|
[
"Includes",
"the",
"metrics",
"slugs",
"in",
"the",
"context",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L152-L172
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
CategoryFormView.get
|
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)
|
python
|
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)
|
[
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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.
|
[
"See",
"if",
"this",
"view",
"was",
"called",
"with",
"a",
"specified",
"category",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L180-L183
|
train
|
bradmontgomery/django-redis-metrics
|
redis_metrics/views.py
|
CategoryFormView.form_valid
|
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)
|
python
|
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)
|
[
"def",
"form_valid",
"(",
"self",
",",
"form",
")",
":",
"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.
|
[
"Get",
"the",
"category",
"name",
"/",
"metric",
"slugs",
"from",
"the",
"form",
"and",
"update",
"the",
"category",
"so",
"contains",
"the",
"given",
"metrics",
"."
] |
2c92332920113d28c39234b949aa496b39a091d1
|
https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/views.py#L193-L197
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline.rerun
|
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)
|
python
|
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)
|
[
"def",
"rerun",
"(",
"self",
")",
":",
"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
|
[
"Rerun",
"sets",
"the",
"state",
"of",
"the",
"Pipeline",
"to",
"scheduling",
"so",
"that",
"the",
"Pipeline",
"can",
"be",
"checked",
"for",
"new",
"stages"
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L204-L213
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline.to_dict
|
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._state_history,
'completed': self._completed_flag.is_set()
}
return pipeline_desc_as_dict
|
python
|
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._state_history,
'completed': self._completed_flag.is_set()
}
return pipeline_desc_as_dict
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"pipeline_desc_as_dict",
"=",
"{",
"'uid'",
":",
"self",
".",
"_uid",
",",
"'name'",
":",
"self",
".",
"_name",
",",
"'state'",
":",
"self",
".",
"_state",
",",
"'state_history'",
":",
"self",
".",
"_state_history",
",",
"'completed'",
":",
"self",
".",
"_completed_flag",
".",
"is_set",
"(",
")",
"}",
"return",
"pipeline_desc_as_dict"
] |
Convert current Pipeline (i.e. its attributes) into a dictionary
:return: python dictionary
|
[
"Convert",
"current",
"Pipeline",
"(",
"i",
".",
"e",
".",
"its",
"attributes",
")",
"into",
"a",
"dictionary"
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L215-L231
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline.from_dict
|
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']:
self._name = d['name']
if 'state' in d:
if isinstance(d['state'], str) or isinstance(d['state'], unicode):
if d['state'] in states._pipeline_state_values.keys():
self._state = d['state']
else:
raise ValueError(obj=self._uid,
attribute='state',
expected_value=states._pipeline_state_values.keys(),
actual_value=d['state'])
else:
raise TypeError(entity='state', expected_type=str,
actual_type=type(d['state']))
else:
self._state = states.INITIAL
if 'state_history' in d:
if isinstance(d['state_history'], list):
self._state_history = d['state_history']
else:
raise TypeError(entity='state_history', expected_type=list, actual_type=type(
d['state_history']))
if 'completed' in d:
if isinstance(d['completed'], bool):
if d['completed']:
self._completed_flag.set()
else:
raise TypeError(entity='completed', expected_type=bool,
actual_type=type(d['completed']))
|
python
|
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']:
self._name = d['name']
if 'state' in d:
if isinstance(d['state'], str) or isinstance(d['state'], unicode):
if d['state'] in states._pipeline_state_values.keys():
self._state = d['state']
else:
raise ValueError(obj=self._uid,
attribute='state',
expected_value=states._pipeline_state_values.keys(),
actual_value=d['state'])
else:
raise TypeError(entity='state', expected_type=str,
actual_type=type(d['state']))
else:
self._state = states.INITIAL
if 'state_history' in d:
if isinstance(d['state_history'], list):
self._state_history = d['state_history']
else:
raise TypeError(entity='state_history', expected_type=list, actual_type=type(
d['state_history']))
if 'completed' in d:
if isinstance(d['completed'], bool):
if d['completed']:
self._completed_flag.set()
else:
raise TypeError(entity='completed', expected_type=bool,
actual_type=type(d['completed']))
|
[
"def",
"from_dict",
"(",
"self",
",",
"d",
")",
":",
"if",
"'uid'",
"in",
"d",
":",
"if",
"d",
"[",
"'uid'",
"]",
":",
"self",
".",
"_uid",
"=",
"d",
"[",
"'uid'",
"]",
"if",
"'name'",
"in",
"d",
":",
"if",
"d",
"[",
"'name'",
"]",
":",
"self",
".",
"_name",
"=",
"d",
"[",
"'name'",
"]",
"if",
"'state'",
"in",
"d",
":",
"if",
"isinstance",
"(",
"d",
"[",
"'state'",
"]",
",",
"str",
")",
"or",
"isinstance",
"(",
"d",
"[",
"'state'",
"]",
",",
"unicode",
")",
":",
"if",
"d",
"[",
"'state'",
"]",
"in",
"states",
".",
"_pipeline_state_values",
".",
"keys",
"(",
")",
":",
"self",
".",
"_state",
"=",
"d",
"[",
"'state'",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"obj",
"=",
"self",
".",
"_uid",
",",
"attribute",
"=",
"'state'",
",",
"expected_value",
"=",
"states",
".",
"_pipeline_state_values",
".",
"keys",
"(",
")",
",",
"actual_value",
"=",
"d",
"[",
"'state'",
"]",
")",
"else",
":",
"raise",
"TypeError",
"(",
"entity",
"=",
"'state'",
",",
"expected_type",
"=",
"str",
",",
"actual_type",
"=",
"type",
"(",
"d",
"[",
"'state'",
"]",
")",
")",
"else",
":",
"self",
".",
"_state",
"=",
"states",
".",
"INITIAL",
"if",
"'state_history'",
"in",
"d",
":",
"if",
"isinstance",
"(",
"d",
"[",
"'state_history'",
"]",
",",
"list",
")",
":",
"self",
".",
"_state_history",
"=",
"d",
"[",
"'state_history'",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"entity",
"=",
"'state_history'",
",",
"expected_type",
"=",
"list",
",",
"actual_type",
"=",
"type",
"(",
"d",
"[",
"'state_history'",
"]",
")",
")",
"if",
"'completed'",
"in",
"d",
":",
"if",
"isinstance",
"(",
"d",
"[",
"'completed'",
"]",
",",
"bool",
")",
":",
"if",
"d",
"[",
"'completed'",
"]",
":",
"self",
".",
"_completed_flag",
".",
"set",
"(",
")",
"else",
":",
"raise",
"TypeError",
"(",
"entity",
"=",
"'completed'",
",",
"expected_type",
"=",
"bool",
",",
"actual_type",
"=",
"type",
"(",
"d",
"[",
"'completed'",
"]",
")",
")"
] |
Create a Pipeline from a dictionary. The change is in inplace.
:argument: python dictionary
:return: None
|
[
"Create",
"a",
"Pipeline",
"from",
"a",
"dictionary",
".",
"The",
"change",
"is",
"in",
"inplace",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L233-L278
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline._increment_stage
|
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 Exception, ex:
raise EnTKError(text=ex)
|
python
|
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 Exception, ex:
raise EnTKError(text=ex)
|
[
"def",
"_increment_stage",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_cur_stage",
"<",
"self",
".",
"_stage_count",
":",
"self",
".",
"_cur_stage",
"+=",
"1",
"else",
":",
"self",
".",
"_completed_flag",
".",
"set",
"(",
")",
"except",
"Exception",
",",
"ex",
":",
"raise",
"EnTKError",
"(",
"text",
"=",
"ex",
")"
] |
Purpose: Increment stage pointer. Also check if Pipeline has completed.
|
[
"Purpose",
":",
"Increment",
"stage",
"pointer",
".",
"Also",
"check",
"if",
"Pipeline",
"has",
"completed",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L300-L313
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline._decrement_stage
|
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 EnTKError(text=ex)
|
python
|
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 EnTKError(text=ex)
|
[
"def",
"_decrement_stage",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_cur_stage",
">",
"0",
":",
"self",
".",
"_cur_stage",
"-=",
"1",
"self",
".",
"_completed_flag",
"=",
"threading",
".",
"Event",
"(",
")",
"# reset",
"except",
"Exception",
",",
"ex",
":",
"raise",
"EnTKError",
"(",
"text",
"=",
"ex",
")"
] |
Purpose: Decrement stage pointer. Reset completed flag.
|
[
"Purpose",
":",
"Decrement",
"stage",
"pointer",
".",
"Reset",
"completed",
"flag",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L315-L327
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline._validate_entities
|
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, list):
stages = [stages]
for value in stages:
if not isinstance(value, Stage):
raise TypeError(expected_type=Stage, actual_type=type(value))
return stages
|
python
|
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, list):
stages = [stages]
for value in stages:
if not isinstance(value, Stage):
raise TypeError(expected_type=Stage, actual_type=type(value))
return stages
|
[
"def",
"_validate_entities",
"(",
"self",
",",
"stages",
")",
":",
"if",
"not",
"stages",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"Stage",
",",
"actual_type",
"=",
"type",
"(",
"stages",
")",
")",
"if",
"not",
"isinstance",
"(",
"stages",
",",
"list",
")",
":",
"stages",
"=",
"[",
"stages",
"]",
"for",
"value",
"in",
"stages",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Stage",
")",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"Stage",
",",
"actual_type",
"=",
"type",
"(",
"value",
")",
")",
"return",
"stages"
] |
Purpose: Validate whether the argument 'stages' is of list of Stage objects
:argument: list of Stage objects
|
[
"Purpose",
":",
"Validate",
"whether",
"the",
"argument",
"stages",
"is",
"of",
"list",
"of",
"Stage",
"objects"
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L330-L346
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline._assign_uid
|
def _assign_uid(self, sid):
"""
Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of
current object
"""
self._uid = ru.generate_id(
'pipeline.%(item_counter)04d', ru.ID_CUSTOM, namespace=sid)
for stage in self._stages:
stage._assign_uid(sid)
self._pass_uid()
|
python
|
def _assign_uid(self, sid):
"""
Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of
current object
"""
self._uid = ru.generate_id(
'pipeline.%(item_counter)04d', ru.ID_CUSTOM, namespace=sid)
for stage in self._stages:
stage._assign_uid(sid)
self._pass_uid()
|
[
"def",
"_assign_uid",
"(",
"self",
",",
"sid",
")",
":",
"self",
".",
"_uid",
"=",
"ru",
".",
"generate_id",
"(",
"'pipeline.%(item_counter)04d'",
",",
"ru",
".",
"ID_CUSTOM",
",",
"namespace",
"=",
"sid",
")",
"for",
"stage",
"in",
"self",
".",
"_stages",
":",
"stage",
".",
"_assign_uid",
"(",
"sid",
")",
"self",
".",
"_pass_uid",
"(",
")"
] |
Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of
current object
|
[
"Purpose",
":",
"Assign",
"a",
"uid",
"to",
"the",
"current",
"object",
"based",
"on",
"the",
"sid",
"passed",
".",
"Pass",
"the",
"current",
"uid",
"to",
"children",
"of",
"current",
"object"
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L369-L379
|
train
|
radical-cybertools/radical.entk
|
src/radical/entk/pipeline/pipeline.py
|
Pipeline._pass_uid
|
def _pass_uid(self):
"""
Purpose: Pass current Pipeline's uid to all Stages.
:argument: List of Stage objects (optional)
"""
for stage in self._stages:
stage.parent_pipeline['uid'] = self._uid
stage.parent_pipeline['name'] = self._name
stage._pass_uid()
|
python
|
def _pass_uid(self):
"""
Purpose: Pass current Pipeline's uid to all Stages.
:argument: List of Stage objects (optional)
"""
for stage in self._stages:
stage.parent_pipeline['uid'] = self._uid
stage.parent_pipeline['name'] = self._name
stage._pass_uid()
|
[
"def",
"_pass_uid",
"(",
"self",
")",
":",
"for",
"stage",
"in",
"self",
".",
"_stages",
":",
"stage",
".",
"parent_pipeline",
"[",
"'uid'",
"]",
"=",
"self",
".",
"_uid",
"stage",
".",
"parent_pipeline",
"[",
"'name'",
"]",
"=",
"self",
".",
"_name",
"stage",
".",
"_pass_uid",
"(",
")"
] |
Purpose: Pass current Pipeline's uid to all Stages.
:argument: List of Stage objects (optional)
|
[
"Purpose",
":",
"Pass",
"current",
"Pipeline",
"s",
"uid",
"to",
"all",
"Stages",
"."
] |
945f6c93c9a62db90ad191b306418d5c1cdd9d24
|
https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L381-L391
|
train
|
xym-tool/xym
|
xym/xym.py
|
hexdump
|
def hexdump(src, length=16, sep='.'):
"""
Hexdump function by sbz and 7h3rAm on Github:
(https://gist.github.com/7h3rAm/5603718).
:param src: Source, the string to be shown in hexadecimal format
:param length: Number of hex characters to print in one row
:param sep: Unprintable characters representation
:return:
"""
filtr = ''.join([(len(repr(chr(x))) == 3) and chr(x) or sep for x in range(256)])
lines = []
for c in xrange(0, len(src), length):
chars = src[c:c+length]
hexstring = ' '.join(["%02x" % ord(x) for x in chars])
if len(hexstring) > 24:
hexstring = "%s %s" % (hexstring[:24], hexstring[24:])
printable = ''.join(["%s" % ((ord(x) <= 127 and filtr[ord(x)]) or sep) for x in chars])
lines.append(" %02x: %-*s |%s|\n" % (c, length*3, hexstring, printable))
print(''.join(lines))
|
python
|
def hexdump(src, length=16, sep='.'):
"""
Hexdump function by sbz and 7h3rAm on Github:
(https://gist.github.com/7h3rAm/5603718).
:param src: Source, the string to be shown in hexadecimal format
:param length: Number of hex characters to print in one row
:param sep: Unprintable characters representation
:return:
"""
filtr = ''.join([(len(repr(chr(x))) == 3) and chr(x) or sep for x in range(256)])
lines = []
for c in xrange(0, len(src), length):
chars = src[c:c+length]
hexstring = ' '.join(["%02x" % ord(x) for x in chars])
if len(hexstring) > 24:
hexstring = "%s %s" % (hexstring[:24], hexstring[24:])
printable = ''.join(["%s" % ((ord(x) <= 127 and filtr[ord(x)]) or sep) for x in chars])
lines.append(" %02x: %-*s |%s|\n" % (c, length*3, hexstring, printable))
print(''.join(lines))
|
[
"def",
"hexdump",
"(",
"src",
",",
"length",
"=",
"16",
",",
"sep",
"=",
"'.'",
")",
":",
"filtr",
"=",
"''",
".",
"join",
"(",
"[",
"(",
"len",
"(",
"repr",
"(",
"chr",
"(",
"x",
")",
")",
")",
"==",
"3",
")",
"and",
"chr",
"(",
"x",
")",
"or",
"sep",
"for",
"x",
"in",
"range",
"(",
"256",
")",
"]",
")",
"lines",
"=",
"[",
"]",
"for",
"c",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"src",
")",
",",
"length",
")",
":",
"chars",
"=",
"src",
"[",
"c",
":",
"c",
"+",
"length",
"]",
"hexstring",
"=",
"' '",
".",
"join",
"(",
"[",
"\"%02x\"",
"%",
"ord",
"(",
"x",
")",
"for",
"x",
"in",
"chars",
"]",
")",
"if",
"len",
"(",
"hexstring",
")",
">",
"24",
":",
"hexstring",
"=",
"\"%s %s\"",
"%",
"(",
"hexstring",
"[",
":",
"24",
"]",
",",
"hexstring",
"[",
"24",
":",
"]",
")",
"printable",
"=",
"''",
".",
"join",
"(",
"[",
"\"%s\"",
"%",
"(",
"(",
"ord",
"(",
"x",
")",
"<=",
"127",
"and",
"filtr",
"[",
"ord",
"(",
"x",
")",
"]",
")",
"or",
"sep",
")",
"for",
"x",
"in",
"chars",
"]",
")",
"lines",
".",
"append",
"(",
"\" %02x: %-*s |%s|\\n\"",
"%",
"(",
"c",
",",
"length",
"*",
"3",
",",
"hexstring",
",",
"printable",
")",
")",
"print",
"(",
"''",
".",
"join",
"(",
"lines",
")",
")"
] |
Hexdump function by sbz and 7h3rAm on Github:
(https://gist.github.com/7h3rAm/5603718).
:param src: Source, the string to be shown in hexadecimal format
:param length: Number of hex characters to print in one row
:param sep: Unprintable characters representation
:return:
|
[
"Hexdump",
"function",
"by",
"sbz",
"and",
"7h3rAm",
"on",
"Github",
":",
"(",
"https",
":",
"//",
"gist",
".",
"github",
".",
"com",
"/",
"7h3rAm",
"/",
"5603718",
")",
".",
":",
"param",
"src",
":",
"Source",
"the",
"string",
"to",
"be",
"shown",
"in",
"hexadecimal",
"format",
":",
"param",
"length",
":",
"Number",
"of",
"hex",
"characters",
"to",
"print",
"in",
"one",
"row",
":",
"param",
"sep",
":",
"Unprintable",
"characters",
"representation",
":",
"return",
":"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L30-L48
|
train
|
xym-tool/xym
|
xym/xym.py
|
xym
|
def xym(source_id, srcdir, dstdir, strict=False, strict_examples=False, debug_level=0, add_line_refs=False,
force_revision_pyang=False, force_revision_regexp=False):
"""
Extracts YANG model from an IETF RFC or draft text file.
This is the main (external) API entry for the module.
:param add_line_refs:
:param source_id: identifier (file name or URL) of a draft or RFC file containing
one or more YANG models
:param srcdir: If source_id points to a file, the optional parameter identifies
the directory where the file is located
:param dstdir: Directory where to put the extracted YANG models
:param strict: Strict syntax enforcement
:param strict_examples: Only output valid examples when in strict mode
:param debug_level: Determines how much debug output is printed to the console
:param force_revision_regexp: Whether it should create a <filename>@<revision>.yang even on error using regexp
:param force_revision_pyang: Whether it should create a <filename>@<revision>.yang even on error using pyang
:return: None
"""
if force_revision_regexp and force_revision_pyang:
print('Can not use both methods for parsing name and revision - using regular expression method only')
force_revision_pyang = False
url = re.compile(r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
rqst_hdrs = {'Accept': 'text/plain', 'Accept-Charset': 'utf-8'}
ye = YangModuleExtractor(source_id, dstdir, strict, strict_examples, add_line_refs, debug_level)
is_url = url.match(source_id)
if is_url:
r = requests.get(source_id, headers=rqst_hdrs)
if r.status_code == 200:
content = r.text.encode('utf8').splitlines(True)
ye.extract_yang_model(content)
else:
print("Failed to fetch file from URL '%s', error '%d'" % (source_id, r.status_code), file=sys.stderr)
else:
try:
with open(os.path.join(srcdir, source_id)) as sf:
ye.extract_yang_model(sf.readlines())
except IOError as ioe:
print(ioe)
return ye.get_extracted_models(force_revision_pyang, force_revision_regexp)
|
python
|
def xym(source_id, srcdir, dstdir, strict=False, strict_examples=False, debug_level=0, add_line_refs=False,
force_revision_pyang=False, force_revision_regexp=False):
"""
Extracts YANG model from an IETF RFC or draft text file.
This is the main (external) API entry for the module.
:param add_line_refs:
:param source_id: identifier (file name or URL) of a draft or RFC file containing
one or more YANG models
:param srcdir: If source_id points to a file, the optional parameter identifies
the directory where the file is located
:param dstdir: Directory where to put the extracted YANG models
:param strict: Strict syntax enforcement
:param strict_examples: Only output valid examples when in strict mode
:param debug_level: Determines how much debug output is printed to the console
:param force_revision_regexp: Whether it should create a <filename>@<revision>.yang even on error using regexp
:param force_revision_pyang: Whether it should create a <filename>@<revision>.yang even on error using pyang
:return: None
"""
if force_revision_regexp and force_revision_pyang:
print('Can not use both methods for parsing name and revision - using regular expression method only')
force_revision_pyang = False
url = re.compile(r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
rqst_hdrs = {'Accept': 'text/plain', 'Accept-Charset': 'utf-8'}
ye = YangModuleExtractor(source_id, dstdir, strict, strict_examples, add_line_refs, debug_level)
is_url = url.match(source_id)
if is_url:
r = requests.get(source_id, headers=rqst_hdrs)
if r.status_code == 200:
content = r.text.encode('utf8').splitlines(True)
ye.extract_yang_model(content)
else:
print("Failed to fetch file from URL '%s', error '%d'" % (source_id, r.status_code), file=sys.stderr)
else:
try:
with open(os.path.join(srcdir, source_id)) as sf:
ye.extract_yang_model(sf.readlines())
except IOError as ioe:
print(ioe)
return ye.get_extracted_models(force_revision_pyang, force_revision_regexp)
|
[
"def",
"xym",
"(",
"source_id",
",",
"srcdir",
",",
"dstdir",
",",
"strict",
"=",
"False",
",",
"strict_examples",
"=",
"False",
",",
"debug_level",
"=",
"0",
",",
"add_line_refs",
"=",
"False",
",",
"force_revision_pyang",
"=",
"False",
",",
"force_revision_regexp",
"=",
"False",
")",
":",
"if",
"force_revision_regexp",
"and",
"force_revision_pyang",
":",
"print",
"(",
"'Can not use both methods for parsing name and revision - using regular expression method only'",
")",
"force_revision_pyang",
"=",
"False",
"url",
"=",
"re",
".",
"compile",
"(",
"r'^(?:http|ftp)s?://'",
"# http:// or https://",
"r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'",
"# domain",
"r'localhost|'",
"# localhost...",
"r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'",
"# ...or ip",
"r'(?::\\d+)?'",
"# optional port",
"r'(?:/?|[/?]\\S+)$'",
",",
"re",
".",
"IGNORECASE",
")",
"rqst_hdrs",
"=",
"{",
"'Accept'",
":",
"'text/plain'",
",",
"'Accept-Charset'",
":",
"'utf-8'",
"}",
"ye",
"=",
"YangModuleExtractor",
"(",
"source_id",
",",
"dstdir",
",",
"strict",
",",
"strict_examples",
",",
"add_line_refs",
",",
"debug_level",
")",
"is_url",
"=",
"url",
".",
"match",
"(",
"source_id",
")",
"if",
"is_url",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"source_id",
",",
"headers",
"=",
"rqst_hdrs",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"content",
"=",
"r",
".",
"text",
".",
"encode",
"(",
"'utf8'",
")",
".",
"splitlines",
"(",
"True",
")",
"ye",
".",
"extract_yang_model",
"(",
"content",
")",
"else",
":",
"print",
"(",
"\"Failed to fetch file from URL '%s', error '%d'\"",
"%",
"(",
"source_id",
",",
"r",
".",
"status_code",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"else",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"srcdir",
",",
"source_id",
")",
")",
"as",
"sf",
":",
"ye",
".",
"extract_yang_model",
"(",
"sf",
".",
"readlines",
"(",
")",
")",
"except",
"IOError",
"as",
"ioe",
":",
"print",
"(",
"ioe",
")",
"return",
"ye",
".",
"get_extracted_models",
"(",
"force_revision_pyang",
",",
"force_revision_regexp",
")"
] |
Extracts YANG model from an IETF RFC or draft text file.
This is the main (external) API entry for the module.
:param add_line_refs:
:param source_id: identifier (file name or URL) of a draft or RFC file containing
one or more YANG models
:param srcdir: If source_id points to a file, the optional parameter identifies
the directory where the file is located
:param dstdir: Directory where to put the extracted YANG models
:param strict: Strict syntax enforcement
:param strict_examples: Only output valid examples when in strict mode
:param debug_level: Determines how much debug output is printed to the console
:param force_revision_regexp: Whether it should create a <filename>@<revision>.yang even on error using regexp
:param force_revision_pyang: Whether it should create a <filename>@<revision>.yang even on error using pyang
:return: None
|
[
"Extracts",
"YANG",
"model",
"from",
"an",
"IETF",
"RFC",
"or",
"draft",
"text",
"file",
".",
"This",
"is",
"the",
"main",
"(",
"external",
")",
"API",
"entry",
"for",
"the",
"module",
"."
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L527-L574
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.warning
|
def warning(self, s):
"""
Prints out a warning message to stderr.
:param s: The warning string to print
:return: None
"""
print(" WARNING: '%s', %s" % (self.src_id, s), file=sys.stderr)
|
python
|
def warning(self, s):
"""
Prints out a warning message to stderr.
:param s: The warning string to print
:return: None
"""
print(" WARNING: '%s', %s" % (self.src_id, s), file=sys.stderr)
|
[
"def",
"warning",
"(",
"self",
",",
"s",
")",
":",
"print",
"(",
"\" WARNING: '%s', %s\"",
"%",
"(",
"self",
".",
"src_id",
",",
"s",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] |
Prints out a warning message to stderr.
:param s: The warning string to print
:return: None
|
[
"Prints",
"out",
"a",
"warning",
"message",
"to",
"stderr",
".",
":",
"param",
"s",
":",
"The",
"warning",
"string",
"to",
"print",
":",
"return",
":",
"None"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L95-L101
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.error
|
def error(self, s):
"""
Prints out an error message to stderr.
:param s: The error string to print
:return: None
"""
print(" ERROR: '%s', %s" % (self.src_id, s), file=sys.stderr)
|
python
|
def error(self, s):
"""
Prints out an error message to stderr.
:param s: The error string to print
:return: None
"""
print(" ERROR: '%s', %s" % (self.src_id, s), file=sys.stderr)
|
[
"def",
"error",
"(",
"self",
",",
"s",
")",
":",
"print",
"(",
"\" ERROR: '%s', %s\"",
"%",
"(",
"self",
".",
"src_id",
",",
"s",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] |
Prints out an error message to stderr.
:param s: The error string to print
:return: None
|
[
"Prints",
"out",
"an",
"error",
"message",
"to",
"stderr",
".",
":",
"param",
"s",
":",
"The",
"error",
"string",
"to",
"print",
":",
"return",
":",
"None"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L103-L109
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.remove_leading_spaces
|
def remove_leading_spaces(self, input_model):
"""
This function is a part of the model post-processing pipeline. It
removes leading spaces from an extracted module; depending on the
formatting of the draft/rfc text, may have multiple spaces prepended
to each line. The function also determines the length of the longest
line in the module - this value can be used by later stages of the
model post-processing pipeline.
:param input_model: The YANG model to be processed
:return: YANG model lines with leading spaces removed
"""
leading_spaces = 1024
output_model = []
for mline in input_model:
line = mline[0]
if line.rstrip(' \r\n') != '':
leading_spaces = min(leading_spaces, len(line) - len(line.lstrip(' ')))
output_model.append([line[leading_spaces:], mline[1]])
line_len = len(line[leading_spaces:])
if line_len > self.max_line_len:
self.max_line_len = line_len
else:
output_model.append(['\n', mline[1]])
return output_model
|
python
|
def remove_leading_spaces(self, input_model):
"""
This function is a part of the model post-processing pipeline. It
removes leading spaces from an extracted module; depending on the
formatting of the draft/rfc text, may have multiple spaces prepended
to each line. The function also determines the length of the longest
line in the module - this value can be used by later stages of the
model post-processing pipeline.
:param input_model: The YANG model to be processed
:return: YANG model lines with leading spaces removed
"""
leading_spaces = 1024
output_model = []
for mline in input_model:
line = mline[0]
if line.rstrip(' \r\n') != '':
leading_spaces = min(leading_spaces, len(line) - len(line.lstrip(' ')))
output_model.append([line[leading_spaces:], mline[1]])
line_len = len(line[leading_spaces:])
if line_len > self.max_line_len:
self.max_line_len = line_len
else:
output_model.append(['\n', mline[1]])
return output_model
|
[
"def",
"remove_leading_spaces",
"(",
"self",
",",
"input_model",
")",
":",
"leading_spaces",
"=",
"1024",
"output_model",
"=",
"[",
"]",
"for",
"mline",
"in",
"input_model",
":",
"line",
"=",
"mline",
"[",
"0",
"]",
"if",
"line",
".",
"rstrip",
"(",
"' \\r\\n'",
")",
"!=",
"''",
":",
"leading_spaces",
"=",
"min",
"(",
"leading_spaces",
",",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
"' '",
")",
")",
")",
"output_model",
".",
"append",
"(",
"[",
"line",
"[",
"leading_spaces",
":",
"]",
",",
"mline",
"[",
"1",
"]",
"]",
")",
"line_len",
"=",
"len",
"(",
"line",
"[",
"leading_spaces",
":",
"]",
")",
"if",
"line_len",
">",
"self",
".",
"max_line_len",
":",
"self",
".",
"max_line_len",
"=",
"line_len",
"else",
":",
"output_model",
".",
"append",
"(",
"[",
"'\\n'",
",",
"mline",
"[",
"1",
"]",
"]",
")",
"return",
"output_model"
] |
This function is a part of the model post-processing pipeline. It
removes leading spaces from an extracted module; depending on the
formatting of the draft/rfc text, may have multiple spaces prepended
to each line. The function also determines the length of the longest
line in the module - this value can be used by later stages of the
model post-processing pipeline.
:param input_model: The YANG model to be processed
:return: YANG model lines with leading spaces removed
|
[
"This",
"function",
"is",
"a",
"part",
"of",
"the",
"model",
"post",
"-",
"processing",
"pipeline",
".",
"It",
"removes",
"leading",
"spaces",
"from",
"an",
"extracted",
"module",
";",
"depending",
"on",
"the",
"formatting",
"of",
"the",
"draft",
"/",
"rfc",
"text",
"may",
"have",
"multiple",
"spaces",
"prepended",
"to",
"each",
"line",
".",
"The",
"function",
"also",
"determines",
"the",
"length",
"of",
"the",
"longest",
"line",
"in",
"the",
"module",
"-",
"this",
"value",
"can",
"be",
"used",
"by",
"later",
"stages",
"of",
"the",
"model",
"post",
"-",
"processing",
"pipeline",
".",
":",
"param",
"input_model",
":",
"The",
"YANG",
"model",
"to",
"be",
"processed",
":",
"return",
":",
"YANG",
"model",
"lines",
"with",
"leading",
"spaces",
"removed"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L211-L235
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.add_line_references
|
def add_line_references(self, input_model):
"""
This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG model to be processed
:return: Modified YANG model, where line numbers from the RFC/Draft
text file are added as comments at the end of each line in
the modified model
"""
output_model = []
for ln in input_model:
line_len = len(ln[0])
line_ref = ('// %4d' % ln[1]).rjust((self.max_line_len - line_len + 7), ' ')
new_line = '%s %s\n' % (ln[0].rstrip(' \r\n\t\f'), line_ref)
output_model.append([new_line, ln[1]])
return output_model
|
python
|
def add_line_references(self, input_model):
"""
This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG model to be processed
:return: Modified YANG model, where line numbers from the RFC/Draft
text file are added as comments at the end of each line in
the modified model
"""
output_model = []
for ln in input_model:
line_len = len(ln[0])
line_ref = ('// %4d' % ln[1]).rjust((self.max_line_len - line_len + 7), ' ')
new_line = '%s %s\n' % (ln[0].rstrip(' \r\n\t\f'), line_ref)
output_model.append([new_line, ln[1]])
return output_model
|
[
"def",
"add_line_references",
"(",
"self",
",",
"input_model",
")",
":",
"output_model",
"=",
"[",
"]",
"for",
"ln",
"in",
"input_model",
":",
"line_len",
"=",
"len",
"(",
"ln",
"[",
"0",
"]",
")",
"line_ref",
"=",
"(",
"'// %4d'",
"%",
"ln",
"[",
"1",
"]",
")",
".",
"rjust",
"(",
"(",
"self",
".",
"max_line_len",
"-",
"line_len",
"+",
"7",
")",
",",
"' '",
")",
"new_line",
"=",
"'%s %s\\n'",
"%",
"(",
"ln",
"[",
"0",
"]",
".",
"rstrip",
"(",
"' \\r\\n\\t\\f'",
")",
",",
"line_ref",
")",
"output_model",
".",
"append",
"(",
"[",
"new_line",
",",
"ln",
"[",
"1",
"]",
"]",
")",
"return",
"output_model"
] |
This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG model to be processed
:return: Modified YANG model, where line numbers from the RFC/Draft
text file are added as comments at the end of each line in
the modified model
|
[
"This",
"function",
"is",
"a",
"part",
"of",
"the",
"model",
"post",
"-",
"processing",
"pipeline",
".",
"For",
"each",
"line",
"in",
"the",
"module",
"it",
"adds",
"a",
"reference",
"to",
"the",
"line",
"number",
"in",
"the",
"original",
"draft",
"/",
"RFC",
"from",
"where",
"the",
"module",
"line",
"was",
"extracted",
".",
":",
"param",
"input_model",
":",
"The",
"YANG",
"model",
"to",
"be",
"processed",
":",
"return",
":",
"Modified",
"YANG",
"model",
"where",
"line",
"numbers",
"from",
"the",
"RFC",
"/",
"Draft",
"text",
"file",
"are",
"added",
"as",
"comments",
"at",
"the",
"end",
"of",
"each",
"line",
"in",
"the",
"modified",
"model"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L237-L253
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.remove_extra_empty_lines
|
def remove_extra_empty_lines(self, input_model):
"""
Removes superfluous newlines from a YANG model that was extracted
from a draft or RFC text. Newlines are removed whenever 2 or more
consecutive empty lines are found in the model. This function is a
part of the model post-processing pipeline.
:param input_model: The YANG model to be processed
:return: YANG model with superfluous newlines removed
"""
ncnt = 0
output_model = []
for ln in input_model:
if ln[0].strip(' \n\r') is '':
if ncnt is 0:
output_model.append(ln)
elif self.debug_level > 1:
self.debug_print_strip_msg(ln[1] - 1, ln[0])
ncnt += 1
else:
output_model.append(ln)
ncnt = 0
if self.debug_level > 0:
print(' Removed %d empty lines' % (len(input_model) - len(output_model)))
return output_model
|
python
|
def remove_extra_empty_lines(self, input_model):
"""
Removes superfluous newlines from a YANG model that was extracted
from a draft or RFC text. Newlines are removed whenever 2 or more
consecutive empty lines are found in the model. This function is a
part of the model post-processing pipeline.
:param input_model: The YANG model to be processed
:return: YANG model with superfluous newlines removed
"""
ncnt = 0
output_model = []
for ln in input_model:
if ln[0].strip(' \n\r') is '':
if ncnt is 0:
output_model.append(ln)
elif self.debug_level > 1:
self.debug_print_strip_msg(ln[1] - 1, ln[0])
ncnt += 1
else:
output_model.append(ln)
ncnt = 0
if self.debug_level > 0:
print(' Removed %d empty lines' % (len(input_model) - len(output_model)))
return output_model
|
[
"def",
"remove_extra_empty_lines",
"(",
"self",
",",
"input_model",
")",
":",
"ncnt",
"=",
"0",
"output_model",
"=",
"[",
"]",
"for",
"ln",
"in",
"input_model",
":",
"if",
"ln",
"[",
"0",
"]",
".",
"strip",
"(",
"' \\n\\r'",
")",
"is",
"''",
":",
"if",
"ncnt",
"is",
"0",
":",
"output_model",
".",
"append",
"(",
"ln",
")",
"elif",
"self",
".",
"debug_level",
">",
"1",
":",
"self",
".",
"debug_print_strip_msg",
"(",
"ln",
"[",
"1",
"]",
"-",
"1",
",",
"ln",
"[",
"0",
"]",
")",
"ncnt",
"+=",
"1",
"else",
":",
"output_model",
".",
"append",
"(",
"ln",
")",
"ncnt",
"=",
"0",
"if",
"self",
".",
"debug_level",
">",
"0",
":",
"print",
"(",
"' Removed %d empty lines'",
"%",
"(",
"len",
"(",
"input_model",
")",
"-",
"len",
"(",
"output_model",
")",
")",
")",
"return",
"output_model"
] |
Removes superfluous newlines from a YANG model that was extracted
from a draft or RFC text. Newlines are removed whenever 2 or more
consecutive empty lines are found in the model. This function is a
part of the model post-processing pipeline.
:param input_model: The YANG model to be processed
:return: YANG model with superfluous newlines removed
|
[
"Removes",
"superfluous",
"newlines",
"from",
"a",
"YANG",
"model",
"that",
"was",
"extracted",
"from",
"a",
"draft",
"or",
"RFC",
"text",
".",
"Newlines",
"are",
"removed",
"whenever",
"2",
"or",
"more",
"consecutive",
"empty",
"lines",
"are",
"found",
"in",
"the",
"model",
".",
"This",
"function",
"is",
"a",
"part",
"of",
"the",
"model",
"post",
"-",
"processing",
"pipeline",
".",
":",
"param",
"input_model",
":",
"The",
"YANG",
"model",
"to",
"be",
"processed",
":",
"return",
":",
"YANG",
"model",
"with",
"superfluous",
"newlines",
"removed"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L255-L278
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.post_process_model
|
def post_process_model(self, input_model, add_line_refs):
"""
This function defines the order and execution logic for actions
that are performed in the model post-processing pipeline.
:param input_model: The YANG model to be processed in the pipeline
:param add_line_refs: Flag that controls whether line number
references should be added to the model.
:return: List of strings that constitute the final YANG model to
be written to its module file.
"""
intermediate_model = self.remove_leading_spaces(input_model)
intermediate_model = self.remove_extra_empty_lines(intermediate_model)
if add_line_refs:
intermediate_model = self.add_line_references(intermediate_model)
return finalize_model(intermediate_model)
|
python
|
def post_process_model(self, input_model, add_line_refs):
"""
This function defines the order and execution logic for actions
that are performed in the model post-processing pipeline.
:param input_model: The YANG model to be processed in the pipeline
:param add_line_refs: Flag that controls whether line number
references should be added to the model.
:return: List of strings that constitute the final YANG model to
be written to its module file.
"""
intermediate_model = self.remove_leading_spaces(input_model)
intermediate_model = self.remove_extra_empty_lines(intermediate_model)
if add_line_refs:
intermediate_model = self.add_line_references(intermediate_model)
return finalize_model(intermediate_model)
|
[
"def",
"post_process_model",
"(",
"self",
",",
"input_model",
",",
"add_line_refs",
")",
":",
"intermediate_model",
"=",
"self",
".",
"remove_leading_spaces",
"(",
"input_model",
")",
"intermediate_model",
"=",
"self",
".",
"remove_extra_empty_lines",
"(",
"intermediate_model",
")",
"if",
"add_line_refs",
":",
"intermediate_model",
"=",
"self",
".",
"add_line_references",
"(",
"intermediate_model",
")",
"return",
"finalize_model",
"(",
"intermediate_model",
")"
] |
This function defines the order and execution logic for actions
that are performed in the model post-processing pipeline.
:param input_model: The YANG model to be processed in the pipeline
:param add_line_refs: Flag that controls whether line number
references should be added to the model.
:return: List of strings that constitute the final YANG model to
be written to its module file.
|
[
"This",
"function",
"defines",
"the",
"order",
"and",
"execution",
"logic",
"for",
"actions",
"that",
"are",
"performed",
"in",
"the",
"model",
"post",
"-",
"processing",
"pipeline",
".",
":",
"param",
"input_model",
":",
"The",
"YANG",
"model",
"to",
"be",
"processed",
"in",
"the",
"pipeline",
":",
"param",
"add_line_refs",
":",
"Flag",
"that",
"controls",
"whether",
"line",
"number",
"references",
"should",
"be",
"added",
"to",
"the",
"model",
".",
":",
"return",
":",
"List",
"of",
"strings",
"that",
"constitute",
"the",
"final",
"YANG",
"model",
"to",
"be",
"written",
"to",
"its",
"module",
"file",
"."
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L280-L294
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.write_model_to_file
|
def write_model_to_file(self, mdl, fn):
"""
Write a YANG model that was extracted from a source identifier
(URL or source .txt file) to a .yang destination file
:param mdl: YANG model, as a list of lines
:param fn: Name of the YANG model file
:return:
"""
# Write the model to file
output = ''.join(self.post_process_model(mdl, self.add_line_refs))
if fn:
fqfn = self.dst_dir + '/' + fn
if os.path.isfile(fqfn):
self.error("File '%s' exists" % fqfn)
return
with open(fqfn, 'w') as of:
of.write(output)
of.close()
self.extracted_models.append(fn)
else:
self.error("Output file name can not be determined; YANG file not created")
|
python
|
def write_model_to_file(self, mdl, fn):
"""
Write a YANG model that was extracted from a source identifier
(URL or source .txt file) to a .yang destination file
:param mdl: YANG model, as a list of lines
:param fn: Name of the YANG model file
:return:
"""
# Write the model to file
output = ''.join(self.post_process_model(mdl, self.add_line_refs))
if fn:
fqfn = self.dst_dir + '/' + fn
if os.path.isfile(fqfn):
self.error("File '%s' exists" % fqfn)
return
with open(fqfn, 'w') as of:
of.write(output)
of.close()
self.extracted_models.append(fn)
else:
self.error("Output file name can not be determined; YANG file not created")
|
[
"def",
"write_model_to_file",
"(",
"self",
",",
"mdl",
",",
"fn",
")",
":",
"# Write the model to file",
"output",
"=",
"''",
".",
"join",
"(",
"self",
".",
"post_process_model",
"(",
"mdl",
",",
"self",
".",
"add_line_refs",
")",
")",
"if",
"fn",
":",
"fqfn",
"=",
"self",
".",
"dst_dir",
"+",
"'/'",
"+",
"fn",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fqfn",
")",
":",
"self",
".",
"error",
"(",
"\"File '%s' exists\"",
"%",
"fqfn",
")",
"return",
"with",
"open",
"(",
"fqfn",
",",
"'w'",
")",
"as",
"of",
":",
"of",
".",
"write",
"(",
"output",
")",
"of",
".",
"close",
"(",
")",
"self",
".",
"extracted_models",
".",
"append",
"(",
"fn",
")",
"else",
":",
"self",
".",
"error",
"(",
"\"Output file name can not be determined; YANG file not created\"",
")"
] |
Write a YANG model that was extracted from a source identifier
(URL or source .txt file) to a .yang destination file
:param mdl: YANG model, as a list of lines
:param fn: Name of the YANG model file
:return:
|
[
"Write",
"a",
"YANG",
"model",
"that",
"was",
"extracted",
"from",
"a",
"source",
"identifier",
"(",
"URL",
"or",
"source",
".",
"txt",
"file",
")",
"to",
"a",
".",
"yang",
"destination",
"file",
":",
"param",
"mdl",
":",
"YANG",
"model",
"as",
"a",
"list",
"of",
"lines",
":",
"param",
"fn",
":",
"Name",
"of",
"the",
"YANG",
"model",
"file",
":",
"return",
":"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L296-L316
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.debug_print_line
|
def debug_print_line(self, i, level, line):
"""
Debug print of the currently parsed line
:param i: The line number of the line that is being currently parsed
:param level: Parser level
:param line: the line that is currently being parsed
:return: None
"""
if self.debug_level == 2:
print("Line %d (%d): '%s'" % (i + 1, level, line.rstrip(' \r\n\t\f')))
if self.debug_level > 2:
print("Line %d (%d):" % (i + 1, level))
hexdump(line)
|
python
|
def debug_print_line(self, i, level, line):
"""
Debug print of the currently parsed line
:param i: The line number of the line that is being currently parsed
:param level: Parser level
:param line: the line that is currently being parsed
:return: None
"""
if self.debug_level == 2:
print("Line %d (%d): '%s'" % (i + 1, level, line.rstrip(' \r\n\t\f')))
if self.debug_level > 2:
print("Line %d (%d):" % (i + 1, level))
hexdump(line)
|
[
"def",
"debug_print_line",
"(",
"self",
",",
"i",
",",
"level",
",",
"line",
")",
":",
"if",
"self",
".",
"debug_level",
"==",
"2",
":",
"print",
"(",
"\"Line %d (%d): '%s'\"",
"%",
"(",
"i",
"+",
"1",
",",
"level",
",",
"line",
".",
"rstrip",
"(",
"' \\r\\n\\t\\f'",
")",
")",
")",
"if",
"self",
".",
"debug_level",
">",
"2",
":",
"print",
"(",
"\"Line %d (%d):\"",
"%",
"(",
"i",
"+",
"1",
",",
"level",
")",
")",
"hexdump",
"(",
"line",
")"
] |
Debug print of the currently parsed line
:param i: The line number of the line that is being currently parsed
:param level: Parser level
:param line: the line that is currently being parsed
:return: None
|
[
"Debug",
"print",
"of",
"the",
"currently",
"parsed",
"line",
":",
"param",
"i",
":",
"The",
"line",
"number",
"of",
"the",
"line",
"that",
"is",
"being",
"currently",
"parsed",
":",
"param",
"level",
":",
"Parser",
"level",
":",
"param",
"line",
":",
"the",
"line",
"that",
"is",
"currently",
"being",
"parsed",
":",
"return",
":",
"None"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L318-L330
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.debug_print_strip_msg
|
def debug_print_strip_msg(self, i, line):
"""
Debug print indicating that an empty line is being skipped
:param i: The line number of the line that is being currently parsed
:param line: the parsed line
:return: None
"""
if self.debug_level == 2:
print(" Stripping Line %d: '%s'" % (i + 1, line.rstrip(' \r\n\t\f')))
elif self.debug_level > 2:
print(" Stripping Line %d:" % (i + 1))
hexdump(line)
|
python
|
def debug_print_strip_msg(self, i, line):
"""
Debug print indicating that an empty line is being skipped
:param i: The line number of the line that is being currently parsed
:param line: the parsed line
:return: None
"""
if self.debug_level == 2:
print(" Stripping Line %d: '%s'" % (i + 1, line.rstrip(' \r\n\t\f')))
elif self.debug_level > 2:
print(" Stripping Line %d:" % (i + 1))
hexdump(line)
|
[
"def",
"debug_print_strip_msg",
"(",
"self",
",",
"i",
",",
"line",
")",
":",
"if",
"self",
".",
"debug_level",
"==",
"2",
":",
"print",
"(",
"\" Stripping Line %d: '%s'\"",
"%",
"(",
"i",
"+",
"1",
",",
"line",
".",
"rstrip",
"(",
"' \\r\\n\\t\\f'",
")",
")",
")",
"elif",
"self",
".",
"debug_level",
">",
"2",
":",
"print",
"(",
"\" Stripping Line %d:\"",
"%",
"(",
"i",
"+",
"1",
")",
")",
"hexdump",
"(",
"line",
")"
] |
Debug print indicating that an empty line is being skipped
:param i: The line number of the line that is being currently parsed
:param line: the parsed line
:return: None
|
[
"Debug",
"print",
"indicating",
"that",
"an",
"empty",
"line",
"is",
"being",
"skipped",
":",
"param",
"i",
":",
"The",
"line",
"number",
"of",
"the",
"line",
"that",
"is",
"being",
"currently",
"parsed",
":",
"param",
"line",
":",
"the",
"parsed",
"line",
":",
"return",
":",
"None"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L332-L343
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.strip_empty_lines_forward
|
def strip_empty_lines_forward(self, content, i):
"""
Skip over empty lines
:param content: parsed text
:param i: current parsed line
:return: number of skipped lined
"""
while i < len(content):
line = content[i].strip(' \r\n\t\f')
if line != '':
break
self.debug_print_strip_msg(i, content[i])
i += 1 # Strip an empty line
return i
|
python
|
def strip_empty_lines_forward(self, content, i):
"""
Skip over empty lines
:param content: parsed text
:param i: current parsed line
:return: number of skipped lined
"""
while i < len(content):
line = content[i].strip(' \r\n\t\f')
if line != '':
break
self.debug_print_strip_msg(i, content[i])
i += 1 # Strip an empty line
return i
|
[
"def",
"strip_empty_lines_forward",
"(",
"self",
",",
"content",
",",
"i",
")",
":",
"while",
"i",
"<",
"len",
"(",
"content",
")",
":",
"line",
"=",
"content",
"[",
"i",
"]",
".",
"strip",
"(",
"' \\r\\n\\t\\f'",
")",
"if",
"line",
"!=",
"''",
":",
"break",
"self",
".",
"debug_print_strip_msg",
"(",
"i",
",",
"content",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"# Strip an empty line",
"return",
"i"
] |
Skip over empty lines
:param content: parsed text
:param i: current parsed line
:return: number of skipped lined
|
[
"Skip",
"over",
"empty",
"lines",
":",
"param",
"content",
":",
"parsed",
"text",
":",
"param",
"i",
":",
"current",
"parsed",
"line",
":",
"return",
":",
"number",
"of",
"skipped",
"lined"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L345-L358
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.strip_empty_lines_backward
|
def strip_empty_lines_backward(self, model, max_lines_to_strip):
"""
Strips empty lines preceding the line that is currently being parsed. This
fucntion is called when the parser encounters a Footer.
:param model: lines that were added to the model up to this point
:param line_num: the number of teh line being parsed
:param max_lines_to_strip: max number of lines to strip from the model
:return: None
"""
for l in range(0, max_lines_to_strip):
if model[-1][0].strip(' \r\n\t\f') != '':
return
self.debug_print_strip_msg(model[-1][1] - 1, model[-1][0])
model.pop()
|
python
|
def strip_empty_lines_backward(self, model, max_lines_to_strip):
"""
Strips empty lines preceding the line that is currently being parsed. This
fucntion is called when the parser encounters a Footer.
:param model: lines that were added to the model up to this point
:param line_num: the number of teh line being parsed
:param max_lines_to_strip: max number of lines to strip from the model
:return: None
"""
for l in range(0, max_lines_to_strip):
if model[-1][0].strip(' \r\n\t\f') != '':
return
self.debug_print_strip_msg(model[-1][1] - 1, model[-1][0])
model.pop()
|
[
"def",
"strip_empty_lines_backward",
"(",
"self",
",",
"model",
",",
"max_lines_to_strip",
")",
":",
"for",
"l",
"in",
"range",
"(",
"0",
",",
"max_lines_to_strip",
")",
":",
"if",
"model",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
".",
"strip",
"(",
"' \\r\\n\\t\\f'",
")",
"!=",
"''",
":",
"return",
"self",
".",
"debug_print_strip_msg",
"(",
"model",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"-",
"1",
",",
"model",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
")",
"model",
".",
"pop",
"(",
")"
] |
Strips empty lines preceding the line that is currently being parsed. This
fucntion is called when the parser encounters a Footer.
:param model: lines that were added to the model up to this point
:param line_num: the number of teh line being parsed
:param max_lines_to_strip: max number of lines to strip from the model
:return: None
|
[
"Strips",
"empty",
"lines",
"preceding",
"the",
"line",
"that",
"is",
"currently",
"being",
"parsed",
".",
"This",
"fucntion",
"is",
"called",
"when",
"the",
"parser",
"encounters",
"a",
"Footer",
".",
":",
"param",
"model",
":",
"lines",
"that",
"were",
"added",
"to",
"the",
"model",
"up",
"to",
"this",
"point",
":",
"param",
"line_num",
":",
"the",
"number",
"of",
"teh",
"line",
"being",
"parsed",
":",
"param",
"max_lines_to_strip",
":",
"max",
"number",
"of",
"lines",
"to",
"strip",
"from",
"the",
"model",
":",
"return",
":",
"None"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L360-L373
|
train
|
xym-tool/xym
|
xym/xym.py
|
YangModuleExtractor.extract_yang_model
|
def extract_yang_model(self, content):
"""
Extracts one or more YANG models from an RFC or draft text string in
which the models are specified. The function skips over page
formatting (Page Headers and Footers) and performs basic YANG module
syntax checking. In strict mode, the function also enforces the
<CODE BEGINS> / <CODE ENDS> tags - a model is not extracted unless
the tags are present.
:return: None
"""
model = []
output_file = None
in_model = False
example_match = False
i = 0
level = 0
quotes = 0
while i < len(content):
line = content[i]
# Try to match '<CODE ENDS>'
if self.CODE_ENDS_TAG.match(line):
if in_model is False:
self.warning("Line %d: misplaced <CODE ENDS>" % i)
in_model = False
if "\"" in line:
if line.count("\"") % 2 == 0:
quotes = 0
else:
if quotes == 1:
quotes = 0
else:
quotes = 1
# Try to match '(sub)module <module_name> {'
match = self.MODULE_STATEMENT.match(line)
if match:
# We're already parsing a module
if quotes == 0:
if level > 0:
self.error("Line %d - 'module' statement within another module" % i)
return
# Check if we should enforce <CODE BEGINS> / <CODE ENDS>
# if we do enforce, we ignore models not enclosed in <CODE BEGINS> / <CODE ENDS>
if match.groups()[1] or match.groups()[4]:
self.warning('Line %d - Module name should not be enclosed in quotes' % i)
# do the module name checking, etc.
example_match = self.EXAMPLE_TAG.match(match.groups()[2])
if in_model is True:
if example_match:
self.error("Line %d - YANG module '%s' with <CODE BEGINS> and starting with 'example-'" %
(i, match.groups()[2]))
else:
if not example_match:
self.error("Line %d - YANG module '%s' with no <CODE BEGINS> and not starting with 'example-'" %
(i, match.groups()[2]))
# now decide if we're allowed to set the level
# (i.e. signal that we're in a module) to 1 and if
# we're allowed to output the module at all with the
# strict examples flag
# if self.strict is True:
# if in_model is True:
# level = 1
# else:
# level = 1
# always set the level to 1; we decide whether or not
# to output at the end
if quotes == 0:
level = 1
if not output_file and level == 1 and quotes == 0:
print("\nExtracting '%s'" % match.groups()[2])
output_file = '%s.yang' % match.groups()[2].strip('"\'')
if self.debug_level > 0:
print(' Getting YANG file name from module name: %s' % output_file)
if level > 0:
self.debug_print_line(i, level, content[i])
# Try to match the Footer ('[Page <page_num>]')
# If match found, skip over page headers and footers
if self.PAGE_TAG.match(line):
self.strip_empty_lines_backward(model, 3)
self.debug_print_strip_msg(i, content[i])
i += 1 # Strip the
# Strip empty lines between the Footer and the next page Header
i = self.strip_empty_lines_forward(content, i)
if i < len(content):
self.debug_print_strip_msg(i, content[i])
i += 1 # Strip the next page Header
else:
self.error("<End of File> - EOF encountered while parsing the model")
return
# Strip empty lines between the page Header and real content on the page
i = self.strip_empty_lines_forward(content, i) - 1
if i >= len(content):
self.error("<End of File> - EOF encountered while parsing the model")
return
else:
model.append([line, i + 1])
counter = Counter(line)
if quotes == 0:
if "\"" in line and "}" in line:
if line.index("}") > line.rindex("\"") or line.index("}") < line.index("\""):
level += (counter['{'] - counter['}'])
else:
level += (counter['{'] - counter['}'])
if level == 1:
if self.strict:
if self.strict_examples:
if example_match and not in_model:
self.write_model_to_file(model, output_file)
elif in_model:
self.write_model_to_file(model, output_file)
else:
self.write_model_to_file(model, output_file)
self.max_line_len = 0
model = []
output_file = None
level = 0
# Try to match '<CODE BEGINS>'
match = self.CODE_BEGINS_TAG.match(line)
if match:
# Found the beginning of the YANG module code section; make sure we're not parsing a model already
if level > 0:
self.error("Line %d - <CODE BEGINS> within a model" % i)
return
if in_model is True:
self.error("Line %d - Misplaced <CODE BEGINS> or missing <CODE ENDS>" % i)
in_model = True
mg = match.groups()
# Get the YANG module's file name
if mg[2]:
print("\nExtracting '%s'" % match.groups()[2])
output_file = mg[2].strip()
else:
if mg[0] and mg[1] is None:
self.error('Line %d - Missing file name in <CODE BEGINS>' % i)
else:
self.error("Line %d - YANG file not specified in <CODE BEGINS>" % i)
i += 1
if level > 0:
self.error("<End of File> - EOF encountered while parsing the model")
return
if in_model is True:
self.error("Line %d - Missing <CODE ENDS>" % i)
|
python
|
def extract_yang_model(self, content):
"""
Extracts one or more YANG models from an RFC or draft text string in
which the models are specified. The function skips over page
formatting (Page Headers and Footers) and performs basic YANG module
syntax checking. In strict mode, the function also enforces the
<CODE BEGINS> / <CODE ENDS> tags - a model is not extracted unless
the tags are present.
:return: None
"""
model = []
output_file = None
in_model = False
example_match = False
i = 0
level = 0
quotes = 0
while i < len(content):
line = content[i]
# Try to match '<CODE ENDS>'
if self.CODE_ENDS_TAG.match(line):
if in_model is False:
self.warning("Line %d: misplaced <CODE ENDS>" % i)
in_model = False
if "\"" in line:
if line.count("\"") % 2 == 0:
quotes = 0
else:
if quotes == 1:
quotes = 0
else:
quotes = 1
# Try to match '(sub)module <module_name> {'
match = self.MODULE_STATEMENT.match(line)
if match:
# We're already parsing a module
if quotes == 0:
if level > 0:
self.error("Line %d - 'module' statement within another module" % i)
return
# Check if we should enforce <CODE BEGINS> / <CODE ENDS>
# if we do enforce, we ignore models not enclosed in <CODE BEGINS> / <CODE ENDS>
if match.groups()[1] or match.groups()[4]:
self.warning('Line %d - Module name should not be enclosed in quotes' % i)
# do the module name checking, etc.
example_match = self.EXAMPLE_TAG.match(match.groups()[2])
if in_model is True:
if example_match:
self.error("Line %d - YANG module '%s' with <CODE BEGINS> and starting with 'example-'" %
(i, match.groups()[2]))
else:
if not example_match:
self.error("Line %d - YANG module '%s' with no <CODE BEGINS> and not starting with 'example-'" %
(i, match.groups()[2]))
# now decide if we're allowed to set the level
# (i.e. signal that we're in a module) to 1 and if
# we're allowed to output the module at all with the
# strict examples flag
# if self.strict is True:
# if in_model is True:
# level = 1
# else:
# level = 1
# always set the level to 1; we decide whether or not
# to output at the end
if quotes == 0:
level = 1
if not output_file and level == 1 and quotes == 0:
print("\nExtracting '%s'" % match.groups()[2])
output_file = '%s.yang' % match.groups()[2].strip('"\'')
if self.debug_level > 0:
print(' Getting YANG file name from module name: %s' % output_file)
if level > 0:
self.debug_print_line(i, level, content[i])
# Try to match the Footer ('[Page <page_num>]')
# If match found, skip over page headers and footers
if self.PAGE_TAG.match(line):
self.strip_empty_lines_backward(model, 3)
self.debug_print_strip_msg(i, content[i])
i += 1 # Strip the
# Strip empty lines between the Footer and the next page Header
i = self.strip_empty_lines_forward(content, i)
if i < len(content):
self.debug_print_strip_msg(i, content[i])
i += 1 # Strip the next page Header
else:
self.error("<End of File> - EOF encountered while parsing the model")
return
# Strip empty lines between the page Header and real content on the page
i = self.strip_empty_lines_forward(content, i) - 1
if i >= len(content):
self.error("<End of File> - EOF encountered while parsing the model")
return
else:
model.append([line, i + 1])
counter = Counter(line)
if quotes == 0:
if "\"" in line and "}" in line:
if line.index("}") > line.rindex("\"") or line.index("}") < line.index("\""):
level += (counter['{'] - counter['}'])
else:
level += (counter['{'] - counter['}'])
if level == 1:
if self.strict:
if self.strict_examples:
if example_match and not in_model:
self.write_model_to_file(model, output_file)
elif in_model:
self.write_model_to_file(model, output_file)
else:
self.write_model_to_file(model, output_file)
self.max_line_len = 0
model = []
output_file = None
level = 0
# Try to match '<CODE BEGINS>'
match = self.CODE_BEGINS_TAG.match(line)
if match:
# Found the beginning of the YANG module code section; make sure we're not parsing a model already
if level > 0:
self.error("Line %d - <CODE BEGINS> within a model" % i)
return
if in_model is True:
self.error("Line %d - Misplaced <CODE BEGINS> or missing <CODE ENDS>" % i)
in_model = True
mg = match.groups()
# Get the YANG module's file name
if mg[2]:
print("\nExtracting '%s'" % match.groups()[2])
output_file = mg[2].strip()
else:
if mg[0] and mg[1] is None:
self.error('Line %d - Missing file name in <CODE BEGINS>' % i)
else:
self.error("Line %d - YANG file not specified in <CODE BEGINS>" % i)
i += 1
if level > 0:
self.error("<End of File> - EOF encountered while parsing the model")
return
if in_model is True:
self.error("Line %d - Missing <CODE ENDS>" % i)
|
[
"def",
"extract_yang_model",
"(",
"self",
",",
"content",
")",
":",
"model",
"=",
"[",
"]",
"output_file",
"=",
"None",
"in_model",
"=",
"False",
"example_match",
"=",
"False",
"i",
"=",
"0",
"level",
"=",
"0",
"quotes",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"content",
")",
":",
"line",
"=",
"content",
"[",
"i",
"]",
"# Try to match '<CODE ENDS>'",
"if",
"self",
".",
"CODE_ENDS_TAG",
".",
"match",
"(",
"line",
")",
":",
"if",
"in_model",
"is",
"False",
":",
"self",
".",
"warning",
"(",
"\"Line %d: misplaced <CODE ENDS>\"",
"%",
"i",
")",
"in_model",
"=",
"False",
"if",
"\"\\\"\"",
"in",
"line",
":",
"if",
"line",
".",
"count",
"(",
"\"\\\"\"",
")",
"%",
"2",
"==",
"0",
":",
"quotes",
"=",
"0",
"else",
":",
"if",
"quotes",
"==",
"1",
":",
"quotes",
"=",
"0",
"else",
":",
"quotes",
"=",
"1",
"# Try to match '(sub)module <module_name> {'",
"match",
"=",
"self",
".",
"MODULE_STATEMENT",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"# We're already parsing a module",
"if",
"quotes",
"==",
"0",
":",
"if",
"level",
">",
"0",
":",
"self",
".",
"error",
"(",
"\"Line %d - 'module' statement within another module\"",
"%",
"i",
")",
"return",
"# Check if we should enforce <CODE BEGINS> / <CODE ENDS>",
"# if we do enforce, we ignore models not enclosed in <CODE BEGINS> / <CODE ENDS>",
"if",
"match",
".",
"groups",
"(",
")",
"[",
"1",
"]",
"or",
"match",
".",
"groups",
"(",
")",
"[",
"4",
"]",
":",
"self",
".",
"warning",
"(",
"'Line %d - Module name should not be enclosed in quotes'",
"%",
"i",
")",
"# do the module name checking, etc.",
"example_match",
"=",
"self",
".",
"EXAMPLE_TAG",
".",
"match",
"(",
"match",
".",
"groups",
"(",
")",
"[",
"2",
"]",
")",
"if",
"in_model",
"is",
"True",
":",
"if",
"example_match",
":",
"self",
".",
"error",
"(",
"\"Line %d - YANG module '%s' with <CODE BEGINS> and starting with 'example-'\"",
"%",
"(",
"i",
",",
"match",
".",
"groups",
"(",
")",
"[",
"2",
"]",
")",
")",
"else",
":",
"if",
"not",
"example_match",
":",
"self",
".",
"error",
"(",
"\"Line %d - YANG module '%s' with no <CODE BEGINS> and not starting with 'example-'\"",
"%",
"(",
"i",
",",
"match",
".",
"groups",
"(",
")",
"[",
"2",
"]",
")",
")",
"# now decide if we're allowed to set the level",
"# (i.e. signal that we're in a module) to 1 and if",
"# we're allowed to output the module at all with the",
"# strict examples flag",
"# if self.strict is True:",
"# if in_model is True:",
"# level = 1",
"# else:",
"# level = 1",
"# always set the level to 1; we decide whether or not",
"# to output at the end",
"if",
"quotes",
"==",
"0",
":",
"level",
"=",
"1",
"if",
"not",
"output_file",
"and",
"level",
"==",
"1",
"and",
"quotes",
"==",
"0",
":",
"print",
"(",
"\"\\nExtracting '%s'\"",
"%",
"match",
".",
"groups",
"(",
")",
"[",
"2",
"]",
")",
"output_file",
"=",
"'%s.yang'",
"%",
"match",
".",
"groups",
"(",
")",
"[",
"2",
"]",
".",
"strip",
"(",
"'\"\\''",
")",
"if",
"self",
".",
"debug_level",
">",
"0",
":",
"print",
"(",
"' Getting YANG file name from module name: %s'",
"%",
"output_file",
")",
"if",
"level",
">",
"0",
":",
"self",
".",
"debug_print_line",
"(",
"i",
",",
"level",
",",
"content",
"[",
"i",
"]",
")",
"# Try to match the Footer ('[Page <page_num>]')",
"# If match found, skip over page headers and footers",
"if",
"self",
".",
"PAGE_TAG",
".",
"match",
"(",
"line",
")",
":",
"self",
".",
"strip_empty_lines_backward",
"(",
"model",
",",
"3",
")",
"self",
".",
"debug_print_strip_msg",
"(",
"i",
",",
"content",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"# Strip the",
"# Strip empty lines between the Footer and the next page Header",
"i",
"=",
"self",
".",
"strip_empty_lines_forward",
"(",
"content",
",",
"i",
")",
"if",
"i",
"<",
"len",
"(",
"content",
")",
":",
"self",
".",
"debug_print_strip_msg",
"(",
"i",
",",
"content",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"# Strip the next page Header",
"else",
":",
"self",
".",
"error",
"(",
"\"<End of File> - EOF encountered while parsing the model\"",
")",
"return",
"# Strip empty lines between the page Header and real content on the page",
"i",
"=",
"self",
".",
"strip_empty_lines_forward",
"(",
"content",
",",
"i",
")",
"-",
"1",
"if",
"i",
">=",
"len",
"(",
"content",
")",
":",
"self",
".",
"error",
"(",
"\"<End of File> - EOF encountered while parsing the model\"",
")",
"return",
"else",
":",
"model",
".",
"append",
"(",
"[",
"line",
",",
"i",
"+",
"1",
"]",
")",
"counter",
"=",
"Counter",
"(",
"line",
")",
"if",
"quotes",
"==",
"0",
":",
"if",
"\"\\\"\"",
"in",
"line",
"and",
"\"}\"",
"in",
"line",
":",
"if",
"line",
".",
"index",
"(",
"\"}\"",
")",
">",
"line",
".",
"rindex",
"(",
"\"\\\"\"",
")",
"or",
"line",
".",
"index",
"(",
"\"}\"",
")",
"<",
"line",
".",
"index",
"(",
"\"\\\"\"",
")",
":",
"level",
"+=",
"(",
"counter",
"[",
"'{'",
"]",
"-",
"counter",
"[",
"'}'",
"]",
")",
"else",
":",
"level",
"+=",
"(",
"counter",
"[",
"'{'",
"]",
"-",
"counter",
"[",
"'}'",
"]",
")",
"if",
"level",
"==",
"1",
":",
"if",
"self",
".",
"strict",
":",
"if",
"self",
".",
"strict_examples",
":",
"if",
"example_match",
"and",
"not",
"in_model",
":",
"self",
".",
"write_model_to_file",
"(",
"model",
",",
"output_file",
")",
"elif",
"in_model",
":",
"self",
".",
"write_model_to_file",
"(",
"model",
",",
"output_file",
")",
"else",
":",
"self",
".",
"write_model_to_file",
"(",
"model",
",",
"output_file",
")",
"self",
".",
"max_line_len",
"=",
"0",
"model",
"=",
"[",
"]",
"output_file",
"=",
"None",
"level",
"=",
"0",
"# Try to match '<CODE BEGINS>'",
"match",
"=",
"self",
".",
"CODE_BEGINS_TAG",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"# Found the beginning of the YANG module code section; make sure we're not parsing a model already",
"if",
"level",
">",
"0",
":",
"self",
".",
"error",
"(",
"\"Line %d - <CODE BEGINS> within a model\"",
"%",
"i",
")",
"return",
"if",
"in_model",
"is",
"True",
":",
"self",
".",
"error",
"(",
"\"Line %d - Misplaced <CODE BEGINS> or missing <CODE ENDS>\"",
"%",
"i",
")",
"in_model",
"=",
"True",
"mg",
"=",
"match",
".",
"groups",
"(",
")",
"# Get the YANG module's file name",
"if",
"mg",
"[",
"2",
"]",
":",
"print",
"(",
"\"\\nExtracting '%s'\"",
"%",
"match",
".",
"groups",
"(",
")",
"[",
"2",
"]",
")",
"output_file",
"=",
"mg",
"[",
"2",
"]",
".",
"strip",
"(",
")",
"else",
":",
"if",
"mg",
"[",
"0",
"]",
"and",
"mg",
"[",
"1",
"]",
"is",
"None",
":",
"self",
".",
"error",
"(",
"'Line %d - Missing file name in <CODE BEGINS>'",
"%",
"i",
")",
"else",
":",
"self",
".",
"error",
"(",
"\"Line %d - YANG file not specified in <CODE BEGINS>\"",
"%",
"i",
")",
"i",
"+=",
"1",
"if",
"level",
">",
"0",
":",
"self",
".",
"error",
"(",
"\"<End of File> - EOF encountered while parsing the model\"",
")",
"return",
"if",
"in_model",
"is",
"True",
":",
"self",
".",
"error",
"(",
"\"Line %d - Missing <CODE ENDS>\"",
"%",
"i",
")"
] |
Extracts one or more YANG models from an RFC or draft text string in
which the models are specified. The function skips over page
formatting (Page Headers and Footers) and performs basic YANG module
syntax checking. In strict mode, the function also enforces the
<CODE BEGINS> / <CODE ENDS> tags - a model is not extracted unless
the tags are present.
:return: None
|
[
"Extracts",
"one",
"or",
"more",
"YANG",
"models",
"from",
"an",
"RFC",
"or",
"draft",
"text",
"string",
"in",
"which",
"the",
"models",
"are",
"specified",
".",
"The",
"function",
"skips",
"over",
"page",
"formatting",
"(",
"Page",
"Headers",
"and",
"Footers",
")",
"and",
"performs",
"basic",
"YANG",
"module",
"syntax",
"checking",
".",
"In",
"strict",
"mode",
"the",
"function",
"also",
"enforces",
"the",
"<CODE",
"BEGINS",
">",
"/",
"<CODE",
"ENDS",
">",
"tags",
"-",
"a",
"model",
"is",
"not",
"extracted",
"unless",
"the",
"tags",
"are",
"present",
".",
":",
"return",
":",
"None"
] |
48984e6bd41595df8f383e6dc7e6eedfecc96898
|
https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L375-L524
|
train
|
rbarrois/mpdlcd
|
mpdlcd/utils.py
|
auto_retry
|
def auto_retry(fun):
"""Decorator for retrying method calls, based on instance parameters."""
@functools.wraps(fun)
def decorated(instance, *args, **kwargs):
"""Wrapper around a decorated function."""
cfg = instance._retry_config
remaining_tries = cfg.retry_attempts
current_wait = cfg.retry_wait
retry_backoff = cfg.retry_backoff
last_error = None
while remaining_tries >= 0:
try:
return fun(instance, *args, **kwargs)
except socket.error as e:
last_error = e
instance._retry_logger.warning('Connection failed: %s', e)
remaining_tries -= 1
if remaining_tries == 0:
# Last attempt
break
# Wait a bit
time.sleep(current_wait)
current_wait *= retry_backoff
# All attempts failed, let's raise the last error.
raise last_error
return decorated
|
python
|
def auto_retry(fun):
"""Decorator for retrying method calls, based on instance parameters."""
@functools.wraps(fun)
def decorated(instance, *args, **kwargs):
"""Wrapper around a decorated function."""
cfg = instance._retry_config
remaining_tries = cfg.retry_attempts
current_wait = cfg.retry_wait
retry_backoff = cfg.retry_backoff
last_error = None
while remaining_tries >= 0:
try:
return fun(instance, *args, **kwargs)
except socket.error as e:
last_error = e
instance._retry_logger.warning('Connection failed: %s', e)
remaining_tries -= 1
if remaining_tries == 0:
# Last attempt
break
# Wait a bit
time.sleep(current_wait)
current_wait *= retry_backoff
# All attempts failed, let's raise the last error.
raise last_error
return decorated
|
[
"def",
"auto_retry",
"(",
"fun",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fun",
")",
"def",
"decorated",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper around a decorated function.\"\"\"",
"cfg",
"=",
"instance",
".",
"_retry_config",
"remaining_tries",
"=",
"cfg",
".",
"retry_attempts",
"current_wait",
"=",
"cfg",
".",
"retry_wait",
"retry_backoff",
"=",
"cfg",
".",
"retry_backoff",
"last_error",
"=",
"None",
"while",
"remaining_tries",
">=",
"0",
":",
"try",
":",
"return",
"fun",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"last_error",
"=",
"e",
"instance",
".",
"_retry_logger",
".",
"warning",
"(",
"'Connection failed: %s'",
",",
"e",
")",
"remaining_tries",
"-=",
"1",
"if",
"remaining_tries",
"==",
"0",
":",
"# Last attempt",
"break",
"# Wait a bit",
"time",
".",
"sleep",
"(",
"current_wait",
")",
"current_wait",
"*=",
"retry_backoff",
"# All attempts failed, let's raise the last error.",
"raise",
"last_error",
"return",
"decorated"
] |
Decorator for retrying method calls, based on instance parameters.
|
[
"Decorator",
"for",
"retrying",
"method",
"calls",
"based",
"on",
"instance",
"parameters",
"."
] |
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
|
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/utils.py#L50-L81
|
train
|
rbarrois/mpdlcd
|
mpdlcd/utils.py
|
extract_pattern
|
def extract_pattern(fmt):
"""Extracts used strings from a %(foo)s pattern."""
class FakeDict(object):
def __init__(self):
self.seen_keys = set()
def __getitem__(self, key):
self.seen_keys.add(key)
return ''
def keys(self):
return self.seen_keys
fake = FakeDict()
try:
fmt % fake
except TypeError:
# Formatting error
pass
return set(fake.keys())
|
python
|
def extract_pattern(fmt):
"""Extracts used strings from a %(foo)s pattern."""
class FakeDict(object):
def __init__(self):
self.seen_keys = set()
def __getitem__(self, key):
self.seen_keys.add(key)
return ''
def keys(self):
return self.seen_keys
fake = FakeDict()
try:
fmt % fake
except TypeError:
# Formatting error
pass
return set(fake.keys())
|
[
"def",
"extract_pattern",
"(",
"fmt",
")",
":",
"class",
"FakeDict",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"seen_keys",
"=",
"set",
"(",
")",
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"seen_keys",
".",
"add",
"(",
"key",
")",
"return",
"''",
"def",
"keys",
"(",
"self",
")",
":",
"return",
"self",
".",
"seen_keys",
"fake",
"=",
"FakeDict",
"(",
")",
"try",
":",
"fmt",
"%",
"fake",
"except",
"TypeError",
":",
"# Formatting error",
"pass",
"return",
"set",
"(",
"fake",
".",
"keys",
"(",
")",
")"
] |
Extracts used strings from a %(foo)s pattern.
|
[
"Extracts",
"used",
"strings",
"from",
"a",
"%",
"(",
"foo",
")",
"s",
"pattern",
"."
] |
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
|
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/utils.py#L84-L103
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/isoline.py
|
iso_mesh_line
|
def iso_mesh_line(vertices, tris, vertex_data, levels):
"""Generate an isocurve from vertex data in a surface mesh.
Parameters
----------
vertices : ndarray, shape (Nv, 3)
Vertex coordinates.
tris : ndarray, shape (Nf, 3)
Indices of triangular element into the vertices array.
vertex_data : ndarray, shape (Nv,)
data at vertex.
levels : ndarray, shape (Nl,)
Levels at which to generate an isocurve
Returns
-------
lines : ndarray, shape (Nvout, 3)
Vertex coordinates for lines points
connects : ndarray, shape (Ne, 2)
Indices of line element into the vertex array.
vertex_level: ndarray, shape (Nvout,)
level for vertex in lines
Notes
-----
Uses a marching squares algorithm to generate the isolines.
"""
lines = None
connects = None
vertex_level = None
level_index = None
if not all([isinstance(x, np.ndarray) for x in (vertices, tris,
vertex_data, levels)]):
raise ValueError('all inputs must be numpy arrays')
if vertices.shape[1] <= 3:
verts = vertices
elif vertices.shape[1] == 4:
verts = vertices[:, :-1]
else:
verts = None
if (verts is not None and tris.shape[1] == 3 and
vertex_data.shape[0] == verts.shape[0]):
edges = np.vstack((tris.reshape((-1)),
np.roll(tris, -1, axis=1).reshape((-1)))).T
edge_datas = vertex_data[edges]
edge_coors = verts[edges].reshape(tris.shape[0]*3, 2, 3)
for lev in levels:
# index for select edges with vertices have only False - True
# or True - False at extremity
index = (edge_datas >= lev)
index = index[:, 0] ^ index[:, 1] # xor calculation
# Selectect edge
edge_datas_Ok = edge_datas[index, :]
xyz = edge_coors[index]
# Linear interpolation
ratio = np.array([(lev - edge_datas_Ok[:, 0]) /
(edge_datas_Ok[:, 1] - edge_datas_Ok[:, 0])])
point = xyz[:, 0, :] + ratio.T * (xyz[:, 1, :] - xyz[:, 0, :])
nbr = point.shape[0]//2
if connects is not None:
connect = np.arange(0, nbr*2).reshape((nbr, 2)) + \
len(lines)
connects = np.append(connects, connect, axis=0)
lines = np.append(lines, point, axis=0)
vertex_level = np.append(vertex_level,
np.zeros(len(point)) +
lev)
level_index = np.append(level_index, np.array(len(point)))
else:
lines = point
connects = np.arange(0, nbr*2).reshape((nbr, 2))
vertex_level = np.zeros(len(point)) + lev
level_index = np.array(len(point))
vertex_level = vertex_level.reshape((vertex_level.size, 1))
return lines, connects, vertex_level, level_index
|
python
|
def iso_mesh_line(vertices, tris, vertex_data, levels):
"""Generate an isocurve from vertex data in a surface mesh.
Parameters
----------
vertices : ndarray, shape (Nv, 3)
Vertex coordinates.
tris : ndarray, shape (Nf, 3)
Indices of triangular element into the vertices array.
vertex_data : ndarray, shape (Nv,)
data at vertex.
levels : ndarray, shape (Nl,)
Levels at which to generate an isocurve
Returns
-------
lines : ndarray, shape (Nvout, 3)
Vertex coordinates for lines points
connects : ndarray, shape (Ne, 2)
Indices of line element into the vertex array.
vertex_level: ndarray, shape (Nvout,)
level for vertex in lines
Notes
-----
Uses a marching squares algorithm to generate the isolines.
"""
lines = None
connects = None
vertex_level = None
level_index = None
if not all([isinstance(x, np.ndarray) for x in (vertices, tris,
vertex_data, levels)]):
raise ValueError('all inputs must be numpy arrays')
if vertices.shape[1] <= 3:
verts = vertices
elif vertices.shape[1] == 4:
verts = vertices[:, :-1]
else:
verts = None
if (verts is not None and tris.shape[1] == 3 and
vertex_data.shape[0] == verts.shape[0]):
edges = np.vstack((tris.reshape((-1)),
np.roll(tris, -1, axis=1).reshape((-1)))).T
edge_datas = vertex_data[edges]
edge_coors = verts[edges].reshape(tris.shape[0]*3, 2, 3)
for lev in levels:
# index for select edges with vertices have only False - True
# or True - False at extremity
index = (edge_datas >= lev)
index = index[:, 0] ^ index[:, 1] # xor calculation
# Selectect edge
edge_datas_Ok = edge_datas[index, :]
xyz = edge_coors[index]
# Linear interpolation
ratio = np.array([(lev - edge_datas_Ok[:, 0]) /
(edge_datas_Ok[:, 1] - edge_datas_Ok[:, 0])])
point = xyz[:, 0, :] + ratio.T * (xyz[:, 1, :] - xyz[:, 0, :])
nbr = point.shape[0]//2
if connects is not None:
connect = np.arange(0, nbr*2).reshape((nbr, 2)) + \
len(lines)
connects = np.append(connects, connect, axis=0)
lines = np.append(lines, point, axis=0)
vertex_level = np.append(vertex_level,
np.zeros(len(point)) +
lev)
level_index = np.append(level_index, np.array(len(point)))
else:
lines = point
connects = np.arange(0, nbr*2).reshape((nbr, 2))
vertex_level = np.zeros(len(point)) + lev
level_index = np.array(len(point))
vertex_level = vertex_level.reshape((vertex_level.size, 1))
return lines, connects, vertex_level, level_index
|
[
"def",
"iso_mesh_line",
"(",
"vertices",
",",
"tris",
",",
"vertex_data",
",",
"levels",
")",
":",
"lines",
"=",
"None",
"connects",
"=",
"None",
"vertex_level",
"=",
"None",
"level_index",
"=",
"None",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
"for",
"x",
"in",
"(",
"vertices",
",",
"tris",
",",
"vertex_data",
",",
"levels",
")",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'all inputs must be numpy arrays'",
")",
"if",
"vertices",
".",
"shape",
"[",
"1",
"]",
"<=",
"3",
":",
"verts",
"=",
"vertices",
"elif",
"vertices",
".",
"shape",
"[",
"1",
"]",
"==",
"4",
":",
"verts",
"=",
"vertices",
"[",
":",
",",
":",
"-",
"1",
"]",
"else",
":",
"verts",
"=",
"None",
"if",
"(",
"verts",
"is",
"not",
"None",
"and",
"tris",
".",
"shape",
"[",
"1",
"]",
"==",
"3",
"and",
"vertex_data",
".",
"shape",
"[",
"0",
"]",
"==",
"verts",
".",
"shape",
"[",
"0",
"]",
")",
":",
"edges",
"=",
"np",
".",
"vstack",
"(",
"(",
"tris",
".",
"reshape",
"(",
"(",
"-",
"1",
")",
")",
",",
"np",
".",
"roll",
"(",
"tris",
",",
"-",
"1",
",",
"axis",
"=",
"1",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
")",
")",
")",
")",
".",
"T",
"edge_datas",
"=",
"vertex_data",
"[",
"edges",
"]",
"edge_coors",
"=",
"verts",
"[",
"edges",
"]",
".",
"reshape",
"(",
"tris",
".",
"shape",
"[",
"0",
"]",
"*",
"3",
",",
"2",
",",
"3",
")",
"for",
"lev",
"in",
"levels",
":",
"# index for select edges with vertices have only False - True",
"# or True - False at extremity",
"index",
"=",
"(",
"edge_datas",
">=",
"lev",
")",
"index",
"=",
"index",
"[",
":",
",",
"0",
"]",
"^",
"index",
"[",
":",
",",
"1",
"]",
"# xor calculation",
"# Selectect edge",
"edge_datas_Ok",
"=",
"edge_datas",
"[",
"index",
",",
":",
"]",
"xyz",
"=",
"edge_coors",
"[",
"index",
"]",
"# Linear interpolation",
"ratio",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"lev",
"-",
"edge_datas_Ok",
"[",
":",
",",
"0",
"]",
")",
"/",
"(",
"edge_datas_Ok",
"[",
":",
",",
"1",
"]",
"-",
"edge_datas_Ok",
"[",
":",
",",
"0",
"]",
")",
"]",
")",
"point",
"=",
"xyz",
"[",
":",
",",
"0",
",",
":",
"]",
"+",
"ratio",
".",
"T",
"*",
"(",
"xyz",
"[",
":",
",",
"1",
",",
":",
"]",
"-",
"xyz",
"[",
":",
",",
"0",
",",
":",
"]",
")",
"nbr",
"=",
"point",
".",
"shape",
"[",
"0",
"]",
"//",
"2",
"if",
"connects",
"is",
"not",
"None",
":",
"connect",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"nbr",
"*",
"2",
")",
".",
"reshape",
"(",
"(",
"nbr",
",",
"2",
")",
")",
"+",
"len",
"(",
"lines",
")",
"connects",
"=",
"np",
".",
"append",
"(",
"connects",
",",
"connect",
",",
"axis",
"=",
"0",
")",
"lines",
"=",
"np",
".",
"append",
"(",
"lines",
",",
"point",
",",
"axis",
"=",
"0",
")",
"vertex_level",
"=",
"np",
".",
"append",
"(",
"vertex_level",
",",
"np",
".",
"zeros",
"(",
"len",
"(",
"point",
")",
")",
"+",
"lev",
")",
"level_index",
"=",
"np",
".",
"append",
"(",
"level_index",
",",
"np",
".",
"array",
"(",
"len",
"(",
"point",
")",
")",
")",
"else",
":",
"lines",
"=",
"point",
"connects",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"nbr",
"*",
"2",
")",
".",
"reshape",
"(",
"(",
"nbr",
",",
"2",
")",
")",
"vertex_level",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"point",
")",
")",
"+",
"lev",
"level_index",
"=",
"np",
".",
"array",
"(",
"len",
"(",
"point",
")",
")",
"vertex_level",
"=",
"vertex_level",
".",
"reshape",
"(",
"(",
"vertex_level",
".",
"size",
",",
"1",
")",
")",
"return",
"lines",
",",
"connects",
",",
"vertex_level",
",",
"level_index"
] |
Generate an isocurve from vertex data in a surface mesh.
Parameters
----------
vertices : ndarray, shape (Nv, 3)
Vertex coordinates.
tris : ndarray, shape (Nf, 3)
Indices of triangular element into the vertices array.
vertex_data : ndarray, shape (Nv,)
data at vertex.
levels : ndarray, shape (Nl,)
Levels at which to generate an isocurve
Returns
-------
lines : ndarray, shape (Nvout, 3)
Vertex coordinates for lines points
connects : ndarray, shape (Ne, 2)
Indices of line element into the vertex array.
vertex_level: ndarray, shape (Nvout,)
level for vertex in lines
Notes
-----
Uses a marching squares algorithm to generate the isolines.
|
[
"Generate",
"an",
"isocurve",
"from",
"vertex",
"data",
"in",
"a",
"surface",
"mesh",
"."
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/isoline.py#L14-L91
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/isoline.py
|
IsolineVisual.set_data
|
def set_data(self, vertices=None, tris=None, data=None):
"""Set the data
Parameters
----------
vertices : ndarray, shape (Nv, 3) | None
Vertex coordinates.
tris : ndarray, shape (Nf, 3) | None
Indices into the vertex array.
data : ndarray, shape (Nv,) | None
scalar at vertices
"""
# modifier pour tenier compte des None self._recompute = True
if data is not None:
self._data = data
self._need_recompute = True
if vertices is not None:
self._vertices = vertices
self._need_recompute = True
if tris is not None:
self._tris = tris
self._need_recompute = True
self.update()
|
python
|
def set_data(self, vertices=None, tris=None, data=None):
"""Set the data
Parameters
----------
vertices : ndarray, shape (Nv, 3) | None
Vertex coordinates.
tris : ndarray, shape (Nf, 3) | None
Indices into the vertex array.
data : ndarray, shape (Nv,) | None
scalar at vertices
"""
# modifier pour tenier compte des None self._recompute = True
if data is not None:
self._data = data
self._need_recompute = True
if vertices is not None:
self._vertices = vertices
self._need_recompute = True
if tris is not None:
self._tris = tris
self._need_recompute = True
self.update()
|
[
"def",
"set_data",
"(",
"self",
",",
"vertices",
"=",
"None",
",",
"tris",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"# modifier pour tenier compte des None self._recompute = True",
"if",
"data",
"is",
"not",
"None",
":",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_need_recompute",
"=",
"True",
"if",
"vertices",
"is",
"not",
"None",
":",
"self",
".",
"_vertices",
"=",
"vertices",
"self",
".",
"_need_recompute",
"=",
"True",
"if",
"tris",
"is",
"not",
"None",
":",
"self",
".",
"_tris",
"=",
"tris",
"self",
".",
"_need_recompute",
"=",
"True",
"self",
".",
"update",
"(",
")"
] |
Set the data
Parameters
----------
vertices : ndarray, shape (Nv, 3) | None
Vertex coordinates.
tris : ndarray, shape (Nf, 3) | None
Indices into the vertex array.
data : ndarray, shape (Nv,) | None
scalar at vertices
|
[
"Set",
"the",
"data"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/isoline.py#L150-L172
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/isoline.py
|
IsolineVisual.set_color
|
def set_color(self, color):
"""Set the color
Parameters
----------
color : instance of Color
The color to use.
"""
if color is not None:
self._color_lev = color
self._need_color_update = True
self.update()
|
python
|
def set_color(self, color):
"""Set the color
Parameters
----------
color : instance of Color
The color to use.
"""
if color is not None:
self._color_lev = color
self._need_color_update = True
self.update()
|
[
"def",
"set_color",
"(",
"self",
",",
"color",
")",
":",
"if",
"color",
"is",
"not",
"None",
":",
"self",
".",
"_color_lev",
"=",
"color",
"self",
".",
"_need_color_update",
"=",
"True",
"self",
".",
"update",
"(",
")"
] |
Set the color
Parameters
----------
color : instance of Color
The color to use.
|
[
"Set",
"the",
"color"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/isoline.py#L178-L189
|
train
|
glue-viz/glue-vispy-viewers
|
glue_vispy_viewers/extern/vispy/visuals/isoline.py
|
IsolineVisual._compute_iso_color
|
def _compute_iso_color(self):
""" compute LineVisual color from level index and corresponding level
color
"""
level_color = []
colors = self._lc
for i, index in enumerate(self._li):
level_color.append(np.zeros((index, 4)) + colors[i])
self._cl = np.vstack(level_color)
|
python
|
def _compute_iso_color(self):
""" compute LineVisual color from level index and corresponding level
color
"""
level_color = []
colors = self._lc
for i, index in enumerate(self._li):
level_color.append(np.zeros((index, 4)) + colors[i])
self._cl = np.vstack(level_color)
|
[
"def",
"_compute_iso_color",
"(",
"self",
")",
":",
"level_color",
"=",
"[",
"]",
"colors",
"=",
"self",
".",
"_lc",
"for",
"i",
",",
"index",
"in",
"enumerate",
"(",
"self",
".",
"_li",
")",
":",
"level_color",
".",
"append",
"(",
"np",
".",
"zeros",
"(",
"(",
"index",
",",
"4",
")",
")",
"+",
"colors",
"[",
"i",
"]",
")",
"self",
".",
"_cl",
"=",
"np",
".",
"vstack",
"(",
"level_color",
")"
] |
compute LineVisual color from level index and corresponding level
color
|
[
"compute",
"LineVisual",
"color",
"from",
"level",
"index",
"and",
"corresponding",
"level",
"color"
] |
54a4351d98c1f90dfb1a557d1b447c1f57470eea
|
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/isoline.py#L214-L222
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.