repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zrange | def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param end:
:param desc:
:param withscores:
:param score_cast_func:
:return:
"""
with self.pipe as pipe:
f = Future()
res = pipe.zrange(
self.redis_key(name), start, end, desc=desc,
withscores=withscores, score_cast_func=score_cast_func)
def cb():
if withscores:
f.set([(self.valueparse.decode(v), s) for v, s in
res.result])
else:
f.set([self.valueparse.decode(v) for v in res.result])
pipe.on_execute(cb)
return f | python | def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param end:
:param desc:
:param withscores:
:param score_cast_func:
:return:
"""
with self.pipe as pipe:
f = Future()
res = pipe.zrange(
self.redis_key(name), start, end, desc=desc,
withscores=withscores, score_cast_func=score_cast_func)
def cb():
if withscores:
f.set([(self.valueparse.decode(v), s) for v, s in
res.result])
else:
f.set([self.valueparse.decode(v) for v in res.result])
pipe.on_execute(cb)
return f | [
"def",
"zrange",
"(",
"self",
",",
"name",
",",
"start",
",",
"end",
",",
"desc",
"=",
"False",
",",
"withscores",
"=",
"False",
",",
"score_cast_func",
"=",
"float",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"("... | Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param end:
:param desc:
:param withscores:
:param score_cast_func:
:return: | [
"Returns",
"all",
"the",
"elements",
"including",
"between",
"start",
"(",
"non",
"included",
")",
"and",
"stop",
"(",
"included",
")",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1503-L1531 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zrangebyscore | def zrangebyscore(self, name, min, max, start=None, num=None,
withscores=False, score_cast_func=float):
"""
Returns the range of elements included between the scores (min and max)
:param name: str the name of the redis key
:param min:
:param max:
:param start:
:param num:
:param withscores:
:param score_cast_func:
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.zrangebyscore(self.redis_key(name), min, max,
start=start, num=num,
withscores=withscores,
score_cast_func=score_cast_func)
def cb():
if withscores:
f.set([(self.valueparse.decode(v), s) for v, s in
res.result])
else:
f.set([self.valueparse.decode(v) for v in res.result])
pipe.on_execute(cb)
return f | python | def zrangebyscore(self, name, min, max, start=None, num=None,
withscores=False, score_cast_func=float):
"""
Returns the range of elements included between the scores (min and max)
:param name: str the name of the redis key
:param min:
:param max:
:param start:
:param num:
:param withscores:
:param score_cast_func:
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.zrangebyscore(self.redis_key(name), min, max,
start=start, num=num,
withscores=withscores,
score_cast_func=score_cast_func)
def cb():
if withscores:
f.set([(self.valueparse.decode(v), s) for v, s in
res.result])
else:
f.set([self.valueparse.decode(v) for v in res.result])
pipe.on_execute(cb)
return f | [
"def",
"zrangebyscore",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
",",
"start",
"=",
"None",
",",
"num",
"=",
"None",
",",
"withscores",
"=",
"False",
",",
"score_cast_func",
"=",
"float",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
... | Returns the range of elements included between the scores (min and max)
:param name: str the name of the redis key
:param min:
:param max:
:param start:
:param num:
:param withscores:
:param score_cast_func:
:return: Future() | [
"Returns",
"the",
"range",
"of",
"elements",
"included",
"between",
"the",
"scores",
"(",
"min",
"and",
"max",
")"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1563-L1592 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zcard | def zcard(self, name):
"""
Returns the cardinality of the SortedSet.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
return pipe.zcard(self.redis_key(name)) | python | def zcard(self, name):
"""
Returns the cardinality of the SortedSet.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
return pipe.zcard(self.redis_key(name)) | [
"def",
"zcard",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zcard",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
")"
] | Returns the cardinality of the SortedSet.
:param name: str the name of the redis key
:return: Future() | [
"Returns",
"the",
"cardinality",
"of",
"the",
"SortedSet",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1634-L1642 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zcount | def zcount(self, name, min, max):
"""
Returns the number of elements in the sorted set at key ``name`` with
a score between ``min`` and ``max``.
:param name: str
:param min: float
:param max: float
:return: Future()
"""
with self.pipe as pipe:
return pipe.zcount(self.redis_key(name), min, max) | python | def zcount(self, name, min, max):
"""
Returns the number of elements in the sorted set at key ``name`` with
a score between ``min`` and ``max``.
:param name: str
:param min: float
:param max: float
:return: Future()
"""
with self.pipe as pipe:
return pipe.zcount(self.redis_key(name), min, max) | [
"def",
"zcount",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zcount",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"min",
",",
"max",
")"
] | Returns the number of elements in the sorted set at key ``name`` with
a score between ``min`` and ``max``.
:param name: str
:param min: float
:param max: float
:return: Future() | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"the",
"sorted",
"set",
"at",
"key",
"name",
"with",
"a",
"score",
"between",
"min",
"and",
"max",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1644-L1655 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zscore | def zscore(self, name, value):
"""
Return the score of an element
:param name: str the name of the redis key
:param value: the element in the sorted set key
:return: Future()
"""
with self.pipe as pipe:
return pipe.zscore(self.redis_key(name),
self.valueparse.encode(value)) | python | def zscore(self, name, value):
"""
Return the score of an element
:param name: str the name of the redis key
:param value: the element in the sorted set key
:return: Future()
"""
with self.pipe as pipe:
return pipe.zscore(self.redis_key(name),
self.valueparse.encode(value)) | [
"def",
"zscore",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zscore",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"self",
".",
"valueparse",
".",
"encode",
"(",... | Return the score of an element
:param name: str the name of the redis key
:param value: the element in the sorted set key
:return: Future() | [
"Return",
"the",
"score",
"of",
"an",
"element"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1657-L1667 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zremrangebyrank | def zremrangebyrank(self, name, min, max):
"""
Remove a range of element between the rank ``start`` and
``stop`` both included.
:param name: str the name of the redis key
:param min:
:param max:
:return: Future()
"""
with self.pipe as pipe:
return pipe.zremrangebyrank(self.redis_key(name), min, max) | python | def zremrangebyrank(self, name, min, max):
"""
Remove a range of element between the rank ``start`` and
``stop`` both included.
:param name: str the name of the redis key
:param min:
:param max:
:return: Future()
"""
with self.pipe as pipe:
return pipe.zremrangebyrank(self.redis_key(name), min, max) | [
"def",
"zremrangebyrank",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zremrangebyrank",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"min",
",",
"max",
... | Remove a range of element between the rank ``start`` and
``stop`` both included.
:param name: str the name of the redis key
:param min:
:param max:
:return: Future() | [
"Remove",
"a",
"range",
"of",
"element",
"between",
"the",
"rank",
"start",
"and",
"stop",
"both",
"included",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1669-L1680 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zremrangebyscore | def zremrangebyscore(self, name, min, max):
"""
Remove a range of element by between score ``min_value`` and
``max_value`` both included.
:param name: str the name of the redis key
:param min:
:param max:
:return: Future()
"""
with self.pipe as pipe:
return pipe.zremrangebyscore(self.redis_key(name), min, max) | python | def zremrangebyscore(self, name, min, max):
"""
Remove a range of element by between score ``min_value`` and
``max_value`` both included.
:param name: str the name of the redis key
:param min:
:param max:
:return: Future()
"""
with self.pipe as pipe:
return pipe.zremrangebyscore(self.redis_key(name), min, max) | [
"def",
"zremrangebyscore",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zremrangebyscore",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"min",
",",
"max",... | Remove a range of element by between score ``min_value`` and
``max_value`` both included.
:param name: str the name of the redis key
:param min:
:param max:
:return: Future() | [
"Remove",
"a",
"range",
"of",
"element",
"by",
"between",
"score",
"min_value",
"and",
"max_value",
"both",
"included",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1683-L1694 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zrank | def zrank(self, name, value):
"""
Returns the rank of the element.
:param name: str the name of the redis key
:param value: the element in the sorted set
"""
with self.pipe as pipe:
value = self.valueparse.encode(value)
return pipe.zrank(self.redis_key(name), value) | python | def zrank(self, name, value):
"""
Returns the rank of the element.
:param name: str the name of the redis key
:param value: the element in the sorted set
"""
with self.pipe as pipe:
value = self.valueparse.encode(value)
return pipe.zrank(self.redis_key(name), value) | [
"def",
"zrank",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"value",
"=",
"self",
".",
"valueparse",
".",
"encode",
"(",
"value",
")",
"return",
"pipe",
".",
"zrank",
"(",
"self",
".",
"redis_ke... | Returns the rank of the element.
:param name: str the name of the redis key
:param value: the element in the sorted set | [
"Returns",
"the",
"rank",
"of",
"the",
"element",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1696-L1705 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zlexcount | def zlexcount(self, name, min, max):
"""
Return the number of items in the sorted set between the
lexicographical range ``min`` and ``max``.
:param name: str the name of the redis key
:param min: int or '-inf'
:param max: int or '+inf'
:return: Future()
"""
with self.pipe as pipe:
return pipe.zlexcount(self.redis_key(name), min, max) | python | def zlexcount(self, name, min, max):
"""
Return the number of items in the sorted set between the
lexicographical range ``min`` and ``max``.
:param name: str the name of the redis key
:param min: int or '-inf'
:param max: int or '+inf'
:return: Future()
"""
with self.pipe as pipe:
return pipe.zlexcount(self.redis_key(name), min, max) | [
"def",
"zlexcount",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zlexcount",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"min",
",",
"max",
")"
] | Return the number of items in the sorted set between the
lexicographical range ``min`` and ``max``.
:param name: str the name of the redis key
:param min: int or '-inf'
:param max: int or '+inf'
:return: Future() | [
"Return",
"the",
"number",
"of",
"items",
"in",
"the",
"sorted",
"set",
"between",
"the",
"lexicographical",
"range",
"min",
"and",
"max",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1708-L1719 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zrevrangebylex | def zrevrangebylex(self, name, max, min, start=None, num=None):
"""
Return the reversed lexicographical range of values from the sorted set
between ``max`` and ``min``.
If ``start`` and ``num`` are specified, then return a slice of the
range.
:param name: str the name of the redis key
:param max: int or '+inf'
:param min: int or '-inf'
:param start: int
:param num: int
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.zrevrangebylex(self.redis_key(name), max, min,
start=start, num=num)
def cb():
f.set([self.valueparse.decode(v) for v in res])
pipe.on_execute(cb)
return f | python | def zrevrangebylex(self, name, max, min, start=None, num=None):
"""
Return the reversed lexicographical range of values from the sorted set
between ``max`` and ``min``.
If ``start`` and ``num`` are specified, then return a slice of the
range.
:param name: str the name of the redis key
:param max: int or '+inf'
:param min: int or '-inf'
:param start: int
:param num: int
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.zrevrangebylex(self.redis_key(name), max, min,
start=start, num=num)
def cb():
f.set([self.valueparse.decode(v) for v in res])
pipe.on_execute(cb)
return f | [
"def",
"zrevrangebylex",
"(",
"self",
",",
"name",
",",
"max",
",",
"min",
",",
"start",
"=",
"None",
",",
"num",
"=",
"None",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"(",
")",
"res",
"=",
"pipe",
".",
"zre... | Return the reversed lexicographical range of values from the sorted set
between ``max`` and ``min``.
If ``start`` and ``num`` are specified, then return a slice of the
range.
:param name: str the name of the redis key
:param max: int or '+inf'
:param min: int or '-inf'
:param start: int
:param num: int
:return: Future() | [
"Return",
"the",
"reversed",
"lexicographical",
"range",
"of",
"values",
"from",
"the",
"sorted",
"set",
"between",
"max",
"and",
"min",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1749-L1773 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zremrangebylex | def zremrangebylex(self, name, min, max):
"""
Remove all elements in the sorted set between the
lexicographical range specified by ``min`` and ``max``.
Returns the number of elements removed.
:param name: str the name of the redis key
:param min: int or -inf
:param max: into or +inf
:return: Future()
"""
with self.pipe as pipe:
return pipe.zremrangebylex(self.redis_key(name), min, max) | python | def zremrangebylex(self, name, min, max):
"""
Remove all elements in the sorted set between the
lexicographical range specified by ``min`` and ``max``.
Returns the number of elements removed.
:param name: str the name of the redis key
:param min: int or -inf
:param max: into or +inf
:return: Future()
"""
with self.pipe as pipe:
return pipe.zremrangebylex(self.redis_key(name), min, max) | [
"def",
"zremrangebylex",
"(",
"self",
",",
"name",
",",
"min",
",",
"max",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"zremrangebylex",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"min",
",",
"max",
"... | Remove all elements in the sorted set between the
lexicographical range specified by ``min`` and ``max``.
Returns the number of elements removed.
:param name: str the name of the redis key
:param min: int or -inf
:param max: into or +inf
:return: Future() | [
"Remove",
"all",
"elements",
"in",
"the",
"sorted",
"set",
"between",
"the",
"lexicographical",
"range",
"specified",
"by",
"min",
"and",
"max",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1776-L1788 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zunionstore | def zunionstore(self, dest, keys, aggregate=None):
"""
Union multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
with self.pipe as pipe:
keys = [self.redis_key(k) for k in keys]
return pipe.zunionstore(self.redis_key(dest), keys,
aggregate=aggregate) | python | def zunionstore(self, dest, keys, aggregate=None):
"""
Union multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
with self.pipe as pipe:
keys = [self.redis_key(k) for k in keys]
return pipe.zunionstore(self.redis_key(dest), keys,
aggregate=aggregate) | [
"def",
"zunionstore",
"(",
"self",
",",
"dest",
",",
"keys",
",",
"aggregate",
"=",
"None",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"keys",
"=",
"[",
"self",
".",
"redis_key",
"(",
"k",
")",
"for",
"k",
"in",
"keys",
"]",
"retur... | Union multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided. | [
"Union",
"multiple",
"sorted",
"sets",
"specified",
"by",
"keys",
"into",
"a",
"new",
"sorted",
"set",
"dest",
".",
"Scores",
"in",
"the",
"destination",
"will",
"be",
"aggregated",
"based",
"on",
"the",
"aggregate",
"or",
"SUM",
"if",
"none",
"is",
"provi... | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1790-L1799 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zscan | def zscan(self, name, cursor=0, match=None, count=None,
score_cast_func=float):
"""
Incrementally return lists of elements in a sorted set. Also return a
cursor indicating the scan position.
``match`` allows for filtering the members by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value
"""
with self.pipe as pipe:
f = Future()
res = pipe.zscan(self.redis_key(name), cursor=cursor,
match=match, count=count,
score_cast_func=score_cast_func)
def cb():
f.set((res[0], [(self.valueparse.decode(k), v)
for k, v in res[1]]))
pipe.on_execute(cb)
return f | python | def zscan(self, name, cursor=0, match=None, count=None,
score_cast_func=float):
"""
Incrementally return lists of elements in a sorted set. Also return a
cursor indicating the scan position.
``match`` allows for filtering the members by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value
"""
with self.pipe as pipe:
f = Future()
res = pipe.zscan(self.redis_key(name), cursor=cursor,
match=match, count=count,
score_cast_func=score_cast_func)
def cb():
f.set((res[0], [(self.valueparse.decode(k), v)
for k, v in res[1]]))
pipe.on_execute(cb)
return f | [
"def",
"zscan",
"(",
"self",
",",
"name",
",",
"cursor",
"=",
"0",
",",
"match",
"=",
"None",
",",
"count",
"=",
"None",
",",
"score_cast_func",
"=",
"float",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"(",
")",... | Incrementally return lists of elements in a sorted set. Also return a
cursor indicating the scan position.
``match`` allows for filtering the members by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value | [
"Incrementally",
"return",
"lists",
"of",
"elements",
"in",
"a",
"sorted",
"set",
".",
"Also",
"return",
"a",
"cursor",
"indicating",
"the",
"scan",
"position",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1801-L1824 |
72squared/redpipe | redpipe/keyspaces.py | SortedSet.zscan_iter | def zscan_iter(self, name, match=None, count=None,
score_cast_func=float):
"""
Make an iterator using the ZSCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value
"""
if self._pipe is not None:
raise InvalidOperation('cannot pipeline scan operations')
cursor = '0'
while cursor != 0:
cursor, data = self.zscan(name, cursor=cursor, match=match,
count=count,
score_cast_func=score_cast_func)
for item in data:
yield item | python | def zscan_iter(self, name, match=None, count=None,
score_cast_func=float):
"""
Make an iterator using the ZSCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value
"""
if self._pipe is not None:
raise InvalidOperation('cannot pipeline scan operations')
cursor = '0'
while cursor != 0:
cursor, data = self.zscan(name, cursor=cursor, match=match,
count=count,
score_cast_func=score_cast_func)
for item in data:
yield item | [
"def",
"zscan_iter",
"(",
"self",
",",
"name",
",",
"match",
"=",
"None",
",",
"count",
"=",
"None",
",",
"score_cast_func",
"=",
"float",
")",
":",
"if",
"self",
".",
"_pipe",
"is",
"not",
"None",
":",
"raise",
"InvalidOperation",
"(",
"'cannot pipeline... | Make an iterator using the ZSCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value | [
"Make",
"an",
"iterator",
"using",
"the",
"ZSCAN",
"command",
"so",
"that",
"the",
"client",
"doesn",
"t",
"need",
"to",
"remember",
"the",
"cursor",
"position",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1826-L1846 |
72squared/redpipe | redpipe/keyspaces.py | Hash._value_encode | def _value_encode(cls, member, value):
"""
Internal method used to encode values into the hash.
:param member: str
:param value: multi
:return: bytes
"""
try:
field_validator = cls.fields[member]
except KeyError:
return cls.valueparse.encode(value)
return field_validator.encode(value) | python | def _value_encode(cls, member, value):
"""
Internal method used to encode values into the hash.
:param member: str
:param value: multi
:return: bytes
"""
try:
field_validator = cls.fields[member]
except KeyError:
return cls.valueparse.encode(value)
return field_validator.encode(value) | [
"def",
"_value_encode",
"(",
"cls",
",",
"member",
",",
"value",
")",
":",
"try",
":",
"field_validator",
"=",
"cls",
".",
"fields",
"[",
"member",
"]",
"except",
"KeyError",
":",
"return",
"cls",
".",
"valueparse",
".",
"encode",
"(",
"value",
")",
"r... | Internal method used to encode values into the hash.
:param member: str
:param value: multi
:return: bytes | [
"Internal",
"method",
"used",
"to",
"encode",
"values",
"into",
"the",
"hash",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1859-L1872 |
72squared/redpipe | redpipe/keyspaces.py | Hash._value_decode | def _value_decode(cls, member, value):
"""
Internal method used to decode values from redis hash
:param member: str
:param value: bytes
:return: multi
"""
if value is None:
return None
try:
field_validator = cls.fields[member]
except KeyError:
return cls.valueparse.decode(value)
return field_validator.decode(value) | python | def _value_decode(cls, member, value):
"""
Internal method used to decode values from redis hash
:param member: str
:param value: bytes
:return: multi
"""
if value is None:
return None
try:
field_validator = cls.fields[member]
except KeyError:
return cls.valueparse.decode(value)
return field_validator.decode(value) | [
"def",
"_value_decode",
"(",
"cls",
",",
"member",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"try",
":",
"field_validator",
"=",
"cls",
".",
"fields",
"[",
"member",
"]",
"except",
"KeyError",
":",
"return",
"cls",
"."... | Internal method used to decode values from redis hash
:param member: str
:param value: bytes
:return: multi | [
"Internal",
"method",
"used",
"to",
"decode",
"values",
"from",
"redis",
"hash"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1875-L1890 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hlen | def hlen(self, name):
"""
Returns the number of elements in the Hash.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
return pipe.hlen(self.redis_key(name)) | python | def hlen(self, name):
"""
Returns the number of elements in the Hash.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
return pipe.hlen(self.redis_key(name)) | [
"def",
"hlen",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hlen",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
")"
] | Returns the number of elements in the Hash.
:param name: str the name of the redis key
:return: Future() | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"the",
"Hash",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1892-L1900 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hstrlen | def hstrlen(self, name, key):
"""
Return the number of bytes stored in the value of ``key``
within hash ``name``
"""
with self.pipe as pipe:
return pipe.hstrlen(self.redis_key(name), key) | python | def hstrlen(self, name, key):
"""
Return the number of bytes stored in the value of ``key``
within hash ``name``
"""
with self.pipe as pipe:
return pipe.hstrlen(self.redis_key(name), key) | [
"def",
"hstrlen",
"(",
"self",
",",
"name",
",",
"key",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hstrlen",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"key",
")"
] | Return the number of bytes stored in the value of ``key``
within hash ``name`` | [
"Return",
"the",
"number",
"of",
"bytes",
"stored",
"in",
"the",
"value",
"of",
"key",
"within",
"hash",
"name"
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1902-L1908 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hset | def hset(self, name, key, value):
"""
Set ``member`` in the Hash at ``value``.
:param name: str the name of the redis key
:param value:
:param key: the member of the hash key
:return: Future()
"""
with self.pipe as pipe:
value = self._value_encode(key, value)
key = self.memberparse.encode(key)
return pipe.hset(self.redis_key(name), key, value) | python | def hset(self, name, key, value):
"""
Set ``member`` in the Hash at ``value``.
:param name: str the name of the redis key
:param value:
:param key: the member of the hash key
:return: Future()
"""
with self.pipe as pipe:
value = self._value_encode(key, value)
key = self.memberparse.encode(key)
return pipe.hset(self.redis_key(name), key, value) | [
"def",
"hset",
"(",
"self",
",",
"name",
",",
"key",
",",
"value",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"value",
"=",
"self",
".",
"_value_encode",
"(",
"key",
",",
"value",
")",
"key",
"=",
"self",
".",
"memberparse",
".",
"... | Set ``member`` in the Hash at ``value``.
:param name: str the name of the redis key
:param value:
:param key: the member of the hash key
:return: Future() | [
"Set",
"member",
"in",
"the",
"Hash",
"at",
"value",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1910-L1922 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hdel | def hdel(self, name, *keys):
"""
Delete one or more hash field.
:param name: str the name of the redis key
:param keys: on or more members to remove from the key.
:return: Future()
"""
with self.pipe as pipe:
m_encode = self.memberparse.encode
keys = [m_encode(m) for m in self._parse_values(keys)]
return pipe.hdel(self.redis_key(name), *keys) | python | def hdel(self, name, *keys):
"""
Delete one or more hash field.
:param name: str the name of the redis key
:param keys: on or more members to remove from the key.
:return: Future()
"""
with self.pipe as pipe:
m_encode = self.memberparse.encode
keys = [m_encode(m) for m in self._parse_values(keys)]
return pipe.hdel(self.redis_key(name), *keys) | [
"def",
"hdel",
"(",
"self",
",",
"name",
",",
"*",
"keys",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"m_encode",
"=",
"self",
".",
"memberparse",
".",
"encode",
"keys",
"=",
"[",
"m_encode",
"(",
"m",
")",
"for",
"m",
"in",
"self"... | Delete one or more hash field.
:param name: str the name of the redis key
:param keys: on or more members to remove from the key.
:return: Future() | [
"Delete",
"one",
"or",
"more",
"hash",
"field",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1938-L1949 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hkeys | def hkeys(self, name):
"""
Returns all fields name in the Hash.
:param name: str the name of the redis key
:return: Future
"""
with self.pipe as pipe:
f = Future()
res = pipe.hkeys(self.redis_key(name))
def cb():
m_decode = self.memberparse.decode
f.set([m_decode(v) for v in res.result])
pipe.on_execute(cb)
return f | python | def hkeys(self, name):
"""
Returns all fields name in the Hash.
:param name: str the name of the redis key
:return: Future
"""
with self.pipe as pipe:
f = Future()
res = pipe.hkeys(self.redis_key(name))
def cb():
m_decode = self.memberparse.decode
f.set([m_decode(v) for v in res.result])
pipe.on_execute(cb)
return f | [
"def",
"hkeys",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"(",
")",
"res",
"=",
"pipe",
".",
"hkeys",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
")",
"def",
"cb",
"(",
")",
"... | Returns all fields name in the Hash.
:param name: str the name of the redis key
:return: Future | [
"Returns",
"all",
"fields",
"name",
"in",
"the",
"Hash",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1951-L1967 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hgetall | def hgetall(self, name):
"""
Returns all the fields and values in the Hash.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.hgetall(self.redis_key(name))
def cb():
data = {}
m_decode = self.memberparse.decode
v_decode = self._value_decode
for k, v in res.result.items():
k = m_decode(k)
v = v_decode(k, v)
data[k] = v
f.set(data)
pipe.on_execute(cb)
return f | python | def hgetall(self, name):
"""
Returns all the fields and values in the Hash.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.hgetall(self.redis_key(name))
def cb():
data = {}
m_decode = self.memberparse.decode
v_decode = self._value_decode
for k, v in res.result.items():
k = m_decode(k)
v = v_decode(k, v)
data[k] = v
f.set(data)
pipe.on_execute(cb)
return f | [
"def",
"hgetall",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"(",
")",
"res",
"=",
"pipe",
".",
"hgetall",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
")",
"def",
"cb",
"(",
")",... | Returns all the fields and values in the Hash.
:param name: str the name of the redis key
:return: Future() | [
"Returns",
"all",
"the",
"fields",
"and",
"values",
"in",
"the",
"Hash",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1969-L1991 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hget | def hget(self, name, key):
"""
Returns the value stored in the field, None if the field doesn't exist.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.hget(self.redis_key(name),
self.memberparse.encode(key))
def cb():
f.set(self._value_decode(key, res.result))
pipe.on_execute(cb)
return f | python | def hget(self, name, key):
"""
Returns the value stored in the field, None if the field doesn't exist.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.hget(self.redis_key(name),
self.memberparse.encode(key))
def cb():
f.set(self._value_decode(key, res.result))
pipe.on_execute(cb)
return f | [
"def",
"hget",
"(",
"self",
",",
"name",
",",
"key",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"(",
")",
"res",
"=",
"pipe",
".",
"hget",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"self",
".",
"... | Returns the value stored in the field, None if the field doesn't exist.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future() | [
"Returns",
"the",
"value",
"stored",
"in",
"the",
"field",
"None",
"if",
"the",
"field",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2012-L2029 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hexists | def hexists(self, name, key):
"""
Returns ``True`` if the field exists, ``False`` otherwise.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future()
"""
with self.pipe as pipe:
return pipe.hexists(self.redis_key(name),
self.memberparse.encode(key)) | python | def hexists(self, name, key):
"""
Returns ``True`` if the field exists, ``False`` otherwise.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future()
"""
with self.pipe as pipe:
return pipe.hexists(self.redis_key(name),
self.memberparse.encode(key)) | [
"def",
"hexists",
"(",
"self",
",",
"name",
",",
"key",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hexists",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"self",
".",
"memberparse",
".",
"encode",
"("... | Returns ``True`` if the field exists, ``False`` otherwise.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future() | [
"Returns",
"True",
"if",
"the",
"field",
"exists",
"False",
"otherwise",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2031-L2041 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hincrby | def hincrby(self, name, key, amount=1):
"""
Increment the value of the field.
:param name: str the name of the redis key
:param increment: int
:param field: str
:return: Future()
"""
with self.pipe as pipe:
return pipe.hincrby(self.redis_key(name),
self.memberparse.encode(key),
amount) | python | def hincrby(self, name, key, amount=1):
"""
Increment the value of the field.
:param name: str the name of the redis key
:param increment: int
:param field: str
:return: Future()
"""
with self.pipe as pipe:
return pipe.hincrby(self.redis_key(name),
self.memberparse.encode(key),
amount) | [
"def",
"hincrby",
"(",
"self",
",",
"name",
",",
"key",
",",
"amount",
"=",
"1",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hincrby",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"self",
".",
"membe... | Increment the value of the field.
:param name: str the name of the redis key
:param increment: int
:param field: str
:return: Future() | [
"Increment",
"the",
"value",
"of",
"the",
"field",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2043-L2055 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hmget | def hmget(self, name, keys, *args):
"""
Returns the values stored in the fields.
:param name: str the name of the redis key
:param fields:
:return: Future()
"""
member_encode = self.memberparse.encode
keys = [k for k in self._parse_values(keys, args)]
with self.pipe as pipe:
f = Future()
res = pipe.hmget(self.redis_key(name),
[member_encode(k) for k in keys])
def cb():
f.set([self._value_decode(keys[i], v)
for i, v in enumerate(res.result)])
pipe.on_execute(cb)
return f | python | def hmget(self, name, keys, *args):
"""
Returns the values stored in the fields.
:param name: str the name of the redis key
:param fields:
:return: Future()
"""
member_encode = self.memberparse.encode
keys = [k for k in self._parse_values(keys, args)]
with self.pipe as pipe:
f = Future()
res = pipe.hmget(self.redis_key(name),
[member_encode(k) for k in keys])
def cb():
f.set([self._value_decode(keys[i], v)
for i, v in enumerate(res.result)])
pipe.on_execute(cb)
return f | [
"def",
"hmget",
"(",
"self",
",",
"name",
",",
"keys",
",",
"*",
"args",
")",
":",
"member_encode",
"=",
"self",
".",
"memberparse",
".",
"encode",
"keys",
"=",
"[",
"k",
"for",
"k",
"in",
"self",
".",
"_parse_values",
"(",
"keys",
",",
"args",
")"... | Returns the values stored in the fields.
:param name: str the name of the redis key
:param fields:
:return: Future() | [
"Returns",
"the",
"values",
"stored",
"in",
"the",
"fields",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2071-L2091 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hmset | def hmset(self, name, mapping):
"""
Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future()
"""
with self.pipe as pipe:
m_encode = self.memberparse.encode
mapping = {m_encode(k): self._value_encode(k, v)
for k, v in mapping.items()}
return pipe.hmset(self.redis_key(name), mapping) | python | def hmset(self, name, mapping):
"""
Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future()
"""
with self.pipe as pipe:
m_encode = self.memberparse.encode
mapping = {m_encode(k): self._value_encode(k, v)
for k, v in mapping.items()}
return pipe.hmset(self.redis_key(name), mapping) | [
"def",
"hmset",
"(",
"self",
",",
"name",
",",
"mapping",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"m_encode",
"=",
"self",
".",
"memberparse",
".",
"encode",
"mapping",
"=",
"{",
"m_encode",
"(",
"k",
")",
":",
"self",
".",
"_valu... | Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future() | [
"Sets",
"or",
"updates",
"the",
"fields",
"with",
"their",
"corresponding",
"values",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2093-L2105 |
72squared/redpipe | redpipe/keyspaces.py | Hash.hscan | def hscan(self, name, cursor=0, match=None, count=None):
"""
Incrementally return key/value slices in a hash. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
with self.pipe as pipe:
f = Future()
res = pipe.hscan(self.redis_key(name), cursor=cursor,
match=match, count=count)
def cb():
data = {}
m_decode = self.memberparse.decode
for k, v in res[1].items():
k = m_decode(k)
v = self._value_decode(k, v)
data[k] = v
f.set((res[0], data))
pipe.on_execute(cb)
return f | python | def hscan(self, name, cursor=0, match=None, count=None):
"""
Incrementally return key/value slices in a hash. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
with self.pipe as pipe:
f = Future()
res = pipe.hscan(self.redis_key(name), cursor=cursor,
match=match, count=count)
def cb():
data = {}
m_decode = self.memberparse.decode
for k, v in res[1].items():
k = m_decode(k)
v = self._value_decode(k, v)
data[k] = v
f.set((res[0], data))
pipe.on_execute(cb)
return f | [
"def",
"hscan",
"(",
"self",
",",
"name",
",",
"cursor",
"=",
"0",
",",
"match",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"f",
"=",
"Future",
"(",
")",
"res",
"=",
"pipe",
".",
"hscan",
... | Incrementally return key/value slices in a hash. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns | [
"Incrementally",
"return",
"key",
"/",
"value",
"slices",
"in",
"a",
"hash",
".",
"Also",
"return",
"a",
"cursor",
"indicating",
"the",
"scan",
"position",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2107-L2132 |
72squared/redpipe | redpipe/keyspaces.py | HyperLogLog.pfcount | def pfcount(self, *sources):
"""
Return the approximated cardinality of
the set observed by the HyperLogLog at key(s).
Using the execute_command because redis-py-cluster disabled it
unnecessarily. but you can only send one key at a time in that case,
or only keys that map to the same keyslot.
Use at your own risk.
:param sources: [str] the names of the redis keys
"""
sources = [self.redis_key(s) for s in sources]
with self.pipe as pipe:
return pipe.execute_command('PFCOUNT', *sources) | python | def pfcount(self, *sources):
"""
Return the approximated cardinality of
the set observed by the HyperLogLog at key(s).
Using the execute_command because redis-py-cluster disabled it
unnecessarily. but you can only send one key at a time in that case,
or only keys that map to the same keyslot.
Use at your own risk.
:param sources: [str] the names of the redis keys
"""
sources = [self.redis_key(s) for s in sources]
with self.pipe as pipe:
return pipe.execute_command('PFCOUNT', *sources) | [
"def",
"pfcount",
"(",
"self",
",",
"*",
"sources",
")",
":",
"sources",
"=",
"[",
"self",
".",
"redis_key",
"(",
"s",
")",
"for",
"s",
"in",
"sources",
"]",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"execute_command",
... | Return the approximated cardinality of
the set observed by the HyperLogLog at key(s).
Using the execute_command because redis-py-cluster disabled it
unnecessarily. but you can only send one key at a time in that case,
or only keys that map to the same keyslot.
Use at your own risk.
:param sources: [str] the names of the redis keys | [
"Return",
"the",
"approximated",
"cardinality",
"of",
"the",
"set",
"observed",
"by",
"the",
"HyperLogLog",
"at",
"key",
"(",
"s",
")",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2170-L2184 |
72squared/redpipe | redpipe/keyspaces.py | HyperLogLog.pfmerge | def pfmerge(self, dest, *sources):
"""
Merge N different HyperLogLogs into a single one.
:param dest:
:param sources:
:return:
"""
sources = [self.redis_key(k) for k in sources]
with self.pipe as pipe:
return pipe.pfmerge(self.redis_key(dest), *sources) | python | def pfmerge(self, dest, *sources):
"""
Merge N different HyperLogLogs into a single one.
:param dest:
:param sources:
:return:
"""
sources = [self.redis_key(k) for k in sources]
with self.pipe as pipe:
return pipe.pfmerge(self.redis_key(dest), *sources) | [
"def",
"pfmerge",
"(",
"self",
",",
"dest",
",",
"*",
"sources",
")",
":",
"sources",
"=",
"[",
"self",
".",
"redis_key",
"(",
"k",
")",
"for",
"k",
"in",
"sources",
"]",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"pfm... | Merge N different HyperLogLogs into a single one.
:param dest:
:param sources:
:return: | [
"Merge",
"N",
"different",
"HyperLogLogs",
"into",
"a",
"single",
"one",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L2186-L2196 |
zenotech/MyCluster | mycluster/lsf.py | job_stats_enhanced | def job_stats_enhanced(job_id):
"""
Get full job and step stats for job_id
"""
stats_dict = {}
with os.popen('bjobs -o "jobid run_time cpu_used queue slots stat exit_code start_time estimated_start_time finish_time delimiter=\'|\'" -noheader ' + str(job_id)) as f:
try:
line = f.readline()
cols = line.split('|')
stats_dict['job_id'] = cols[0]
if cols[1] != '-':
stats_dict['wallclock'] = timedelta(
seconds=float(cols[1].split(' ')[0]))
if cols[2] != '-':
stats_dict['cpu'] = timedelta(
seconds=float(cols[2].split(' ')[0]))
stats_dict['queue'] = cols[3]
stats_dict['status'] = cols[5]
stats_dict['exit_code'] = cols[6]
stats_dict['start'] = cols[7]
stats_dict['start_time'] = cols[8]
if stats_dict['status'] in ['DONE', 'EXIT']:
stats_dict['end'] = cols[9]
steps = []
stats_dict['steps'] = steps
except:
with os.popen('bhist -l ' + str(job_id)) as f:
try:
output = f.readlines()
for line in output:
if "Done successfully" in line:
stats_dict['status'] = 'DONE'
return stats_dict
elif "Completed <exit>" in line:
stats_dict['status'] = 'EXIT'
return stats_dict
else:
stats_dict['status'] = 'UNKNOWN'
except Exception as e:
print(e)
print('LSF: Error reading job stats')
stats_dict['status'] = 'UNKNOWN'
return stats_dict | python | def job_stats_enhanced(job_id):
"""
Get full job and step stats for job_id
"""
stats_dict = {}
with os.popen('bjobs -o "jobid run_time cpu_used queue slots stat exit_code start_time estimated_start_time finish_time delimiter=\'|\'" -noheader ' + str(job_id)) as f:
try:
line = f.readline()
cols = line.split('|')
stats_dict['job_id'] = cols[0]
if cols[1] != '-':
stats_dict['wallclock'] = timedelta(
seconds=float(cols[1].split(' ')[0]))
if cols[2] != '-':
stats_dict['cpu'] = timedelta(
seconds=float(cols[2].split(' ')[0]))
stats_dict['queue'] = cols[3]
stats_dict['status'] = cols[5]
stats_dict['exit_code'] = cols[6]
stats_dict['start'] = cols[7]
stats_dict['start_time'] = cols[8]
if stats_dict['status'] in ['DONE', 'EXIT']:
stats_dict['end'] = cols[9]
steps = []
stats_dict['steps'] = steps
except:
with os.popen('bhist -l ' + str(job_id)) as f:
try:
output = f.readlines()
for line in output:
if "Done successfully" in line:
stats_dict['status'] = 'DONE'
return stats_dict
elif "Completed <exit>" in line:
stats_dict['status'] = 'EXIT'
return stats_dict
else:
stats_dict['status'] = 'UNKNOWN'
except Exception as e:
print(e)
print('LSF: Error reading job stats')
stats_dict['status'] = 'UNKNOWN'
return stats_dict | [
"def",
"job_stats_enhanced",
"(",
"job_id",
")",
":",
"stats_dict",
"=",
"{",
"}",
"with",
"os",
".",
"popen",
"(",
"'bjobs -o \"jobid run_time cpu_used queue slots stat exit_code start_time estimated_start_time finish_time delimiter=\\'|\\'\" -noheader '",
"+",
"str",
"(",
"... | Get full job and step stats for job_id | [
"Get",
"full",
"job",
"and",
"step",
"stats",
"for",
"job_id"
] | train | https://github.com/zenotech/MyCluster/blob/d2b7e35c57a515926e83bbc083d26930cd67e1bd/mycluster/lsf.py#L255-L298 |
rmed/pyemtmad | pyemtmad/wrapper.py | Wrapper.initialize | def initialize(self, emt_id, emt_pass):
"""Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon registration
emt_pass (str): Token given by the server upon registration
"""
self._emt_id = emt_id
self._emt_pass = emt_pass
# Initialize modules
self.bus = BusApi(self)
self.geo = GeoApi(self)
self.parking = ParkingApi(self) | python | def initialize(self, emt_id, emt_pass):
"""Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon registration
emt_pass (str): Token given by the server upon registration
"""
self._emt_id = emt_id
self._emt_pass = emt_pass
# Initialize modules
self.bus = BusApi(self)
self.geo = GeoApi(self)
self.parking = ParkingApi(self) | [
"def",
"initialize",
"(",
"self",
",",
"emt_id",
",",
"emt_pass",
")",
":",
"self",
".",
"_emt_id",
"=",
"emt_id",
"self",
".",
"_emt_pass",
"=",
"emt_pass",
"# Initialize modules",
"self",
".",
"bus",
"=",
"BusApi",
"(",
"self",
")",
"self",
".",
"geo",... | Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon registration
emt_pass (str): Token given by the server upon registration | [
"Manual",
"initialization",
"of",
"the",
"interface",
"attributes",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/wrapper.py#L95-L111 |
rmed/pyemtmad | pyemtmad/wrapper.py | Wrapper.request_openbus | def request_openbus(self, service, endpoint, **kwargs):
"""Make a request to the given endpoint of the ``openbus`` server.
This returns the plain JSON (dict) response which can then be parsed
using one of the implemented types.
Args:
service (str): Service to fetch ('bus' or 'geo').
endpoint (str): Endpoint to send the request to.
This string corresponds to the key in the ``ENDPOINTS`` dict.
**kwargs: Request arguments.
Returns:
Obtained response (dict) or None if the endpoint was not found.
"""
if service == 'bus':
endpoints = ENDPOINTS_BUS
elif service == 'geo':
endpoints = ENDPOINTS_GEO
else:
# Unknown service
return None
if endpoint not in endpoints:
# Unknown endpoint
return None
url = URL_OPENBUS + endpoints[endpoint]
# Append credentials to request
kwargs['idClient'] = self._emt_id
kwargs['passKey'] = self._emt_pass
# SSL verification fails...
# return requests.post(url, data=kwargs, verify=False).json()
return requests.post(url, data=kwargs, verify=True).json() | python | def request_openbus(self, service, endpoint, **kwargs):
"""Make a request to the given endpoint of the ``openbus`` server.
This returns the plain JSON (dict) response which can then be parsed
using one of the implemented types.
Args:
service (str): Service to fetch ('bus' or 'geo').
endpoint (str): Endpoint to send the request to.
This string corresponds to the key in the ``ENDPOINTS`` dict.
**kwargs: Request arguments.
Returns:
Obtained response (dict) or None if the endpoint was not found.
"""
if service == 'bus':
endpoints = ENDPOINTS_BUS
elif service == 'geo':
endpoints = ENDPOINTS_GEO
else:
# Unknown service
return None
if endpoint not in endpoints:
# Unknown endpoint
return None
url = URL_OPENBUS + endpoints[endpoint]
# Append credentials to request
kwargs['idClient'] = self._emt_id
kwargs['passKey'] = self._emt_pass
# SSL verification fails...
# return requests.post(url, data=kwargs, verify=False).json()
return requests.post(url, data=kwargs, verify=True).json() | [
"def",
"request_openbus",
"(",
"self",
",",
"service",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"service",
"==",
"'bus'",
":",
"endpoints",
"=",
"ENDPOINTS_BUS",
"elif",
"service",
"==",
"'geo'",
":",
"endpoints",
"=",
"ENDPOINTS_GEO",
"el... | Make a request to the given endpoint of the ``openbus`` server.
This returns the plain JSON (dict) response which can then be parsed
using one of the implemented types.
Args:
service (str): Service to fetch ('bus' or 'geo').
endpoint (str): Endpoint to send the request to.
This string corresponds to the key in the ``ENDPOINTS`` dict.
**kwargs: Request arguments.
Returns:
Obtained response (dict) or None if the endpoint was not found. | [
"Make",
"a",
"request",
"to",
"the",
"given",
"endpoint",
"of",
"the",
"openbus",
"server",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/wrapper.py#L113-L150 |
rmed/pyemtmad | pyemtmad/wrapper.py | Wrapper.request_parking | def request_parking(self, endpoint, url_args={}, **kwargs):
"""Make a request to the given endpoint of the ``parking`` server.
This returns the plain JSON (dict) response which can then be parsed
using one of the implemented types.
Args:
endpoint (str): Endpoint to send the request to.
This string corresponds to the key in the ``ENDPOINTS`` dict.
url_args (dict): Dictionary for URL string replacements.
**kwargs: Request arguments.
Returns:
Obtained response (dict) or None if the endpoint was not found.
"""
if endpoint not in ENDPOINTS_PARKING:
# Unknown endpoint
return None
url = URL_OPENBUS + ENDPOINTS_PARKING[endpoint]
# Append additional info to URL
lang = url_args.get('lang', 'ES')
address = url_args.get('address', '')
url = url.format(
id_client=self._emt_id,
passkey=self._emt_pass,
address=address,
lang=lang
)
# This server uses TLSv1
return _parking_req.post(url, data=kwargs).json() | python | def request_parking(self, endpoint, url_args={}, **kwargs):
"""Make a request to the given endpoint of the ``parking`` server.
This returns the plain JSON (dict) response which can then be parsed
using one of the implemented types.
Args:
endpoint (str): Endpoint to send the request to.
This string corresponds to the key in the ``ENDPOINTS`` dict.
url_args (dict): Dictionary for URL string replacements.
**kwargs: Request arguments.
Returns:
Obtained response (dict) or None if the endpoint was not found.
"""
if endpoint not in ENDPOINTS_PARKING:
# Unknown endpoint
return None
url = URL_OPENBUS + ENDPOINTS_PARKING[endpoint]
# Append additional info to URL
lang = url_args.get('lang', 'ES')
address = url_args.get('address', '')
url = url.format(
id_client=self._emt_id,
passkey=self._emt_pass,
address=address,
lang=lang
)
# This server uses TLSv1
return _parking_req.post(url, data=kwargs).json() | [
"def",
"request_parking",
"(",
"self",
",",
"endpoint",
",",
"url_args",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"endpoint",
"not",
"in",
"ENDPOINTS_PARKING",
":",
"# Unknown endpoint",
"return",
"None",
"url",
"=",
"URL_OPENBUS",
"+",
"END... | Make a request to the given endpoint of the ``parking`` server.
This returns the plain JSON (dict) response which can then be parsed
using one of the implemented types.
Args:
endpoint (str): Endpoint to send the request to.
This string corresponds to the key in the ``ENDPOINTS`` dict.
url_args (dict): Dictionary for URL string replacements.
**kwargs: Request arguments.
Returns:
Obtained response (dict) or None if the endpoint was not found. | [
"Make",
"a",
"request",
"to",
"the",
"given",
"endpoint",
"of",
"the",
"parking",
"server",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/wrapper.py#L152-L185 |
twisted/mantissa | xmantissa/search.py | parseSearchTerm | def parseSearchTerm(term):
"""
Turn a string search query into a two-tuple of a search term and a
dictionary of search keywords.
"""
terms = []
keywords = {}
for word in term.split():
if word.count(':') == 1:
k, v = word.split(u':')
if k and v:
keywords[k] = v
elif k or v:
terms.append(k or v)
else:
terms.append(word)
term = u' '.join(terms)
if keywords:
return term, keywords
return term, None | python | def parseSearchTerm(term):
"""
Turn a string search query into a two-tuple of a search term and a
dictionary of search keywords.
"""
terms = []
keywords = {}
for word in term.split():
if word.count(':') == 1:
k, v = word.split(u':')
if k and v:
keywords[k] = v
elif k or v:
terms.append(k or v)
else:
terms.append(word)
term = u' '.join(terms)
if keywords:
return term, keywords
return term, None | [
"def",
"parseSearchTerm",
"(",
"term",
")",
":",
"terms",
"=",
"[",
"]",
"keywords",
"=",
"{",
"}",
"for",
"word",
"in",
"term",
".",
"split",
"(",
")",
":",
"if",
"word",
".",
"count",
"(",
"':'",
")",
"==",
"1",
":",
"k",
",",
"v",
"=",
"wo... | Turn a string search query into a two-tuple of a search term and a
dictionary of search keywords. | [
"Turn",
"a",
"string",
"search",
"query",
"into",
"a",
"two",
"-",
"tuple",
"of",
"a",
"search",
"term",
"and",
"a",
"dictionary",
"of",
"search",
"keywords",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/search.py#L97-L116 |
twisted/mantissa | axiom/plugins/mantissacmd.py | gtpswd | def gtpswd(prompt, confirmPassword):
"""
Temporary wrapper for Twisted's getPassword until a version that supports
customizing the 'confirm' prompt is released.
"""
try:
return util.getPassword(prompt=prompt,
confirmPrompt=confirmPassword,
confirm=True)
except TypeError:
return util.getPassword(prompt=prompt,
confirm=True) | python | def gtpswd(prompt, confirmPassword):
"""
Temporary wrapper for Twisted's getPassword until a version that supports
customizing the 'confirm' prompt is released.
"""
try:
return util.getPassword(prompt=prompt,
confirmPrompt=confirmPassword,
confirm=True)
except TypeError:
return util.getPassword(prompt=prompt,
confirm=True) | [
"def",
"gtpswd",
"(",
"prompt",
",",
"confirmPassword",
")",
":",
"try",
":",
"return",
"util",
".",
"getPassword",
"(",
"prompt",
"=",
"prompt",
",",
"confirmPrompt",
"=",
"confirmPassword",
",",
"confirm",
"=",
"True",
")",
"except",
"TypeError",
":",
"r... | Temporary wrapper for Twisted's getPassword until a version that supports
customizing the 'confirm' prompt is released. | [
"Temporary",
"wrapper",
"for",
"Twisted",
"s",
"getPassword",
"until",
"a",
"version",
"that",
"supports",
"customizing",
"the",
"confirm",
"prompt",
"is",
"released",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/axiom/plugins/mantissacmd.py#L42-L53 |
twisted/mantissa | axiom/plugins/mantissacmd.py | Mantissa._createCert | def _createCert(self, hostname, serial):
"""
Create a self-signed X.509 certificate.
@type hostname: L{unicode}
@param hostname: The hostname this certificate should be valid for.
@type serial: L{int}
@param serial: The serial number the certificate should have.
@rtype: L{bytes}
@return: The serialized certificate in PEM format.
"""
privateKey = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend())
publicKey = privateKey.public_key()
name = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, hostname)])
certificate = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.not_valid_before(datetime.today() - timedelta(days=1))
.not_valid_after(datetime.today() + timedelta(days=365))
.serial_number(serial)
.public_key(publicKey)
.add_extension(
x509.BasicConstraints(ca=False, path_length=None),
critical=True)
.add_extension(
x509.SubjectAlternativeName([
x509.DNSName(hostname)]),
critical=False)
.add_extension(
x509.KeyUsage(
digital_signature=True,
content_commitment=False,
key_encipherment=True,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False),
critical=True)
.add_extension(
x509.ExtendedKeyUsage([
ExtendedKeyUsageOID.SERVER_AUTH]),
critical=False)
.sign(
private_key=privateKey,
algorithm=hashes.SHA256(),
backend=default_backend()))
return '\n'.join([
privateKey.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()),
certificate.public_bytes(
encoding=serialization.Encoding.PEM),
]) | python | def _createCert(self, hostname, serial):
"""
Create a self-signed X.509 certificate.
@type hostname: L{unicode}
@param hostname: The hostname this certificate should be valid for.
@type serial: L{int}
@param serial: The serial number the certificate should have.
@rtype: L{bytes}
@return: The serialized certificate in PEM format.
"""
privateKey = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend())
publicKey = privateKey.public_key()
name = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, hostname)])
certificate = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.not_valid_before(datetime.today() - timedelta(days=1))
.not_valid_after(datetime.today() + timedelta(days=365))
.serial_number(serial)
.public_key(publicKey)
.add_extension(
x509.BasicConstraints(ca=False, path_length=None),
critical=True)
.add_extension(
x509.SubjectAlternativeName([
x509.DNSName(hostname)]),
critical=False)
.add_extension(
x509.KeyUsage(
digital_signature=True,
content_commitment=False,
key_encipherment=True,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False),
critical=True)
.add_extension(
x509.ExtendedKeyUsage([
ExtendedKeyUsageOID.SERVER_AUTH]),
critical=False)
.sign(
private_key=privateKey,
algorithm=hashes.SHA256(),
backend=default_backend()))
return '\n'.join([
privateKey.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()),
certificate.public_bytes(
encoding=serialization.Encoding.PEM),
]) | [
"def",
"_createCert",
"(",
"self",
",",
"hostname",
",",
"serial",
")",
":",
"privateKey",
"=",
"rsa",
".",
"generate_private_key",
"(",
"public_exponent",
"=",
"65537",
",",
"key_size",
"=",
"2048",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"... | Create a self-signed X.509 certificate.
@type hostname: L{unicode}
@param hostname: The hostname this certificate should be valid for.
@type serial: L{int}
@param serial: The serial number the certificate should have.
@rtype: L{bytes}
@return: The serialized certificate in PEM format. | [
"Create",
"a",
"self",
"-",
"signed",
"X",
".",
"509",
"certificate",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/axiom/plugins/mantissacmd.py#L141-L203 |
twisted/mantissa | axiom/plugins/mantissacmd.py | Mantissa.installSite | def installSite(self, siteStore, domain, publicURL, generateCert=True):
"""
Create the necessary items to run an HTTP server and an SSH server.
"""
certPath = siteStore.filesdir.child("server.pem")
if generateCert and not certPath.exists():
certPath.setContent(self._createCert(domain, genSerial()))
# Install the base Mantissa offering.
IOfferingTechnician(siteStore).installOffering(baseOffering)
# Make the HTTP server baseOffering includes listen somewhere.
site = siteStore.findUnique(SiteConfiguration)
site.hostname = domain
installOn(
TCPPort(store=siteStore, factory=site, portNumber=8080),
siteStore)
installOn(
SSLPort(store=siteStore, factory=site, portNumber=8443,
certificatePath=certPath),
siteStore)
# Make the SSH server baseOffering includes listen somewhere.
shell = siteStore.findUnique(SecureShellConfiguration)
installOn(
TCPPort(store=siteStore, factory=shell, portNumber=8022),
siteStore)
# Install a front page on the top level store so that the
# developer will have something to look at when they start up
# the server.
fp = siteStore.findOrCreate(publicweb.FrontPage, prefixURL=u'')
installOn(fp, siteStore) | python | def installSite(self, siteStore, domain, publicURL, generateCert=True):
"""
Create the necessary items to run an HTTP server and an SSH server.
"""
certPath = siteStore.filesdir.child("server.pem")
if generateCert and not certPath.exists():
certPath.setContent(self._createCert(domain, genSerial()))
# Install the base Mantissa offering.
IOfferingTechnician(siteStore).installOffering(baseOffering)
# Make the HTTP server baseOffering includes listen somewhere.
site = siteStore.findUnique(SiteConfiguration)
site.hostname = domain
installOn(
TCPPort(store=siteStore, factory=site, portNumber=8080),
siteStore)
installOn(
SSLPort(store=siteStore, factory=site, portNumber=8443,
certificatePath=certPath),
siteStore)
# Make the SSH server baseOffering includes listen somewhere.
shell = siteStore.findUnique(SecureShellConfiguration)
installOn(
TCPPort(store=siteStore, factory=shell, portNumber=8022),
siteStore)
# Install a front page on the top level store so that the
# developer will have something to look at when they start up
# the server.
fp = siteStore.findOrCreate(publicweb.FrontPage, prefixURL=u'')
installOn(fp, siteStore) | [
"def",
"installSite",
"(",
"self",
",",
"siteStore",
",",
"domain",
",",
"publicURL",
",",
"generateCert",
"=",
"True",
")",
":",
"certPath",
"=",
"siteStore",
".",
"filesdir",
".",
"child",
"(",
"\"server.pem\"",
")",
"if",
"generateCert",
"and",
"not",
"... | Create the necessary items to run an HTTP server and an SSH server. | [
"Create",
"the",
"necessary",
"items",
"to",
"run",
"an",
"HTTP",
"server",
"and",
"an",
"SSH",
"server",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/axiom/plugins/mantissacmd.py#L206-L238 |
jwodder/doapi | doapi/tag.py | Tag.fetch | def fetch(self):
"""
Fetch & return a new `Tag` object representing the tag's current state
:rtype: Tag
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the tag no longer exists)
"""
api = self.doapi_manager
return api._tag(api.request(self.url)["tag"]) | python | def fetch(self):
"""
Fetch & return a new `Tag` object representing the tag's current state
:rtype: Tag
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the tag no longer exists)
"""
api = self.doapi_manager
return api._tag(api.request(self.url)["tag"]) | [
"def",
"fetch",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"doapi_manager",
"return",
"api",
".",
"_tag",
"(",
"api",
".",
"request",
"(",
"self",
".",
"url",
")",
"[",
"\"tag\"",
"]",
")"
] | Fetch & return a new `Tag` object representing the tag's current state
:rtype: Tag
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the tag no longer exists) | [
"Fetch",
"&",
"return",
"a",
"new",
"Tag",
"object",
"representing",
"the",
"tag",
"s",
"current",
"state"
] | train | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/tag.py#L54-L63 |
jwodder/doapi | doapi/tag.py | Tag.update_tag | def update_tag(self, name):
# The `_tag` is to avoid conflicts with MutableMapping.update.
"""
Update (i.e., rename) the tag
:param str name: the new name for the tag
:return: an updated `Tag` object
:rtype: Tag
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return api._tag(api.request(self.url, method='PUT',
data={"name": name})["tag"]) | python | def update_tag(self, name):
# The `_tag` is to avoid conflicts with MutableMapping.update.
"""
Update (i.e., rename) the tag
:param str name: the new name for the tag
:return: an updated `Tag` object
:rtype: Tag
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return api._tag(api.request(self.url, method='PUT',
data={"name": name})["tag"]) | [
"def",
"update_tag",
"(",
"self",
",",
"name",
")",
":",
"# The `_tag` is to avoid conflicts with MutableMapping.update.",
"api",
"=",
"self",
".",
"doapi_manager",
"return",
"api",
".",
"_tag",
"(",
"api",
".",
"request",
"(",
"self",
".",
"url",
",",
"method",... | Update (i.e., rename) the tag
:param str name: the new name for the tag
:return: an updated `Tag` object
:rtype: Tag
:raises DOAPIError: if the API endpoint replies with an error | [
"Update",
"(",
"i",
".",
"e",
".",
"rename",
")",
"the",
"tag"
] | train | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/tag.py#L69-L81 |
jwodder/doapi | doapi/tag.py | Tag.add | def add(self, *resources):
"""
Apply the tag to one or more resources
:param resources: one or more `Resource` objects to which tags can be
applied
:return: `None`
:raises DOAPIError: if the API endpoint replies with an error
"""
self.doapi_manager.request(self.url + '/resources', method='POST',
data={"resources": _to_taggable(resources)}) | python | def add(self, *resources):
"""
Apply the tag to one or more resources
:param resources: one or more `Resource` objects to which tags can be
applied
:return: `None`
:raises DOAPIError: if the API endpoint replies with an error
"""
self.doapi_manager.request(self.url + '/resources', method='POST',
data={"resources": _to_taggable(resources)}) | [
"def",
"add",
"(",
"self",
",",
"*",
"resources",
")",
":",
"self",
".",
"doapi_manager",
".",
"request",
"(",
"self",
".",
"url",
"+",
"'/resources'",
",",
"method",
"=",
"'POST'",
",",
"data",
"=",
"{",
"\"resources\"",
":",
"_to_taggable",
"(",
"res... | Apply the tag to one or more resources
:param resources: one or more `Resource` objects to which tags can be
applied
:return: `None`
:raises DOAPIError: if the API endpoint replies with an error | [
"Apply",
"the",
"tag",
"to",
"one",
"or",
"more",
"resources"
] | train | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/tag.py#L92-L102 |
jwodder/doapi | doapi/tag.py | Tag.act_on_droplets | def act_on_droplets(self, **data):
r"""
Perform an arbitrary action on all of the droplets to which the tag is
applied. ``data`` will be serialized as JSON and POSTed to the proper
API endpoint. All currently-documented actions require the POST body
to be a JSON object containing, at a minimum, a ``"type"`` field.
:return: a generator of `Action`\ s representing the in-progress
operations on the droplets
:rtype: generator of `Action`\ s
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return map(api._action, api.request('/v2/droplets/actions', method='POST', params={"tag_name": self.name}, data=data)["actions"]) | python | def act_on_droplets(self, **data):
r"""
Perform an arbitrary action on all of the droplets to which the tag is
applied. ``data`` will be serialized as JSON and POSTed to the proper
API endpoint. All currently-documented actions require the POST body
to be a JSON object containing, at a minimum, a ``"type"`` field.
:return: a generator of `Action`\ s representing the in-progress
operations on the droplets
:rtype: generator of `Action`\ s
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return map(api._action, api.request('/v2/droplets/actions', method='POST', params={"tag_name": self.name}, data=data)["actions"]) | [
"def",
"act_on_droplets",
"(",
"self",
",",
"*",
"*",
"data",
")",
":",
"api",
"=",
"self",
".",
"doapi_manager",
"return",
"map",
"(",
"api",
".",
"_action",
",",
"api",
".",
"request",
"(",
"'/v2/droplets/actions'",
",",
"method",
"=",
"'POST'",
",",
... | r"""
Perform an arbitrary action on all of the droplets to which the tag is
applied. ``data`` will be serialized as JSON and POSTed to the proper
API endpoint. All currently-documented actions require the POST body
to be a JSON object containing, at a minimum, a ``"type"`` field.
:return: a generator of `Action`\ s representing the in-progress
operations on the droplets
:rtype: generator of `Action`\ s
:raises DOAPIError: if the API endpoint replies with an error | [
"r",
"Perform",
"an",
"arbitrary",
"action",
"on",
"all",
"of",
"the",
"droplets",
"to",
"which",
"the",
"tag",
"is",
"applied",
".",
"data",
"will",
"be",
"serialized",
"as",
"JSON",
"and",
"POSTed",
"to",
"the",
"proper",
"API",
"endpoint",
".",
"All",... | train | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/tag.py#L136-L149 |
typlog/sphinx-typlog-theme | sphinx_typlog_theme/__init__.py | add_badge_roles | def add_badge_roles(app):
"""Add ``badge`` role to your sphinx documents. It can create
a colorful badge inline.
"""
from docutils.nodes import inline, make_id
from docutils.parsers.rst.roles import set_classes
def create_badge_role(color=None):
def badge_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
options = options or {}
set_classes(options)
classes = ['badge']
if color is None:
classes.append('badge-' + make_id(text))
else:
classes.append('badge-' + color)
if len(text) == 1:
classes.append('badge-one')
options['classes'] = classes
node = inline(rawtext, text, **options)
return [node], []
return badge_role
app.add_role('badge', create_badge_role())
app.add_role('badge-red', create_badge_role('red'))
app.add_role('badge-blue', create_badge_role('blue'))
app.add_role('badge-green', create_badge_role('green'))
app.add_role('badge-yellow', create_badge_role('yellow')) | python | def add_badge_roles(app):
"""Add ``badge`` role to your sphinx documents. It can create
a colorful badge inline.
"""
from docutils.nodes import inline, make_id
from docutils.parsers.rst.roles import set_classes
def create_badge_role(color=None):
def badge_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
options = options or {}
set_classes(options)
classes = ['badge']
if color is None:
classes.append('badge-' + make_id(text))
else:
classes.append('badge-' + color)
if len(text) == 1:
classes.append('badge-one')
options['classes'] = classes
node = inline(rawtext, text, **options)
return [node], []
return badge_role
app.add_role('badge', create_badge_role())
app.add_role('badge-red', create_badge_role('red'))
app.add_role('badge-blue', create_badge_role('blue'))
app.add_role('badge-green', create_badge_role('green'))
app.add_role('badge-yellow', create_badge_role('yellow')) | [
"def",
"add_badge_roles",
"(",
"app",
")",
":",
"from",
"docutils",
".",
"nodes",
"import",
"inline",
",",
"make_id",
"from",
"docutils",
".",
"parsers",
".",
"rst",
".",
"roles",
"import",
"set_classes",
"def",
"create_badge_role",
"(",
"color",
"=",
"None"... | Add ``badge`` role to your sphinx documents. It can create
a colorful badge inline. | [
"Add",
"badge",
"role",
"to",
"your",
"sphinx",
"documents",
".",
"It",
"can",
"create",
"a",
"colorful",
"badge",
"inline",
"."
] | train | https://github.com/typlog/sphinx-typlog-theme/blob/25e26fbbf406da82d842a5ee995aa177be931340/sphinx_typlog_theme/__init__.py#L19-L47 |
typlog/sphinx-typlog-theme | sphinx_typlog_theme/__init__.py | add_github_roles | def add_github_roles(app, repo):
"""Add ``gh`` role to your sphinx documents. It can generate GitHub
links easily::
:gh:`issue#57` will generate the issue link
:gh:`PR#85` will generate the pull request link
Use this function in ``conf.py`` to enable this feature::
def setup(app):
sphinx_typlog_theme.add_github_roles(app, 'lepture/authlib')
:param app: sphinx app
:param repo: GitHub repo, e.g. "lepture/authlib"
"""
from docutils.nodes import reference
from docutils.parsers.rst.roles import set_classes
base_url = 'https://github.com/{}'.format(repo)
def github_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
if '#' in text:
t, n = text.split('#', 1)
if t.lower() in ['issue', 'issues']:
url = base_url + '/issues/{}'.format(n)
elif t.lower() in ['pr', 'pull', 'pull request']:
url = base_url + '/pull/{}'.format(n)
elif t.lower() in ['commit', 'commits']:
url = base_url + '/commit/{}'.format(n)
else:
url = base_url + '/' + text
options = options or {'classes': ['gh']}
set_classes(options)
node = reference(rawtext, text, refuri=url, **options)
return [node], []
app.add_role('gh', github_role) | python | def add_github_roles(app, repo):
"""Add ``gh`` role to your sphinx documents. It can generate GitHub
links easily::
:gh:`issue#57` will generate the issue link
:gh:`PR#85` will generate the pull request link
Use this function in ``conf.py`` to enable this feature::
def setup(app):
sphinx_typlog_theme.add_github_roles(app, 'lepture/authlib')
:param app: sphinx app
:param repo: GitHub repo, e.g. "lepture/authlib"
"""
from docutils.nodes import reference
from docutils.parsers.rst.roles import set_classes
base_url = 'https://github.com/{}'.format(repo)
def github_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
if '#' in text:
t, n = text.split('#', 1)
if t.lower() in ['issue', 'issues']:
url = base_url + '/issues/{}'.format(n)
elif t.lower() in ['pr', 'pull', 'pull request']:
url = base_url + '/pull/{}'.format(n)
elif t.lower() in ['commit', 'commits']:
url = base_url + '/commit/{}'.format(n)
else:
url = base_url + '/' + text
options = options or {'classes': ['gh']}
set_classes(options)
node = reference(rawtext, text, refuri=url, **options)
return [node], []
app.add_role('gh', github_role) | [
"def",
"add_github_roles",
"(",
"app",
",",
"repo",
")",
":",
"from",
"docutils",
".",
"nodes",
"import",
"reference",
"from",
"docutils",
".",
"parsers",
".",
"rst",
".",
"roles",
"import",
"set_classes",
"base_url",
"=",
"'https://github.com/{}'",
".",
"form... | Add ``gh`` role to your sphinx documents. It can generate GitHub
links easily::
:gh:`issue#57` will generate the issue link
:gh:`PR#85` will generate the pull request link
Use this function in ``conf.py`` to enable this feature::
def setup(app):
sphinx_typlog_theme.add_github_roles(app, 'lepture/authlib')
:param app: sphinx app
:param repo: GitHub repo, e.g. "lepture/authlib" | [
"Add",
"gh",
"role",
"to",
"your",
"sphinx",
"documents",
".",
"It",
"can",
"generate",
"GitHub",
"links",
"easily",
"::"
] | train | https://github.com/typlog/sphinx-typlog-theme/blob/25e26fbbf406da82d842a5ee995aa177be931340/sphinx_typlog_theme/__init__.py#L50-L88 |
72squared/redpipe | redpipe/tasks.py | TaskManager.promise | def promise(cls, fn, *args, **kwargs):
"""
Used to build a task based on a callable function and the arguments.
Kick it off and start execution of the task.
:param fn: callable
:param args: tuple
:param kwargs: dict
:return: SynchronousTask or AsynchronousTask
"""
task = cls.task(target=fn, args=args, kwargs=kwargs)
task.start()
return task | python | def promise(cls, fn, *args, **kwargs):
"""
Used to build a task based on a callable function and the arguments.
Kick it off and start execution of the task.
:param fn: callable
:param args: tuple
:param kwargs: dict
:return: SynchronousTask or AsynchronousTask
"""
task = cls.task(target=fn, args=args, kwargs=kwargs)
task.start()
return task | [
"def",
"promise",
"(",
"cls",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"task",
"=",
"cls",
".",
"task",
"(",
"target",
"=",
"fn",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"task",
".",
"start",
"(",
"... | Used to build a task based on a callable function and the arguments.
Kick it off and start execution of the task.
:param fn: callable
:param args: tuple
:param kwargs: dict
:return: SynchronousTask or AsynchronousTask | [
"Used",
"to",
"build",
"a",
"task",
"based",
"on",
"a",
"callable",
"function",
"and",
"the",
"arguments",
".",
"Kick",
"it",
"off",
"and",
"start",
"execution",
"of",
"the",
"task",
"."
] | train | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/tasks.py#L112-L124 |
twisted/mantissa | xmantissa/sharing.py | _interfacesToNames | def _interfacesToNames(interfaces):
"""
Convert from a list of interfaces to a unicode string of names suitable for
storage in the database.
@param interfaces: an iterable of Interface objects.
@return: a unicode string, a comma-separated list of names of interfaces.
@raise ConflictingNames: if any of the names conflict: see
L{_checkConflictingNames}.
"""
if interfaces is ALL_IMPLEMENTED:
names = ALL_IMPLEMENTED_DB
else:
_checkConflictingNames(interfaces)
names = u','.join(map(qual, interfaces))
return names | python | def _interfacesToNames(interfaces):
"""
Convert from a list of interfaces to a unicode string of names suitable for
storage in the database.
@param interfaces: an iterable of Interface objects.
@return: a unicode string, a comma-separated list of names of interfaces.
@raise ConflictingNames: if any of the names conflict: see
L{_checkConflictingNames}.
"""
if interfaces is ALL_IMPLEMENTED:
names = ALL_IMPLEMENTED_DB
else:
_checkConflictingNames(interfaces)
names = u','.join(map(qual, interfaces))
return names | [
"def",
"_interfacesToNames",
"(",
"interfaces",
")",
":",
"if",
"interfaces",
"is",
"ALL_IMPLEMENTED",
":",
"names",
"=",
"ALL_IMPLEMENTED_DB",
"else",
":",
"_checkConflictingNames",
"(",
"interfaces",
")",
"names",
"=",
"u','",
".",
"join",
"(",
"map",
"(",
"... | Convert from a list of interfaces to a unicode string of names suitable for
storage in the database.
@param interfaces: an iterable of Interface objects.
@return: a unicode string, a comma-separated list of names of interfaces.
@raise ConflictingNames: if any of the names conflict: see
L{_checkConflictingNames}. | [
"Convert",
"from",
"a",
"list",
"of",
"interfaces",
"to",
"a",
"unicode",
"string",
"of",
"names",
"suitable",
"for",
"storage",
"in",
"the",
"database",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L470-L487 |
twisted/mantissa | xmantissa/sharing.py | upgradeShare1to2 | def upgradeShare1to2(oldShare):
"Upgrader from Share version 1 to version 2."
sharedInterfaces = []
attrs = set(oldShare.sharedAttributeNames.split(u','))
for iface in implementedBy(oldShare.sharedItem.__class__):
if set(iface) == attrs or attrs == set('*'):
sharedInterfaces.append(iface)
newShare = oldShare.upgradeVersion('sharing_share', 1, 2,
shareID=oldShare.shareID,
sharedItem=oldShare.sharedItem,
sharedTo=oldShare.sharedTo,
sharedInterfaces=sharedInterfaces)
return newShare | python | def upgradeShare1to2(oldShare):
"Upgrader from Share version 1 to version 2."
sharedInterfaces = []
attrs = set(oldShare.sharedAttributeNames.split(u','))
for iface in implementedBy(oldShare.sharedItem.__class__):
if set(iface) == attrs or attrs == set('*'):
sharedInterfaces.append(iface)
newShare = oldShare.upgradeVersion('sharing_share', 1, 2,
shareID=oldShare.shareID,
sharedItem=oldShare.sharedItem,
sharedTo=oldShare.sharedTo,
sharedInterfaces=sharedInterfaces)
return newShare | [
"def",
"upgradeShare1to2",
"(",
"oldShare",
")",
":",
"sharedInterfaces",
"=",
"[",
"]",
"attrs",
"=",
"set",
"(",
"oldShare",
".",
"sharedAttributeNames",
".",
"split",
"(",
"u','",
")",
")",
"for",
"iface",
"in",
"implementedBy",
"(",
"oldShare",
".",
"s... | Upgrader from Share version 1 to version 2. | [
"Upgrader",
"from",
"Share",
"version",
"1",
"to",
"version",
"2",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L576-L589 |
twisted/mantissa | xmantissa/sharing.py | getAuthenticatedRole | def getAuthenticatedRole(store):
"""
Get the base 'Authenticated' role for this store, which is the role that is
given to every user who is explicitly identified by a non-anonymous
username.
"""
def tx():
def addToEveryone(newAuthenticatedRole):
newAuthenticatedRole.becomeMemberOf(getEveryoneRole(store))
return newAuthenticatedRole
return store.findOrCreate(Role, addToEveryone, externalID=u'Authenticated')
return store.transact(tx) | python | def getAuthenticatedRole(store):
"""
Get the base 'Authenticated' role for this store, which is the role that is
given to every user who is explicitly identified by a non-anonymous
username.
"""
def tx():
def addToEveryone(newAuthenticatedRole):
newAuthenticatedRole.becomeMemberOf(getEveryoneRole(store))
return newAuthenticatedRole
return store.findOrCreate(Role, addToEveryone, externalID=u'Authenticated')
return store.transact(tx) | [
"def",
"getAuthenticatedRole",
"(",
"store",
")",
":",
"def",
"tx",
"(",
")",
":",
"def",
"addToEveryone",
"(",
"newAuthenticatedRole",
")",
":",
"newAuthenticatedRole",
".",
"becomeMemberOf",
"(",
"getEveryoneRole",
"(",
"store",
")",
")",
"return",
"newAuthent... | Get the base 'Authenticated' role for this store, which is the role that is
given to every user who is explicitly identified by a non-anonymous
username. | [
"Get",
"the",
"base",
"Authenticated",
"role",
"for",
"this",
"store",
"which",
"is",
"the",
"role",
"that",
"is",
"given",
"to",
"every",
"user",
"who",
"is",
"explicitly",
"identified",
"by",
"a",
"non",
"-",
"anonymous",
"username",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L618-L629 |
twisted/mantissa | xmantissa/sharing.py | getPrimaryRole | def getPrimaryRole(store, primaryRoleName, createIfNotFound=False):
"""
Get Role object corresponding to an identifier name. If the role name
passed is the empty string, it is assumed that the user is not
authenticated, and the 'Everybody' role is primary. If the role name
passed is non-empty, but has no corresponding role, the 'Authenticated'
role - which is a member of 'Everybody' - is primary. Finally, a specific
role can be primary if one exists for the user's given credentials, that
will automatically always be a member of 'Authenticated', and by extension,
of 'Everybody'.
@param primaryRoleName: a unicode string identifying the role to be
retrieved. This corresponds to L{Role}'s externalID attribute.
@param createIfNotFound: a boolean. If True, create a role for the given
primary role name if no exact match is found. The default, False, will
instead retrieve the 'nearest match' role, which can be Authenticated or
Everybody depending on whether the user is logged in or not.
@return: a L{Role}.
"""
if not primaryRoleName:
return getEveryoneRole(store)
ff = store.findUnique(Role, Role.externalID == primaryRoleName, default=None)
if ff is not None:
return ff
authRole = getAuthenticatedRole(store)
if createIfNotFound:
role = Role(store=store,
externalID=primaryRoleName)
role.becomeMemberOf(authRole)
return role
return authRole | python | def getPrimaryRole(store, primaryRoleName, createIfNotFound=False):
"""
Get Role object corresponding to an identifier name. If the role name
passed is the empty string, it is assumed that the user is not
authenticated, and the 'Everybody' role is primary. If the role name
passed is non-empty, but has no corresponding role, the 'Authenticated'
role - which is a member of 'Everybody' - is primary. Finally, a specific
role can be primary if one exists for the user's given credentials, that
will automatically always be a member of 'Authenticated', and by extension,
of 'Everybody'.
@param primaryRoleName: a unicode string identifying the role to be
retrieved. This corresponds to L{Role}'s externalID attribute.
@param createIfNotFound: a boolean. If True, create a role for the given
primary role name if no exact match is found. The default, False, will
instead retrieve the 'nearest match' role, which can be Authenticated or
Everybody depending on whether the user is logged in or not.
@return: a L{Role}.
"""
if not primaryRoleName:
return getEveryoneRole(store)
ff = store.findUnique(Role, Role.externalID == primaryRoleName, default=None)
if ff is not None:
return ff
authRole = getAuthenticatedRole(store)
if createIfNotFound:
role = Role(store=store,
externalID=primaryRoleName)
role.becomeMemberOf(authRole)
return role
return authRole | [
"def",
"getPrimaryRole",
"(",
"store",
",",
"primaryRoleName",
",",
"createIfNotFound",
"=",
"False",
")",
":",
"if",
"not",
"primaryRoleName",
":",
"return",
"getEveryoneRole",
"(",
"store",
")",
"ff",
"=",
"store",
".",
"findUnique",
"(",
"Role",
",",
"Rol... | Get Role object corresponding to an identifier name. If the role name
passed is the empty string, it is assumed that the user is not
authenticated, and the 'Everybody' role is primary. If the role name
passed is non-empty, but has no corresponding role, the 'Authenticated'
role - which is a member of 'Everybody' - is primary. Finally, a specific
role can be primary if one exists for the user's given credentials, that
will automatically always be a member of 'Authenticated', and by extension,
of 'Everybody'.
@param primaryRoleName: a unicode string identifying the role to be
retrieved. This corresponds to L{Role}'s externalID attribute.
@param createIfNotFound: a boolean. If True, create a role for the given
primary role name if no exact match is found. The default, False, will
instead retrieve the 'nearest match' role, which can be Authenticated or
Everybody depending on whether the user is logged in or not.
@return: a L{Role}. | [
"Get",
"Role",
"object",
"corresponding",
"to",
"an",
"identifier",
"name",
".",
"If",
"the",
"role",
"name",
"passed",
"is",
"the",
"empty",
"string",
"it",
"is",
"assumed",
"that",
"the",
"user",
"is",
"not",
"authenticated",
"and",
"the",
"Everybody",
"... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L633-L665 |
twisted/mantissa | xmantissa/sharing.py | getAccountRole | def getAccountRole(store, accountNames):
"""
Retrieve the first Role in the given store which corresponds an account
name in C{accountNames}.
Note: the implementation currently ignores all of the values in
C{accountNames} except for the first.
@param accountNames: A C{list} of two-tuples of account local parts and
domains.
@raise ValueError: If C{accountNames} is empty.
@rtype: L{Role}
"""
for (localpart, domain) in accountNames:
return getPrimaryRole(store, u'%s@%s' % (localpart, domain),
createIfNotFound=True)
raise ValueError("Cannot get named role for unnamed account.") | python | def getAccountRole(store, accountNames):
"""
Retrieve the first Role in the given store which corresponds an account
name in C{accountNames}.
Note: the implementation currently ignores all of the values in
C{accountNames} except for the first.
@param accountNames: A C{list} of two-tuples of account local parts and
domains.
@raise ValueError: If C{accountNames} is empty.
@rtype: L{Role}
"""
for (localpart, domain) in accountNames:
return getPrimaryRole(store, u'%s@%s' % (localpart, domain),
createIfNotFound=True)
raise ValueError("Cannot get named role for unnamed account.") | [
"def",
"getAccountRole",
"(",
"store",
",",
"accountNames",
")",
":",
"for",
"(",
"localpart",
",",
"domain",
")",
"in",
"accountNames",
":",
"return",
"getPrimaryRole",
"(",
"store",
",",
"u'%s@%s'",
"%",
"(",
"localpart",
",",
"domain",
")",
",",
"create... | Retrieve the first Role in the given store which corresponds an account
name in C{accountNames}.
Note: the implementation currently ignores all of the values in
C{accountNames} except for the first.
@param accountNames: A C{list} of two-tuples of account local parts and
domains.
@raise ValueError: If C{accountNames} is empty.
@rtype: L{Role} | [
"Retrieve",
"the",
"first",
"Role",
"in",
"the",
"given",
"store",
"which",
"corresponds",
"an",
"account",
"name",
"in",
"C",
"{",
"accountNames",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L677-L695 |
twisted/mantissa | xmantissa/sharing.py | shareItem | def shareItem(sharedItem, toRole=None, toName=None, shareID=None,
interfaces=ALL_IMPLEMENTED):
"""
Share an item with a given role. This provides a way to expose items to
users for later retrieval with L{Role.getShare}.
This API is slated for deprecation. Prefer L{Role.shareItem} in new code.
@param sharedItem: an item to be shared.
@param toRole: a L{Role} instance which represents the group that has
access to the given item. May not be specified if toName is also
specified.
@param toName: a unicode string which uniquely identifies a L{Role} in the
same store as the sharedItem.
@param shareID: a unicode string. If provided, specify the ID under which
the shared item will be shared.
@param interfaces: a list of Interface objects which specify the methods
and attributes accessible to C{toRole} on C{sharedItem}.
@return: a L{Share} which records the ability of the given role to access
the given item.
"""
warnings.warn("Use Role.shareItem() instead of sharing.shareItem().",
PendingDeprecationWarning,
stacklevel=2)
if toRole is None:
if toName is not None:
toRole = getPrimaryRole(sharedItem.store, toName, True)
else:
toRole = getEveryoneRole(sharedItem.store)
return toRole.shareItem(sharedItem, shareID, interfaces) | python | def shareItem(sharedItem, toRole=None, toName=None, shareID=None,
interfaces=ALL_IMPLEMENTED):
"""
Share an item with a given role. This provides a way to expose items to
users for later retrieval with L{Role.getShare}.
This API is slated for deprecation. Prefer L{Role.shareItem} in new code.
@param sharedItem: an item to be shared.
@param toRole: a L{Role} instance which represents the group that has
access to the given item. May not be specified if toName is also
specified.
@param toName: a unicode string which uniquely identifies a L{Role} in the
same store as the sharedItem.
@param shareID: a unicode string. If provided, specify the ID under which
the shared item will be shared.
@param interfaces: a list of Interface objects which specify the methods
and attributes accessible to C{toRole} on C{sharedItem}.
@return: a L{Share} which records the ability of the given role to access
the given item.
"""
warnings.warn("Use Role.shareItem() instead of sharing.shareItem().",
PendingDeprecationWarning,
stacklevel=2)
if toRole is None:
if toName is not None:
toRole = getPrimaryRole(sharedItem.store, toName, True)
else:
toRole = getEveryoneRole(sharedItem.store)
return toRole.shareItem(sharedItem, shareID, interfaces) | [
"def",
"shareItem",
"(",
"sharedItem",
",",
"toRole",
"=",
"None",
",",
"toName",
"=",
"None",
",",
"shareID",
"=",
"None",
",",
"interfaces",
"=",
"ALL_IMPLEMENTED",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use Role.shareItem() instead of sharing.shareItem().\"... | Share an item with a given role. This provides a way to expose items to
users for later retrieval with L{Role.getShare}.
This API is slated for deprecation. Prefer L{Role.shareItem} in new code.
@param sharedItem: an item to be shared.
@param toRole: a L{Role} instance which represents the group that has
access to the given item. May not be specified if toName is also
specified.
@param toName: a unicode string which uniquely identifies a L{Role} in the
same store as the sharedItem.
@param shareID: a unicode string. If provided, specify the ID under which
the shared item will be shared.
@param interfaces: a list of Interface objects which specify the methods
and attributes accessible to C{toRole} on C{sharedItem}.
@return: a L{Share} which records the ability of the given role to access
the given item. | [
"Share",
"an",
"item",
"with",
"a",
"given",
"role",
".",
"This",
"provides",
"a",
"way",
"to",
"expose",
"items",
"to",
"users",
"for",
"later",
"retrieval",
"with",
"L",
"{",
"Role",
".",
"getShare",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L699-L733 |
twisted/mantissa | xmantissa/sharing.py | _linearize | def _linearize(interface):
"""
Return a list of all the bases of a given interface in depth-first order.
@param interface: an Interface object.
@return: a L{list} of Interface objects, the input in all its bases, in
subclass-to-base-class, depth-first order.
"""
L = [interface]
for baseInterface in interface.__bases__:
if baseInterface is not Interface:
L.extend(_linearize(baseInterface))
return L | python | def _linearize(interface):
"""
Return a list of all the bases of a given interface in depth-first order.
@param interface: an Interface object.
@return: a L{list} of Interface objects, the input in all its bases, in
subclass-to-base-class, depth-first order.
"""
L = [interface]
for baseInterface in interface.__bases__:
if baseInterface is not Interface:
L.extend(_linearize(baseInterface))
return L | [
"def",
"_linearize",
"(",
"interface",
")",
":",
"L",
"=",
"[",
"interface",
"]",
"for",
"baseInterface",
"in",
"interface",
".",
"__bases__",
":",
"if",
"baseInterface",
"is",
"not",
"Interface",
":",
"L",
".",
"extend",
"(",
"_linearize",
"(",
"baseInter... | Return a list of all the bases of a given interface in depth-first order.
@param interface: an Interface object.
@return: a L{list} of Interface objects, the input in all its bases, in
subclass-to-base-class, depth-first order. | [
"Return",
"a",
"list",
"of",
"all",
"the",
"bases",
"of",
"a",
"given",
"interface",
"in",
"depth",
"-",
"first",
"order",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L737-L750 |
twisted/mantissa | xmantissa/sharing.py | _commonParent | def _commonParent(zi1, zi2):
"""
Locate the common parent of two Interface objects.
@param zi1: a zope Interface object.
@param zi2: another Interface object.
@return: the rightmost common parent of the two provided Interface objects,
or None, if they have no common parent other than Interface itself.
"""
shorter, longer = sorted([_linearize(x)[::-1] for x in zi1, zi2],
key=len)
for n in range(len(shorter)):
if shorter[n] != longer[n]:
if n == 0:
return None
return shorter[n-1]
return shorter[-1] | python | def _commonParent(zi1, zi2):
"""
Locate the common parent of two Interface objects.
@param zi1: a zope Interface object.
@param zi2: another Interface object.
@return: the rightmost common parent of the two provided Interface objects,
or None, if they have no common parent other than Interface itself.
"""
shorter, longer = sorted([_linearize(x)[::-1] for x in zi1, zi2],
key=len)
for n in range(len(shorter)):
if shorter[n] != longer[n]:
if n == 0:
return None
return shorter[n-1]
return shorter[-1] | [
"def",
"_commonParent",
"(",
"zi1",
",",
"zi2",
")",
":",
"shorter",
",",
"longer",
"=",
"sorted",
"(",
"[",
"_linearize",
"(",
"x",
")",
"[",
":",
":",
"-",
"1",
"]",
"for",
"x",
"in",
"zi1",
",",
"zi2",
"]",
",",
"key",
"=",
"len",
")",
"fo... | Locate the common parent of two Interface objects.
@param zi1: a zope Interface object.
@param zi2: another Interface object.
@return: the rightmost common parent of the two provided Interface objects,
or None, if they have no common parent other than Interface itself. | [
"Locate",
"the",
"common",
"parent",
"of",
"two",
"Interface",
"objects",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L754-L772 |
twisted/mantissa | xmantissa/sharing.py | _checkConflictingNames | def _checkConflictingNames(interfaces):
"""
Raise an exception if any of the names present in the given interfaces
conflict with each other.
@param interfaces: a list of Zope Interface objects.
@return: None
@raise ConflictingNames: if any of the attributes of the provided
interfaces are the same, and they do not have a common base interface which
provides that name.
"""
names = {}
for interface in interfaces:
for name in interface:
if name in names:
otherInterface = names[name]
parent = _commonParent(interface, otherInterface)
if parent is None or name not in parent:
raise ConflictingNames("%s conflicts with %s over %s" % (
interface, otherInterface, name))
names[name] = interface | python | def _checkConflictingNames(interfaces):
"""
Raise an exception if any of the names present in the given interfaces
conflict with each other.
@param interfaces: a list of Zope Interface objects.
@return: None
@raise ConflictingNames: if any of the attributes of the provided
interfaces are the same, and they do not have a common base interface which
provides that name.
"""
names = {}
for interface in interfaces:
for name in interface:
if name in names:
otherInterface = names[name]
parent = _commonParent(interface, otherInterface)
if parent is None or name not in parent:
raise ConflictingNames("%s conflicts with %s over %s" % (
interface, otherInterface, name))
names[name] = interface | [
"def",
"_checkConflictingNames",
"(",
"interfaces",
")",
":",
"names",
"=",
"{",
"}",
"for",
"interface",
"in",
"interfaces",
":",
"for",
"name",
"in",
"interface",
":",
"if",
"name",
"in",
"names",
":",
"otherInterface",
"=",
"names",
"[",
"name",
"]",
... | Raise an exception if any of the names present in the given interfaces
conflict with each other.
@param interfaces: a list of Zope Interface objects.
@return: None
@raise ConflictingNames: if any of the attributes of the provided
interfaces are the same, and they do not have a common base interface which
provides that name. | [
"Raise",
"an",
"exception",
"if",
"any",
"of",
"the",
"names",
"present",
"in",
"the",
"given",
"interfaces",
"conflict",
"with",
"each",
"other",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L775-L797 |
twisted/mantissa | xmantissa/sharing.py | getShare | def getShare(store, role, shareID):
"""
Retrieve the accessible facet of an Item previously shared with
L{shareItem}.
This method is pending deprecation, and L{Role.getShare} should be
preferred in new code.
@param store: an axiom store (XXX must be the same as role.store)
@param role: a L{Role}, the primary role for a user attempting to retrieve
the given item.
@return: a L{SharedProxy}. This is a wrapper around the shared item which
only exposes those interfaces explicitly allowed for the given role.
@raise: L{NoSuchShare} if there is no item shared to the given role for the
given shareID.
"""
warnings.warn("Use Role.getShare() instead of sharing.getShare().",
PendingDeprecationWarning,
stacklevel=2)
return role.getShare(shareID) | python | def getShare(store, role, shareID):
"""
Retrieve the accessible facet of an Item previously shared with
L{shareItem}.
This method is pending deprecation, and L{Role.getShare} should be
preferred in new code.
@param store: an axiom store (XXX must be the same as role.store)
@param role: a L{Role}, the primary role for a user attempting to retrieve
the given item.
@return: a L{SharedProxy}. This is a wrapper around the shared item which
only exposes those interfaces explicitly allowed for the given role.
@raise: L{NoSuchShare} if there is no item shared to the given role for the
given shareID.
"""
warnings.warn("Use Role.getShare() instead of sharing.getShare().",
PendingDeprecationWarning,
stacklevel=2)
return role.getShare(shareID) | [
"def",
"getShare",
"(",
"store",
",",
"role",
",",
"shareID",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use Role.getShare() instead of sharing.getShare().\"",
",",
"PendingDeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"role",
".",
"getShare",
"... | Retrieve the accessible facet of an Item previously shared with
L{shareItem}.
This method is pending deprecation, and L{Role.getShare} should be
preferred in new code.
@param store: an axiom store (XXX must be the same as role.store)
@param role: a L{Role}, the primary role for a user attempting to retrieve
the given item.
@return: a L{SharedProxy}. This is a wrapper around the shared item which
only exposes those interfaces explicitly allowed for the given role.
@raise: L{NoSuchShare} if there is no item shared to the given role for the
given shareID. | [
"Retrieve",
"the",
"accessible",
"facet",
"of",
"an",
"Item",
"previously",
"shared",
"with",
"L",
"{",
"shareItem",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L801-L823 |
twisted/mantissa | xmantissa/sharing.py | asAccessibleTo | def asAccessibleTo(role, query):
"""
Return an iterable which yields the shared proxies that are available to
the given role, from the given query.
This method is pending deprecation, and L{Role.asAccessibleTo} should be
preferred in new code.
@param role: The role to retrieve L{SharedProxy}s for.
@param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
"""
warnings.warn(
"Use Role.asAccessibleTo() instead of sharing.asAccessibleTo().",
PendingDeprecationWarning,
stacklevel=2)
return role.asAccessibleTo(query) | python | def asAccessibleTo(role, query):
"""
Return an iterable which yields the shared proxies that are available to
the given role, from the given query.
This method is pending deprecation, and L{Role.asAccessibleTo} should be
preferred in new code.
@param role: The role to retrieve L{SharedProxy}s for.
@param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
"""
warnings.warn(
"Use Role.asAccessibleTo() instead of sharing.asAccessibleTo().",
PendingDeprecationWarning,
stacklevel=2)
return role.asAccessibleTo(query) | [
"def",
"asAccessibleTo",
"(",
"role",
",",
"query",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use Role.asAccessibleTo() instead of sharing.asAccessibleTo().\"",
",",
"PendingDeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"role",
".",
"asAccessibleTo",... | Return an iterable which yields the shared proxies that are available to
the given role, from the given query.
This method is pending deprecation, and L{Role.asAccessibleTo} should be
preferred in new code.
@param role: The role to retrieve L{SharedProxy}s for.
@param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider. | [
"Return",
"an",
"iterable",
"which",
"yields",
"the",
"shared",
"proxies",
"that",
"are",
"available",
"to",
"the",
"given",
"role",
"from",
"the",
"given",
"query",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L827-L845 |
twisted/mantissa | xmantissa/sharing.py | unShare | def unShare(sharedItem):
"""
Remove all instances of this item from public or shared view.
"""
sharedItem.store.query(Share, Share.sharedItem == sharedItem).deleteFromStore() | python | def unShare(sharedItem):
"""
Remove all instances of this item from public or shared view.
"""
sharedItem.store.query(Share, Share.sharedItem == sharedItem).deleteFromStore() | [
"def",
"unShare",
"(",
"sharedItem",
")",
":",
"sharedItem",
".",
"store",
".",
"query",
"(",
"Share",
",",
"Share",
".",
"sharedItem",
"==",
"sharedItem",
")",
".",
"deleteFromStore",
"(",
")"
] | Remove all instances of this item from public or shared view. | [
"Remove",
"all",
"instances",
"of",
"this",
"item",
"from",
"public",
"or",
"shared",
"view",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L879-L883 |
twisted/mantissa | xmantissa/sharing.py | randomEarlyShared | def randomEarlyShared(store, role):
"""
If there are no explicitly-published public index pages to display, find a
shared item to present to the user as first.
"""
for r in role.allRoles():
share = store.findFirst(Share, Share.sharedTo == r,
sort=Share.storeID.ascending)
if share is not None:
return share.sharedItem
raise NoSuchShare("Why, that user hasn't shared anything at all!") | python | def randomEarlyShared(store, role):
"""
If there are no explicitly-published public index pages to display, find a
shared item to present to the user as first.
"""
for r in role.allRoles():
share = store.findFirst(Share, Share.sharedTo == r,
sort=Share.storeID.ascending)
if share is not None:
return share.sharedItem
raise NoSuchShare("Why, that user hasn't shared anything at all!") | [
"def",
"randomEarlyShared",
"(",
"store",
",",
"role",
")",
":",
"for",
"r",
"in",
"role",
".",
"allRoles",
"(",
")",
":",
"share",
"=",
"store",
".",
"findFirst",
"(",
"Share",
",",
"Share",
".",
"sharedTo",
"==",
"r",
",",
"sort",
"=",
"Share",
"... | If there are no explicitly-published public index pages to display, find a
shared item to present to the user as first. | [
"If",
"there",
"are",
"no",
"explicitly",
"-",
"published",
"public",
"index",
"pages",
"to",
"display",
"find",
"a",
"shared",
"item",
"to",
"present",
"to",
"the",
"user",
"as",
"first",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L887-L897 |
twisted/mantissa | xmantissa/sharing.py | Identifier.fromSharedItem | def fromSharedItem(cls, sharedItem):
"""
Return an instance of C{cls} derived from the given L{Item} that has
been shared.
Note that this API does not provide any guarantees of which result it
will choose. If there are are multiple possible return values, it will
select and return only one. Items may be shared under multiple
L{shareID}s. A user may have multiple valid account names. It is
sometimes impossible to tell from context which one is appropriate, so
if your application has another way to select a specific shareID you
should use that instead.
@param sharedItem: an L{Item} that should be shared.
@return: an L{Identifier} describing the C{sharedItem} parameter.
@raise L{NoSuchShare}: if the given item is not shared or its store
does not contain any L{LoginMethod} items which would identify a user.
"""
localpart = None
for (localpart, domain) in userbase.getAccountNames(sharedItem.store):
break
if localpart is None:
raise NoSuchShare()
for share in sharedItem.store.query(Share,
Share.sharedItem == sharedItem):
break
else:
raise NoSuchShare()
return cls(
shareID=share.shareID,
localpart=localpart, domain=domain) | python | def fromSharedItem(cls, sharedItem):
"""
Return an instance of C{cls} derived from the given L{Item} that has
been shared.
Note that this API does not provide any guarantees of which result it
will choose. If there are are multiple possible return values, it will
select and return only one. Items may be shared under multiple
L{shareID}s. A user may have multiple valid account names. It is
sometimes impossible to tell from context which one is appropriate, so
if your application has another way to select a specific shareID you
should use that instead.
@param sharedItem: an L{Item} that should be shared.
@return: an L{Identifier} describing the C{sharedItem} parameter.
@raise L{NoSuchShare}: if the given item is not shared or its store
does not contain any L{LoginMethod} items which would identify a user.
"""
localpart = None
for (localpart, domain) in userbase.getAccountNames(sharedItem.store):
break
if localpart is None:
raise NoSuchShare()
for share in sharedItem.store.query(Share,
Share.sharedItem == sharedItem):
break
else:
raise NoSuchShare()
return cls(
shareID=share.shareID,
localpart=localpart, domain=domain) | [
"def",
"fromSharedItem",
"(",
"cls",
",",
"sharedItem",
")",
":",
"localpart",
"=",
"None",
"for",
"(",
"localpart",
",",
"domain",
")",
"in",
"userbase",
".",
"getAccountNames",
"(",
"sharedItem",
".",
"store",
")",
":",
"break",
"if",
"localpart",
"is",
... | Return an instance of C{cls} derived from the given L{Item} that has
been shared.
Note that this API does not provide any guarantees of which result it
will choose. If there are are multiple possible return values, it will
select and return only one. Items may be shared under multiple
L{shareID}s. A user may have multiple valid account names. It is
sometimes impossible to tell from context which one is appropriate, so
if your application has another way to select a specific shareID you
should use that instead.
@param sharedItem: an L{Item} that should be shared.
@return: an L{Identifier} describing the C{sharedItem} parameter.
@raise L{NoSuchShare}: if the given item is not shared or its store
does not contain any L{LoginMethod} items which would identify a user. | [
"Return",
"an",
"instance",
"of",
"C",
"{",
"cls",
"}",
"derived",
"from",
"the",
"given",
"L",
"{",
"Item",
"}",
"that",
"has",
"been",
"shared",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L76-L108 |
twisted/mantissa | xmantissa/sharing.py | IdentifierArgument.toString | def toString(self, obj):
"""
Convert the given L{Identifier} to a string.
"""
return Box(shareID=obj.shareID.encode('utf-8'),
localpart=obj.localpart.encode('utf-8'),
domain=obj.domain.encode('utf-8')).serialize() | python | def toString(self, obj):
"""
Convert the given L{Identifier} to a string.
"""
return Box(shareID=obj.shareID.encode('utf-8'),
localpart=obj.localpart.encode('utf-8'),
domain=obj.domain.encode('utf-8')).serialize() | [
"def",
"toString",
"(",
"self",
",",
"obj",
")",
":",
"return",
"Box",
"(",
"shareID",
"=",
"obj",
".",
"shareID",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"localpart",
"=",
"obj",
".",
"localpart",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"domain",
... | Convert the given L{Identifier} to a string. | [
"Convert",
"the",
"given",
"L",
"{",
"Identifier",
"}",
"to",
"a",
"string",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L128-L134 |
twisted/mantissa | xmantissa/sharing.py | IdentifierArgument.fromString | def fromString(self, inString):
"""
Convert the given string to an L{Identifier}.
"""
box = parseString(inString)[0]
return Identifier(shareID=box['shareID'].decode('utf-8'),
localpart=box['localpart'].decode('utf-8'),
domain=box['domain'].decode('utf-8')) | python | def fromString(self, inString):
"""
Convert the given string to an L{Identifier}.
"""
box = parseString(inString)[0]
return Identifier(shareID=box['shareID'].decode('utf-8'),
localpart=box['localpart'].decode('utf-8'),
domain=box['domain'].decode('utf-8')) | [
"def",
"fromString",
"(",
"self",
",",
"inString",
")",
":",
"box",
"=",
"parseString",
"(",
"inString",
")",
"[",
"0",
"]",
"return",
"Identifier",
"(",
"shareID",
"=",
"box",
"[",
"'shareID'",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"localpart"... | Convert the given string to an L{Identifier}. | [
"Convert",
"the",
"given",
"string",
"to",
"an",
"L",
"{",
"Identifier",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L137-L144 |
twisted/mantissa | xmantissa/sharing.py | Role.becomeMemberOf | def becomeMemberOf(self, groupRole):
"""
Instruct this (user or group) Role to become a member of a group role.
@param groupRole: The role that this group should become a member of.
"""
self.store.findOrCreate(RoleRelationship,
group=groupRole,
member=self) | python | def becomeMemberOf(self, groupRole):
"""
Instruct this (user or group) Role to become a member of a group role.
@param groupRole: The role that this group should become a member of.
"""
self.store.findOrCreate(RoleRelationship,
group=groupRole,
member=self) | [
"def",
"becomeMemberOf",
"(",
"self",
",",
"groupRole",
")",
":",
"self",
".",
"store",
".",
"findOrCreate",
"(",
"RoleRelationship",
",",
"group",
"=",
"groupRole",
",",
"member",
"=",
"self",
")"
] | Instruct this (user or group) Role to become a member of a group role.
@param groupRole: The role that this group should become a member of. | [
"Instruct",
"this",
"(",
"user",
"or",
"group",
")",
"Role",
"to",
"become",
"a",
"member",
"of",
"a",
"group",
"role",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L191-L199 |
twisted/mantissa | xmantissa/sharing.py | Role.allRoles | def allRoles(self, memo=None):
"""
Identify all the roles that this role is authorized to act as.
@param memo: used only for recursion. Do not pass this.
@return: an iterator of all roles that this role is a member of,
including itself.
"""
if memo is None:
memo = set()
elif self in memo:
# this is bad, but we have successfully detected and prevented the
# only really bad symptom, an infinite loop.
return
memo.add(self)
yield self
for groupRole in self.store.query(Role,
AND(RoleRelationship.member == self,
RoleRelationship.group == Role.storeID)):
for roleRole in groupRole.allRoles(memo):
yield roleRole | python | def allRoles(self, memo=None):
"""
Identify all the roles that this role is authorized to act as.
@param memo: used only for recursion. Do not pass this.
@return: an iterator of all roles that this role is a member of,
including itself.
"""
if memo is None:
memo = set()
elif self in memo:
# this is bad, but we have successfully detected and prevented the
# only really bad symptom, an infinite loop.
return
memo.add(self)
yield self
for groupRole in self.store.query(Role,
AND(RoleRelationship.member == self,
RoleRelationship.group == Role.storeID)):
for roleRole in groupRole.allRoles(memo):
yield roleRole | [
"def",
"allRoles",
"(",
"self",
",",
"memo",
"=",
"None",
")",
":",
"if",
"memo",
"is",
"None",
":",
"memo",
"=",
"set",
"(",
")",
"elif",
"self",
"in",
"memo",
":",
"# this is bad, but we have successfully detected and prevented the",
"# only really bad symptom, ... | Identify all the roles that this role is authorized to act as.
@param memo: used only for recursion. Do not pass this.
@return: an iterator of all roles that this role is a member of,
including itself. | [
"Identify",
"all",
"the",
"roles",
"that",
"this",
"role",
"is",
"authorized",
"to",
"act",
"as",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L202-L223 |
twisted/mantissa | xmantissa/sharing.py | Role.shareItem | def shareItem(self, sharedItem, shareID=None, interfaces=ALL_IMPLEMENTED):
"""
Share an item with this role. This provides a way to expose items to
users for later retrieval with L{Role.getShare}.
@param sharedItem: an item to be shared.
@param shareID: a unicode string. If provided, specify the ID under which
the shared item will be shared.
@param interfaces: a list of Interface objects which specify the methods
and attributes accessible to C{toRole} on C{sharedItem}.
@return: a L{Share} which records the ability of the given role to
access the given item.
"""
if shareID is None:
shareID = genShareID(sharedItem.store)
return Share(store=self.store,
shareID=shareID,
sharedItem=sharedItem,
sharedTo=self,
sharedInterfaces=interfaces) | python | def shareItem(self, sharedItem, shareID=None, interfaces=ALL_IMPLEMENTED):
"""
Share an item with this role. This provides a way to expose items to
users for later retrieval with L{Role.getShare}.
@param sharedItem: an item to be shared.
@param shareID: a unicode string. If provided, specify the ID under which
the shared item will be shared.
@param interfaces: a list of Interface objects which specify the methods
and attributes accessible to C{toRole} on C{sharedItem}.
@return: a L{Share} which records the ability of the given role to
access the given item.
"""
if shareID is None:
shareID = genShareID(sharedItem.store)
return Share(store=self.store,
shareID=shareID,
sharedItem=sharedItem,
sharedTo=self,
sharedInterfaces=interfaces) | [
"def",
"shareItem",
"(",
"self",
",",
"sharedItem",
",",
"shareID",
"=",
"None",
",",
"interfaces",
"=",
"ALL_IMPLEMENTED",
")",
":",
"if",
"shareID",
"is",
"None",
":",
"shareID",
"=",
"genShareID",
"(",
"sharedItem",
".",
"store",
")",
"return",
"Share",... | Share an item with this role. This provides a way to expose items to
users for later retrieval with L{Role.getShare}.
@param sharedItem: an item to be shared.
@param shareID: a unicode string. If provided, specify the ID under which
the shared item will be shared.
@param interfaces: a list of Interface objects which specify the methods
and attributes accessible to C{toRole} on C{sharedItem}.
@return: a L{Share} which records the ability of the given role to
access the given item. | [
"Share",
"an",
"item",
"with",
"this",
"role",
".",
"This",
"provides",
"a",
"way",
"to",
"expose",
"items",
"to",
"users",
"for",
"later",
"retrieval",
"with",
"L",
"{",
"Role",
".",
"getShare",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L226-L248 |
twisted/mantissa | xmantissa/sharing.py | Role.getShare | def getShare(self, shareID):
"""
Retrieve a proxy object for a given shareID, previously shared with
this role or one of its group roles via L{Role.shareItem}.
@return: a L{SharedProxy}. This is a wrapper around the shared item
which only exposes those interfaces explicitly allowed for the given
role.
@raise: L{NoSuchShare} if there is no item shared to the given role for
the given shareID.
"""
shares = list(
self.store.query(Share,
AND(Share.shareID == shareID,
Share.sharedTo.oneOf(self.allRoles()))))
interfaces = []
for share in shares:
interfaces += share.sharedInterfaces
if shares:
return SharedProxy(shares[0].sharedItem,
interfaces,
shareID)
raise NoSuchShare() | python | def getShare(self, shareID):
"""
Retrieve a proxy object for a given shareID, previously shared with
this role or one of its group roles via L{Role.shareItem}.
@return: a L{SharedProxy}. This is a wrapper around the shared item
which only exposes those interfaces explicitly allowed for the given
role.
@raise: L{NoSuchShare} if there is no item shared to the given role for
the given shareID.
"""
shares = list(
self.store.query(Share,
AND(Share.shareID == shareID,
Share.sharedTo.oneOf(self.allRoles()))))
interfaces = []
for share in shares:
interfaces += share.sharedInterfaces
if shares:
return SharedProxy(shares[0].sharedItem,
interfaces,
shareID)
raise NoSuchShare() | [
"def",
"getShare",
"(",
"self",
",",
"shareID",
")",
":",
"shares",
"=",
"list",
"(",
"self",
".",
"store",
".",
"query",
"(",
"Share",
",",
"AND",
"(",
"Share",
".",
"shareID",
"==",
"shareID",
",",
"Share",
".",
"sharedTo",
".",
"oneOf",
"(",
"se... | Retrieve a proxy object for a given shareID, previously shared with
this role or one of its group roles via L{Role.shareItem}.
@return: a L{SharedProxy}. This is a wrapper around the shared item
which only exposes those interfaces explicitly allowed for the given
role.
@raise: L{NoSuchShare} if there is no item shared to the given role for
the given shareID. | [
"Retrieve",
"a",
"proxy",
"object",
"for",
"a",
"given",
"shareID",
"previously",
"shared",
"with",
"this",
"role",
"or",
"one",
"of",
"its",
"group",
"roles",
"via",
"L",
"{",
"Role",
".",
"shareItem",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L251-L274 |
twisted/mantissa | xmantissa/sharing.py | Role.asAccessibleTo | def asAccessibleTo(self, query):
"""
@param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
@return: an iterable which yields the shared proxies that are available
to the given role, from the given query.
"""
# XXX TODO #2371: this method really *should* be returning an L{IQuery}
# provider as well, but that is kind of tricky to do. Currently, doing
# queries leaks authority, because the resulting objects have stores
# and "real" items as part of their interface; having this be a "real"
# query provider would obviate the need to escape the L{SharedProxy}
# security constraints in order to do any querying.
allRoles = list(self.allRoles())
count = 0
unlimited = query.cloneQuery(limit=None)
for result in unlimited:
allShares = list(query.store.query(
Share,
AND(Share.sharedItem == result,
Share.sharedTo.oneOf(allRoles))))
interfaces = []
for share in allShares:
interfaces += share.sharedInterfaces
if allShares:
count += 1
yield SharedProxy(result, interfaces, allShares[0].shareID)
if count == query.limit:
return | python | def asAccessibleTo(self, query):
"""
@param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
@return: an iterable which yields the shared proxies that are available
to the given role, from the given query.
"""
# XXX TODO #2371: this method really *should* be returning an L{IQuery}
# provider as well, but that is kind of tricky to do. Currently, doing
# queries leaks authority, because the resulting objects have stores
# and "real" items as part of their interface; having this be a "real"
# query provider would obviate the need to escape the L{SharedProxy}
# security constraints in order to do any querying.
allRoles = list(self.allRoles())
count = 0
unlimited = query.cloneQuery(limit=None)
for result in unlimited:
allShares = list(query.store.query(
Share,
AND(Share.sharedItem == result,
Share.sharedTo.oneOf(allRoles))))
interfaces = []
for share in allShares:
interfaces += share.sharedInterfaces
if allShares:
count += 1
yield SharedProxy(result, interfaces, allShares[0].shareID)
if count == query.limit:
return | [
"def",
"asAccessibleTo",
"(",
"self",
",",
"query",
")",
":",
"# XXX TODO #2371: this method really *should* be returning an L{IQuery}",
"# provider as well, but that is kind of tricky to do. Currently, doing",
"# queries leaks authority, because the resulting objects have stores",
"# and \"r... | @param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
@return: an iterable which yields the shared proxies that are available
to the given role, from the given query. | [
"@param",
"query",
":",
"An",
"Axiom",
"query",
"describing",
"the",
"Items",
"to",
"retrieve",
"which",
"this",
"role",
"can",
"access",
".",
"@type",
"query",
":",
"an",
"L",
"{",
"iaxiom",
".",
"IQuery",
"}",
"provider",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L277-L307 |
twisted/mantissa | xmantissa/sharing.py | Share.sharedInterfaces | def sharedInterfaces():
"""
This attribute is the public interface for code which wishes to discover
the list of interfaces allowed by this Share. It is a list of
Interface objects.
"""
def get(self):
if not self.sharedInterfaceNames:
return ()
if self.sharedInterfaceNames == ALL_IMPLEMENTED_DB:
I = implementedBy(self.sharedItem.__class__)
L = list(I)
T = tuple(L)
return T
else:
return tuple(map(namedAny, self.sharedInterfaceNames.split(u',')))
def set(self, newValue):
self.sharedAttributeNames = _interfacesToNames(newValue)
return get, set | python | def sharedInterfaces():
"""
This attribute is the public interface for code which wishes to discover
the list of interfaces allowed by this Share. It is a list of
Interface objects.
"""
def get(self):
if not self.sharedInterfaceNames:
return ()
if self.sharedInterfaceNames == ALL_IMPLEMENTED_DB:
I = implementedBy(self.sharedItem.__class__)
L = list(I)
T = tuple(L)
return T
else:
return tuple(map(namedAny, self.sharedInterfaceNames.split(u',')))
def set(self, newValue):
self.sharedAttributeNames = _interfacesToNames(newValue)
return get, set | [
"def",
"sharedInterfaces",
"(",
")",
":",
"def",
"get",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"sharedInterfaceNames",
":",
"return",
"(",
")",
"if",
"self",
".",
"sharedInterfaceNames",
"==",
"ALL_IMPLEMENTED_DB",
":",
"I",
"=",
"implementedBy",
... | This attribute is the public interface for code which wishes to discover
the list of interfaces allowed by this Share. It is a list of
Interface objects. | [
"This",
"attribute",
"is",
"the",
"public",
"interface",
"for",
"code",
"which",
"wishes",
"to",
"discover",
"the",
"list",
"of",
"interfaces",
"allowed",
"by",
"this",
"Share",
".",
"It",
"is",
"a",
"list",
"of",
"Interface",
"objects",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/sharing.py#L550-L568 |
miku/gluish | gluish/intervals.py | every_minute | def every_minute(dt=datetime.datetime.utcnow(), fmt=None):
"""
Just pass on the given date.
"""
date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, 1, 0, dt.tzinfo)
if fmt is not None:
return date.strftime(fmt)
return date | python | def every_minute(dt=datetime.datetime.utcnow(), fmt=None):
"""
Just pass on the given date.
"""
date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, 1, 0, dt.tzinfo)
if fmt is not None:
return date.strftime(fmt)
return date | [
"def",
"every_minute",
"(",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
",",
"fmt",
"=",
"None",
")",
":",
"date",
"=",
"datetime",
".",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
",",... | Just pass on the given date. | [
"Just",
"pass",
"on",
"the",
"given",
"date",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L43-L50 |
miku/gluish | gluish/intervals.py | hourly | def hourly(dt=datetime.datetime.utcnow(), fmt=None):
"""
Get a new datetime object every hour.
"""
date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, 1, 1, 0, dt.tzinfo)
if fmt is not None:
return date.strftime(fmt)
return date | python | def hourly(dt=datetime.datetime.utcnow(), fmt=None):
"""
Get a new datetime object every hour.
"""
date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, 1, 1, 0, dt.tzinfo)
if fmt is not None:
return date.strftime(fmt)
return date | [
"def",
"hourly",
"(",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
",",
"fmt",
"=",
"None",
")",
":",
"date",
"=",
"datetime",
".",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
",",
"dt... | Get a new datetime object every hour. | [
"Get",
"a",
"new",
"datetime",
"object",
"every",
"hour",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L52-L59 |
miku/gluish | gluish/intervals.py | weekly | def weekly(date=datetime.date.today()):
"""
Weeks start are fixes at Monday for now.
"""
return date - datetime.timedelta(days=date.weekday()) | python | def weekly(date=datetime.date.today()):
"""
Weeks start are fixes at Monday for now.
"""
return date - datetime.timedelta(days=date.weekday()) | [
"def",
"weekly",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"return",
"date",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"date",
".",
"weekday",
"(",
")",
")"
] | Weeks start are fixes at Monday for now. | [
"Weeks",
"start",
"are",
"fixes",
"at",
"Monday",
"for",
"now",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L67-L71 |
miku/gluish | gluish/intervals.py | biweekly | def biweekly(date=datetime.date.today()):
"""
Every two weeks.
"""
return datetime.date(date.year, date.month, 1 if date.day < 15 else 15) | python | def biweekly(date=datetime.date.today()):
"""
Every two weeks.
"""
return datetime.date(date.year, date.month, 1 if date.day < 15 else 15) | [
"def",
"biweekly",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"return",
"datetime",
".",
"date",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"1",
"if",
"date",
".",
"day",
"<",
"15",
"else",
"15",
... | Every two weeks. | [
"Every",
"two",
"weeks",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L73-L77 |
miku/gluish | gluish/intervals.py | monthly | def monthly(date=datetime.date.today()):
"""
Take a date object and return the first day of the month.
"""
return datetime.date(date.year, date.month, 1) | python | def monthly(date=datetime.date.today()):
"""
Take a date object and return the first day of the month.
"""
return datetime.date(date.year, date.month, 1) | [
"def",
"monthly",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"return",
"datetime",
".",
"date",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"1",
")"
] | Take a date object and return the first day of the month. | [
"Take",
"a",
"date",
"object",
"and",
"return",
"the",
"first",
"day",
"of",
"the",
"month",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L79-L83 |
miku/gluish | gluish/intervals.py | quarterly | def quarterly(date=datetime.date.today()):
"""
Fixed at: 1/1, 4/1, 7/1, 10/1.
"""
return datetime.date(date.year, ((date.month - 1)//3) * 3 + 1, 1) | python | def quarterly(date=datetime.date.today()):
"""
Fixed at: 1/1, 4/1, 7/1, 10/1.
"""
return datetime.date(date.year, ((date.month - 1)//3) * 3 + 1, 1) | [
"def",
"quarterly",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"return",
"datetime",
".",
"date",
"(",
"date",
".",
"year",
",",
"(",
"(",
"date",
".",
"month",
"-",
"1",
")",
"//",
"3",
")",
"*",
"3",
"+",
"... | Fixed at: 1/1, 4/1, 7/1, 10/1. | [
"Fixed",
"at",
":",
"1",
"/",
"1",
"4",
"/",
"1",
"7",
"/",
"1",
"10",
"/",
"1",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L85-L89 |
miku/gluish | gluish/intervals.py | semiyearly | def semiyearly(date=datetime.date.today()):
"""
Twice a year.
"""
return datetime.date(date.year, 1 if date.month < 7 else 7, 1) | python | def semiyearly(date=datetime.date.today()):
"""
Twice a year.
"""
return datetime.date(date.year, 1 if date.month < 7 else 7, 1) | [
"def",
"semiyearly",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"return",
"datetime",
".",
"date",
"(",
"date",
".",
"year",
",",
"1",
"if",
"date",
".",
"month",
"<",
"7",
"else",
"7",
",",
"1",
")"
] | Twice a year. | [
"Twice",
"a",
"year",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/intervals.py#L91-L95 |
twisted/mantissa | xmantissa/prefs.py | PreferenceCollectionFragment.fragments | def fragments(self, req, tag):
"""
Render our preference collection, any child preference
collections we discover by looking at self.tab.children,
and any fragments returned by its C{getSections} method.
Subtabs and C{getSections} fragments are rendered as fieldsets
inside the parent preference collection's tab.
"""
f = self._collectionToLiveform()
if f is not None:
yield tags.fieldset[tags.legend[self.tab.name], f]
for t in self.tab.children:
f = inevow.IRenderer(
self.collection.store.getItemByID(t.storeID))
f.tab = t
if hasattr(f, 'setFragmentParent'):
f.setFragmentParent(self)
yield f
for f in self.collection.getSections() or ():
f = ixmantissa.INavigableFragment(f)
f.setFragmentParent(self)
f.docFactory = getLoader(f.fragmentName)
yield tags.fieldset[tags.legend[f.title], f] | python | def fragments(self, req, tag):
"""
Render our preference collection, any child preference
collections we discover by looking at self.tab.children,
and any fragments returned by its C{getSections} method.
Subtabs and C{getSections} fragments are rendered as fieldsets
inside the parent preference collection's tab.
"""
f = self._collectionToLiveform()
if f is not None:
yield tags.fieldset[tags.legend[self.tab.name], f]
for t in self.tab.children:
f = inevow.IRenderer(
self.collection.store.getItemByID(t.storeID))
f.tab = t
if hasattr(f, 'setFragmentParent'):
f.setFragmentParent(self)
yield f
for f in self.collection.getSections() or ():
f = ixmantissa.INavigableFragment(f)
f.setFragmentParent(self)
f.docFactory = getLoader(f.fragmentName)
yield tags.fieldset[tags.legend[f.title], f] | [
"def",
"fragments",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"f",
"=",
"self",
".",
"_collectionToLiveform",
"(",
")",
"if",
"f",
"is",
"not",
"None",
":",
"yield",
"tags",
".",
"fieldset",
"[",
"tags",
".",
"legend",
"[",
"self",
".",
"tab",... | Render our preference collection, any child preference
collections we discover by looking at self.tab.children,
and any fragments returned by its C{getSections} method.
Subtabs and C{getSections} fragments are rendered as fieldsets
inside the parent preference collection's tab. | [
"Render",
"our",
"preference",
"collection",
"any",
"child",
"preference",
"collections",
"we",
"discover",
"by",
"looking",
"at",
"self",
".",
"tab",
".",
"children",
"and",
"any",
"fragments",
"returned",
"by",
"its",
"C",
"{",
"getSections",
"}",
"method",
... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/prefs.py#L106-L131 |
twisted/mantissa | xmantissa/prefs.py | PreferenceEditor.tabbedPane | def tabbedPane(self, req, tag):
"""
Render a tabbed pane tab for each top-level
L{xmantissa.ixmantissa.IPreferenceCollection} tab
"""
navigation = webnav.getTabs(self.aggregator.getPreferenceCollections())
pages = list()
for tab in navigation:
f = inevow.IRenderer(
self.aggregator.store.getItemByID(tab.storeID))
f.tab = tab
if hasattr(f, 'setFragmentParent'):
f.setFragmentParent(self)
pages.append((tab.name, f))
f = tabbedPane.TabbedPaneFragment(pages, name='preference-editor')
f.setFragmentParent(self)
return f | python | def tabbedPane(self, req, tag):
"""
Render a tabbed pane tab for each top-level
L{xmantissa.ixmantissa.IPreferenceCollection} tab
"""
navigation = webnav.getTabs(self.aggregator.getPreferenceCollections())
pages = list()
for tab in navigation:
f = inevow.IRenderer(
self.aggregator.store.getItemByID(tab.storeID))
f.tab = tab
if hasattr(f, 'setFragmentParent'):
f.setFragmentParent(self)
pages.append((tab.name, f))
f = tabbedPane.TabbedPaneFragment(pages, name='preference-editor')
f.setFragmentParent(self)
return f | [
"def",
"tabbedPane",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"navigation",
"=",
"webnav",
".",
"getTabs",
"(",
"self",
".",
"aggregator",
".",
"getPreferenceCollections",
"(",
")",
")",
"pages",
"=",
"list",
"(",
")",
"for",
"tab",
"in",
"naviga... | Render a tabbed pane tab for each top-level
L{xmantissa.ixmantissa.IPreferenceCollection} tab | [
"Render",
"a",
"tabbed",
"pane",
"tab",
"for",
"each",
"top",
"-",
"level",
"L",
"{",
"xmantissa",
".",
"ixmantissa",
".",
"IPreferenceCollection",
"}",
"tab"
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/prefs.py#L202-L219 |
twisted/mantissa | xmantissa/tdb.py | TabularDataModel.resort | def resort(self, attributeID, isAscending=None):
"""Sort by one of my specified columns, identified by attributeID
"""
if isAscending is None:
isAscending = self.defaultSortAscending
newSortColumn = self.columns[attributeID]
if newSortColumn.sortAttribute() is None:
raise Unsortable('column %r has no sort attribute' % (attributeID,))
if self.currentSortColumn == newSortColumn:
# if this query is to be re-sorted on the same column, but in the
# opposite direction to our last query, then use the first item in
# the result set as the marker
if self.isAscending == isAscending:
offset = 0
else:
# otherwise use the last
offset = -1
else:
offset = 0
self.currentSortColumn = newSortColumn
self.isAscending = isAscending
self._updateResults(self._sortAttributeValue(offset), True) | python | def resort(self, attributeID, isAscending=None):
"""Sort by one of my specified columns, identified by attributeID
"""
if isAscending is None:
isAscending = self.defaultSortAscending
newSortColumn = self.columns[attributeID]
if newSortColumn.sortAttribute() is None:
raise Unsortable('column %r has no sort attribute' % (attributeID,))
if self.currentSortColumn == newSortColumn:
# if this query is to be re-sorted on the same column, but in the
# opposite direction to our last query, then use the first item in
# the result set as the marker
if self.isAscending == isAscending:
offset = 0
else:
# otherwise use the last
offset = -1
else:
offset = 0
self.currentSortColumn = newSortColumn
self.isAscending = isAscending
self._updateResults(self._sortAttributeValue(offset), True) | [
"def",
"resort",
"(",
"self",
",",
"attributeID",
",",
"isAscending",
"=",
"None",
")",
":",
"if",
"isAscending",
"is",
"None",
":",
"isAscending",
"=",
"self",
".",
"defaultSortAscending",
"newSortColumn",
"=",
"self",
".",
"columns",
"[",
"attributeID",
"]... | Sort by one of my specified columns, identified by attributeID | [
"Sort",
"by",
"one",
"of",
"my",
"specified",
"columns",
"identified",
"by",
"attributeID"
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/tdb.py#L82-L104 |
twisted/mantissa | xmantissa/tdb.py | TabularDataModel.currentPage | def currentPage(self):
"""
Return a sequence of mappings of attribute IDs to column values, to
display to the user.
nextPage/prevPage will strive never to skip items whose column values
have not been returned by this method.
This is best explained by a demonstration. Let's say you have a table
viewing an item with attributes 'a' and 'b', like this:
oid | a | b
----+---+--
0 | 1 | 2
1 | 3 | 4
2 | 5 | 6
3 | 7 | 8
4 | 9 | 0
The table has 2 items per page. You call currentPage and receive a
page which contains items oid 0 and oid 1. item oid 1 is deleted.
If the next thing you do is to call nextPage, the result of currentPage
following that will be items beginning with item oid 2. This is
because although there are no longer enough items to populate a full
page from 0-1, the user has never seen item #2 on a page, so the 'next'
page from the user's point of view contains #2.
If instead, at that same point, the next thing you did was to call
currentPage, *then* nextPage and currentPage again, the first
currentPage results would contain items #0 and #2; the following
currentPage results would contain items #3 and #4. In this case, the
user *has* seen #2 already, so the user expects to see the following
item, not the same item again.
"""
self._updateResults(self._sortAttributeValue(0), equalToStart=True, refresh=True)
return self._currentResults | python | def currentPage(self):
"""
Return a sequence of mappings of attribute IDs to column values, to
display to the user.
nextPage/prevPage will strive never to skip items whose column values
have not been returned by this method.
This is best explained by a demonstration. Let's say you have a table
viewing an item with attributes 'a' and 'b', like this:
oid | a | b
----+---+--
0 | 1 | 2
1 | 3 | 4
2 | 5 | 6
3 | 7 | 8
4 | 9 | 0
The table has 2 items per page. You call currentPage and receive a
page which contains items oid 0 and oid 1. item oid 1 is deleted.
If the next thing you do is to call nextPage, the result of currentPage
following that will be items beginning with item oid 2. This is
because although there are no longer enough items to populate a full
page from 0-1, the user has never seen item #2 on a page, so the 'next'
page from the user's point of view contains #2.
If instead, at that same point, the next thing you did was to call
currentPage, *then* nextPage and currentPage again, the first
currentPage results would contain items #0 and #2; the following
currentPage results would contain items #3 and #4. In this case, the
user *has* seen #2 already, so the user expects to see the following
item, not the same item again.
"""
self._updateResults(self._sortAttributeValue(0), equalToStart=True, refresh=True)
return self._currentResults | [
"def",
"currentPage",
"(",
"self",
")",
":",
"self",
".",
"_updateResults",
"(",
"self",
".",
"_sortAttributeValue",
"(",
"0",
")",
",",
"equalToStart",
"=",
"True",
",",
"refresh",
"=",
"True",
")",
"return",
"self",
".",
"_currentResults"
] | Return a sequence of mappings of attribute IDs to column values, to
display to the user.
nextPage/prevPage will strive never to skip items whose column values
have not been returned by this method.
This is best explained by a demonstration. Let's say you have a table
viewing an item with attributes 'a' and 'b', like this:
oid | a | b
----+---+--
0 | 1 | 2
1 | 3 | 4
2 | 5 | 6
3 | 7 | 8
4 | 9 | 0
The table has 2 items per page. You call currentPage and receive a
page which contains items oid 0 and oid 1. item oid 1 is deleted.
If the next thing you do is to call nextPage, the result of currentPage
following that will be items beginning with item oid 2. This is
because although there are no longer enough items to populate a full
page from 0-1, the user has never seen item #2 on a page, so the 'next'
page from the user's point of view contains #2.
If instead, at that same point, the next thing you did was to call
currentPage, *then* nextPage and currentPage again, the first
currentPage results would contain items #0 and #2; the following
currentPage results would contain items #3 and #4. In this case, the
user *has* seen #2 already, so the user expects to see the following
item, not the same item again. | [
"Return",
"a",
"sequence",
"of",
"mappings",
"of",
"attribute",
"IDs",
"to",
"column",
"values",
"to",
"display",
"to",
"the",
"user",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/tdb.py#L106-L143 |
twisted/mantissa | xmantissa/tdb.py | TabularDataModel._sortAttributeValue | def _sortAttributeValue(self, offset):
"""
return the value of the sort attribute for the item at
'offset' in the results of the last query, otherwise None.
"""
if self._currentResults:
pageStart = (self._currentResults[offset][
self.currentSortColumn.attributeID],
self._currentResults[offset][
'__item__'].storeID)
else:
pageStart = None
return pageStart | python | def _sortAttributeValue(self, offset):
"""
return the value of the sort attribute for the item at
'offset' in the results of the last query, otherwise None.
"""
if self._currentResults:
pageStart = (self._currentResults[offset][
self.currentSortColumn.attributeID],
self._currentResults[offset][
'__item__'].storeID)
else:
pageStart = None
return pageStart | [
"def",
"_sortAttributeValue",
"(",
"self",
",",
"offset",
")",
":",
"if",
"self",
".",
"_currentResults",
":",
"pageStart",
"=",
"(",
"self",
".",
"_currentResults",
"[",
"offset",
"]",
"[",
"self",
".",
"currentSortColumn",
".",
"attributeID",
"]",
",",
"... | return the value of the sort attribute for the item at
'offset' in the results of the last query, otherwise None. | [
"return",
"the",
"value",
"of",
"the",
"sort",
"attribute",
"for",
"the",
"item",
"at",
"offset",
"in",
"the",
"results",
"of",
"the",
"last",
"query",
"otherwise",
"None",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/tdb.py#L226-L238 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.open_display | def open_display(self):
"""Establishes connection with X server and prepares objects
necessary to retrieve and send data.
"""
self.close_display() # Properly finish previous open_display()
XkbIgnoreExtension(False)
display_name = None
major = c_int(XkbMajorVersion)
minor = c_int(XkbMinorVersion)
reason = c_int()
self._display = XkbOpenDisplay(
display_name,
None, None, byref(major), byref(minor), byref(reason))
if not self._display:
if reason.value in OPEN_DISPLAY_ERRORS:
# Assume POSIX conformance
display_name = os.getenv("DISPLAY") or "default"
raise X11Error(OPEN_DISPLAY_ERRORS[reason.value].format(
libname="xkbgroup",
used_major=XkbMajorVersion,
used_minor=XkbMinorVersion,
found_major=major.value,
found_minor=minor.value,
display_name=display_name)
+ ".")
else:
raise X11Error("Unknown error {} from XkbOpenDisplay.".format(reason.value))
self._keyboard_description = XkbGetMap(self._display, 0, XkbUseCoreKbd)
if not self._keyboard_description:
self.close_display()
raise X11Error("Failed to get keyboard description.")
# Controls mask doesn't affect the availability of xkb->ctrls->num_groups anyway
# Just use a valid value, and xkb->ctrls->num_groups will be definitely set
status = XkbGetControls(self._display, XkbAllControlsMask, self._keyboard_description)
if status != Success:
self.close_display()
raise X11Error(GET_CONTROLS_ERRORS[status] + ".")
names_mask = XkbSymbolsNameMask | XkbGroupNamesMask
status = XkbGetNames(self._display, names_mask, self._keyboard_description)
if status != Success:
self.close_display()
raise X11Error(GET_NAMES_ERRORS[status] + ".") | python | def open_display(self):
"""Establishes connection with X server and prepares objects
necessary to retrieve and send data.
"""
self.close_display() # Properly finish previous open_display()
XkbIgnoreExtension(False)
display_name = None
major = c_int(XkbMajorVersion)
minor = c_int(XkbMinorVersion)
reason = c_int()
self._display = XkbOpenDisplay(
display_name,
None, None, byref(major), byref(minor), byref(reason))
if not self._display:
if reason.value in OPEN_DISPLAY_ERRORS:
# Assume POSIX conformance
display_name = os.getenv("DISPLAY") or "default"
raise X11Error(OPEN_DISPLAY_ERRORS[reason.value].format(
libname="xkbgroup",
used_major=XkbMajorVersion,
used_minor=XkbMinorVersion,
found_major=major.value,
found_minor=minor.value,
display_name=display_name)
+ ".")
else:
raise X11Error("Unknown error {} from XkbOpenDisplay.".format(reason.value))
self._keyboard_description = XkbGetMap(self._display, 0, XkbUseCoreKbd)
if not self._keyboard_description:
self.close_display()
raise X11Error("Failed to get keyboard description.")
# Controls mask doesn't affect the availability of xkb->ctrls->num_groups anyway
# Just use a valid value, and xkb->ctrls->num_groups will be definitely set
status = XkbGetControls(self._display, XkbAllControlsMask, self._keyboard_description)
if status != Success:
self.close_display()
raise X11Error(GET_CONTROLS_ERRORS[status] + ".")
names_mask = XkbSymbolsNameMask | XkbGroupNamesMask
status = XkbGetNames(self._display, names_mask, self._keyboard_description)
if status != Success:
self.close_display()
raise X11Error(GET_NAMES_ERRORS[status] + ".") | [
"def",
"open_display",
"(",
"self",
")",
":",
"self",
".",
"close_display",
"(",
")",
"# Properly finish previous open_display()",
"XkbIgnoreExtension",
"(",
"False",
")",
"display_name",
"=",
"None",
"major",
"=",
"c_int",
"(",
"XkbMajorVersion",
")",
"minor",
"=... | Establishes connection with X server and prepares objects
necessary to retrieve and send data. | [
"Establishes",
"connection",
"with",
"X",
"server",
"and",
"prepares",
"objects",
"necessary",
"to",
"retrieve",
"and",
"send",
"data",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L149-L197 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.close_display | def close_display(self):
"""Closes connection with X server and cleans up objects
created on open_display().
"""
if hasattr(self, "_keyboard_description") and self._keyboard_description:
names_mask = XkbSymbolsNameMask | XkbGroupNamesMask
XkbFreeNames(self._keyboard_description, names_mask, True)
XkbFreeControls(self._keyboard_description, XkbAllControlsMask, True)
XkbFreeClientMap(self._keyboard_description, 0, True)
del self._keyboard_description
if hasattr(self, "_display") and self._display:
XCloseDisplay(self._display)
del self._display | python | def close_display(self):
"""Closes connection with X server and cleans up objects
created on open_display().
"""
if hasattr(self, "_keyboard_description") and self._keyboard_description:
names_mask = XkbSymbolsNameMask | XkbGroupNamesMask
XkbFreeNames(self._keyboard_description, names_mask, True)
XkbFreeControls(self._keyboard_description, XkbAllControlsMask, True)
XkbFreeClientMap(self._keyboard_description, 0, True)
del self._keyboard_description
if hasattr(self, "_display") and self._display:
XCloseDisplay(self._display)
del self._display | [
"def",
"close_display",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_keyboard_description\"",
")",
"and",
"self",
".",
"_keyboard_description",
":",
"names_mask",
"=",
"XkbSymbolsNameMask",
"|",
"XkbGroupNamesMask",
"XkbFreeNames",
"(",
"self",
".... | Closes connection with X server and cleans up objects
created on open_display(). | [
"Closes",
"connection",
"with",
"X",
"server",
"and",
"cleans",
"up",
"objects",
"created",
"on",
"open_display",
"()",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L199-L212 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.groups_data | def groups_data(self):
"""All data about all groups (get-only).
:getter: Returns all data about all groups
:type: list of GroupData
"""
return _ListProxy(GroupData(num, name, symbol, variant)
for (num, name, symbol, variant)
in zip(range(self.groups_count),
self.groups_names,
self.groups_symbols,
self.groups_variants)) | python | def groups_data(self):
"""All data about all groups (get-only).
:getter: Returns all data about all groups
:type: list of GroupData
"""
return _ListProxy(GroupData(num, name, symbol, variant)
for (num, name, symbol, variant)
in zip(range(self.groups_count),
self.groups_names,
self.groups_symbols,
self.groups_variants)) | [
"def",
"groups_data",
"(",
"self",
")",
":",
"return",
"_ListProxy",
"(",
"GroupData",
"(",
"num",
",",
"name",
",",
"symbol",
",",
"variant",
")",
"for",
"(",
"num",
",",
"name",
",",
"symbol",
",",
"variant",
")",
"in",
"zip",
"(",
"range",
"(",
... | All data about all groups (get-only).
:getter: Returns all data about all groups
:type: list of GroupData | [
"All",
"data",
"about",
"all",
"groups",
"(",
"get",
"-",
"only",
")",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L228-L239 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.groups_count | def groups_count(self):
"""Number of all groups (get-only).
:getter: Returns number of all groups
:type: int
"""
if self._keyboard_description.contents.ctrls is not None:
return self._keyboard_description.contents.ctrls.contents.num_groups
else:
groups_source = self._groups_source
groups_count = 0
while (groups_count < XkbNumKbdGroups and
groups_source[groups_count] != None_):
groups_count += 1
return groups_count | python | def groups_count(self):
"""Number of all groups (get-only).
:getter: Returns number of all groups
:type: int
"""
if self._keyboard_description.contents.ctrls is not None:
return self._keyboard_description.contents.ctrls.contents.num_groups
else:
groups_source = self._groups_source
groups_count = 0
while (groups_count < XkbNumKbdGroups and
groups_source[groups_count] != None_):
groups_count += 1
return groups_count | [
"def",
"groups_count",
"(",
"self",
")",
":",
"if",
"self",
".",
"_keyboard_description",
".",
"contents",
".",
"ctrls",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_keyboard_description",
".",
"contents",
".",
"ctrls",
".",
"contents",
".",
"num_group... | Number of all groups (get-only).
:getter: Returns number of all groups
:type: int | [
"Number",
"of",
"all",
"groups",
"(",
"get",
"-",
"only",
")",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L242-L258 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.groups_names | def groups_names(self):
"""Names of all groups (get-only).
:getter: Returns names of all groups
:type: list of str
"""
return _ListProxy(self._get_group_name_by_num(i) for i in range(self.groups_count)) | python | def groups_names(self):
"""Names of all groups (get-only).
:getter: Returns names of all groups
:type: list of str
"""
return _ListProxy(self._get_group_name_by_num(i) for i in range(self.groups_count)) | [
"def",
"groups_names",
"(",
"self",
")",
":",
"return",
"_ListProxy",
"(",
"self",
".",
"_get_group_name_by_num",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"groups_count",
")",
")"
] | Names of all groups (get-only).
:getter: Returns names of all groups
:type: list of str | [
"Names",
"of",
"all",
"groups",
"(",
"get",
"-",
"only",
")",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L261-L267 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.group_data | def group_data(self):
"""All data about the current group (get-only).
:getter: Returns all data about the current group
:type: GroupData
"""
return GroupData(self.group_num,
self.group_name,
self.group_symbol,
self.group_variant) | python | def group_data(self):
"""All data about the current group (get-only).
:getter: Returns all data about the current group
:type: GroupData
"""
return GroupData(self.group_num,
self.group_name,
self.group_symbol,
self.group_variant) | [
"def",
"group_data",
"(",
"self",
")",
":",
"return",
"GroupData",
"(",
"self",
".",
"group_num",
",",
"self",
".",
"group_name",
",",
"self",
".",
"group_symbol",
",",
"self",
".",
"group_variant",
")"
] | All data about the current group (get-only).
:getter: Returns all data about the current group
:type: GroupData | [
"All",
"data",
"about",
"the",
"current",
"group",
"(",
"get",
"-",
"only",
")",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L291-L300 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.group_num | def group_num(self):
"""Current group number.
:getter: Returns current group number
:setter: Sets current group number
:type: int
"""
xkb_state = XkbStateRec()
XkbGetState(self._display, XkbUseCoreKbd, byref(xkb_state))
return xkb_state.group | python | def group_num(self):
"""Current group number.
:getter: Returns current group number
:setter: Sets current group number
:type: int
"""
xkb_state = XkbStateRec()
XkbGetState(self._display, XkbUseCoreKbd, byref(xkb_state))
return xkb_state.group | [
"def",
"group_num",
"(",
"self",
")",
":",
"xkb_state",
"=",
"XkbStateRec",
"(",
")",
"XkbGetState",
"(",
"self",
".",
"_display",
",",
"XkbUseCoreKbd",
",",
"byref",
"(",
"xkb_state",
")",
")",
"return",
"xkb_state",
".",
"group"
] | Current group number.
:getter: Returns current group number
:setter: Sets current group number
:type: int | [
"Current",
"group",
"number",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L303-L312 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.group_symbol | def group_symbol(self):
"""Current group symbol.
:getter: Returns current group symbol
:setter: Sets current group symbol
:type: str
"""
s_mapping = {symdata.index: symdata.symbol for symdata in self._symboldata_list}
return s_mapping[self.group_num] | python | def group_symbol(self):
"""Current group symbol.
:getter: Returns current group symbol
:setter: Sets current group symbol
:type: str
"""
s_mapping = {symdata.index: symdata.symbol for symdata in self._symboldata_list}
return s_mapping[self.group_num] | [
"def",
"group_symbol",
"(",
"self",
")",
":",
"s_mapping",
"=",
"{",
"symdata",
".",
"index",
":",
"symdata",
".",
"symbol",
"for",
"symdata",
"in",
"self",
".",
"_symboldata_list",
"}",
"return",
"s_mapping",
"[",
"self",
".",
"group_num",
"]"
] | Current group symbol.
:getter: Returns current group symbol
:setter: Sets current group symbol
:type: str | [
"Current",
"group",
"symbol",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L346-L354 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.group_variant | def group_variant(self):
"""Current group variant (get-only).
:getter: Returns current group variant
:type: str
"""
v_mapping = {symdata.index: symdata.variant for symdata in self._symboldata_list}
return v_mapping[self.group_num] or "" | python | def group_variant(self):
"""Current group variant (get-only).
:getter: Returns current group variant
:type: str
"""
v_mapping = {symdata.index: symdata.variant for symdata in self._symboldata_list}
return v_mapping[self.group_num] or "" | [
"def",
"group_variant",
"(",
"self",
")",
":",
"v_mapping",
"=",
"{",
"symdata",
".",
"index",
":",
"symdata",
".",
"variant",
"for",
"symdata",
"in",
"self",
".",
"_symboldata_list",
"}",
"return",
"v_mapping",
"[",
"self",
".",
"group_num",
"]",
"or",
... | Current group variant (get-only).
:getter: Returns current group variant
:type: str | [
"Current",
"group",
"variant",
"(",
"get",
"-",
"only",
")",
"."
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L367-L374 |
hcpl/xkbgroup | xkbgroup/core.py | XKeyboard.format | def format(self, format_str):
"""Returns a formatted version of format_str.
The only named replacement fields supported by this method and
their corresponding API calls are:
* {num} group_num
* {name} group_name
* {symbol} group_symbol
* {variant} group_variant
* {current_data} group_data
* {nums} groups_nums
* {names} groups_names
* {symbols} groups_symbols
* {variants} groups_variants
* {all_data} groups_data
Passing other replacement fields will result in raising exceptions.
:param format_str: a new style format string
:rtype: str
"""
return format_str.format(**{
"num": self.group_num,
"name": self.group_name,
"symbol": self.group_symbol,
"variant": self.group_variant,
"current_data": self.group_data,
"count": self.groups_count,
"names": self.groups_names,
"symbols": self.groups_symbols,
"variants": self.groups_variants,
"all_data": self.groups_data}) | python | def format(self, format_str):
"""Returns a formatted version of format_str.
The only named replacement fields supported by this method and
their corresponding API calls are:
* {num} group_num
* {name} group_name
* {symbol} group_symbol
* {variant} group_variant
* {current_data} group_data
* {nums} groups_nums
* {names} groups_names
* {symbols} groups_symbols
* {variants} groups_variants
* {all_data} groups_data
Passing other replacement fields will result in raising exceptions.
:param format_str: a new style format string
:rtype: str
"""
return format_str.format(**{
"num": self.group_num,
"name": self.group_name,
"symbol": self.group_symbol,
"variant": self.group_variant,
"current_data": self.group_data,
"count": self.groups_count,
"names": self.groups_names,
"symbols": self.groups_symbols,
"variants": self.groups_variants,
"all_data": self.groups_data}) | [
"def",
"format",
"(",
"self",
",",
"format_str",
")",
":",
"return",
"format_str",
".",
"format",
"(",
"*",
"*",
"{",
"\"num\"",
":",
"self",
".",
"group_num",
",",
"\"name\"",
":",
"self",
".",
"group_name",
",",
"\"symbol\"",
":",
"self",
".",
"group... | Returns a formatted version of format_str.
The only named replacement fields supported by this method and
their corresponding API calls are:
* {num} group_num
* {name} group_name
* {symbol} group_symbol
* {variant} group_variant
* {current_data} group_data
* {nums} groups_nums
* {names} groups_names
* {symbols} groups_symbols
* {variants} groups_variants
* {all_data} groups_data
Passing other replacement fields will result in raising exceptions.
:param format_str: a new style format string
:rtype: str | [
"Returns",
"a",
"formatted",
"version",
"of",
"format_str",
".",
"The",
"only",
"named",
"replacement",
"fields",
"supported",
"by",
"this",
"method",
"and",
"their",
"corresponding",
"API",
"calls",
"are",
":"
] | train | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L383-L414 |
p3trus/slave | slave/iec60488.py | _construct_register | def _construct_register(reg, default_reg):
"""Constructs a register dict."""
if reg:
x = dict((k, reg.get(k, d)) for k, d in default_reg.items())
else:
x = dict(default_reg)
return x | python | def _construct_register(reg, default_reg):
"""Constructs a register dict."""
if reg:
x = dict((k, reg.get(k, d)) for k, d in default_reg.items())
else:
x = dict(default_reg)
return x | [
"def",
"_construct_register",
"(",
"reg",
",",
"default_reg",
")",
":",
"if",
"reg",
":",
"x",
"=",
"dict",
"(",
"(",
"k",
",",
"reg",
".",
"get",
"(",
"k",
",",
"d",
")",
")",
"for",
"k",
",",
"d",
"in",
"default_reg",
".",
"items",
"(",
")",
... | Constructs a register dict. | [
"Constructs",
"a",
"register",
"dict",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/iec60488.py#L198-L204 |
p3trus/slave | slave/iec60488.py | PassingControl.pass_control_back | def pass_control_back(self, primary, secondary):
"""The address to which the controll is to be passed back.
Tells a potential controller device the address to which the control is
to be passed back.
:param primary: An integer in the range 0 to 30 representing the
primary address of the controller sending the command.
:param secondary: An integer in the range of 0 to 30 representing the
secondary address of the controller sending the command. If it is
missing, it indicates that the controller sending this command does
not have extended addressing.
"""
if secondary is None:
self._write(('*PCB', Integer(min=0, max=30)), primary)
else:
self._write(
('*PCB', [Integer(min=0, max=30), Integer(min=0, max=30)]),
primary,
secondary
) | python | def pass_control_back(self, primary, secondary):
"""The address to which the controll is to be passed back.
Tells a potential controller device the address to which the control is
to be passed back.
:param primary: An integer in the range 0 to 30 representing the
primary address of the controller sending the command.
:param secondary: An integer in the range of 0 to 30 representing the
secondary address of the controller sending the command. If it is
missing, it indicates that the controller sending this command does
not have extended addressing.
"""
if secondary is None:
self._write(('*PCB', Integer(min=0, max=30)), primary)
else:
self._write(
('*PCB', [Integer(min=0, max=30), Integer(min=0, max=30)]),
primary,
secondary
) | [
"def",
"pass_control_back",
"(",
"self",
",",
"primary",
",",
"secondary",
")",
":",
"if",
"secondary",
"is",
"None",
":",
"self",
".",
"_write",
"(",
"(",
"'*PCB'",
",",
"Integer",
"(",
"min",
"=",
"0",
",",
"max",
"=",
"30",
")",
")",
",",
"prima... | The address to which the controll is to be passed back.
Tells a potential controller device the address to which the control is
to be passed back.
:param primary: An integer in the range 0 to 30 representing the
primary address of the controller sending the command.
:param secondary: An integer in the range of 0 to 30 representing the
secondary address of the controller sending the command. If it is
missing, it indicates that the controller sending this command does
not have extended addressing. | [
"The",
"address",
"to",
"which",
"the",
"controll",
"is",
"to",
"be",
"passed",
"back",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/iec60488.py#L638-L659 |
jaraco/portend | portend.py | free | def free(host, port, timeout=float('Inf')):
"""
Wait for the specified port to become free (dropping or rejecting
requests). Return when the port is free or raise a Timeout if timeout has
elapsed.
Timeout may be specified in seconds or as a timedelta.
If timeout is None or ∞, the routine will run indefinitely.
>>> free('localhost', find_available_local_port())
"""
if not host:
raise ValueError("Host values of '' or None are not allowed.")
timer = timing.Timer(timeout)
while not timer.expired():
try:
# Expect a free port, so use a small timeout
Checker(timeout=0.1).assert_free(host, port)
return
except PortNotFree:
# Politely wait.
time.sleep(0.1)
raise Timeout("Port {port} not free on {host}.".format(**locals())) | python | def free(host, port, timeout=float('Inf')):
"""
Wait for the specified port to become free (dropping or rejecting
requests). Return when the port is free or raise a Timeout if timeout has
elapsed.
Timeout may be specified in seconds or as a timedelta.
If timeout is None or ∞, the routine will run indefinitely.
>>> free('localhost', find_available_local_port())
"""
if not host:
raise ValueError("Host values of '' or None are not allowed.")
timer = timing.Timer(timeout)
while not timer.expired():
try:
# Expect a free port, so use a small timeout
Checker(timeout=0.1).assert_free(host, port)
return
except PortNotFree:
# Politely wait.
time.sleep(0.1)
raise Timeout("Port {port} not free on {host}.".format(**locals())) | [
"def",
"free",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"float",
"(",
"'Inf'",
")",
")",
":",
"if",
"not",
"host",
":",
"raise",
"ValueError",
"(",
"\"Host values of '' or None are not allowed.\"",
")",
"timer",
"=",
"timing",
".",
"Timer",
"(",
"tim... | Wait for the specified port to become free (dropping or rejecting
requests). Return when the port is free or raise a Timeout if timeout has
elapsed.
Timeout may be specified in seconds or as a timedelta.
If timeout is None or ∞, the routine will run indefinitely.
>>> free('localhost', find_available_local_port()) | [
"Wait",
"for",
"the",
"specified",
"port",
"to",
"become",
"free",
"(",
"dropping",
"or",
"rejecting",
"requests",
")",
".",
"Return",
"when",
"the",
"port",
"is",
"free",
"or",
"raise",
"a",
"Timeout",
"if",
"timeout",
"has",
"elapsed",
"."
] | train | https://github.com/jaraco/portend/blob/077939464de072bb0caf1d88ac607381e012779e/portend.py#L98-L123 |
jaraco/portend | portend.py | find_available_local_port | def find_available_local_port():
"""
Find a free port on localhost.
>>> 0 < find_available_local_port() < 65536
True
"""
infos = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
family, proto, _, _, addr = next(iter(infos))
sock = socket.socket(family, proto)
sock.bind(addr)
addr, port = sock.getsockname()[:2]
sock.close()
return port | python | def find_available_local_port():
"""
Find a free port on localhost.
>>> 0 < find_available_local_port() < 65536
True
"""
infos = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
family, proto, _, _, addr = next(iter(infos))
sock = socket.socket(family, proto)
sock.bind(addr)
addr, port = sock.getsockname()[:2]
sock.close()
return port | [
"def",
"find_available_local_port",
"(",
")",
":",
"infos",
"=",
"socket",
".",
"getaddrinfo",
"(",
"None",
",",
"0",
",",
"socket",
".",
"AF_UNSPEC",
",",
"socket",
".",
"SOCK_STREAM",
")",
"family",
",",
"proto",
",",
"_",
",",
"_",
",",
"addr",
"=",... | Find a free port on localhost.
>>> 0 < find_available_local_port() < 65536
True | [
"Find",
"a",
"free",
"port",
"on",
"localhost",
"."
] | train | https://github.com/jaraco/portend/blob/077939464de072bb0caf1d88ac607381e012779e/portend.py#L163-L176 |
jaraco/portend | portend.py | Checker.assert_free | def assert_free(self, host, port=None):
"""
Assert that the given addr is free
in that all attempts to connect fail within the timeout
or raise a PortNotFree exception.
>>> free_port = find_available_local_port()
>>> Checker().assert_free('localhost', free_port)
>>> Checker().assert_free('127.0.0.1', free_port)
>>> Checker().assert_free('::1', free_port)
Also accepts an addr tuple
>>> addr = '::1', free_port, 0, 0
>>> Checker().assert_free(addr)
Host might refer to a server bind address like '::', which
should use localhost to perform the check.
>>> Checker().assert_free('::', free_port)
"""
if port is None and isinstance(host, abc.Sequence):
host, port = host[:2]
if platform.system() == 'Windows':
host = client_host(host)
info = socket.getaddrinfo(
host, port, socket.AF_UNSPEC, socket.SOCK_STREAM,
)
list(itertools.starmap(self._connect, info)) | python | def assert_free(self, host, port=None):
"""
Assert that the given addr is free
in that all attempts to connect fail within the timeout
or raise a PortNotFree exception.
>>> free_port = find_available_local_port()
>>> Checker().assert_free('localhost', free_port)
>>> Checker().assert_free('127.0.0.1', free_port)
>>> Checker().assert_free('::1', free_port)
Also accepts an addr tuple
>>> addr = '::1', free_port, 0, 0
>>> Checker().assert_free(addr)
Host might refer to a server bind address like '::', which
should use localhost to perform the check.
>>> Checker().assert_free('::', free_port)
"""
if port is None and isinstance(host, abc.Sequence):
host, port = host[:2]
if platform.system() == 'Windows':
host = client_host(host)
info = socket.getaddrinfo(
host, port, socket.AF_UNSPEC, socket.SOCK_STREAM,
)
list(itertools.starmap(self._connect, info)) | [
"def",
"assert_free",
"(",
"self",
",",
"host",
",",
"port",
"=",
"None",
")",
":",
"if",
"port",
"is",
"None",
"and",
"isinstance",
"(",
"host",
",",
"abc",
".",
"Sequence",
")",
":",
"host",
",",
"port",
"=",
"host",
"[",
":",
"2",
"]",
"if",
... | Assert that the given addr is free
in that all attempts to connect fail within the timeout
or raise a PortNotFree exception.
>>> free_port = find_available_local_port()
>>> Checker().assert_free('localhost', free_port)
>>> Checker().assert_free('127.0.0.1', free_port)
>>> Checker().assert_free('::1', free_port)
Also accepts an addr tuple
>>> addr = '::1', free_port, 0, 0
>>> Checker().assert_free(addr)
Host might refer to a server bind address like '::', which
should use localhost to perform the check.
>>> Checker().assert_free('::', free_port) | [
"Assert",
"that",
"the",
"given",
"addr",
"is",
"free",
"in",
"that",
"all",
"attempts",
"to",
"connect",
"fail",
"within",
"the",
"timeout",
"or",
"raise",
"a",
"PortNotFree",
"exception",
"."
] | train | https://github.com/jaraco/portend/blob/077939464de072bb0caf1d88ac607381e012779e/portend.py#L42-L71 |
twisted/mantissa | xmantissa/interstore.py | _createLocalRouter | def _createLocalRouter(siteStore):
"""
Create an L{IMessageRouter} provider for the default case, where no
L{IMessageRouter} powerup is installed on the top-level store.
It wraps a L{LocalMessageRouter} around the L{LoginSystem} installed on the
given site store.
If no L{LoginSystem} is present, this returns a null router which will
simply log an error but not deliver the message anywhere, until this
configuration error can be corrected.
@rtype: L{IMessageRouter}
"""
ls = siteStore.findUnique(LoginSystem, default=None)
if ls is None:
try:
raise UnsatisfiedRequirement()
except UnsatisfiedRequirement:
log.err(Failure(),
"You have opened a substore from a site store with no "
"LoginSystem. Message routing is disabled.")
return _NullRouter()
return LocalMessageRouter(ls) | python | def _createLocalRouter(siteStore):
"""
Create an L{IMessageRouter} provider for the default case, where no
L{IMessageRouter} powerup is installed on the top-level store.
It wraps a L{LocalMessageRouter} around the L{LoginSystem} installed on the
given site store.
If no L{LoginSystem} is present, this returns a null router which will
simply log an error but not deliver the message anywhere, until this
configuration error can be corrected.
@rtype: L{IMessageRouter}
"""
ls = siteStore.findUnique(LoginSystem, default=None)
if ls is None:
try:
raise UnsatisfiedRequirement()
except UnsatisfiedRequirement:
log.err(Failure(),
"You have opened a substore from a site store with no "
"LoginSystem. Message routing is disabled.")
return _NullRouter()
return LocalMessageRouter(ls) | [
"def",
"_createLocalRouter",
"(",
"siteStore",
")",
":",
"ls",
"=",
"siteStore",
".",
"findUnique",
"(",
"LoginSystem",
",",
"default",
"=",
"None",
")",
"if",
"ls",
"is",
"None",
":",
"try",
":",
"raise",
"UnsatisfiedRequirement",
"(",
")",
"except",
"Uns... | Create an L{IMessageRouter} provider for the default case, where no
L{IMessageRouter} powerup is installed on the top-level store.
It wraps a L{LocalMessageRouter} around the L{LoginSystem} installed on the
given site store.
If no L{LoginSystem} is present, this returns a null router which will
simply log an error but not deliver the message anywhere, until this
configuration error can be corrected.
@rtype: L{IMessageRouter} | [
"Create",
"an",
"L",
"{",
"IMessageRouter",
"}",
"provider",
"for",
"the",
"default",
"case",
"where",
"no",
"L",
"{",
"IMessageRouter",
"}",
"powerup",
"is",
"installed",
"on",
"the",
"top",
"-",
"level",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/interstore.py#L493-L516 |
twisted/mantissa | xmantissa/interstore.py | _FailedAnswer.redeliver | def redeliver(self):
"""
Re-deliver the answer to the consequence which previously handled it
by raising an exception.
This method is intended to be invoked after the code in question has
been upgraded. Since there are no buggy answer receivers in
production, nothing calls it yet.
"""
self.consequence.answerReceived(self.answerValue,
self.messageValue,
self.sender,
self.target)
self.deleteFromStore() | python | def redeliver(self):
"""
Re-deliver the answer to the consequence which previously handled it
by raising an exception.
This method is intended to be invoked after the code in question has
been upgraded. Since there are no buggy answer receivers in
production, nothing calls it yet.
"""
self.consequence.answerReceived(self.answerValue,
self.messageValue,
self.sender,
self.target)
self.deleteFromStore() | [
"def",
"redeliver",
"(",
"self",
")",
":",
"self",
".",
"consequence",
".",
"answerReceived",
"(",
"self",
".",
"answerValue",
",",
"self",
".",
"messageValue",
",",
"self",
".",
"sender",
",",
"self",
".",
"target",
")",
"self",
".",
"deleteFromStore",
... | Re-deliver the answer to the consequence which previously handled it
by raising an exception.
This method is intended to be invoked after the code in question has
been upgraded. Since there are no buggy answer receivers in
production, nothing calls it yet. | [
"Re",
"-",
"deliver",
"the",
"answer",
"to",
"the",
"consequence",
"which",
"previously",
"handled",
"it",
"by",
"raising",
"an",
"exception",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/interstore.py#L281-L294 |
twisted/mantissa | xmantissa/interstore.py | LocalMessageRouter._routerForAccount | def _routerForAccount(self, identifier):
"""
Locate an avatar by the username and domain portions of an
L{Identifier}, so that we can deliver a message to the appropriate
user.
"""
acct = self.loginSystem.accountByAddress(identifier.localpart,
identifier.domain)
return IMessageRouter(acct, None) | python | def _routerForAccount(self, identifier):
"""
Locate an avatar by the username and domain portions of an
L{Identifier}, so that we can deliver a message to the appropriate
user.
"""
acct = self.loginSystem.accountByAddress(identifier.localpart,
identifier.domain)
return IMessageRouter(acct, None) | [
"def",
"_routerForAccount",
"(",
"self",
",",
"identifier",
")",
":",
"acct",
"=",
"self",
".",
"loginSystem",
".",
"accountByAddress",
"(",
"identifier",
".",
"localpart",
",",
"identifier",
".",
"domain",
")",
"return",
"IMessageRouter",
"(",
"acct",
",",
... | Locate an avatar by the username and domain portions of an
L{Identifier}, so that we can deliver a message to the appropriate
user. | [
"Locate",
"an",
"avatar",
"by",
"the",
"username",
"and",
"domain",
"portions",
"of",
"an",
"L",
"{",
"Identifier",
"}",
"so",
"that",
"we",
"can",
"deliver",
"a",
"message",
"to",
"the",
"appropriate",
"user",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/interstore.py#L438-L446 |
twisted/mantissa | xmantissa/interstore.py | LocalMessageRouter.routeMessage | def routeMessage(self, sender, target, value, messageID):
"""
Implement L{IMessageRouter.routeMessage} by synchronously locating an
account via L{axiom.userbase.LoginSystem.accountByAddress}, and
delivering a message to it by calling a method on it.
"""
router = self._routerForAccount(target)
if router is not None:
router.routeMessage(sender, target, value, messageID)
else:
reverseRouter = self._routerForAccount(sender)
reverseRouter.routeAnswer(sender, target,
Value(DELIVERY_ERROR, ERROR_NO_USER),
messageID) | python | def routeMessage(self, sender, target, value, messageID):
"""
Implement L{IMessageRouter.routeMessage} by synchronously locating an
account via L{axiom.userbase.LoginSystem.accountByAddress}, and
delivering a message to it by calling a method on it.
"""
router = self._routerForAccount(target)
if router is not None:
router.routeMessage(sender, target, value, messageID)
else:
reverseRouter = self._routerForAccount(sender)
reverseRouter.routeAnswer(sender, target,
Value(DELIVERY_ERROR, ERROR_NO_USER),
messageID) | [
"def",
"routeMessage",
"(",
"self",
",",
"sender",
",",
"target",
",",
"value",
",",
"messageID",
")",
":",
"router",
"=",
"self",
".",
"_routerForAccount",
"(",
"target",
")",
"if",
"router",
"is",
"not",
"None",
":",
"router",
".",
"routeMessage",
"(",... | Implement L{IMessageRouter.routeMessage} by synchronously locating an
account via L{axiom.userbase.LoginSystem.accountByAddress}, and
delivering a message to it by calling a method on it. | [
"Implement",
"L",
"{",
"IMessageRouter",
".",
"routeMessage",
"}",
"by",
"synchronously",
"locating",
"an",
"account",
"via",
"L",
"{",
"axiom",
".",
"userbase",
".",
"LoginSystem",
".",
"accountByAddress",
"}",
"and",
"delivering",
"a",
"message",
"to",
"it",... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/interstore.py#L449-L462 |
twisted/mantissa | xmantissa/interstore.py | LocalMessageRouter.routeAnswer | def routeAnswer(self, originalSender, originalTarget, value, messageID):
"""
Implement L{IMessageRouter.routeMessage} by synchronously locating an
account via L{axiom.userbase.LoginSystem.accountByAddress}, and
delivering a response to it by calling a method on it and returning a
deferred containing its answer.
"""
router = self._routerForAccount(originalSender)
return router.routeAnswer(originalSender, originalTarget,
value, messageID) | python | def routeAnswer(self, originalSender, originalTarget, value, messageID):
"""
Implement L{IMessageRouter.routeMessage} by synchronously locating an
account via L{axiom.userbase.LoginSystem.accountByAddress}, and
delivering a response to it by calling a method on it and returning a
deferred containing its answer.
"""
router = self._routerForAccount(originalSender)
return router.routeAnswer(originalSender, originalTarget,
value, messageID) | [
"def",
"routeAnswer",
"(",
"self",
",",
"originalSender",
",",
"originalTarget",
",",
"value",
",",
"messageID",
")",
":",
"router",
"=",
"self",
".",
"_routerForAccount",
"(",
"originalSender",
")",
"return",
"router",
".",
"routeAnswer",
"(",
"originalSender",... | Implement L{IMessageRouter.routeMessage} by synchronously locating an
account via L{axiom.userbase.LoginSystem.accountByAddress}, and
delivering a response to it by calling a method on it and returning a
deferred containing its answer. | [
"Implement",
"L",
"{",
"IMessageRouter",
".",
"routeMessage",
"}",
"by",
"synchronously",
"locating",
"an",
"account",
"via",
"L",
"{",
"axiom",
".",
"userbase",
".",
"LoginSystem",
".",
"accountByAddress",
"}",
"and",
"delivering",
"a",
"response",
"to",
"it"... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/interstore.py#L465-L474 |
twisted/mantissa | xmantissa/interstore.py | MessageQueue._scheduleMePlease | def _scheduleMePlease(self):
"""
This queue needs to have its run() method invoked at some point in the
future. Tell the dependent scheduler to schedule it if it isn't
already pending execution.
"""
sched = IScheduler(self.store)
if len(list(sched.scheduledTimes(self))) == 0:
sched.schedule(self, sched.now()) | python | def _scheduleMePlease(self):
"""
This queue needs to have its run() method invoked at some point in the
future. Tell the dependent scheduler to schedule it if it isn't
already pending execution.
"""
sched = IScheduler(self.store)
if len(list(sched.scheduledTimes(self))) == 0:
sched.schedule(self, sched.now()) | [
"def",
"_scheduleMePlease",
"(",
"self",
")",
":",
"sched",
"=",
"IScheduler",
"(",
"self",
".",
"store",
")",
"if",
"len",
"(",
"list",
"(",
"sched",
".",
"scheduledTimes",
"(",
"self",
")",
")",
")",
"==",
"0",
":",
"sched",
".",
"schedule",
"(",
... | This queue needs to have its run() method invoked at some point in the
future. Tell the dependent scheduler to schedule it if it isn't
already pending execution. | [
"This",
"queue",
"needs",
"to",
"have",
"its",
"run",
"()",
"method",
"invoked",
"at",
"some",
"point",
"in",
"the",
"future",
".",
"Tell",
"the",
"dependent",
"scheduler",
"to",
"schedule",
"it",
"if",
"it",
"isn",
"t",
"already",
"pending",
"execution",
... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/interstore.py#L538-L546 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.