repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
newville/asteval | asteval/asteval.py | Interpreter.on_excepthandler | def on_excepthandler(self, node): # ('type', 'name', 'body')
"""Exception handler..."""
return (self.run(node.type), node.name, node.body) | python | def on_excepthandler(self, node): # ('type', 'name', 'body')
"""Exception handler..."""
return (self.run(node.type), node.name, node.body) | [
"def",
"on_excepthandler",
"(",
"self",
",",
"node",
")",
":",
"# ('type', 'name', 'body')",
"return",
"(",
"self",
".",
"run",
"(",
"node",
".",
"type",
")",
",",
"node",
".",
"name",
",",
"node",
".",
"body",
")"
] | Exception handler... | [
"Exception",
"handler",
"..."
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L697-L699 | train |
newville/asteval | asteval/asteval.py | Interpreter.on_call | def on_call(self, node):
"""Function execution."""
# ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)
func = self.run(node.func)
if not hasattr(func, '__call__') and not isinstance(func, type):
msg = "'%s' is not callable!!" % (func)
self.raise_exception(node, exc=TypeError, msg=msg)
args = [self.run(targ) for targ in node.args]
starargs = getattr(node, 'starargs', None)
if starargs is not None:
args = args + self.run(starargs)
keywords = {}
if six.PY3 and func == print:
keywords['file'] = self.writer
for key in node.keywords:
if not isinstance(key, ast.keyword):
msg = "keyword error in function call '%s'" % (func)
self.raise_exception(node, msg=msg)
keywords[key.arg] = self.run(key.value)
kwargs = getattr(node, 'kwargs', None)
if kwargs is not None:
keywords.update(self.run(kwargs))
try:
return func(*args, **keywords)
except Exception as ex:
self.raise_exception(
node, msg="Error running function call '%s' with args %s and "
"kwargs %s: %s" % (func.__name__, args, keywords, ex)) | python | def on_call(self, node):
"""Function execution."""
# ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)
func = self.run(node.func)
if not hasattr(func, '__call__') and not isinstance(func, type):
msg = "'%s' is not callable!!" % (func)
self.raise_exception(node, exc=TypeError, msg=msg)
args = [self.run(targ) for targ in node.args]
starargs = getattr(node, 'starargs', None)
if starargs is not None:
args = args + self.run(starargs)
keywords = {}
if six.PY3 and func == print:
keywords['file'] = self.writer
for key in node.keywords:
if not isinstance(key, ast.keyword):
msg = "keyword error in function call '%s'" % (func)
self.raise_exception(node, msg=msg)
keywords[key.arg] = self.run(key.value)
kwargs = getattr(node, 'kwargs', None)
if kwargs is not None:
keywords.update(self.run(kwargs))
try:
return func(*args, **keywords)
except Exception as ex:
self.raise_exception(
node, msg="Error running function call '%s' with args %s and "
"kwargs %s: %s" % (func.__name__, args, keywords, ex)) | [
"def",
"on_call",
"(",
"self",
",",
"node",
")",
":",
"# ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)",
"func",
"=",
"self",
".",
"run",
"(",
"node",
".",
"func",
")",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'__call__'",
")",
"and",
"not",
"isinstance",
"(",
"func",
",",
"type",
")",
":",
"msg",
"=",
"\"'%s' is not callable!!\"",
"%",
"(",
"func",
")",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"TypeError",
",",
"msg",
"=",
"msg",
")",
"args",
"=",
"[",
"self",
".",
"run",
"(",
"targ",
")",
"for",
"targ",
"in",
"node",
".",
"args",
"]",
"starargs",
"=",
"getattr",
"(",
"node",
",",
"'starargs'",
",",
"None",
")",
"if",
"starargs",
"is",
"not",
"None",
":",
"args",
"=",
"args",
"+",
"self",
".",
"run",
"(",
"starargs",
")",
"keywords",
"=",
"{",
"}",
"if",
"six",
".",
"PY3",
"and",
"func",
"==",
"print",
":",
"keywords",
"[",
"'file'",
"]",
"=",
"self",
".",
"writer",
"for",
"key",
"in",
"node",
".",
"keywords",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"ast",
".",
"keyword",
")",
":",
"msg",
"=",
"\"keyword error in function call '%s'\"",
"%",
"(",
"func",
")",
"self",
".",
"raise_exception",
"(",
"node",
",",
"msg",
"=",
"msg",
")",
"keywords",
"[",
"key",
".",
"arg",
"]",
"=",
"self",
".",
"run",
"(",
"key",
".",
"value",
")",
"kwargs",
"=",
"getattr",
"(",
"node",
",",
"'kwargs'",
",",
"None",
")",
"if",
"kwargs",
"is",
"not",
"None",
":",
"keywords",
".",
"update",
"(",
"self",
".",
"run",
"(",
"kwargs",
")",
")",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"raise_exception",
"(",
"node",
",",
"msg",
"=",
"\"Error running function call '%s' with args %s and \"",
"\"kwargs %s: %s\"",
"%",
"(",
"func",
".",
"__name__",
",",
"args",
",",
"keywords",
",",
"ex",
")",
")"
] | Function execution. | [
"Function",
"execution",
"."
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L744-L776 | train |
newville/asteval | asteval/asteval.py | Interpreter.on_functiondef | def on_functiondef(self, node):
"""Define procedures."""
# ('name', 'args', 'body', 'decorator_list')
if node.decorator_list:
raise Warning("decorated procedures not supported!")
kwargs = []
if not valid_symbol_name(node.name) or node.name in self.readonly_symbols:
errmsg = "invalid function name (reserved word?) %s" % node.name
self.raise_exception(node, exc=NameError, msg=errmsg)
offset = len(node.args.args) - len(node.args.defaults)
for idef, defnode in enumerate(node.args.defaults):
defval = self.run(defnode)
keyval = self.run(node.args.args[idef+offset])
kwargs.append((keyval, defval))
if version_info[0] == 3:
args = [tnode.arg for tnode in node.args.args[:offset]]
else:
args = [tnode.id for tnode in node.args.args[:offset]]
doc = None
nb0 = node.body[0]
if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str):
doc = nb0.value.s
varkws = node.args.kwarg
vararg = node.args.vararg
if version_info[0] == 3:
if isinstance(vararg, ast.arg):
vararg = vararg.arg
if isinstance(varkws, ast.arg):
varkws = varkws.arg
self.symtable[node.name] = Procedure(node.name, self, doc=doc,
lineno=self.lineno,
body=node.body,
args=args, kwargs=kwargs,
vararg=vararg, varkws=varkws)
if node.name in self.no_deepcopy:
self.no_deepcopy.remove(node.name) | python | def on_functiondef(self, node):
"""Define procedures."""
# ('name', 'args', 'body', 'decorator_list')
if node.decorator_list:
raise Warning("decorated procedures not supported!")
kwargs = []
if not valid_symbol_name(node.name) or node.name in self.readonly_symbols:
errmsg = "invalid function name (reserved word?) %s" % node.name
self.raise_exception(node, exc=NameError, msg=errmsg)
offset = len(node.args.args) - len(node.args.defaults)
for idef, defnode in enumerate(node.args.defaults):
defval = self.run(defnode)
keyval = self.run(node.args.args[idef+offset])
kwargs.append((keyval, defval))
if version_info[0] == 3:
args = [tnode.arg for tnode in node.args.args[:offset]]
else:
args = [tnode.id for tnode in node.args.args[:offset]]
doc = None
nb0 = node.body[0]
if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str):
doc = nb0.value.s
varkws = node.args.kwarg
vararg = node.args.vararg
if version_info[0] == 3:
if isinstance(vararg, ast.arg):
vararg = vararg.arg
if isinstance(varkws, ast.arg):
varkws = varkws.arg
self.symtable[node.name] = Procedure(node.name, self, doc=doc,
lineno=self.lineno,
body=node.body,
args=args, kwargs=kwargs,
vararg=vararg, varkws=varkws)
if node.name in self.no_deepcopy:
self.no_deepcopy.remove(node.name) | [
"def",
"on_functiondef",
"(",
"self",
",",
"node",
")",
":",
"# ('name', 'args', 'body', 'decorator_list')",
"if",
"node",
".",
"decorator_list",
":",
"raise",
"Warning",
"(",
"\"decorated procedures not supported!\"",
")",
"kwargs",
"=",
"[",
"]",
"if",
"not",
"valid_symbol_name",
"(",
"node",
".",
"name",
")",
"or",
"node",
".",
"name",
"in",
"self",
".",
"readonly_symbols",
":",
"errmsg",
"=",
"\"invalid function name (reserved word?) %s\"",
"%",
"node",
".",
"name",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"NameError",
",",
"msg",
"=",
"errmsg",
")",
"offset",
"=",
"len",
"(",
"node",
".",
"args",
".",
"args",
")",
"-",
"len",
"(",
"node",
".",
"args",
".",
"defaults",
")",
"for",
"idef",
",",
"defnode",
"in",
"enumerate",
"(",
"node",
".",
"args",
".",
"defaults",
")",
":",
"defval",
"=",
"self",
".",
"run",
"(",
"defnode",
")",
"keyval",
"=",
"self",
".",
"run",
"(",
"node",
".",
"args",
".",
"args",
"[",
"idef",
"+",
"offset",
"]",
")",
"kwargs",
".",
"append",
"(",
"(",
"keyval",
",",
"defval",
")",
")",
"if",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"args",
"=",
"[",
"tnode",
".",
"arg",
"for",
"tnode",
"in",
"node",
".",
"args",
".",
"args",
"[",
":",
"offset",
"]",
"]",
"else",
":",
"args",
"=",
"[",
"tnode",
".",
"id",
"for",
"tnode",
"in",
"node",
".",
"args",
".",
"args",
"[",
":",
"offset",
"]",
"]",
"doc",
"=",
"None",
"nb0",
"=",
"node",
".",
"body",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"nb0",
",",
"ast",
".",
"Expr",
")",
"and",
"isinstance",
"(",
"nb0",
".",
"value",
",",
"ast",
".",
"Str",
")",
":",
"doc",
"=",
"nb0",
".",
"value",
".",
"s",
"varkws",
"=",
"node",
".",
"args",
".",
"kwarg",
"vararg",
"=",
"node",
".",
"args",
".",
"vararg",
"if",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"if",
"isinstance",
"(",
"vararg",
",",
"ast",
".",
"arg",
")",
":",
"vararg",
"=",
"vararg",
".",
"arg",
"if",
"isinstance",
"(",
"varkws",
",",
"ast",
".",
"arg",
")",
":",
"varkws",
"=",
"varkws",
".",
"arg",
"self",
".",
"symtable",
"[",
"node",
".",
"name",
"]",
"=",
"Procedure",
"(",
"node",
".",
"name",
",",
"self",
",",
"doc",
"=",
"doc",
",",
"lineno",
"=",
"self",
".",
"lineno",
",",
"body",
"=",
"node",
".",
"body",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"vararg",
"=",
"vararg",
",",
"varkws",
"=",
"varkws",
")",
"if",
"node",
".",
"name",
"in",
"self",
".",
"no_deepcopy",
":",
"self",
".",
"no_deepcopy",
".",
"remove",
"(",
"node",
".",
"name",
")"
] | Define procedures. | [
"Define",
"procedures",
"."
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L782-L823 | train |
newville/asteval | asteval/astutils.py | safe_pow | def safe_pow(base, exp):
"""safe version of pow"""
if exp > MAX_EXPONENT:
raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT))
return base ** exp | python | def safe_pow(base, exp):
"""safe version of pow"""
if exp > MAX_EXPONENT:
raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT))
return base ** exp | [
"def",
"safe_pow",
"(",
"base",
",",
"exp",
")",
":",
"if",
"exp",
">",
"MAX_EXPONENT",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid exponent, max exponent is {}\"",
".",
"format",
"(",
"MAX_EXPONENT",
")",
")",
"return",
"base",
"**",
"exp"
] | safe version of pow | [
"safe",
"version",
"of",
"pow"
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L183-L187 | train |
newville/asteval | asteval/astutils.py | safe_mult | def safe_mult(a, b):
"""safe version of multiply"""
if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a * b | python | def safe_mult(a, b):
"""safe version of multiply"""
if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a * b | [
"def",
"safe_mult",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"str",
")",
"and",
"isinstance",
"(",
"b",
",",
"int",
")",
"and",
"len",
"(",
"a",
")",
"*",
"b",
">",
"MAX_STR_LEN",
":",
"raise",
"RuntimeError",
"(",
"\"String length exceeded, max string length is {}\"",
".",
"format",
"(",
"MAX_STR_LEN",
")",
")",
"return",
"a",
"*",
"b"
] | safe version of multiply | [
"safe",
"version",
"of",
"multiply"
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L190-L194 | train |
newville/asteval | asteval/astutils.py | safe_add | def safe_add(a, b):
"""safe version of add"""
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a + b | python | def safe_add(a, b):
"""safe version of add"""
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a + b | [
"def",
"safe_add",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"str",
")",
"and",
"isinstance",
"(",
"b",
",",
"str",
")",
"and",
"len",
"(",
"a",
")",
"+",
"len",
"(",
"b",
")",
">",
"MAX_STR_LEN",
":",
"raise",
"RuntimeError",
"(",
"\"String length exceeded, max string length is {}\"",
".",
"format",
"(",
"MAX_STR_LEN",
")",
")",
"return",
"a",
"+",
"b"
] | safe version of add | [
"safe",
"version",
"of",
"add"
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L197-L201 | train |
newville/asteval | asteval/astutils.py | safe_lshift | def safe_lshift(a, b):
"""safe version of lshift"""
if b > MAX_SHIFT:
raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT))
return a << b | python | def safe_lshift(a, b):
"""safe version of lshift"""
if b > MAX_SHIFT:
raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT))
return a << b | [
"def",
"safe_lshift",
"(",
"a",
",",
"b",
")",
":",
"if",
"b",
">",
"MAX_SHIFT",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid left shift, max left shift is {}\"",
".",
"format",
"(",
"MAX_SHIFT",
")",
")",
"return",
"a",
"<<",
"b"
] | safe version of lshift | [
"safe",
"version",
"of",
"lshift"
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L204-L208 | train |
newville/asteval | asteval/astutils.py | valid_symbol_name | def valid_symbol_name(name):
"""Determine whether the input symbol name is a valid name.
Arguments
---------
name : str
name to check for validity.
Returns
--------
valid : bool
whether name is a a valid symbol name
This checks for Python reserved words and that the name matches
the regular expression ``[a-zA-Z_][a-zA-Z0-9_]``
"""
if name in RESERVED_WORDS:
return False
gen = generate_tokens(io.BytesIO(name.encode('utf-8')).readline)
typ, _, start, end, _ = next(gen)
if typ == tk_ENCODING:
typ, _, start, end, _ = next(gen)
return typ == tk_NAME and start == (1, 0) and end == (1, len(name)) | python | def valid_symbol_name(name):
"""Determine whether the input symbol name is a valid name.
Arguments
---------
name : str
name to check for validity.
Returns
--------
valid : bool
whether name is a a valid symbol name
This checks for Python reserved words and that the name matches
the regular expression ``[a-zA-Z_][a-zA-Z0-9_]``
"""
if name in RESERVED_WORDS:
return False
gen = generate_tokens(io.BytesIO(name.encode('utf-8')).readline)
typ, _, start, end, _ = next(gen)
if typ == tk_ENCODING:
typ, _, start, end, _ = next(gen)
return typ == tk_NAME and start == (1, 0) and end == (1, len(name)) | [
"def",
"valid_symbol_name",
"(",
"name",
")",
":",
"if",
"name",
"in",
"RESERVED_WORDS",
":",
"return",
"False",
"gen",
"=",
"generate_tokens",
"(",
"io",
".",
"BytesIO",
"(",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"readline",
")",
"typ",
",",
"_",
",",
"start",
",",
"end",
",",
"_",
"=",
"next",
"(",
"gen",
")",
"if",
"typ",
"==",
"tk_ENCODING",
":",
"typ",
",",
"_",
",",
"start",
",",
"end",
",",
"_",
"=",
"next",
"(",
"gen",
")",
"return",
"typ",
"==",
"tk_NAME",
"and",
"start",
"==",
"(",
"1",
",",
"0",
")",
"and",
"end",
"==",
"(",
"1",
",",
"len",
"(",
"name",
")",
")"
] | Determine whether the input symbol name is a valid name.
Arguments
---------
name : str
name to check for validity.
Returns
--------
valid : bool
whether name is a a valid symbol name
This checks for Python reserved words and that the name matches
the regular expression ``[a-zA-Z_][a-zA-Z0-9_]`` | [
"Determine",
"whether",
"the",
"input",
"symbol",
"name",
"is",
"a",
"valid",
"name",
"."
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L241-L264 | train |
newville/asteval | asteval/astutils.py | make_symbol_table | def make_symbol_table(use_numpy=True, **kws):
"""Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Returns
--------
symbol_table : dict
a symbol table that can be used in `asteval.Interpereter`
"""
symtable = {}
for sym in FROM_PY:
if sym in builtins:
symtable[sym] = builtins[sym]
for sym in FROM_MATH:
if hasattr(math, sym):
symtable[sym] = getattr(math, sym)
if HAS_NUMPY and use_numpy:
for sym in FROM_NUMPY:
if hasattr(numpy, sym):
symtable[sym] = getattr(numpy, sym)
for name, sym in NUMPY_RENAMES.items():
if hasattr(numpy, sym):
symtable[name] = getattr(numpy, sym)
symtable.update(LOCALFUNCS)
symtable.update(kws)
return symtable | python | def make_symbol_table(use_numpy=True, **kws):
"""Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Returns
--------
symbol_table : dict
a symbol table that can be used in `asteval.Interpereter`
"""
symtable = {}
for sym in FROM_PY:
if sym in builtins:
symtable[sym] = builtins[sym]
for sym in FROM_MATH:
if hasattr(math, sym):
symtable[sym] = getattr(math, sym)
if HAS_NUMPY and use_numpy:
for sym in FROM_NUMPY:
if hasattr(numpy, sym):
symtable[sym] = getattr(numpy, sym)
for name, sym in NUMPY_RENAMES.items():
if hasattr(numpy, sym):
symtable[name] = getattr(numpy, sym)
symtable.update(LOCALFUNCS)
symtable.update(kws)
return symtable | [
"def",
"make_symbol_table",
"(",
"use_numpy",
"=",
"True",
",",
"*",
"*",
"kws",
")",
":",
"symtable",
"=",
"{",
"}",
"for",
"sym",
"in",
"FROM_PY",
":",
"if",
"sym",
"in",
"builtins",
":",
"symtable",
"[",
"sym",
"]",
"=",
"builtins",
"[",
"sym",
"]",
"for",
"sym",
"in",
"FROM_MATH",
":",
"if",
"hasattr",
"(",
"math",
",",
"sym",
")",
":",
"symtable",
"[",
"sym",
"]",
"=",
"getattr",
"(",
"math",
",",
"sym",
")",
"if",
"HAS_NUMPY",
"and",
"use_numpy",
":",
"for",
"sym",
"in",
"FROM_NUMPY",
":",
"if",
"hasattr",
"(",
"numpy",
",",
"sym",
")",
":",
"symtable",
"[",
"sym",
"]",
"=",
"getattr",
"(",
"numpy",
",",
"sym",
")",
"for",
"name",
",",
"sym",
"in",
"NUMPY_RENAMES",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"numpy",
",",
"sym",
")",
":",
"symtable",
"[",
"name",
"]",
"=",
"getattr",
"(",
"numpy",
",",
"sym",
")",
"symtable",
".",
"update",
"(",
"LOCALFUNCS",
")",
"symtable",
".",
"update",
"(",
"kws",
")",
"return",
"symtable"
] | Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Returns
--------
symbol_table : dict
a symbol table that can be used in `asteval.Interpereter` | [
"Create",
"a",
"default",
"symboltable",
"taking",
"dict",
"of",
"user",
"-",
"defined",
"symbols",
"."
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L351-L389 | train |
newville/asteval | asteval/astutils.py | ExceptionHolder.get_error | def get_error(self):
"""Retrieve error data."""
col_offset = -1
if self.node is not None:
try:
col_offset = self.node.col_offset
except AttributeError:
pass
try:
exc_name = self.exc.__name__
except AttributeError:
exc_name = str(self.exc)
if exc_name in (None, 'None'):
exc_name = 'UnknownError'
out = [" %s" % self.expr]
if col_offset > 0:
out.append(" %s^^^" % ((col_offset)*' '))
out.append(str(self.msg))
return (exc_name, '\n'.join(out)) | python | def get_error(self):
"""Retrieve error data."""
col_offset = -1
if self.node is not None:
try:
col_offset = self.node.col_offset
except AttributeError:
pass
try:
exc_name = self.exc.__name__
except AttributeError:
exc_name = str(self.exc)
if exc_name in (None, 'None'):
exc_name = 'UnknownError'
out = [" %s" % self.expr]
if col_offset > 0:
out.append(" %s^^^" % ((col_offset)*' '))
out.append(str(self.msg))
return (exc_name, '\n'.join(out)) | [
"def",
"get_error",
"(",
"self",
")",
":",
"col_offset",
"=",
"-",
"1",
"if",
"self",
".",
"node",
"is",
"not",
"None",
":",
"try",
":",
"col_offset",
"=",
"self",
".",
"node",
".",
"col_offset",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"exc_name",
"=",
"self",
".",
"exc",
".",
"__name__",
"except",
"AttributeError",
":",
"exc_name",
"=",
"str",
"(",
"self",
".",
"exc",
")",
"if",
"exc_name",
"in",
"(",
"None",
",",
"'None'",
")",
":",
"exc_name",
"=",
"'UnknownError'",
"out",
"=",
"[",
"\" %s\"",
"%",
"self",
".",
"expr",
"]",
"if",
"col_offset",
">",
"0",
":",
"out",
".",
"append",
"(",
"\" %s^^^\"",
"%",
"(",
"(",
"col_offset",
")",
"*",
"' '",
")",
")",
"out",
".",
"append",
"(",
"str",
"(",
"self",
".",
"msg",
")",
")",
"return",
"(",
"exc_name",
",",
"'\\n'",
".",
"join",
"(",
"out",
")",
")"
] | Retrieve error data. | [
"Retrieve",
"error",
"data",
"."
] | bb7d3a95079f96ead75ea55662014bbcc82f9b28 | https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L303-L322 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.add_config_path | def add_config_path(self, path):
"""Add a path for Vyper to search for the config file in.
Can be called multiple times to define multiple search paths.
"""
abspath = util.abs_pathify(path)
if abspath not in self._config_paths:
log.info("Adding {0} to paths to search".format(abspath))
self._config_paths.append(abspath) | python | def add_config_path(self, path):
"""Add a path for Vyper to search for the config file in.
Can be called multiple times to define multiple search paths.
"""
abspath = util.abs_pathify(path)
if abspath not in self._config_paths:
log.info("Adding {0} to paths to search".format(abspath))
self._config_paths.append(abspath) | [
"def",
"add_config_path",
"(",
"self",
",",
"path",
")",
":",
"abspath",
"=",
"util",
".",
"abs_pathify",
"(",
"path",
")",
"if",
"abspath",
"not",
"in",
"self",
".",
"_config_paths",
":",
"log",
".",
"info",
"(",
"\"Adding {0} to paths to search\"",
".",
"format",
"(",
"abspath",
")",
")",
"self",
".",
"_config_paths",
".",
"append",
"(",
"abspath",
")"
] | Add a path for Vyper to search for the config file in.
Can be called multiple times to define multiple search paths. | [
"Add",
"a",
"path",
"for",
"Vyper",
"to",
"search",
"for",
"the",
"config",
"file",
"in",
".",
"Can",
"be",
"called",
"multiple",
"times",
"to",
"define",
"multiple",
"search",
"paths",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L122-L129 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.sub | def sub(self, key):
"""Returns new Vyper instance representing a sub tree of this instance.
"""
subv = Vyper()
data = self.get(key)
if isinstance(data, dict):
subv._config = data
return subv
else:
return None | python | def sub(self, key):
"""Returns new Vyper instance representing a sub tree of this instance.
"""
subv = Vyper()
data = self.get(key)
if isinstance(data, dict):
subv._config = data
return subv
else:
return None | [
"def",
"sub",
"(",
"self",
",",
"key",
")",
":",
"subv",
"=",
"Vyper",
"(",
")",
"data",
"=",
"self",
".",
"get",
"(",
"key",
")",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"subv",
".",
"_config",
"=",
"data",
"return",
"subv",
"else",
":",
"return",
"None"
] | Returns new Vyper instance representing a sub tree of this instance. | [
"Returns",
"new",
"Vyper",
"instance",
"representing",
"a",
"sub",
"tree",
"of",
"this",
"instance",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L224-L233 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.unmarshall_key | def unmarshall_key(self, key, cls):
"""Takes a single key and unmarshalls it into a class."""
return setattr(cls, key, self.get(key)) | python | def unmarshall_key(self, key, cls):
"""Takes a single key and unmarshalls it into a class."""
return setattr(cls, key, self.get(key)) | [
"def",
"unmarshall_key",
"(",
"self",
",",
"key",
",",
"cls",
")",
":",
"return",
"setattr",
"(",
"cls",
",",
"key",
",",
"self",
".",
"get",
"(",
"key",
")",
")"
] | Takes a single key and unmarshalls it into a class. | [
"Takes",
"a",
"single",
"key",
"and",
"unmarshalls",
"it",
"into",
"a",
"class",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L235-L237 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.unmarshall | def unmarshall(self, cls):
"""Unmarshalls the config into a class. Make sure that the tags on
the attributes of the class are properly set.
"""
for k, v in self.all_settings().items():
setattr(cls, k, v)
return cls | python | def unmarshall(self, cls):
"""Unmarshalls the config into a class. Make sure that the tags on
the attributes of the class are properly set.
"""
for k, v in self.all_settings().items():
setattr(cls, k, v)
return cls | [
"def",
"unmarshall",
"(",
"self",
",",
"cls",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"all_settings",
"(",
")",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"cls",
",",
"k",
",",
"v",
")",
"return",
"cls"
] | Unmarshalls the config into a class. Make sure that the tags on
the attributes of the class are properly set. | [
"Unmarshalls",
"the",
"config",
"into",
"a",
"class",
".",
"Make",
"sure",
"that",
"the",
"tags",
"on",
"the",
"attributes",
"of",
"the",
"class",
"are",
"properly",
"set",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L239-L246 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.bind_env | def bind_env(self, *input_):
"""Binds a Vyper key to a ENV variable.
ENV variables are case sensitive.
If only a key is provided, it will use the env key matching the key,
uppercased.
`env_prefix` will be used when set when env name is not provided.
"""
if len(input_) == 0:
return "bind_env missing key to bind to"
key = input_[0].lower()
if len(input_) == 1:
env_key = self._merge_with_env_prefix(key)
else:
env_key = input_[1]
self._env[key] = env_key
if self._key_delimiter in key:
parts = input_[0].split(self._key_delimiter)
env_info = {
"path": parts[1:-1],
"final_key": parts[-1],
"env_key": env_key
}
if self._env.get(parts[0]) is None:
self._env[parts[0]] = [env_info]
else:
self._env[parts[0]].append(env_info)
return None | python | def bind_env(self, *input_):
"""Binds a Vyper key to a ENV variable.
ENV variables are case sensitive.
If only a key is provided, it will use the env key matching the key,
uppercased.
`env_prefix` will be used when set when env name is not provided.
"""
if len(input_) == 0:
return "bind_env missing key to bind to"
key = input_[0].lower()
if len(input_) == 1:
env_key = self._merge_with_env_prefix(key)
else:
env_key = input_[1]
self._env[key] = env_key
if self._key_delimiter in key:
parts = input_[0].split(self._key_delimiter)
env_info = {
"path": parts[1:-1],
"final_key": parts[-1],
"env_key": env_key
}
if self._env.get(parts[0]) is None:
self._env[parts[0]] = [env_info]
else:
self._env[parts[0]].append(env_info)
return None | [
"def",
"bind_env",
"(",
"self",
",",
"*",
"input_",
")",
":",
"if",
"len",
"(",
"input_",
")",
"==",
"0",
":",
"return",
"\"bind_env missing key to bind to\"",
"key",
"=",
"input_",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"len",
"(",
"input_",
")",
"==",
"1",
":",
"env_key",
"=",
"self",
".",
"_merge_with_env_prefix",
"(",
"key",
")",
"else",
":",
"env_key",
"=",
"input_",
"[",
"1",
"]",
"self",
".",
"_env",
"[",
"key",
"]",
"=",
"env_key",
"if",
"self",
".",
"_key_delimiter",
"in",
"key",
":",
"parts",
"=",
"input_",
"[",
"0",
"]",
".",
"split",
"(",
"self",
".",
"_key_delimiter",
")",
"env_info",
"=",
"{",
"\"path\"",
":",
"parts",
"[",
"1",
":",
"-",
"1",
"]",
",",
"\"final_key\"",
":",
"parts",
"[",
"-",
"1",
"]",
",",
"\"env_key\"",
":",
"env_key",
"}",
"if",
"self",
".",
"_env",
".",
"get",
"(",
"parts",
"[",
"0",
"]",
")",
"is",
"None",
":",
"self",
".",
"_env",
"[",
"parts",
"[",
"0",
"]",
"]",
"=",
"[",
"env_info",
"]",
"else",
":",
"self",
".",
"_env",
"[",
"parts",
"[",
"0",
"]",
"]",
".",
"append",
"(",
"env_info",
")",
"return",
"None"
] | Binds a Vyper key to a ENV variable.
ENV variables are case sensitive.
If only a key is provided, it will use the env key matching the key,
uppercased.
`env_prefix` will be used when set when env name is not provided. | [
"Binds",
"a",
"Vyper",
"key",
"to",
"a",
"ENV",
"variable",
".",
"ENV",
"variables",
"are",
"case",
"sensitive",
".",
"If",
"only",
"a",
"key",
"is",
"provided",
"it",
"will",
"use",
"the",
"env",
"key",
"matching",
"the",
"key",
"uppercased",
".",
"env_prefix",
"will",
"be",
"used",
"when",
"set",
"when",
"env",
"name",
"is",
"not",
"provided",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L289-L321 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.is_set | def is_set(self, key):
"""Check to see if the key has been set in any of the data locations.
"""
path = key.split(self._key_delimiter)
lower_case_key = key.lower()
val = self._find(lower_case_key)
if val is None:
source = self._find(path[0].lower())
if source is not None and isinstance(source, dict):
val = self._search_dict(source, path[1::])
return val is not None | python | def is_set(self, key):
"""Check to see if the key has been set in any of the data locations.
"""
path = key.split(self._key_delimiter)
lower_case_key = key.lower()
val = self._find(lower_case_key)
if val is None:
source = self._find(path[0].lower())
if source is not None and isinstance(source, dict):
val = self._search_dict(source, path[1::])
return val is not None | [
"def",
"is_set",
"(",
"self",
",",
"key",
")",
":",
"path",
"=",
"key",
".",
"split",
"(",
"self",
".",
"_key_delimiter",
")",
"lower_case_key",
"=",
"key",
".",
"lower",
"(",
")",
"val",
"=",
"self",
".",
"_find",
"(",
"lower_case_key",
")",
"if",
"val",
"is",
"None",
":",
"source",
"=",
"self",
".",
"_find",
"(",
"path",
"[",
"0",
"]",
".",
"lower",
"(",
")",
")",
"if",
"source",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"source",
",",
"dict",
")",
":",
"val",
"=",
"self",
".",
"_search_dict",
"(",
"source",
",",
"path",
"[",
"1",
":",
":",
"]",
")",
"return",
"val",
"is",
"not",
"None"
] | Check to see if the key has been set in any of the data locations. | [
"Check",
"to",
"see",
"if",
"the",
"key",
"has",
"been",
"set",
"in",
"any",
"of",
"the",
"data",
"locations",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L438-L451 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.register_alias | def register_alias(self, alias, key):
"""Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application.
"""
alias = alias.lower()
key = key.lower()
if alias != key and alias != self._real_key(key):
exists = self._aliases.get(alias)
if exists is None:
# if we alias something that exists in one of the dicts to
# another name, we'll never be able to get that value using the
# original name, so move the config value to the new _real_key.
val = self._config.get(alias)
if val:
self._config.pop(alias)
self._config[key] = val
val = self._kvstore.get(alias)
if val:
self._kvstore.pop(alias)
self._kvstore[key] = val
val = self._defaults.get(alias)
if val:
self._defaults.pop(alias)
self._defaults[key] = val
val = self._override.get(alias)
if val:
self._override.pop(alias)
self._override[key] = val
self._aliases[alias] = key
else:
log.warning("Creating circular reference alias {0} {1} {2}".format(
alias, key, self._real_key(key))) | python | def register_alias(self, alias, key):
"""Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application.
"""
alias = alias.lower()
key = key.lower()
if alias != key and alias != self._real_key(key):
exists = self._aliases.get(alias)
if exists is None:
# if we alias something that exists in one of the dicts to
# another name, we'll never be able to get that value using the
# original name, so move the config value to the new _real_key.
val = self._config.get(alias)
if val:
self._config.pop(alias)
self._config[key] = val
val = self._kvstore.get(alias)
if val:
self._kvstore.pop(alias)
self._kvstore[key] = val
val = self._defaults.get(alias)
if val:
self._defaults.pop(alias)
self._defaults[key] = val
val = self._override.get(alias)
if val:
self._override.pop(alias)
self._override[key] = val
self._aliases[alias] = key
else:
log.warning("Creating circular reference alias {0} {1} {2}".format(
alias, key, self._real_key(key))) | [
"def",
"register_alias",
"(",
"self",
",",
"alias",
",",
"key",
")",
":",
"alias",
"=",
"alias",
".",
"lower",
"(",
")",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"if",
"alias",
"!=",
"key",
"and",
"alias",
"!=",
"self",
".",
"_real_key",
"(",
"key",
")",
":",
"exists",
"=",
"self",
".",
"_aliases",
".",
"get",
"(",
"alias",
")",
"if",
"exists",
"is",
"None",
":",
"# if we alias something that exists in one of the dicts to",
"# another name, we'll never be able to get that value using the",
"# original name, so move the config value to the new _real_key.",
"val",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_config",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_config",
"[",
"key",
"]",
"=",
"val",
"val",
"=",
"self",
".",
"_kvstore",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_kvstore",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_kvstore",
"[",
"key",
"]",
"=",
"val",
"val",
"=",
"self",
".",
"_defaults",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_defaults",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_defaults",
"[",
"key",
"]",
"=",
"val",
"val",
"=",
"self",
".",
"_override",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_override",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_override",
"[",
"key",
"]",
"=",
"val",
"self",
".",
"_aliases",
"[",
"alias",
"]",
"=",
"key",
"else",
":",
"log",
".",
"warning",
"(",
"\"Creating circular reference alias {0} {1} {2}\"",
".",
"format",
"(",
"alias",
",",
"key",
",",
"self",
".",
"_real_key",
"(",
"key",
")",
")",
")"
] | Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application. | [
"Aliases",
"provide",
"another",
"accessor",
"for",
"the",
"same",
"key",
".",
"This",
"enables",
"one",
"to",
"change",
"a",
"name",
"without",
"breaking",
"the",
"application",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L466-L499 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.set_default | def set_default(self, key, value):
"""Set the default value for this key.
Default only used when no value is provided by the user via
arg, config or env.
"""
k = self._real_key(key.lower())
self._defaults[k] = value | python | def set_default(self, key, value):
"""Set the default value for this key.
Default only used when no value is provided by the user via
arg, config or env.
"""
k = self._real_key(key.lower())
self._defaults[k] = value | [
"def",
"set_default",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"k",
"=",
"self",
".",
"_real_key",
"(",
"key",
".",
"lower",
"(",
")",
")",
"self",
".",
"_defaults",
"[",
"k",
"]",
"=",
"value"
] | Set the default value for this key.
Default only used when no value is provided by the user via
arg, config or env. | [
"Set",
"the",
"default",
"value",
"for",
"this",
"key",
".",
"Default",
"only",
"used",
"when",
"no",
"value",
"is",
"provided",
"by",
"the",
"user",
"via",
"arg",
"config",
"or",
"env",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L517-L523 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper._unmarshall_reader | def _unmarshall_reader(self, file_, d):
"""Unmarshall a file into a `dict`."""
return util.unmarshall_config_reader(file_, d, self._get_config_type()) | python | def _unmarshall_reader(self, file_, d):
"""Unmarshall a file into a `dict`."""
return util.unmarshall_config_reader(file_, d, self._get_config_type()) | [
"def",
"_unmarshall_reader",
"(",
"self",
",",
"file_",
",",
"d",
")",
":",
"return",
"util",
".",
"unmarshall_config_reader",
"(",
"file_",
",",
"d",
",",
"self",
".",
"_get_config_type",
"(",
")",
")"
] | Unmarshall a file into a `dict`. | [
"Unmarshall",
"a",
"file",
"into",
"a",
"dict",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L586-L588 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper._get_key_value_config | def _get_key_value_config(self):
"""Retrieves the first found remote configuration."""
for rp in self._remote_providers:
val = self._get_remote_config(rp)
self._kvstore = val
return None
raise errors.RemoteConfigError("No Files Found") | python | def _get_key_value_config(self):
"""Retrieves the first found remote configuration."""
for rp in self._remote_providers:
val = self._get_remote_config(rp)
self._kvstore = val
return None
raise errors.RemoteConfigError("No Files Found") | [
"def",
"_get_key_value_config",
"(",
"self",
")",
":",
"for",
"rp",
"in",
"self",
".",
"_remote_providers",
":",
"val",
"=",
"self",
".",
"_get_remote_config",
"(",
"rp",
")",
"self",
".",
"_kvstore",
"=",
"val",
"return",
"None",
"raise",
"errors",
".",
"RemoteConfigError",
"(",
"\"No Files Found\"",
")"
] | Retrieves the first found remote configuration. | [
"Retrieves",
"the",
"first",
"found",
"remote",
"configuration",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L590-L597 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.all_keys | def all_keys(self, uppercase_keys=False):
"""Return all keys regardless where they are set."""
d = {}
for k in self._override.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._args.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._env.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._config.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._kvstore.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._defaults.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._aliases.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
return d.keys() | python | def all_keys(self, uppercase_keys=False):
"""Return all keys regardless where they are set."""
d = {}
for k in self._override.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._args.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._env.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._config.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._kvstore.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._defaults.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._aliases.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
return d.keys() | [
"def",
"all_keys",
"(",
"self",
",",
"uppercase_keys",
"=",
"False",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_override",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_args",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_env",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_config",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_kvstore",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_defaults",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_aliases",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"return",
"d",
".",
"keys",
"(",
")"
] | Return all keys regardless where they are set. | [
"Return",
"all",
"keys",
"regardless",
"where",
"they",
"are",
"set",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L617-L642 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.all_settings | def all_settings(self, uppercase_keys=False):
"""Return all settings as a `dict`."""
d = {}
for k in self.all_keys(uppercase_keys):
d[k] = self.get(k)
return d | python | def all_settings(self, uppercase_keys=False):
"""Return all settings as a `dict`."""
d = {}
for k in self.all_keys(uppercase_keys):
d[k] = self.get(k)
return d | [
"def",
"all_settings",
"(",
"self",
",",
"uppercase_keys",
"=",
"False",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"all_keys",
"(",
"uppercase_keys",
")",
":",
"d",
"[",
"k",
"]",
"=",
"self",
".",
"get",
"(",
"k",
")",
"return",
"d"
] | Return all settings as a `dict`. | [
"Return",
"all",
"settings",
"as",
"a",
"dict",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L644-L651 | train |
admiralobvious/vyper | vyper/vyper.py | Vyper.debug | def debug(self): # pragma: no cover
"""Prints all configuration registries for debugging purposes."""
print("Aliases:")
pprint.pprint(self._aliases)
print("Override:")
pprint.pprint(self._override)
print("Args:")
pprint.pprint(self._args)
print("Env:")
pprint.pprint(self._env)
print("Config:")
pprint.pprint(self._config)
print("Key/Value Store:")
pprint.pprint(self._kvstore)
print("Defaults:")
pprint.pprint(self._defaults) | python | def debug(self): # pragma: no cover
"""Prints all configuration registries for debugging purposes."""
print("Aliases:")
pprint.pprint(self._aliases)
print("Override:")
pprint.pprint(self._override)
print("Args:")
pprint.pprint(self._args)
print("Env:")
pprint.pprint(self._env)
print("Config:")
pprint.pprint(self._config)
print("Key/Value Store:")
pprint.pprint(self._kvstore)
print("Defaults:")
pprint.pprint(self._defaults) | [
"def",
"debug",
"(",
"self",
")",
":",
"# pragma: no cover",
"print",
"(",
"\"Aliases:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_aliases",
")",
"print",
"(",
"\"Override:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_override",
")",
"print",
"(",
"\"Args:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_args",
")",
"print",
"(",
"\"Env:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_env",
")",
"print",
"(",
"\"Config:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_config",
")",
"print",
"(",
"\"Key/Value Store:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_kvstore",
")",
"print",
"(",
"\"Defaults:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_defaults",
")"
] | Prints all configuration registries for debugging purposes. | [
"Prints",
"all",
"configuration",
"registries",
"for",
"debugging",
"purposes",
"."
] | 58ec7b90661502b7b2fea7a30849b90b907fcdec | https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L713-L729 | train |
rsalmei/clearly | clearly/command_line.py | server | def server(**kwargs):
"""
Starts the Clearly Server.
BROKER: The broker being used by celery, like "amqp://localhost".
"""
start_server(**{k: v for k, v in kwargs.items() if v},
blocking=True) | python | def server(**kwargs):
"""
Starts the Clearly Server.
BROKER: The broker being used by celery, like "amqp://localhost".
"""
start_server(**{k: v for k, v in kwargs.items() if v},
blocking=True) | [
"def",
"server",
"(",
"*",
"*",
"kwargs",
")",
":",
"start_server",
"(",
"*",
"*",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"v",
"}",
",",
"blocking",
"=",
"True",
")"
] | Starts the Clearly Server.
BROKER: The broker being used by celery, like "amqp://localhost". | [
"Starts",
"the",
"Clearly",
"Server",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/command_line.py#L25-L32 | train |
rsalmei/clearly | clearly/server.py | start_server | def start_server(broker, backend=None, port=12223,
max_tasks=10000, max_workers=100,
blocking=False, debug=False): # pragma: no cover
"""Starts a Clearly Server programmatically."""
_setup_logging(debug)
queue_listener_dispatcher = Queue()
listener = EventListener(broker, queue_listener_dispatcher, backend=backend,
max_tasks_in_memory=max_tasks,
max_workers_in_memory=max_workers)
dispatcher = StreamingDispatcher(queue_listener_dispatcher)
clearlysrv = ClearlyServer(listener, dispatcher)
return _serve(clearlysrv, port, blocking) | python | def start_server(broker, backend=None, port=12223,
max_tasks=10000, max_workers=100,
blocking=False, debug=False): # pragma: no cover
"""Starts a Clearly Server programmatically."""
_setup_logging(debug)
queue_listener_dispatcher = Queue()
listener = EventListener(broker, queue_listener_dispatcher, backend=backend,
max_tasks_in_memory=max_tasks,
max_workers_in_memory=max_workers)
dispatcher = StreamingDispatcher(queue_listener_dispatcher)
clearlysrv = ClearlyServer(listener, dispatcher)
return _serve(clearlysrv, port, blocking) | [
"def",
"start_server",
"(",
"broker",
",",
"backend",
"=",
"None",
",",
"port",
"=",
"12223",
",",
"max_tasks",
"=",
"10000",
",",
"max_workers",
"=",
"100",
",",
"blocking",
"=",
"False",
",",
"debug",
"=",
"False",
")",
":",
"# pragma: no cover",
"_setup_logging",
"(",
"debug",
")",
"queue_listener_dispatcher",
"=",
"Queue",
"(",
")",
"listener",
"=",
"EventListener",
"(",
"broker",
",",
"queue_listener_dispatcher",
",",
"backend",
"=",
"backend",
",",
"max_tasks_in_memory",
"=",
"max_tasks",
",",
"max_workers_in_memory",
"=",
"max_workers",
")",
"dispatcher",
"=",
"StreamingDispatcher",
"(",
"queue_listener_dispatcher",
")",
"clearlysrv",
"=",
"ClearlyServer",
"(",
"listener",
",",
"dispatcher",
")",
"return",
"_serve",
"(",
"clearlysrv",
",",
"port",
",",
"blocking",
")"
] | Starts a Clearly Server programmatically. | [
"Starts",
"a",
"Clearly",
"Server",
"programmatically",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L193-L205 | train |
rsalmei/clearly | clearly/server.py | ClearlyServer._event_to_pb | def _event_to_pb(event):
"""Supports converting internal TaskData and WorkerData, as well as
celery Task and Worker to proto buffers messages.
Args:
event (Union[TaskData|Task|WorkerData|Worker]):
Returns:
ProtoBuf object
"""
if isinstance(event, (TaskData, Task)):
key, klass = 'task', clearly_pb2.TaskMessage
elif isinstance(event, (WorkerData, Worker)):
key, klass = 'worker', clearly_pb2.WorkerMessage
else:
raise ValueError('unknown event')
keys = klass.DESCRIPTOR.fields_by_name.keys()
# noinspection PyProtectedMember
data = {k: v for k, v in
getattr(event, '_asdict', # internal TaskData and WorkerData
lambda: {f: getattr(event, f) for f in event._fields}) # celery Task and Worker
().items() if k in keys}
return key, klass(**data) | python | def _event_to_pb(event):
"""Supports converting internal TaskData and WorkerData, as well as
celery Task and Worker to proto buffers messages.
Args:
event (Union[TaskData|Task|WorkerData|Worker]):
Returns:
ProtoBuf object
"""
if isinstance(event, (TaskData, Task)):
key, klass = 'task', clearly_pb2.TaskMessage
elif isinstance(event, (WorkerData, Worker)):
key, klass = 'worker', clearly_pb2.WorkerMessage
else:
raise ValueError('unknown event')
keys = klass.DESCRIPTOR.fields_by_name.keys()
# noinspection PyProtectedMember
data = {k: v for k, v in
getattr(event, '_asdict', # internal TaskData and WorkerData
lambda: {f: getattr(event, f) for f in event._fields}) # celery Task and Worker
().items() if k in keys}
return key, klass(**data) | [
"def",
"_event_to_pb",
"(",
"event",
")",
":",
"if",
"isinstance",
"(",
"event",
",",
"(",
"TaskData",
",",
"Task",
")",
")",
":",
"key",
",",
"klass",
"=",
"'task'",
",",
"clearly_pb2",
".",
"TaskMessage",
"elif",
"isinstance",
"(",
"event",
",",
"(",
"WorkerData",
",",
"Worker",
")",
")",
":",
"key",
",",
"klass",
"=",
"'worker'",
",",
"clearly_pb2",
".",
"WorkerMessage",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown event'",
")",
"keys",
"=",
"klass",
".",
"DESCRIPTOR",
".",
"fields_by_name",
".",
"keys",
"(",
")",
"# noinspection PyProtectedMember",
"data",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"getattr",
"(",
"event",
",",
"'_asdict'",
",",
"# internal TaskData and WorkerData",
"lambda",
":",
"{",
"f",
":",
"getattr",
"(",
"event",
",",
"f",
")",
"for",
"f",
"in",
"event",
".",
"_fields",
"}",
")",
"# celery Task and Worker",
"(",
")",
".",
"items",
"(",
")",
"if",
"k",
"in",
"keys",
"}",
"return",
"key",
",",
"klass",
"(",
"*",
"*",
"data",
")"
] | Supports converting internal TaskData and WorkerData, as well as
celery Task and Worker to proto buffers messages.
Args:
event (Union[TaskData|Task|WorkerData|Worker]):
Returns:
ProtoBuf object | [
"Supports",
"converting",
"internal",
"TaskData",
"and",
"WorkerData",
"as",
"well",
"as",
"celery",
"Task",
"and",
"Worker",
"to",
"proto",
"buffers",
"messages",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L73-L96 | train |
rsalmei/clearly | clearly/server.py | ClearlyServer.filter_tasks | def filter_tasks(self, request, context):
"""Filter tasks by matching patterns to name, routing key and state."""
_log_request(request, context)
tasks_pattern, tasks_negate = PATTERN_PARAMS_OP(request.tasks_filter)
state_pattern = request.state_pattern
limit, reverse = request.limit, request.reverse
pregex = re.compile(tasks_pattern) # pattern filter condition
sregex = re.compile(state_pattern) # state filter condition
def pcondition(task):
return accepts(pregex, tasks_negate, task.name, task.routing_key)
def scondition(task):
return accepts(sregex, tasks_negate, task.state)
found_tasks = (task for _, task in
self.listener.memory.tasks_by_time(limit=limit or None,
reverse=reverse)
if pcondition(task) and scondition(task))
def callback(t):
logger.debug('%s iterated %d tasks in %s (%s)', self.filter_tasks.__name__,
t.count, t.duration_human, t.throughput_human)
for task in about_time(callback, found_tasks):
yield ClearlyServer._event_to_pb(task)[1] | python | def filter_tasks(self, request, context):
"""Filter tasks by matching patterns to name, routing key and state."""
_log_request(request, context)
tasks_pattern, tasks_negate = PATTERN_PARAMS_OP(request.tasks_filter)
state_pattern = request.state_pattern
limit, reverse = request.limit, request.reverse
pregex = re.compile(tasks_pattern) # pattern filter condition
sregex = re.compile(state_pattern) # state filter condition
def pcondition(task):
return accepts(pregex, tasks_negate, task.name, task.routing_key)
def scondition(task):
return accepts(sregex, tasks_negate, task.state)
found_tasks = (task for _, task in
self.listener.memory.tasks_by_time(limit=limit or None,
reverse=reverse)
if pcondition(task) and scondition(task))
def callback(t):
logger.debug('%s iterated %d tasks in %s (%s)', self.filter_tasks.__name__,
t.count, t.duration_human, t.throughput_human)
for task in about_time(callback, found_tasks):
yield ClearlyServer._event_to_pb(task)[1] | [
"def",
"filter_tasks",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"tasks_pattern",
",",
"tasks_negate",
"=",
"PATTERN_PARAMS_OP",
"(",
"request",
".",
"tasks_filter",
")",
"state_pattern",
"=",
"request",
".",
"state_pattern",
"limit",
",",
"reverse",
"=",
"request",
".",
"limit",
",",
"request",
".",
"reverse",
"pregex",
"=",
"re",
".",
"compile",
"(",
"tasks_pattern",
")",
"# pattern filter condition",
"sregex",
"=",
"re",
".",
"compile",
"(",
"state_pattern",
")",
"# state filter condition",
"def",
"pcondition",
"(",
"task",
")",
":",
"return",
"accepts",
"(",
"pregex",
",",
"tasks_negate",
",",
"task",
".",
"name",
",",
"task",
".",
"routing_key",
")",
"def",
"scondition",
"(",
"task",
")",
":",
"return",
"accepts",
"(",
"sregex",
",",
"tasks_negate",
",",
"task",
".",
"state",
")",
"found_tasks",
"=",
"(",
"task",
"for",
"_",
",",
"task",
"in",
"self",
".",
"listener",
".",
"memory",
".",
"tasks_by_time",
"(",
"limit",
"=",
"limit",
"or",
"None",
",",
"reverse",
"=",
"reverse",
")",
"if",
"pcondition",
"(",
"task",
")",
"and",
"scondition",
"(",
"task",
")",
")",
"def",
"callback",
"(",
"t",
")",
":",
"logger",
".",
"debug",
"(",
"'%s iterated %d tasks in %s (%s)'",
",",
"self",
".",
"filter_tasks",
".",
"__name__",
",",
"t",
".",
"count",
",",
"t",
".",
"duration_human",
",",
"t",
".",
"throughput_human",
")",
"for",
"task",
"in",
"about_time",
"(",
"callback",
",",
"found_tasks",
")",
":",
"yield",
"ClearlyServer",
".",
"_event_to_pb",
"(",
"task",
")",
"[",
"1",
"]"
] | Filter tasks by matching patterns to name, routing key and state. | [
"Filter",
"tasks",
"by",
"matching",
"patterns",
"to",
"name",
"routing",
"key",
"and",
"state",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L98-L124 | train |
rsalmei/clearly | clearly/server.py | ClearlyServer.filter_workers | def filter_workers(self, request, context):
"""Filter workers by matching a pattern to hostname."""
_log_request(request, context)
workers_pattern, workers_negate = PATTERN_PARAMS_OP(request.workers_filter)
hregex = re.compile(workers_pattern) # hostname filter condition
def hcondition(worker):
return accepts(hregex, workers_negate, worker.hostname) # pragma: no branch
found_workers = (worker for worker in
sorted(self.listener.memory.workers.values(),
key=WORKER_HOSTNAME_OP)
if hcondition(worker))
def callback(t):
logger.debug('%s iterated %d workers in %s (%s)', self.filter_workers.__name__,
t.count, t.duration_human, t.throughput_human)
for worker in about_time(callback, found_workers):
yield ClearlyServer._event_to_pb(worker)[1] | python | def filter_workers(self, request, context):
"""Filter workers by matching a pattern to hostname."""
_log_request(request, context)
workers_pattern, workers_negate = PATTERN_PARAMS_OP(request.workers_filter)
hregex = re.compile(workers_pattern) # hostname filter condition
def hcondition(worker):
return accepts(hregex, workers_negate, worker.hostname) # pragma: no branch
found_workers = (worker for worker in
sorted(self.listener.memory.workers.values(),
key=WORKER_HOSTNAME_OP)
if hcondition(worker))
def callback(t):
logger.debug('%s iterated %d workers in %s (%s)', self.filter_workers.__name__,
t.count, t.duration_human, t.throughput_human)
for worker in about_time(callback, found_workers):
yield ClearlyServer._event_to_pb(worker)[1] | [
"def",
"filter_workers",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"workers_pattern",
",",
"workers_negate",
"=",
"PATTERN_PARAMS_OP",
"(",
"request",
".",
"workers_filter",
")",
"hregex",
"=",
"re",
".",
"compile",
"(",
"workers_pattern",
")",
"# hostname filter condition",
"def",
"hcondition",
"(",
"worker",
")",
":",
"return",
"accepts",
"(",
"hregex",
",",
"workers_negate",
",",
"worker",
".",
"hostname",
")",
"# pragma: no branch",
"found_workers",
"=",
"(",
"worker",
"for",
"worker",
"in",
"sorted",
"(",
"self",
".",
"listener",
".",
"memory",
".",
"workers",
".",
"values",
"(",
")",
",",
"key",
"=",
"WORKER_HOSTNAME_OP",
")",
"if",
"hcondition",
"(",
"worker",
")",
")",
"def",
"callback",
"(",
"t",
")",
":",
"logger",
".",
"debug",
"(",
"'%s iterated %d workers in %s (%s)'",
",",
"self",
".",
"filter_workers",
".",
"__name__",
",",
"t",
".",
"count",
",",
"t",
".",
"duration_human",
",",
"t",
".",
"throughput_human",
")",
"for",
"worker",
"in",
"about_time",
"(",
"callback",
",",
"found_workers",
")",
":",
"yield",
"ClearlyServer",
".",
"_event_to_pb",
"(",
"worker",
")",
"[",
"1",
"]"
] | Filter workers by matching a pattern to hostname. | [
"Filter",
"workers",
"by",
"matching",
"a",
"pattern",
"to",
"hostname",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L126-L146 | train |
rsalmei/clearly | clearly/server.py | ClearlyServer.seen_tasks | def seen_tasks(self, request, context):
"""Returns all seen task types."""
_log_request(request, context)
result = clearly_pb2.SeenTasksMessage()
result.task_types.extend(self.listener.memory.task_types())
return result | python | def seen_tasks(self, request, context):
"""Returns all seen task types."""
_log_request(request, context)
result = clearly_pb2.SeenTasksMessage()
result.task_types.extend(self.listener.memory.task_types())
return result | [
"def",
"seen_tasks",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"result",
"=",
"clearly_pb2",
".",
"SeenTasksMessage",
"(",
")",
"result",
".",
"task_types",
".",
"extend",
"(",
"self",
".",
"listener",
".",
"memory",
".",
"task_types",
"(",
")",
")",
"return",
"result"
] | Returns all seen task types. | [
"Returns",
"all",
"seen",
"task",
"types",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L156-L161 | train |
rsalmei/clearly | clearly/server.py | ClearlyServer.reset_tasks | def reset_tasks(self, request, context):
"""Resets all captured tasks."""
_log_request(request, context)
self.listener.memory.clear_tasks()
return clearly_pb2.Empty() | python | def reset_tasks(self, request, context):
"""Resets all captured tasks."""
_log_request(request, context)
self.listener.memory.clear_tasks()
return clearly_pb2.Empty() | [
"def",
"reset_tasks",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"self",
".",
"listener",
".",
"memory",
".",
"clear_tasks",
"(",
")",
"return",
"clearly_pb2",
".",
"Empty",
"(",
")"
] | Resets all captured tasks. | [
"Resets",
"all",
"captured",
"tasks",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L163-L167 | train |
rsalmei/clearly | clearly/server.py | ClearlyServer.get_stats | def get_stats(self, request, context):
"""Returns the server statistics."""
_log_request(request, context)
m = self.listener.memory
return clearly_pb2.StatsMessage(
task_count=m.task_count,
event_count=m.event_count,
len_tasks=len(m.tasks),
len_workers=len(m.workers)
) | python | def get_stats(self, request, context):
"""Returns the server statistics."""
_log_request(request, context)
m = self.listener.memory
return clearly_pb2.StatsMessage(
task_count=m.task_count,
event_count=m.event_count,
len_tasks=len(m.tasks),
len_workers=len(m.workers)
) | [
"def",
"get_stats",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"m",
"=",
"self",
".",
"listener",
".",
"memory",
"return",
"clearly_pb2",
".",
"StatsMessage",
"(",
"task_count",
"=",
"m",
".",
"task_count",
",",
"event_count",
"=",
"m",
".",
"event_count",
",",
"len_tasks",
"=",
"len",
"(",
"m",
".",
"tasks",
")",
",",
"len_workers",
"=",
"len",
"(",
"m",
".",
"workers",
")",
")"
] | Returns the server statistics. | [
"Returns",
"the",
"server",
"statistics",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L169-L178 | train |
rsalmei/clearly | clearly/utils/data.py | accepts | def accepts(regex, negate, *values):
"""Given a compiled regex and a negate, find if any of the values match.
Args:
regex (Pattern):
negate (bool):
*values (str):
Returns:
"""
return any(v and regex.search(v) for v in values) != negate | python | def accepts(regex, negate, *values):
"""Given a compiled regex and a negate, find if any of the values match.
Args:
regex (Pattern):
negate (bool):
*values (str):
Returns:
"""
return any(v and regex.search(v) for v in values) != negate | [
"def",
"accepts",
"(",
"regex",
",",
"negate",
",",
"*",
"values",
")",
":",
"return",
"any",
"(",
"v",
"and",
"regex",
".",
"search",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
"!=",
"negate"
] | Given a compiled regex and a negate, find if any of the values match.
Args:
regex (Pattern):
negate (bool):
*values (str):
Returns: | [
"Given",
"a",
"compiled",
"regex",
"and",
"a",
"negate",
"find",
"if",
"any",
"of",
"the",
"values",
"match",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/utils/data.py#L1-L12 | train |
rsalmei/clearly | clearly/utils/data.py | copy_update | def copy_update(pb_message, **kwds):
"""Returns a copy of the PB object, with some fields updated.
Args:
pb_message:
**kwds:
Returns:
"""
result = pb_message.__class__()
result.CopyFrom(pb_message)
for k, v in kwds.items():
setattr(result, k, v)
return result | python | def copy_update(pb_message, **kwds):
"""Returns a copy of the PB object, with some fields updated.
Args:
pb_message:
**kwds:
Returns:
"""
result = pb_message.__class__()
result.CopyFrom(pb_message)
for k, v in kwds.items():
setattr(result, k, v)
return result | [
"def",
"copy_update",
"(",
"pb_message",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"pb_message",
".",
"__class__",
"(",
")",
"result",
".",
"CopyFrom",
"(",
"pb_message",
")",
"for",
"k",
",",
"v",
"in",
"kwds",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"result",
",",
"k",
",",
"v",
")",
"return",
"result"
] | Returns a copy of the PB object, with some fields updated.
Args:
pb_message:
**kwds:
Returns: | [
"Returns",
"a",
"copy",
"of",
"the",
"PB",
"object",
"with",
"some",
"fields",
"updated",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/utils/data.py#L15-L29 | train |
rsalmei/clearly | clearly/event_core/streaming_dispatcher.py | StreamingDispatcher.__start | def __start(self): # pragma: no cover
"""Starts the real-time engine that captures tasks."""
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher,
name='clearly-dispatcher')
self.dispatcher_thread.daemon = True
self.running = True # graceful shutdown
self.dispatcher_thread.start() | python | def __start(self): # pragma: no cover
"""Starts the real-time engine that captures tasks."""
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher,
name='clearly-dispatcher')
self.dispatcher_thread.daemon = True
self.running = True # graceful shutdown
self.dispatcher_thread.start() | [
"def",
"__start",
"(",
"self",
")",
":",
"# pragma: no cover",
"assert",
"not",
"self",
".",
"dispatcher_thread",
"self",
".",
"dispatcher_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"__run_dispatcher",
",",
"name",
"=",
"'clearly-dispatcher'",
")",
"self",
".",
"dispatcher_thread",
".",
"daemon",
"=",
"True",
"self",
".",
"running",
"=",
"True",
"# graceful shutdown",
"self",
".",
"dispatcher_thread",
".",
"start",
"(",
")"
] | Starts the real-time engine that captures tasks. | [
"Starts",
"the",
"real",
"-",
"time",
"engine",
"that",
"captures",
"tasks",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/event_core/streaming_dispatcher.py#L56-L65 | train |
rsalmei/clearly | clearly/event_core/streaming_dispatcher.py | StreamingDispatcher.streaming_client | def streaming_client(self, tasks_regex, tasks_negate, workers_regex, workers_negate):
"""Connects a client to the streaming capture, filtering the events that are sent
to it.
Args:
tasks_regex (str): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
tasks_negate (bool): if True, finds tasks that do not match criteria
workers_regex (str): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
workers_negate (bool): if True, finds workers that do not match criteria
"""
cc = CapturingClient(Queue(),
re.compile(tasks_regex), tasks_negate,
re.compile(workers_regex), workers_negate)
self.observers.append(cc)
yield cc.queue
self.observers.remove(cc) | python | def streaming_client(self, tasks_regex, tasks_negate, workers_regex, workers_negate):
"""Connects a client to the streaming capture, filtering the events that are sent
to it.
Args:
tasks_regex (str): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
tasks_negate (bool): if True, finds tasks that do not match criteria
workers_regex (str): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
workers_negate (bool): if True, finds workers that do not match criteria
"""
cc = CapturingClient(Queue(),
re.compile(tasks_regex), tasks_negate,
re.compile(workers_regex), workers_negate)
self.observers.append(cc)
yield cc.queue
self.observers.remove(cc) | [
"def",
"streaming_client",
"(",
"self",
",",
"tasks_regex",
",",
"tasks_negate",
",",
"workers_regex",
",",
"workers_negate",
")",
":",
"cc",
"=",
"CapturingClient",
"(",
"Queue",
"(",
")",
",",
"re",
".",
"compile",
"(",
"tasks_regex",
")",
",",
"tasks_negate",
",",
"re",
".",
"compile",
"(",
"workers_regex",
")",
",",
"workers_negate",
")",
"self",
".",
"observers",
".",
"append",
"(",
"cc",
")",
"yield",
"cc",
".",
"queue",
"self",
".",
"observers",
".",
"remove",
"(",
"cc",
")"
] | Connects a client to the streaming capture, filtering the events that are sent
to it.
Args:
tasks_regex (str): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
tasks_negate (bool): if True, finds tasks that do not match criteria
workers_regex (str): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
workers_negate (bool): if True, finds workers that do not match criteria | [
"Connects",
"a",
"client",
"to",
"the",
"streaming",
"capture",
"filtering",
"the",
"events",
"that",
"are",
"sent",
"to",
"it",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/event_core/streaming_dispatcher.py#L79-L100 | train |
rsalmei/clearly | clearly/event_core/event_listener.py | EventListener.__start | def __start(self): # pragma: no cover
"""Starts the real-time engine that captures events."""
assert not self._listener_thread
self._listener_thread = threading.Thread(target=self.__run_listener,
name='clearly-listener')
self._listener_thread.daemon = True
self._listener_thread.start()
self._wait_event.wait()
self._wait_event.clear() | python | def __start(self): # pragma: no cover
"""Starts the real-time engine that captures events."""
assert not self._listener_thread
self._listener_thread = threading.Thread(target=self.__run_listener,
name='clearly-listener')
self._listener_thread.daemon = True
self._listener_thread.start()
self._wait_event.wait()
self._wait_event.clear() | [
"def",
"__start",
"(",
"self",
")",
":",
"# pragma: no cover",
"assert",
"not",
"self",
".",
"_listener_thread",
"self",
".",
"_listener_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"__run_listener",
",",
"name",
"=",
"'clearly-listener'",
")",
"self",
".",
"_listener_thread",
".",
"daemon",
"=",
"True",
"self",
".",
"_listener_thread",
".",
"start",
"(",
")",
"self",
".",
"_wait_event",
".",
"wait",
"(",
")",
"self",
".",
"_wait_event",
".",
"clear",
"(",
")"
] | Starts the real-time engine that captures events. | [
"Starts",
"the",
"real",
"-",
"time",
"engine",
"that",
"captures",
"events",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/event_core/event_listener.py#L71-L81 | train |
rsalmei/clearly | clearly/client.py | ClearlyClient.capture | def capture(self, pattern=None, negate=False, workers=None, negate_workers=False,
params=None, success=False, error=True, stats=False):
"""Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in real-time exactly what your
clients and celery workers are doing.
Press CTRL+C at any time to stop it.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria.
workers (Optional[str]): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
negate_workers (bool): if True, finds workers that do not match criteria.
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results.
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
stats (bool): if True shows complete workers' stats.
default is False
"""
request = clearly_pb2.CaptureRequest(
tasks_capture=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
workers_capture=clearly_pb2.PatternFilter(pattern=workers or '.',
negate=negate_workers),
)
try:
for realtime in self._stub.capture_realtime(request):
if realtime.HasField('task'):
ClearlyClient._display_task(realtime.task, params, success, error)
elif realtime.HasField('worker'):
ClearlyClient._display_worker(realtime.worker, stats)
else:
print('unknown event:', realtime)
break
except KeyboardInterrupt:
pass | python | def capture(self, pattern=None, negate=False, workers=None, negate_workers=False,
params=None, success=False, error=True, stats=False):
"""Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in real-time exactly what your
clients and celery workers are doing.
Press CTRL+C at any time to stop it.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria.
workers (Optional[str]): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
negate_workers (bool): if True, finds workers that do not match criteria.
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results.
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
stats (bool): if True shows complete workers' stats.
default is False
"""
request = clearly_pb2.CaptureRequest(
tasks_capture=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
workers_capture=clearly_pb2.PatternFilter(pattern=workers or '.',
negate=negate_workers),
)
try:
for realtime in self._stub.capture_realtime(request):
if realtime.HasField('task'):
ClearlyClient._display_task(realtime.task, params, success, error)
elif realtime.HasField('worker'):
ClearlyClient._display_worker(realtime.worker, stats)
else:
print('unknown event:', realtime)
break
except KeyboardInterrupt:
pass | [
"def",
"capture",
"(",
"self",
",",
"pattern",
"=",
"None",
",",
"negate",
"=",
"False",
",",
"workers",
"=",
"None",
",",
"negate_workers",
"=",
"False",
",",
"params",
"=",
"None",
",",
"success",
"=",
"False",
",",
"error",
"=",
"True",
",",
"stats",
"=",
"False",
")",
":",
"request",
"=",
"clearly_pb2",
".",
"CaptureRequest",
"(",
"tasks_capture",
"=",
"clearly_pb2",
".",
"PatternFilter",
"(",
"pattern",
"=",
"pattern",
"or",
"'.'",
",",
"negate",
"=",
"negate",
")",
",",
"workers_capture",
"=",
"clearly_pb2",
".",
"PatternFilter",
"(",
"pattern",
"=",
"workers",
"or",
"'.'",
",",
"negate",
"=",
"negate_workers",
")",
",",
")",
"try",
":",
"for",
"realtime",
"in",
"self",
".",
"_stub",
".",
"capture_realtime",
"(",
"request",
")",
":",
"if",
"realtime",
".",
"HasField",
"(",
"'task'",
")",
":",
"ClearlyClient",
".",
"_display_task",
"(",
"realtime",
".",
"task",
",",
"params",
",",
"success",
",",
"error",
")",
"elif",
"realtime",
".",
"HasField",
"(",
"'worker'",
")",
":",
"ClearlyClient",
".",
"_display_worker",
"(",
"realtime",
".",
"worker",
",",
"stats",
")",
"else",
":",
"print",
"(",
"'unknown event:'",
",",
"realtime",
")",
"break",
"except",
"KeyboardInterrupt",
":",
"pass"
] | Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in real-time exactly what your
clients and celery workers are doing.
Press CTRL+C at any time to stop it.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria.
workers (Optional[str]): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
negate_workers (bool): if True, finds workers that do not match criteria.
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results.
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
stats (bool): if True shows complete workers' stats.
default is False | [
"Starts",
"capturing",
"selected",
"events",
"in",
"real",
"-",
"time",
".",
"You",
"can",
"filter",
"exactly",
"what",
"you",
"want",
"to",
"see",
"as",
"the",
"Clearly",
"Server",
"handles",
"all",
"tasks",
"and",
"workers",
"updates",
"being",
"sent",
"to",
"celery",
".",
"Several",
"clients",
"can",
"see",
"different",
"sets",
"of",
"events",
"at",
"the",
"same",
"time",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/client.py#L40-L92 | train |
rsalmei/clearly | clearly/client.py | ClearlyClient.tasks | def tasks(self, pattern=None, negate=False, state=None, limit=None, reverse=True,
params=None, success=False, error=True):
"""Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the LRU event heap instead of the dict storage, so the total number
of tasks fetched may be different than the server `max_tasks` setting. For
instance, the `limit` field refers to max events searched, not max tasks.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria
state (Optional[str]): a celery task state to filter
limit (int): the maximum number of events to fetch
if None or 0, fetches all.
reverse (bool): if True (default), shows the most recent first
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
"""
request = clearly_pb2.FilterTasksRequest(
tasks_filter=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
state_pattern=state or '.', limit=limit, reverse=reverse
)
for task in about_time(ClearlyClient._fetched_callback, self._stub.filter_tasks(request)):
ClearlyClient._display_task(task, params, success, error) | python | def tasks(self, pattern=None, negate=False, state=None, limit=None, reverse=True,
params=None, success=False, error=True):
"""Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the LRU event heap instead of the dict storage, so the total number
of tasks fetched may be different than the server `max_tasks` setting. For
instance, the `limit` field refers to max events searched, not max tasks.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria
state (Optional[str]): a celery task state to filter
limit (int): the maximum number of events to fetch
if None or 0, fetches all.
reverse (bool): if True (default), shows the most recent first
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
"""
request = clearly_pb2.FilterTasksRequest(
tasks_filter=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
state_pattern=state or '.', limit=limit, reverse=reverse
)
for task in about_time(ClearlyClient._fetched_callback, self._stub.filter_tasks(request)):
ClearlyClient._display_task(task, params, success, error) | [
"def",
"tasks",
"(",
"self",
",",
"pattern",
"=",
"None",
",",
"negate",
"=",
"False",
",",
"state",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"reverse",
"=",
"True",
",",
"params",
"=",
"None",
",",
"success",
"=",
"False",
",",
"error",
"=",
"True",
")",
":",
"request",
"=",
"clearly_pb2",
".",
"FilterTasksRequest",
"(",
"tasks_filter",
"=",
"clearly_pb2",
".",
"PatternFilter",
"(",
"pattern",
"=",
"pattern",
"or",
"'.'",
",",
"negate",
"=",
"negate",
")",
",",
"state_pattern",
"=",
"state",
"or",
"'.'",
",",
"limit",
"=",
"limit",
",",
"reverse",
"=",
"reverse",
")",
"for",
"task",
"in",
"about_time",
"(",
"ClearlyClient",
".",
"_fetched_callback",
",",
"self",
".",
"_stub",
".",
"filter_tasks",
"(",
"request",
")",
")",
":",
"ClearlyClient",
".",
"_display_task",
"(",
"task",
",",
"params",
",",
"success",
",",
"error",
")"
] | Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the LRU event heap instead of the dict storage, so the total number
of tasks fetched may be different than the server `max_tasks` setting. For
instance, the `limit` field refers to max events searched, not max tasks.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria
state (Optional[str]): a celery task state to filter
limit (int): the maximum number of events to fetch
if None or 0, fetches all.
reverse (bool): if True (default), shows the most recent first
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right? | [
"Filters",
"stored",
"tasks",
"and",
"displays",
"their",
"current",
"statuses",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/client.py#L118-L158 | train |
rsalmei/clearly | clearly/client.py | ClearlyClient.seen_tasks | def seen_tasks(self):
"""Shows a list of seen task types."""
print('\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types)) | python | def seen_tasks(self):
"""Shows a list of seen task types."""
print('\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types)) | [
"def",
"seen_tasks",
"(",
"self",
")",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"self",
".",
"_stub",
".",
"seen_tasks",
"(",
"clearly_pb2",
".",
"Empty",
"(",
")",
")",
".",
"task_types",
")",
")"
] | Shows a list of seen task types. | [
"Shows",
"a",
"list",
"of",
"seen",
"task",
"types",
"."
] | fd784843d13f0fed28fc192565bec3668f1363f4 | https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/client.py#L197-L199 | train |
linuxlewis/channels-api | channels_api/decorators.py | detail_action | def detail_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for detail actions.
"""
def decorator(func):
func.action = True
func.detail = True
func.kwargs = kwargs
return func
return decorator | python | def detail_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for detail actions.
"""
def decorator(func):
func.action = True
func.detail = True
func.kwargs = kwargs
return func
return decorator | [
"def",
"detail_action",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"func",
".",
"action",
"=",
"True",
"func",
".",
"detail",
"=",
"True",
"func",
".",
"kwargs",
"=",
"kwargs",
"return",
"func",
"return",
"decorator"
] | Used to mark a method on a ResourceBinding that should be routed for detail actions. | [
"Used",
"to",
"mark",
"a",
"method",
"on",
"a",
"ResourceBinding",
"that",
"should",
"be",
"routed",
"for",
"detail",
"actions",
"."
] | ec2a81a1ae83606980ad5bb709bca517fdde077d | https://github.com/linuxlewis/channels-api/blob/ec2a81a1ae83606980ad5bb709bca517fdde077d/channels_api/decorators.py#L1-L10 | train |
linuxlewis/channels-api | channels_api/decorators.py | list_action | def list_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for list actions.
"""
def decorator(func):
func.action = True
func.detail = False
func.kwargs = kwargs
return func
return decorator | python | def list_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for list actions.
"""
def decorator(func):
func.action = True
func.detail = False
func.kwargs = kwargs
return func
return decorator | [
"def",
"list_action",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"func",
".",
"action",
"=",
"True",
"func",
".",
"detail",
"=",
"False",
"func",
".",
"kwargs",
"=",
"kwargs",
"return",
"func",
"return",
"decorator"
] | Used to mark a method on a ResourceBinding that should be routed for list actions. | [
"Used",
"to",
"mark",
"a",
"method",
"on",
"a",
"ResourceBinding",
"that",
"should",
"be",
"routed",
"for",
"list",
"actions",
"."
] | ec2a81a1ae83606980ad5bb709bca517fdde077d | https://github.com/linuxlewis/channels-api/blob/ec2a81a1ae83606980ad5bb709bca517fdde077d/channels_api/decorators.py#L13-L22 | train |
mattja/sdeint | sdeint/_broadcast.py | broadcast_to | def broadcast_to(array, shape, subok=False):
"""Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
"""
return _broadcast_to(array, shape, subok=subok, readonly=True) | python | def broadcast_to(array, shape, subok=False):
"""Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
"""
return _broadcast_to(array, shape, subok=subok, readonly=True) | [
"def",
"broadcast_to",
"(",
"array",
",",
"shape",
",",
"subok",
"=",
"False",
")",
":",
"return",
"_broadcast_to",
"(",
"array",
",",
"shape",
",",
"subok",
"=",
"subok",
",",
"readonly",
"=",
"True",
")"
] | Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]) | [
"Broadcast",
"an",
"array",
"to",
"a",
"new",
"shape",
"."
] | 7cf807cdf97b3bb39d29e1c2dc834b519499b601 | https://github.com/mattja/sdeint/blob/7cf807cdf97b3bb39d29e1c2dc834b519499b601/sdeint/_broadcast.py#L70-L108 | train |
mattja/sdeint | sdeint/wiener.py | _K | def _K(m):
""" matrix K_m from Wiktorsson2001 """
M = m*(m - 1)//2
K = np.zeros((M, m**2), dtype=np.int64)
row = 0
for j in range(1, m):
col = (j - 1)*m + j
s = m - j
K[row:(row+s), col:(col+s)] = np.eye(s)
row += s
return K | python | def _K(m):
""" matrix K_m from Wiktorsson2001 """
M = m*(m - 1)//2
K = np.zeros((M, m**2), dtype=np.int64)
row = 0
for j in range(1, m):
col = (j - 1)*m + j
s = m - j
K[row:(row+s), col:(col+s)] = np.eye(s)
row += s
return K | [
"def",
"_K",
"(",
"m",
")",
":",
"M",
"=",
"m",
"*",
"(",
"m",
"-",
"1",
")",
"//",
"2",
"K",
"=",
"np",
".",
"zeros",
"(",
"(",
"M",
",",
"m",
"**",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"row",
"=",
"0",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"m",
")",
":",
"col",
"=",
"(",
"j",
"-",
"1",
")",
"*",
"m",
"+",
"j",
"s",
"=",
"m",
"-",
"j",
"K",
"[",
"row",
":",
"(",
"row",
"+",
"s",
")",
",",
"col",
":",
"(",
"col",
"+",
"s",
")",
"]",
"=",
"np",
".",
"eye",
"(",
"s",
")",
"row",
"+=",
"s",
"return",
"K"
] | matrix K_m from Wiktorsson2001 | [
"matrix",
"K_m",
"from",
"Wiktorsson2001"
] | 7cf807cdf97b3bb39d29e1c2dc834b519499b601 | https://github.com/mattja/sdeint/blob/7cf807cdf97b3bb39d29e1c2dc834b519499b601/sdeint/wiener.py#L187-L197 | train |
riptano/ccm | ccmlib/cluster.py | Cluster.wait_for_compactions | def wait_for_compactions(self, timeout=600):
"""
Wait for all compactions to finish on all nodes.
"""
for node in list(self.nodes.values()):
if node.is_running():
node.wait_for_compactions(timeout)
return self | python | def wait_for_compactions(self, timeout=600):
"""
Wait for all compactions to finish on all nodes.
"""
for node in list(self.nodes.values()):
if node.is_running():
node.wait_for_compactions(timeout)
return self | [
"def",
"wait_for_compactions",
"(",
"self",
",",
"timeout",
"=",
"600",
")",
":",
"for",
"node",
"in",
"list",
"(",
"self",
".",
"nodes",
".",
"values",
"(",
")",
")",
":",
"if",
"node",
".",
"is_running",
"(",
")",
":",
"node",
".",
"wait_for_compactions",
"(",
"timeout",
")",
"return",
"self"
] | Wait for all compactions to finish on all nodes. | [
"Wait",
"for",
"all",
"compactions",
"to",
"finish",
"on",
"all",
"nodes",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/cluster.py#L472-L479 | train |
riptano/ccm | ccmlib/dse_node.py | DseNode.watch_log_for_alive | def watch_log_for_alive(self, nodes, from_mark=None, timeout=720, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE.
"""
super(DseNode, self).watch_log_for_alive(nodes, from_mark=from_mark, timeout=timeout, filename=filename) | python | def watch_log_for_alive(self, nodes, from_mark=None, timeout=720, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE.
"""
super(DseNode, self).watch_log_for_alive(nodes, from_mark=from_mark, timeout=timeout, filename=filename) | [
"def",
"watch_log_for_alive",
"(",
"self",
",",
"nodes",
",",
"from_mark",
"=",
"None",
",",
"timeout",
"=",
"720",
",",
"filename",
"=",
"'system.log'",
")",
":",
"super",
"(",
"DseNode",
",",
"self",
")",
".",
"watch_log_for_alive",
"(",
"nodes",
",",
"from_mark",
"=",
"from_mark",
",",
"timeout",
"=",
"timeout",
",",
"filename",
"=",
"filename",
")"
] | Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE. | [
"Watch",
"the",
"log",
"of",
"this",
"node",
"until",
"it",
"detects",
"that",
"the",
"provided",
"other",
"nodes",
"are",
"marked",
"UP",
".",
"This",
"method",
"works",
"similarly",
"to",
"watch_log_for_death",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/dse_node.py#L102-L109 | train |
riptano/ccm | ccmlib/node.py | Node.load | def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
"""
node_path = os.path.join(path, name)
filename = os.path.join(node_path, 'node.conf')
with open(filename, 'r') as f:
data = yaml.safe_load(f)
try:
itf = data['interfaces']
initial_token = None
if 'initial_token' in data:
initial_token = data['initial_token']
cassandra_version = None
if 'cassandra_version' in data:
cassandra_version = LooseVersion(data['cassandra_version'])
remote_debug_port = 2000
if 'remote_debug_port' in data:
remote_debug_port = data['remote_debug_port']
binary_interface = None
if 'binary' in itf and itf['binary'] is not None:
binary_interface = tuple(itf['binary'])
thrift_interface = None
if 'thrift' in itf and itf['thrift'] is not None:
thrift_interface = tuple(itf['thrift'])
node = cluster.create_node(data['name'], data['auto_bootstrap'], thrift_interface, tuple(itf['storage']), data['jmx_port'], remote_debug_port, initial_token, save=False, binary_interface=binary_interface, byteman_port=data['byteman_port'], derived_cassandra_version=cassandra_version)
node.status = data['status']
if 'pid' in data:
node.pid = int(data['pid'])
if 'install_dir' in data:
node.__install_dir = data['install_dir']
if 'config_options' in data:
node.__config_options = data['config_options']
if 'dse_config_options' in data:
node._dse_config_options = data['dse_config_options']
if 'environment_variables' in data:
node.__environment_variables = data['environment_variables']
if 'data_center' in data:
node.data_center = data['data_center']
if 'workloads' in data:
node.workloads = data['workloads']
return node
except KeyError as k:
raise common.LoadError("Error Loading " + filename + ", missing property: " + str(k)) | python | def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
"""
node_path = os.path.join(path, name)
filename = os.path.join(node_path, 'node.conf')
with open(filename, 'r') as f:
data = yaml.safe_load(f)
try:
itf = data['interfaces']
initial_token = None
if 'initial_token' in data:
initial_token = data['initial_token']
cassandra_version = None
if 'cassandra_version' in data:
cassandra_version = LooseVersion(data['cassandra_version'])
remote_debug_port = 2000
if 'remote_debug_port' in data:
remote_debug_port = data['remote_debug_port']
binary_interface = None
if 'binary' in itf and itf['binary'] is not None:
binary_interface = tuple(itf['binary'])
thrift_interface = None
if 'thrift' in itf and itf['thrift'] is not None:
thrift_interface = tuple(itf['thrift'])
node = cluster.create_node(data['name'], data['auto_bootstrap'], thrift_interface, tuple(itf['storage']), data['jmx_port'], remote_debug_port, initial_token, save=False, binary_interface=binary_interface, byteman_port=data['byteman_port'], derived_cassandra_version=cassandra_version)
node.status = data['status']
if 'pid' in data:
node.pid = int(data['pid'])
if 'install_dir' in data:
node.__install_dir = data['install_dir']
if 'config_options' in data:
node.__config_options = data['config_options']
if 'dse_config_options' in data:
node._dse_config_options = data['dse_config_options']
if 'environment_variables' in data:
node.__environment_variables = data['environment_variables']
if 'data_center' in data:
node.data_center = data['data_center']
if 'workloads' in data:
node.workloads = data['workloads']
return node
except KeyError as k:
raise common.LoadError("Error Loading " + filename + ", missing property: " + str(k)) | [
"def",
"load",
"(",
"path",
",",
"name",
",",
"cluster",
")",
":",
"node_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"node_path",
",",
"'node.conf'",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"try",
":",
"itf",
"=",
"data",
"[",
"'interfaces'",
"]",
"initial_token",
"=",
"None",
"if",
"'initial_token'",
"in",
"data",
":",
"initial_token",
"=",
"data",
"[",
"'initial_token'",
"]",
"cassandra_version",
"=",
"None",
"if",
"'cassandra_version'",
"in",
"data",
":",
"cassandra_version",
"=",
"LooseVersion",
"(",
"data",
"[",
"'cassandra_version'",
"]",
")",
"remote_debug_port",
"=",
"2000",
"if",
"'remote_debug_port'",
"in",
"data",
":",
"remote_debug_port",
"=",
"data",
"[",
"'remote_debug_port'",
"]",
"binary_interface",
"=",
"None",
"if",
"'binary'",
"in",
"itf",
"and",
"itf",
"[",
"'binary'",
"]",
"is",
"not",
"None",
":",
"binary_interface",
"=",
"tuple",
"(",
"itf",
"[",
"'binary'",
"]",
")",
"thrift_interface",
"=",
"None",
"if",
"'thrift'",
"in",
"itf",
"and",
"itf",
"[",
"'thrift'",
"]",
"is",
"not",
"None",
":",
"thrift_interface",
"=",
"tuple",
"(",
"itf",
"[",
"'thrift'",
"]",
")",
"node",
"=",
"cluster",
".",
"create_node",
"(",
"data",
"[",
"'name'",
"]",
",",
"data",
"[",
"'auto_bootstrap'",
"]",
",",
"thrift_interface",
",",
"tuple",
"(",
"itf",
"[",
"'storage'",
"]",
")",
",",
"data",
"[",
"'jmx_port'",
"]",
",",
"remote_debug_port",
",",
"initial_token",
",",
"save",
"=",
"False",
",",
"binary_interface",
"=",
"binary_interface",
",",
"byteman_port",
"=",
"data",
"[",
"'byteman_port'",
"]",
",",
"derived_cassandra_version",
"=",
"cassandra_version",
")",
"node",
".",
"status",
"=",
"data",
"[",
"'status'",
"]",
"if",
"'pid'",
"in",
"data",
":",
"node",
".",
"pid",
"=",
"int",
"(",
"data",
"[",
"'pid'",
"]",
")",
"if",
"'install_dir'",
"in",
"data",
":",
"node",
".",
"__install_dir",
"=",
"data",
"[",
"'install_dir'",
"]",
"if",
"'config_options'",
"in",
"data",
":",
"node",
".",
"__config_options",
"=",
"data",
"[",
"'config_options'",
"]",
"if",
"'dse_config_options'",
"in",
"data",
":",
"node",
".",
"_dse_config_options",
"=",
"data",
"[",
"'dse_config_options'",
"]",
"if",
"'environment_variables'",
"in",
"data",
":",
"node",
".",
"__environment_variables",
"=",
"data",
"[",
"'environment_variables'",
"]",
"if",
"'data_center'",
"in",
"data",
":",
"node",
".",
"data_center",
"=",
"data",
"[",
"'data_center'",
"]",
"if",
"'workloads'",
"in",
"data",
":",
"node",
".",
"workloads",
"=",
"data",
"[",
"'workloads'",
"]",
"return",
"node",
"except",
"KeyError",
"as",
"k",
":",
"raise",
"common",
".",
"LoadError",
"(",
"\"Error Loading \"",
"+",
"filename",
"+",
"\", missing property: \"",
"+",
"str",
"(",
"k",
")",
")"
] | Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of. | [
"Load",
"a",
"node",
"from",
"from",
"the",
"path",
"on",
"disk",
"to",
"the",
"config",
"files",
"the",
"node",
"name",
"and",
"the",
"cluster",
"the",
"node",
"is",
"part",
"of",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L150-L194 | train |
riptano/ccm | ccmlib/node.py | Node.get_install_dir | def get_install_dir(self):
"""
Returns the path to the cassandra source directory used by this node.
"""
if self.__install_dir is None:
return self.cluster.get_install_dir()
else:
common.validate_install_dir(self.__install_dir)
return self.__install_dir | python | def get_install_dir(self):
"""
Returns the path to the cassandra source directory used by this node.
"""
if self.__install_dir is None:
return self.cluster.get_install_dir()
else:
common.validate_install_dir(self.__install_dir)
return self.__install_dir | [
"def",
"get_install_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"__install_dir",
"is",
"None",
":",
"return",
"self",
".",
"cluster",
".",
"get_install_dir",
"(",
")",
"else",
":",
"common",
".",
"validate_install_dir",
"(",
"self",
".",
"__install_dir",
")",
"return",
"self",
".",
"__install_dir"
] | Returns the path to the cassandra source directory used by this node. | [
"Returns",
"the",
"path",
"to",
"the",
"cassandra",
"source",
"directory",
"used",
"by",
"this",
"node",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L241-L249 | train |
riptano/ccm | ccmlib/node.py | Node.set_install_dir | def set_install_dir(self, install_dir=None, version=None, verbose=False):
"""
Sets the path to the cassandra source directory for use by this node.
"""
if version is None:
self.__install_dir = install_dir
if install_dir is not None:
common.validate_install_dir(install_dir)
else:
self.__install_dir = self.node_setup(version, verbose=verbose)
self._cassandra_version = common.get_version_from_build(self.__install_dir, cassandra=True)
if self.get_base_cassandra_version() >= 4.0:
self.network_interfaces['thrift'] = None
self.import_config_files()
self.import_bin_files()
self.__conf_updated = False
return self | python | def set_install_dir(self, install_dir=None, version=None, verbose=False):
"""
Sets the path to the cassandra source directory for use by this node.
"""
if version is None:
self.__install_dir = install_dir
if install_dir is not None:
common.validate_install_dir(install_dir)
else:
self.__install_dir = self.node_setup(version, verbose=verbose)
self._cassandra_version = common.get_version_from_build(self.__install_dir, cassandra=True)
if self.get_base_cassandra_version() >= 4.0:
self.network_interfaces['thrift'] = None
self.import_config_files()
self.import_bin_files()
self.__conf_updated = False
return self | [
"def",
"set_install_dir",
"(",
"self",
",",
"install_dir",
"=",
"None",
",",
"version",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"version",
"is",
"None",
":",
"self",
".",
"__install_dir",
"=",
"install_dir",
"if",
"install_dir",
"is",
"not",
"None",
":",
"common",
".",
"validate_install_dir",
"(",
"install_dir",
")",
"else",
":",
"self",
".",
"__install_dir",
"=",
"self",
".",
"node_setup",
"(",
"version",
",",
"verbose",
"=",
"verbose",
")",
"self",
".",
"_cassandra_version",
"=",
"common",
".",
"get_version_from_build",
"(",
"self",
".",
"__install_dir",
",",
"cassandra",
"=",
"True",
")",
"if",
"self",
".",
"get_base_cassandra_version",
"(",
")",
">=",
"4.0",
":",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
"=",
"None",
"self",
".",
"import_config_files",
"(",
")",
"self",
".",
"import_bin_files",
"(",
")",
"self",
".",
"__conf_updated",
"=",
"False",
"return",
"self"
] | Sets the path to the cassandra source directory for use by this node. | [
"Sets",
"the",
"path",
"to",
"the",
"cassandra",
"source",
"directory",
"for",
"use",
"by",
"this",
"node",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L255-L274 | train |
riptano/ccm | ccmlib/node.py | Node.show | def show(self, only_status=False, show_cluster=True):
"""
Print infos on this node configuration.
"""
self.__update_status()
indent = ''.join([" " for i in xrange(0, len(self.name) + 2)])
print_("{}: {}".format(self.name, self.__get_status_string()))
if not only_status:
if show_cluster:
print_("{}{}={}".format(indent, 'cluster', self.cluster.name))
print_("{}{}={}".format(indent, 'auto_bootstrap', self.auto_bootstrap))
if self.network_interfaces['thrift'] is not None:
print_("{}{}={}".format(indent, 'thrift', self.network_interfaces['thrift']))
if self.network_interfaces['binary'] is not None:
print_("{}{}={}".format(indent, 'binary', self.network_interfaces['binary']))
print_("{}{}={}".format(indent, 'storage', self.network_interfaces['storage']))
print_("{}{}={}".format(indent, 'jmx_port', self.jmx_port))
print_("{}{}={}".format(indent, 'remote_debug_port', self.remote_debug_port))
print_("{}{}={}".format(indent, 'byteman_port', self.byteman_port))
print_("{}{}={}".format(indent, 'initial_token', self.initial_token))
if self.pid:
print_("{}{}={}".format(indent, 'pid', self.pid)) | python | def show(self, only_status=False, show_cluster=True):
"""
Print infos on this node configuration.
"""
self.__update_status()
indent = ''.join([" " for i in xrange(0, len(self.name) + 2)])
print_("{}: {}".format(self.name, self.__get_status_string()))
if not only_status:
if show_cluster:
print_("{}{}={}".format(indent, 'cluster', self.cluster.name))
print_("{}{}={}".format(indent, 'auto_bootstrap', self.auto_bootstrap))
if self.network_interfaces['thrift'] is not None:
print_("{}{}={}".format(indent, 'thrift', self.network_interfaces['thrift']))
if self.network_interfaces['binary'] is not None:
print_("{}{}={}".format(indent, 'binary', self.network_interfaces['binary']))
print_("{}{}={}".format(indent, 'storage', self.network_interfaces['storage']))
print_("{}{}={}".format(indent, 'jmx_port', self.jmx_port))
print_("{}{}={}".format(indent, 'remote_debug_port', self.remote_debug_port))
print_("{}{}={}".format(indent, 'byteman_port', self.byteman_port))
print_("{}{}={}".format(indent, 'initial_token', self.initial_token))
if self.pid:
print_("{}{}={}".format(indent, 'pid', self.pid)) | [
"def",
"show",
"(",
"self",
",",
"only_status",
"=",
"False",
",",
"show_cluster",
"=",
"True",
")",
":",
"self",
".",
"__update_status",
"(",
")",
"indent",
"=",
"''",
".",
"join",
"(",
"[",
"\" \"",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"self",
".",
"name",
")",
"+",
"2",
")",
"]",
")",
"print_",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"__get_status_string",
"(",
")",
")",
")",
"if",
"not",
"only_status",
":",
"if",
"show_cluster",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'cluster'",
",",
"self",
".",
"cluster",
".",
"name",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'auto_bootstrap'",
",",
"self",
".",
"auto_bootstrap",
")",
")",
"if",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
"is",
"not",
"None",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'thrift'",
",",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
")",
")",
"if",
"self",
".",
"network_interfaces",
"[",
"'binary'",
"]",
"is",
"not",
"None",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'binary'",
",",
"self",
".",
"network_interfaces",
"[",
"'binary'",
"]",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'storage'",
",",
"self",
".",
"network_interfaces",
"[",
"'storage'",
"]",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'jmx_port'",
",",
"self",
".",
"jmx_port",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'remote_debug_port'",
",",
"self",
".",
"remote_debug_port",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'byteman_port'",
",",
"self",
".",
"byteman_port",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'initial_token'",
",",
"self",
".",
"initial_token",
")",
")",
"if",
"self",
".",
"pid",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'pid'",
",",
"self",
".",
"pid",
")",
")"
] | Print infos on this node configuration. | [
"Print",
"infos",
"on",
"this",
"node",
"configuration",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L329-L350 | train |
riptano/ccm | ccmlib/node.py | Node.is_running | def is_running(self):
"""
Return true if the node is running
"""
self.__update_status()
return self.status == Status.UP or self.status == Status.DECOMMISSIONED | python | def is_running(self):
"""
Return true if the node is running
"""
self.__update_status()
return self.status == Status.UP or self.status == Status.DECOMMISSIONED | [
"def",
"is_running",
"(",
"self",
")",
":",
"self",
".",
"__update_status",
"(",
")",
"return",
"self",
".",
"status",
"==",
"Status",
".",
"UP",
"or",
"self",
".",
"status",
"==",
"Status",
".",
"DECOMMISSIONED"
] | Return true if the node is running | [
"Return",
"true",
"if",
"the",
"node",
"is",
"running"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L352-L357 | train |
riptano/ccm | ccmlib/node.py | Node.grep_log | def grep_log(self, expr, filename='system.log', from_mark=None):
"""
Returns a list of lines matching the regular expression in parameter
in the Cassandra log of this node
"""
matchings = []
pattern = re.compile(expr)
with open(os.path.join(self.get_path(), 'logs', filename)) as f:
if from_mark:
f.seek(from_mark)
for line in f:
m = pattern.search(line)
if m:
matchings.append((line, m))
return matchings | python | def grep_log(self, expr, filename='system.log', from_mark=None):
"""
Returns a list of lines matching the regular expression in parameter
in the Cassandra log of this node
"""
matchings = []
pattern = re.compile(expr)
with open(os.path.join(self.get_path(), 'logs', filename)) as f:
if from_mark:
f.seek(from_mark)
for line in f:
m = pattern.search(line)
if m:
matchings.append((line, m))
return matchings | [
"def",
"grep_log",
"(",
"self",
",",
"expr",
",",
"filename",
"=",
"'system.log'",
",",
"from_mark",
"=",
"None",
")",
":",
"matchings",
"=",
"[",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"expr",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"get_path",
"(",
")",
",",
"'logs'",
",",
"filename",
")",
")",
"as",
"f",
":",
"if",
"from_mark",
":",
"f",
".",
"seek",
"(",
"from_mark",
")",
"for",
"line",
"in",
"f",
":",
"m",
"=",
"pattern",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"matchings",
".",
"append",
"(",
"(",
"line",
",",
"m",
")",
")",
"return",
"matchings"
] | Returns a list of lines matching the regular expression in parameter
in the Cassandra log of this node | [
"Returns",
"a",
"list",
"of",
"lines",
"matching",
"the",
"regular",
"expression",
"in",
"parameter",
"in",
"the",
"Cassandra",
"log",
"of",
"this",
"node"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L387-L401 | train |
riptano/ccm | ccmlib/node.py | Node.wait_for_binary_interface | def wait_for_binary_interface(self, **kwargs):
"""
Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '1.2':
self.watch_log_for("Starting listening for CQL clients", **kwargs)
binary_itf = self.network_interfaces['binary']
if not common.check_socket_listening(binary_itf, timeout=30):
warnings.warn("Binary interface %s:%s is not listening after 30 seconds, node may have failed to start."
% (binary_itf[0], binary_itf[1])) | python | def wait_for_binary_interface(self, **kwargs):
"""
Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '1.2':
self.watch_log_for("Starting listening for CQL clients", **kwargs)
binary_itf = self.network_interfaces['binary']
if not common.check_socket_listening(binary_itf, timeout=30):
warnings.warn("Binary interface %s:%s is not listening after 30 seconds, node may have failed to start."
% (binary_itf[0], binary_itf[1])) | [
"def",
"wait_for_binary_interface",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"cluster",
".",
"version",
"(",
")",
">=",
"'1.2'",
":",
"self",
".",
"watch_log_for",
"(",
"\"Starting listening for CQL clients\"",
",",
"*",
"*",
"kwargs",
")",
"binary_itf",
"=",
"self",
".",
"network_interfaces",
"[",
"'binary'",
"]",
"if",
"not",
"common",
".",
"check_socket_listening",
"(",
"binary_itf",
",",
"timeout",
"=",
"30",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Binary interface %s:%s is not listening after 30 seconds, node may have failed to start.\"",
"%",
"(",
"binary_itf",
"[",
"0",
"]",
",",
"binary_itf",
"[",
"1",
"]",
")",
")"
] | Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after 30 seconds. | [
"Waits",
"for",
"the",
"Binary",
"CQL",
"interface",
"to",
"be",
"listening",
".",
"If",
">",
"1",
".",
"2",
"will",
"check",
"log",
"for",
"Starting",
"listening",
"for",
"CQL",
"clients",
"before",
"checking",
"for",
"the",
"interface",
"to",
"be",
"listening",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L544-L558 | train |
riptano/ccm | ccmlib/node.py | Node.wait_for_thrift_interface | def wait_for_thrift_interface(self, **kwargs):
"""
Waits for the Thrift interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '4':
return;
self.watch_log_for("Listening for thrift clients...", **kwargs)
thrift_itf = self.network_interfaces['thrift']
if not common.check_socket_listening(thrift_itf, timeout=30):
warnings.warn("Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.".format(thrift_itf[0], thrift_itf[1])) | python | def wait_for_thrift_interface(self, **kwargs):
"""
Waits for the Thrift interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '4':
return;
self.watch_log_for("Listening for thrift clients...", **kwargs)
thrift_itf = self.network_interfaces['thrift']
if not common.check_socket_listening(thrift_itf, timeout=30):
warnings.warn("Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.".format(thrift_itf[0], thrift_itf[1])) | [
"def",
"wait_for_thrift_interface",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"cluster",
".",
"version",
"(",
")",
">=",
"'4'",
":",
"return",
"self",
".",
"watch_log_for",
"(",
"\"Listening for thrift clients...\"",
",",
"*",
"*",
"kwargs",
")",
"thrift_itf",
"=",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
"if",
"not",
"common",
".",
"check_socket_listening",
"(",
"thrift_itf",
",",
"timeout",
"=",
"30",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.\"",
".",
"format",
"(",
"thrift_itf",
"[",
"0",
"]",
",",
"thrift_itf",
"[",
"1",
"]",
")",
")"
] | Waits for the Thrift interface to be listening.
Emits a warning if not listening after 30 seconds. | [
"Waits",
"for",
"the",
"Thrift",
"interface",
"to",
"be",
"listening",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L560-L573 | train |
riptano/ccm | ccmlib/node.py | Node.wait_for_compactions | def wait_for_compactions(self, timeout=120):
"""
Wait for all compactions to finish on this node.
"""
pattern = re.compile("pending tasks: 0")
start = time.time()
while time.time() - start < timeout:
output, err, rc = self.nodetool("compactionstats")
if pattern.search(output):
return
time.sleep(1)
raise TimeoutError("{} [{}] Compactions did not finish in {} seconds".format(time.strftime("%d %b %Y %H:%M:%S", time.gmtime()), self.name, timeout)) | python | def wait_for_compactions(self, timeout=120):
"""
Wait for all compactions to finish on this node.
"""
pattern = re.compile("pending tasks: 0")
start = time.time()
while time.time() - start < timeout:
output, err, rc = self.nodetool("compactionstats")
if pattern.search(output):
return
time.sleep(1)
raise TimeoutError("{} [{}] Compactions did not finish in {} seconds".format(time.strftime("%d %b %Y %H:%M:%S", time.gmtime()), self.name, timeout)) | [
"def",
"wait_for_compactions",
"(",
"self",
",",
"timeout",
"=",
"120",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"\"pending tasks: 0\"",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
"-",
"start",
"<",
"timeout",
":",
"output",
",",
"err",
",",
"rc",
"=",
"self",
".",
"nodetool",
"(",
"\"compactionstats\"",
")",
"if",
"pattern",
".",
"search",
"(",
"output",
")",
":",
"return",
"time",
".",
"sleep",
"(",
"1",
")",
"raise",
"TimeoutError",
"(",
"\"{} [{}] Compactions did not finish in {} seconds\"",
".",
"format",
"(",
"time",
".",
"strftime",
"(",
"\"%d %b %Y %H:%M:%S\"",
",",
"time",
".",
"gmtime",
"(",
")",
")",
",",
"self",
".",
"name",
",",
"timeout",
")",
")"
] | Wait for all compactions to finish on this node. | [
"Wait",
"for",
"all",
"compactions",
"to",
"finish",
"on",
"this",
"node",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L804-L815 | train |
riptano/ccm | ccmlib/node.py | Node.update_startup_byteman_script | def update_startup_byteman_script(self, byteman_startup_script):
"""
Update the byteman startup script, i.e., rule injected before the node starts.
:param byteman_startup_script: the relative path to the script
:raise common.LoadError: if the node does not have byteman installed
"""
if self.byteman_port == '0':
raise common.LoadError('Byteman is not installed')
self.byteman_startup_script = byteman_startup_script
self.import_config_files() | python | def update_startup_byteman_script(self, byteman_startup_script):
"""
Update the byteman startup script, i.e., rule injected before the node starts.
:param byteman_startup_script: the relative path to the script
:raise common.LoadError: if the node does not have byteman installed
"""
if self.byteman_port == '0':
raise common.LoadError('Byteman is not installed')
self.byteman_startup_script = byteman_startup_script
self.import_config_files() | [
"def",
"update_startup_byteman_script",
"(",
"self",
",",
"byteman_startup_script",
")",
":",
"if",
"self",
".",
"byteman_port",
"==",
"'0'",
":",
"raise",
"common",
".",
"LoadError",
"(",
"'Byteman is not installed'",
")",
"self",
".",
"byteman_startup_script",
"=",
"byteman_startup_script",
"self",
".",
"import_config_files",
"(",
")"
] | Update the byteman startup script, i.e., rule injected before the node starts.
:param byteman_startup_script: the relative path to the script
:raise common.LoadError: if the node does not have byteman installed | [
"Update",
"the",
"byteman",
"startup",
"script",
"i",
".",
"e",
".",
"rule",
"injected",
"before",
"the",
"node",
"starts",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L953-L963 | train |
riptano/ccm | ccmlib/node.py | Node._find_cmd | def _find_cmd(self, cmd):
"""
Locates command under cassandra root and fixes permissions if needed
"""
cdir = self.get_install_cassandra_root()
if self.get_base_cassandra_version() >= 2.1:
fcmd = common.join_bin(cdir, os.path.join('tools', 'bin'), cmd)
else:
fcmd = common.join_bin(cdir, 'bin', cmd)
try:
if os.path.exists(fcmd):
os.chmod(fcmd, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
except:
common.warning("Couldn't change permissions to use {0}.".format(cmd))
common.warning("If it didn't work, you will have to do so manually.")
return fcmd | python | def _find_cmd(self, cmd):
"""
Locates command under cassandra root and fixes permissions if needed
"""
cdir = self.get_install_cassandra_root()
if self.get_base_cassandra_version() >= 2.1:
fcmd = common.join_bin(cdir, os.path.join('tools', 'bin'), cmd)
else:
fcmd = common.join_bin(cdir, 'bin', cmd)
try:
if os.path.exists(fcmd):
os.chmod(fcmd, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
except:
common.warning("Couldn't change permissions to use {0}.".format(cmd))
common.warning("If it didn't work, you will have to do so manually.")
return fcmd | [
"def",
"_find_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"cdir",
"=",
"self",
".",
"get_install_cassandra_root",
"(",
")",
"if",
"self",
".",
"get_base_cassandra_version",
"(",
")",
">=",
"2.1",
":",
"fcmd",
"=",
"common",
".",
"join_bin",
"(",
"cdir",
",",
"os",
".",
"path",
".",
"join",
"(",
"'tools'",
",",
"'bin'",
")",
",",
"cmd",
")",
"else",
":",
"fcmd",
"=",
"common",
".",
"join_bin",
"(",
"cdir",
",",
"'bin'",
",",
"cmd",
")",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fcmd",
")",
":",
"os",
".",
"chmod",
"(",
"fcmd",
",",
"stat",
".",
"S_IRUSR",
"|",
"stat",
".",
"S_IWUSR",
"|",
"stat",
".",
"S_IXUSR",
"|",
"stat",
".",
"S_IRGRP",
"|",
"stat",
".",
"S_IXGRP",
"|",
"stat",
".",
"S_IROTH",
"|",
"stat",
".",
"S_IXOTH",
")",
"except",
":",
"common",
".",
"warning",
"(",
"\"Couldn't change permissions to use {0}.\"",
".",
"format",
"(",
"cmd",
")",
")",
"common",
".",
"warning",
"(",
"\"If it didn't work, you will have to do so manually.\"",
")",
"return",
"fcmd"
] | Locates command under cassandra root and fixes permissions if needed | [
"Locates",
"command",
"under",
"cassandra",
"root",
"and",
"fixes",
"permissions",
"if",
"needed"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L1209-L1224 | train |
riptano/ccm | ccmlib/node.py | Node.data_size | def data_size(self, live_data=None):
"""Uses `nodetool info` to get the size of a node's data in KB."""
if live_data is not None:
warnings.warn("The 'live_data' keyword argument is deprecated.",
DeprecationWarning)
output = self.nodetool('info')[0]
return _get_load_from_info_output(output) | python | def data_size(self, live_data=None):
"""Uses `nodetool info` to get the size of a node's data in KB."""
if live_data is not None:
warnings.warn("The 'live_data' keyword argument is deprecated.",
DeprecationWarning)
output = self.nodetool('info')[0]
return _get_load_from_info_output(output) | [
"def",
"data_size",
"(",
"self",
",",
"live_data",
"=",
"None",
")",
":",
"if",
"live_data",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"The 'live_data' keyword argument is deprecated.\"",
",",
"DeprecationWarning",
")",
"output",
"=",
"self",
".",
"nodetool",
"(",
"'info'",
")",
"[",
"0",
"]",
"return",
"_get_load_from_info_output",
"(",
"output",
")"
] | Uses `nodetool info` to get the size of a node's data in KB. | [
"Uses",
"nodetool",
"info",
"to",
"get",
"the",
"size",
"of",
"a",
"node",
"s",
"data",
"in",
"KB",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L1338-L1344 | train |
riptano/ccm | ccmlib/node.py | Node.get_sstable_data_files | def get_sstable_data_files(self, ks, table):
"""
Read sstable data files by using sstableutil, so we ignore temporary files
"""
p = self.get_sstable_data_files_process(ks=ks, table=table)
out, _, _ = handle_external_tool_process(p, ["sstableutil", '--type', 'final', ks, table])
return sorted(filter(lambda s: s.endswith('-Data.db'), out.splitlines())) | python | def get_sstable_data_files(self, ks, table):
"""
Read sstable data files by using sstableutil, so we ignore temporary files
"""
p = self.get_sstable_data_files_process(ks=ks, table=table)
out, _, _ = handle_external_tool_process(p, ["sstableutil", '--type', 'final', ks, table])
return sorted(filter(lambda s: s.endswith('-Data.db'), out.splitlines())) | [
"def",
"get_sstable_data_files",
"(",
"self",
",",
"ks",
",",
"table",
")",
":",
"p",
"=",
"self",
".",
"get_sstable_data_files_process",
"(",
"ks",
"=",
"ks",
",",
"table",
"=",
"table",
")",
"out",
",",
"_",
",",
"_",
"=",
"handle_external_tool_process",
"(",
"p",
",",
"[",
"\"sstableutil\"",
",",
"'--type'",
",",
"'final'",
",",
"ks",
",",
"table",
"]",
")",
"return",
"sorted",
"(",
"filter",
"(",
"lambda",
"s",
":",
"s",
".",
"endswith",
"(",
"'-Data.db'",
")",
",",
"out",
".",
"splitlines",
"(",
")",
")",
")"
] | Read sstable data files by using sstableutil, so we ignore temporary files | [
"Read",
"sstable",
"data",
"files",
"by",
"using",
"sstableutil",
"so",
"we",
"ignore",
"temporary",
"files"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L2005-L2013 | train |
riptano/ccm | ccmlib/common.py | is_modern_windows_install | def is_modern_windows_install(version):
"""
The 2.1 release line was when Cassandra received beta windows support.
Many features are gated based on that added compatibility.
Handles floats, strings, and LooseVersions by first converting all three types to a string, then to a LooseVersion.
"""
version = LooseVersion(str(version))
if is_win() and version >= LooseVersion('2.1'):
return True
else:
return False | python | def is_modern_windows_install(version):
"""
The 2.1 release line was when Cassandra received beta windows support.
Many features are gated based on that added compatibility.
Handles floats, strings, and LooseVersions by first converting all three types to a string, then to a LooseVersion.
"""
version = LooseVersion(str(version))
if is_win() and version >= LooseVersion('2.1'):
return True
else:
return False | [
"def",
"is_modern_windows_install",
"(",
"version",
")",
":",
"version",
"=",
"LooseVersion",
"(",
"str",
"(",
"version",
")",
")",
"if",
"is_win",
"(",
")",
"and",
"version",
">=",
"LooseVersion",
"(",
"'2.1'",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | The 2.1 release line was when Cassandra received beta windows support.
Many features are gated based on that added compatibility.
Handles floats, strings, and LooseVersions by first converting all three types to a string, then to a LooseVersion. | [
"The",
"2",
".",
"1",
"release",
"line",
"was",
"when",
"Cassandra",
"received",
"beta",
"windows",
"support",
".",
"Many",
"features",
"are",
"gated",
"based",
"on",
"that",
"added",
"compatibility",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/common.py#L354-L365 | train |
riptano/ccm | ccmlib/common.py | get_jdk_version | def get_jdk_version():
"""
Retrieve the Java version as reported in the quoted string returned
by invoking 'java -version'.
Works for Java 1.8, Java 9 and should also be fine for Java 10.
"""
try:
version = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT)
except OSError:
print_("ERROR: Could not find java. Is it in your path?")
exit(1)
return _get_jdk_version(version) | python | def get_jdk_version():
"""
Retrieve the Java version as reported in the quoted string returned
by invoking 'java -version'.
Works for Java 1.8, Java 9 and should also be fine for Java 10.
"""
try:
version = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT)
except OSError:
print_("ERROR: Could not find java. Is it in your path?")
exit(1)
return _get_jdk_version(version) | [
"def",
"get_jdk_version",
"(",
")",
":",
"try",
":",
"version",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'java'",
",",
"'-version'",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"except",
"OSError",
":",
"print_",
"(",
"\"ERROR: Could not find java. Is it in your path?\"",
")",
"exit",
"(",
"1",
")",
"return",
"_get_jdk_version",
"(",
"version",
")"
] | Retrieve the Java version as reported in the quoted string returned
by invoking 'java -version'.
Works for Java 1.8, Java 9 and should also be fine for Java 10. | [
"Retrieve",
"the",
"Java",
"version",
"as",
"reported",
"in",
"the",
"quoted",
"string",
"returned",
"by",
"invoking",
"java",
"-",
"version",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/common.py#L706-L719 | train |
riptano/ccm | ccmlib/common.py | wait_for_any_log | def wait_for_any_log(nodes, pattern, timeout, filename='system.log', marks=None):
"""
Look for a pattern in the system.log of any in a given list
of nodes.
@param nodes The list of nodes whose logs to scan
@param pattern The target pattern
@param timeout How long to wait for the pattern. Note that
strictly speaking, timeout is not really a timeout,
but a maximum number of attempts. This implies that
the all the grepping takes no time at all, so it is
somewhat inaccurate, but probably close enough.
@param marks A dict of nodes to marks in the file. Keys must match the first param list.
@return The first node in whose log the pattern was found
"""
if marks is None:
marks = {}
for _ in range(timeout):
for node in nodes:
found = node.grep_log(pattern, filename=filename, from_mark=marks.get(node, None))
if found:
return node
time.sleep(1)
raise TimeoutError(time.strftime("%d %b %Y %H:%M:%S", time.gmtime()) +
" Unable to find: " + repr(pattern) + " in any node log within " + str(timeout) + "s") | python | def wait_for_any_log(nodes, pattern, timeout, filename='system.log', marks=None):
"""
Look for a pattern in the system.log of any in a given list
of nodes.
@param nodes The list of nodes whose logs to scan
@param pattern The target pattern
@param timeout How long to wait for the pattern. Note that
strictly speaking, timeout is not really a timeout,
but a maximum number of attempts. This implies that
the all the grepping takes no time at all, so it is
somewhat inaccurate, but probably close enough.
@param marks A dict of nodes to marks in the file. Keys must match the first param list.
@return The first node in whose log the pattern was found
"""
if marks is None:
marks = {}
for _ in range(timeout):
for node in nodes:
found = node.grep_log(pattern, filename=filename, from_mark=marks.get(node, None))
if found:
return node
time.sleep(1)
raise TimeoutError(time.strftime("%d %b %Y %H:%M:%S", time.gmtime()) +
" Unable to find: " + repr(pattern) + " in any node log within " + str(timeout) + "s") | [
"def",
"wait_for_any_log",
"(",
"nodes",
",",
"pattern",
",",
"timeout",
",",
"filename",
"=",
"'system.log'",
",",
"marks",
"=",
"None",
")",
":",
"if",
"marks",
"is",
"None",
":",
"marks",
"=",
"{",
"}",
"for",
"_",
"in",
"range",
"(",
"timeout",
")",
":",
"for",
"node",
"in",
"nodes",
":",
"found",
"=",
"node",
".",
"grep_log",
"(",
"pattern",
",",
"filename",
"=",
"filename",
",",
"from_mark",
"=",
"marks",
".",
"get",
"(",
"node",
",",
"None",
")",
")",
"if",
"found",
":",
"return",
"node",
"time",
".",
"sleep",
"(",
"1",
")",
"raise",
"TimeoutError",
"(",
"time",
".",
"strftime",
"(",
"\"%d %b %Y %H:%M:%S\"",
",",
"time",
".",
"gmtime",
"(",
")",
")",
"+",
"\" Unable to find: \"",
"+",
"repr",
"(",
"pattern",
")",
"+",
"\" in any node log within \"",
"+",
"str",
"(",
"timeout",
")",
"+",
"\"s\"",
")"
] | Look for a pattern in the system.log of any in a given list
of nodes.
@param nodes The list of nodes whose logs to scan
@param pattern The target pattern
@param timeout How long to wait for the pattern. Note that
strictly speaking, timeout is not really a timeout,
but a maximum number of attempts. This implies that
the all the grepping takes no time at all, so it is
somewhat inaccurate, but probably close enough.
@param marks A dict of nodes to marks in the file. Keys must match the first param list.
@return The first node in whose log the pattern was found | [
"Look",
"for",
"a",
"pattern",
"in",
"the",
"system",
".",
"log",
"of",
"any",
"in",
"a",
"given",
"list",
"of",
"nodes",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/common.py#L769-L793 | train |
riptano/ccm | ccmlib/repository.py | download_version | def download_version(version, url=None, verbose=False, binary=False):
"""Download, extract, and build Cassandra tarball.
if binary == True, download precompiled tarball, otherwise build from source tarball.
"""
assert_jdk_valid_for_cassandra_version(version)
archive_url = ARCHIVE
if CCM_CONFIG.has_option('repositories', 'cassandra'):
archive_url = CCM_CONFIG.get('repositories', 'cassandra')
if binary:
archive_url = "%s/%s/apache-cassandra-%s-bin.tar.gz" % (archive_url, version.split('-')[0], version) if url is None else url
else:
archive_url = "%s/%s/apache-cassandra-%s-src.tar.gz" % (archive_url, version.split('-')[0], version) if url is None else url
_, target = tempfile.mkstemp(suffix=".tar.gz", prefix="ccm-")
try:
__download(archive_url, target, show_progress=verbose)
common.info("Extracting {} as version {} ...".format(target, version))
tar = tarfile.open(target)
dir = tar.next().name.split("/")[0] # pylint: disable=all
tar.extractall(path=__get_dir())
tar.close()
target_dir = os.path.join(__get_dir(), version)
if os.path.exists(target_dir):
rmdirs(target_dir)
shutil.move(os.path.join(__get_dir(), dir), target_dir)
if binary:
# Binary installs don't have a build.xml that is needed
# for pulling the version from. Write the version number
# into a file to read later in common.get_version_from_build()
with open(os.path.join(target_dir, '0.version.txt'), 'w') as f:
f.write(version)
else:
compile_version(version, target_dir, verbose=verbose)
except urllib.error.URLError as e:
msg = "Invalid version {}".format(version) if url is None else "Invalid url {}".format(url)
msg = msg + " (underlying error is: {})".format(str(e))
raise ArgumentError(msg)
except tarfile.ReadError as e:
raise ArgumentError("Unable to uncompress downloaded file: {}".format(str(e)))
except CCMError as e:
# wipe out the directory if anything goes wrong. Otherwise we will assume it has been compiled the next time it runs.
try:
rmdirs(target_dir)
common.error("Deleted {} due to error".format(target_dir))
except:
raise CCMError("Building C* version {} failed. Attempted to delete {} but failed. This will need to be manually deleted".format(version, target_dir))
raise e | python | def download_version(version, url=None, verbose=False, binary=False):
"""Download, extract, and build Cassandra tarball.
if binary == True, download precompiled tarball, otherwise build from source tarball.
"""
assert_jdk_valid_for_cassandra_version(version)
archive_url = ARCHIVE
if CCM_CONFIG.has_option('repositories', 'cassandra'):
archive_url = CCM_CONFIG.get('repositories', 'cassandra')
if binary:
archive_url = "%s/%s/apache-cassandra-%s-bin.tar.gz" % (archive_url, version.split('-')[0], version) if url is None else url
else:
archive_url = "%s/%s/apache-cassandra-%s-src.tar.gz" % (archive_url, version.split('-')[0], version) if url is None else url
_, target = tempfile.mkstemp(suffix=".tar.gz", prefix="ccm-")
try:
__download(archive_url, target, show_progress=verbose)
common.info("Extracting {} as version {} ...".format(target, version))
tar = tarfile.open(target)
dir = tar.next().name.split("/")[0] # pylint: disable=all
tar.extractall(path=__get_dir())
tar.close()
target_dir = os.path.join(__get_dir(), version)
if os.path.exists(target_dir):
rmdirs(target_dir)
shutil.move(os.path.join(__get_dir(), dir), target_dir)
if binary:
# Binary installs don't have a build.xml that is needed
# for pulling the version from. Write the version number
# into a file to read later in common.get_version_from_build()
with open(os.path.join(target_dir, '0.version.txt'), 'w') as f:
f.write(version)
else:
compile_version(version, target_dir, verbose=verbose)
except urllib.error.URLError as e:
msg = "Invalid version {}".format(version) if url is None else "Invalid url {}".format(url)
msg = msg + " (underlying error is: {})".format(str(e))
raise ArgumentError(msg)
except tarfile.ReadError as e:
raise ArgumentError("Unable to uncompress downloaded file: {}".format(str(e)))
except CCMError as e:
# wipe out the directory if anything goes wrong. Otherwise we will assume it has been compiled the next time it runs.
try:
rmdirs(target_dir)
common.error("Deleted {} due to error".format(target_dir))
except:
raise CCMError("Building C* version {} failed. Attempted to delete {} but failed. This will need to be manually deleted".format(version, target_dir))
raise e | [
"def",
"download_version",
"(",
"version",
",",
"url",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"binary",
"=",
"False",
")",
":",
"assert_jdk_valid_for_cassandra_version",
"(",
"version",
")",
"archive_url",
"=",
"ARCHIVE",
"if",
"CCM_CONFIG",
".",
"has_option",
"(",
"'repositories'",
",",
"'cassandra'",
")",
":",
"archive_url",
"=",
"CCM_CONFIG",
".",
"get",
"(",
"'repositories'",
",",
"'cassandra'",
")",
"if",
"binary",
":",
"archive_url",
"=",
"\"%s/%s/apache-cassandra-%s-bin.tar.gz\"",
"%",
"(",
"archive_url",
",",
"version",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
",",
"version",
")",
"if",
"url",
"is",
"None",
"else",
"url",
"else",
":",
"archive_url",
"=",
"\"%s/%s/apache-cassandra-%s-src.tar.gz\"",
"%",
"(",
"archive_url",
",",
"version",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
",",
"version",
")",
"if",
"url",
"is",
"None",
"else",
"url",
"_",
",",
"target",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"\".tar.gz\"",
",",
"prefix",
"=",
"\"ccm-\"",
")",
"try",
":",
"__download",
"(",
"archive_url",
",",
"target",
",",
"show_progress",
"=",
"verbose",
")",
"common",
".",
"info",
"(",
"\"Extracting {} as version {} ...\"",
".",
"format",
"(",
"target",
",",
"version",
")",
")",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"target",
")",
"dir",
"=",
"tar",
".",
"next",
"(",
")",
".",
"name",
".",
"split",
"(",
"\"/\"",
")",
"[",
"0",
"]",
"# pylint: disable=all",
"tar",
".",
"extractall",
"(",
"path",
"=",
"__get_dir",
"(",
")",
")",
"tar",
".",
"close",
"(",
")",
"target_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__get_dir",
"(",
")",
",",
"version",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target_dir",
")",
":",
"rmdirs",
"(",
"target_dir",
")",
"shutil",
".",
"move",
"(",
"os",
".",
"path",
".",
"join",
"(",
"__get_dir",
"(",
")",
",",
"dir",
")",
",",
"target_dir",
")",
"if",
"binary",
":",
"# Binary installs don't have a build.xml that is needed",
"# for pulling the version from. Write the version number",
"# into a file to read later in common.get_version_from_build()",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"'0.version.txt'",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"version",
")",
"else",
":",
"compile_version",
"(",
"version",
",",
"target_dir",
",",
"verbose",
"=",
"verbose",
")",
"except",
"urllib",
".",
"error",
".",
"URLError",
"as",
"e",
":",
"msg",
"=",
"\"Invalid version {}\"",
".",
"format",
"(",
"version",
")",
"if",
"url",
"is",
"None",
"else",
"\"Invalid url {}\"",
".",
"format",
"(",
"url",
")",
"msg",
"=",
"msg",
"+",
"\" (underlying error is: {})\"",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
"raise",
"ArgumentError",
"(",
"msg",
")",
"except",
"tarfile",
".",
"ReadError",
"as",
"e",
":",
"raise",
"ArgumentError",
"(",
"\"Unable to uncompress downloaded file: {}\"",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"except",
"CCMError",
"as",
"e",
":",
"# wipe out the directory if anything goes wrong. Otherwise we will assume it has been compiled the next time it runs.",
"try",
":",
"rmdirs",
"(",
"target_dir",
")",
"common",
".",
"error",
"(",
"\"Deleted {} due to error\"",
".",
"format",
"(",
"target_dir",
")",
")",
"except",
":",
"raise",
"CCMError",
"(",
"\"Building C* version {} failed. Attempted to delete {} but failed. This will need to be manually deleted\"",
".",
"format",
"(",
"version",
",",
"target_dir",
")",
")",
"raise",
"e"
] | Download, extract, and build Cassandra tarball.
if binary == True, download precompiled tarball, otherwise build from source tarball. | [
"Download",
"extract",
"and",
"build",
"Cassandra",
"tarball",
"."
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/repository.py#L331-L381 | train |
riptano/ccm | ccmlib/repository.py | get_tagged_version_numbers | def get_tagged_version_numbers(series='stable'):
"""Retrieve git tags and find version numbers for a release series
series - 'stable', 'oldstable', or 'testing'"""
releases = []
if series == 'testing':
# Testing releases always have a hyphen after the version number:
tag_regex = re.compile('^refs/tags/cassandra-([0-9]+\.[0-9]+\.[0-9]+-.*$)')
else:
# Stable and oldstable releases are just a number:
tag_regex = re.compile('^refs/tags/cassandra-([0-9]+\.[0-9]+\.[0-9]+$)')
tag_url = urllib.request.urlopen(GITHUB_TAGS)
for ref in (i.get('ref', '') for i in json.loads(tag_url.read())):
m = tag_regex.match(ref)
if m:
releases.append(LooseVersion(m.groups()[0]))
# Sort by semver:
releases.sort(reverse=True)
stable_major_version = LooseVersion(str(releases[0].version[0]) + "." + str(releases[0].version[1]))
stable_releases = [r for r in releases if r >= stable_major_version]
oldstable_releases = [r for r in releases if r not in stable_releases]
oldstable_major_version = LooseVersion(str(oldstable_releases[0].version[0]) + "." + str(oldstable_releases[0].version[1]))
oldstable_releases = [r for r in oldstable_releases if r >= oldstable_major_version]
if series == 'testing':
return [r.vstring for r in releases]
elif series == 'stable':
return [r.vstring for r in stable_releases]
elif series == 'oldstable':
return [r.vstring for r in oldstable_releases]
else:
raise AssertionError("unknown release series: {series}".format(series=series)) | python | def get_tagged_version_numbers(series='stable'):
"""Retrieve git tags and find version numbers for a release series
series - 'stable', 'oldstable', or 'testing'"""
releases = []
if series == 'testing':
# Testing releases always have a hyphen after the version number:
tag_regex = re.compile('^refs/tags/cassandra-([0-9]+\.[0-9]+\.[0-9]+-.*$)')
else:
# Stable and oldstable releases are just a number:
tag_regex = re.compile('^refs/tags/cassandra-([0-9]+\.[0-9]+\.[0-9]+$)')
tag_url = urllib.request.urlopen(GITHUB_TAGS)
for ref in (i.get('ref', '') for i in json.loads(tag_url.read())):
m = tag_regex.match(ref)
if m:
releases.append(LooseVersion(m.groups()[0]))
# Sort by semver:
releases.sort(reverse=True)
stable_major_version = LooseVersion(str(releases[0].version[0]) + "." + str(releases[0].version[1]))
stable_releases = [r for r in releases if r >= stable_major_version]
oldstable_releases = [r for r in releases if r not in stable_releases]
oldstable_major_version = LooseVersion(str(oldstable_releases[0].version[0]) + "." + str(oldstable_releases[0].version[1]))
oldstable_releases = [r for r in oldstable_releases if r >= oldstable_major_version]
if series == 'testing':
return [r.vstring for r in releases]
elif series == 'stable':
return [r.vstring for r in stable_releases]
elif series == 'oldstable':
return [r.vstring for r in oldstable_releases]
else:
raise AssertionError("unknown release series: {series}".format(series=series)) | [
"def",
"get_tagged_version_numbers",
"(",
"series",
"=",
"'stable'",
")",
":",
"releases",
"=",
"[",
"]",
"if",
"series",
"==",
"'testing'",
":",
"# Testing releases always have a hyphen after the version number:",
"tag_regex",
"=",
"re",
".",
"compile",
"(",
"'^refs/tags/cassandra-([0-9]+\\.[0-9]+\\.[0-9]+-.*$)'",
")",
"else",
":",
"# Stable and oldstable releases are just a number:",
"tag_regex",
"=",
"re",
".",
"compile",
"(",
"'^refs/tags/cassandra-([0-9]+\\.[0-9]+\\.[0-9]+$)'",
")",
"tag_url",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"GITHUB_TAGS",
")",
"for",
"ref",
"in",
"(",
"i",
".",
"get",
"(",
"'ref'",
",",
"''",
")",
"for",
"i",
"in",
"json",
".",
"loads",
"(",
"tag_url",
".",
"read",
"(",
")",
")",
")",
":",
"m",
"=",
"tag_regex",
".",
"match",
"(",
"ref",
")",
"if",
"m",
":",
"releases",
".",
"append",
"(",
"LooseVersion",
"(",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
")",
")",
"# Sort by semver:",
"releases",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"stable_major_version",
"=",
"LooseVersion",
"(",
"str",
"(",
"releases",
"[",
"0",
"]",
".",
"version",
"[",
"0",
"]",
")",
"+",
"\".\"",
"+",
"str",
"(",
"releases",
"[",
"0",
"]",
".",
"version",
"[",
"1",
"]",
")",
")",
"stable_releases",
"=",
"[",
"r",
"for",
"r",
"in",
"releases",
"if",
"r",
">=",
"stable_major_version",
"]",
"oldstable_releases",
"=",
"[",
"r",
"for",
"r",
"in",
"releases",
"if",
"r",
"not",
"in",
"stable_releases",
"]",
"oldstable_major_version",
"=",
"LooseVersion",
"(",
"str",
"(",
"oldstable_releases",
"[",
"0",
"]",
".",
"version",
"[",
"0",
"]",
")",
"+",
"\".\"",
"+",
"str",
"(",
"oldstable_releases",
"[",
"0",
"]",
".",
"version",
"[",
"1",
"]",
")",
")",
"oldstable_releases",
"=",
"[",
"r",
"for",
"r",
"in",
"oldstable_releases",
"if",
"r",
">=",
"oldstable_major_version",
"]",
"if",
"series",
"==",
"'testing'",
":",
"return",
"[",
"r",
".",
"vstring",
"for",
"r",
"in",
"releases",
"]",
"elif",
"series",
"==",
"'stable'",
":",
"return",
"[",
"r",
".",
"vstring",
"for",
"r",
"in",
"stable_releases",
"]",
"elif",
"series",
"==",
"'oldstable'",
":",
"return",
"[",
"r",
".",
"vstring",
"for",
"r",
"in",
"oldstable_releases",
"]",
"else",
":",
"raise",
"AssertionError",
"(",
"\"unknown release series: {series}\"",
".",
"format",
"(",
"series",
"=",
"series",
")",
")"
] | Retrieve git tags and find version numbers for a release series
series - 'stable', 'oldstable', or 'testing | [
"Retrieve",
"git",
"tags",
"and",
"find",
"version",
"numbers",
"for",
"a",
"release",
"series"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/repository.py#L477-L511 | train |
riptano/ccm | ccmlib/remote.py | SSHClient.__connect | def __connect(host, port, username, password, private_key):
"""
Establish remote connection
:param host: Hostname or IP address to connect to
:param port: Port number to use for SSH
:param username: Username credentials for SSH access
:param password: Password credentials for SSH access (or private key passphrase)
:param private_key: Private key to bypass clear text password
:return: Paramiko SSH client instance if connection was established
:raises Exception if connection was unsuccessful
"""
# Initialize the SSH connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if private_key is not None and password is not None:
private_key = paramiko.RSAKey.from_private_key_file(private_key, password)
elif private_key is not None:
private_key = paramiko.RSAKey.from_private_key_file(private_key, password)
# Establish the SSH connection
try:
ssh.connect(host, port, username, password, private_key)
except Exception as e:
raise e
# Return the established SSH connection
return ssh | python | def __connect(host, port, username, password, private_key):
"""
Establish remote connection
:param host: Hostname or IP address to connect to
:param port: Port number to use for SSH
:param username: Username credentials for SSH access
:param password: Password credentials for SSH access (or private key passphrase)
:param private_key: Private key to bypass clear text password
:return: Paramiko SSH client instance if connection was established
:raises Exception if connection was unsuccessful
"""
# Initialize the SSH connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if private_key is not None and password is not None:
private_key = paramiko.RSAKey.from_private_key_file(private_key, password)
elif private_key is not None:
private_key = paramiko.RSAKey.from_private_key_file(private_key, password)
# Establish the SSH connection
try:
ssh.connect(host, port, username, password, private_key)
except Exception as e:
raise e
# Return the established SSH connection
return ssh | [
"def",
"__connect",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"private_key",
")",
":",
"# Initialize the SSH connection",
"ssh",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"ssh",
".",
"set_missing_host_key_policy",
"(",
"paramiko",
".",
"AutoAddPolicy",
"(",
")",
")",
"if",
"private_key",
"is",
"not",
"None",
"and",
"password",
"is",
"not",
"None",
":",
"private_key",
"=",
"paramiko",
".",
"RSAKey",
".",
"from_private_key_file",
"(",
"private_key",
",",
"password",
")",
"elif",
"private_key",
"is",
"not",
"None",
":",
"private_key",
"=",
"paramiko",
".",
"RSAKey",
".",
"from_private_key_file",
"(",
"private_key",
",",
"password",
")",
"# Establish the SSH connection",
"try",
":",
"ssh",
".",
"connect",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"private_key",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"# Return the established SSH connection",
"return",
"ssh"
] | Establish remote connection
:param host: Hostname or IP address to connect to
:param port: Port number to use for SSH
:param username: Username credentials for SSH access
:param password: Password credentials for SSH access (or private key passphrase)
:param private_key: Private key to bypass clear text password
:return: Paramiko SSH client instance if connection was established
:raises Exception if connection was unsuccessful | [
"Establish",
"remote",
"connection"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L142-L169 | train |
riptano/ccm | ccmlib/remote.py | SSHClient.execute_ccm_command | def execute_ccm_command(self, ccm_args, is_displayed=True):
"""
Execute a CCM command on the remote server
:param ccm_args: CCM arguments to execute remotely
:param is_displayed: True if information should be display; false to return output
(default: true)
:return: A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script
"""
return self.execute(["ccm"] + ccm_args, profile=self.profile) | python | def execute_ccm_command(self, ccm_args, is_displayed=True):
"""
Execute a CCM command on the remote server
:param ccm_args: CCM arguments to execute remotely
:param is_displayed: True if information should be display; false to return output
(default: true)
:return: A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script
"""
return self.execute(["ccm"] + ccm_args, profile=self.profile) | [
"def",
"execute_ccm_command",
"(",
"self",
",",
"ccm_args",
",",
"is_displayed",
"=",
"True",
")",
":",
"return",
"self",
".",
"execute",
"(",
"[",
"\"ccm\"",
"]",
"+",
"ccm_args",
",",
"profile",
"=",
"self",
".",
"profile",
")"
] | Execute a CCM command on the remote server
:param ccm_args: CCM arguments to execute remotely
:param is_displayed: True if information should be display; false to return output
(default: true)
:return: A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script | [
"Execute",
"a",
"CCM",
"command",
"on",
"the",
"remote",
"server"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L244-L255 | train |
riptano/ccm | ccmlib/remote.py | SSHClient.execute_python_script | def execute_python_script(self, script):
"""
Execute a python script of the remote server
:param script: Inline script to convert to a file and execute remotely
:return: The output of the script execution
"""
# Create the local file to copy to remote
file_handle, filename = tempfile.mkstemp()
temp_file = os.fdopen(file_handle, "wt")
temp_file.write(script)
temp_file.close()
# Put the file into the remote user directory
self.put(filename, "python_execute.py")
command = ["python", "python_execute.py"]
# Execute the python script on the remote system, clean up, and return the output
output = self.execute(command, False)
self.remove("python_execute.py")
os.unlink(filename)
return output | python | def execute_python_script(self, script):
"""
Execute a python script of the remote server
:param script: Inline script to convert to a file and execute remotely
:return: The output of the script execution
"""
# Create the local file to copy to remote
file_handle, filename = tempfile.mkstemp()
temp_file = os.fdopen(file_handle, "wt")
temp_file.write(script)
temp_file.close()
# Put the file into the remote user directory
self.put(filename, "python_execute.py")
command = ["python", "python_execute.py"]
# Execute the python script on the remote system, clean up, and return the output
output = self.execute(command, False)
self.remove("python_execute.py")
os.unlink(filename)
return output | [
"def",
"execute_python_script",
"(",
"self",
",",
"script",
")",
":",
"# Create the local file to copy to remote",
"file_handle",
",",
"filename",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"temp_file",
"=",
"os",
".",
"fdopen",
"(",
"file_handle",
",",
"\"wt\"",
")",
"temp_file",
".",
"write",
"(",
"script",
")",
"temp_file",
".",
"close",
"(",
")",
"# Put the file into the remote user directory",
"self",
".",
"put",
"(",
"filename",
",",
"\"python_execute.py\"",
")",
"command",
"=",
"[",
"\"python\"",
",",
"\"python_execute.py\"",
"]",
"# Execute the python script on the remote system, clean up, and return the output",
"output",
"=",
"self",
".",
"execute",
"(",
"command",
",",
"False",
")",
"self",
".",
"remove",
"(",
"\"python_execute.py\"",
")",
"os",
".",
"unlink",
"(",
"filename",
")",
"return",
"output"
] | Execute a python script of the remote server
:param script: Inline script to convert to a file and execute remotely
:return: The output of the script execution | [
"Execute",
"a",
"python",
"script",
"of",
"the",
"remote",
"server"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L257-L278 | train |
riptano/ccm | ccmlib/remote.py | SSHClient.__put_dir | def __put_dir(self, ftp, local_path, remote_path=None):
"""
Helper function to perform copy operation to remote server
:param ftp: SFTP handle to perform copy operation(s)
:param local_path: Local path to copy to; can be file or directory
:param remote_path: Remote path to copy to (default: None - Copies file or directory to
home directory directory on the remote server)
"""
# Determine if local_path should be put into remote user directory
if remote_path is None:
remote_path = os.path.basename(local_path)
remote_path += self.separator
# Iterate over the local path and perform copy operations to remote server
for current_path, directories, files in os.walk(local_path):
# Create the remote directory (if needed)
try:
ftp.listdir(remote_path)
except IOError:
ftp.mkdir(remote_path)
# Copy the files in the current directory to the remote path
for filename in files:
ftp.put(os.path.join(current_path, filename), remote_path + filename)
# Copy the directory in the current directory to the remote path
for directory in directories:
self.__put_dir(ftp, os.path.join(current_path, directory), remote_path + directory) | python | def __put_dir(self, ftp, local_path, remote_path=None):
"""
Helper function to perform copy operation to remote server
:param ftp: SFTP handle to perform copy operation(s)
:param local_path: Local path to copy to; can be file or directory
:param remote_path: Remote path to copy to (default: None - Copies file or directory to
home directory directory on the remote server)
"""
# Determine if local_path should be put into remote user directory
if remote_path is None:
remote_path = os.path.basename(local_path)
remote_path += self.separator
# Iterate over the local path and perform copy operations to remote server
for current_path, directories, files in os.walk(local_path):
# Create the remote directory (if needed)
try:
ftp.listdir(remote_path)
except IOError:
ftp.mkdir(remote_path)
# Copy the files in the current directory to the remote path
for filename in files:
ftp.put(os.path.join(current_path, filename), remote_path + filename)
# Copy the directory in the current directory to the remote path
for directory in directories:
self.__put_dir(ftp, os.path.join(current_path, directory), remote_path + directory) | [
"def",
"__put_dir",
"(",
"self",
",",
"ftp",
",",
"local_path",
",",
"remote_path",
"=",
"None",
")",
":",
"# Determine if local_path should be put into remote user directory",
"if",
"remote_path",
"is",
"None",
":",
"remote_path",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"local_path",
")",
"remote_path",
"+=",
"self",
".",
"separator",
"# Iterate over the local path and perform copy operations to remote server",
"for",
"current_path",
",",
"directories",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"local_path",
")",
":",
"# Create the remote directory (if needed)",
"try",
":",
"ftp",
".",
"listdir",
"(",
"remote_path",
")",
"except",
"IOError",
":",
"ftp",
".",
"mkdir",
"(",
"remote_path",
")",
"# Copy the files in the current directory to the remote path",
"for",
"filename",
"in",
"files",
":",
"ftp",
".",
"put",
"(",
"os",
".",
"path",
".",
"join",
"(",
"current_path",
",",
"filename",
")",
",",
"remote_path",
"+",
"filename",
")",
"# Copy the directory in the current directory to the remote path",
"for",
"directory",
"in",
"directories",
":",
"self",
".",
"__put_dir",
"(",
"ftp",
",",
"os",
".",
"path",
".",
"join",
"(",
"current_path",
",",
"directory",
")",
",",
"remote_path",
"+",
"directory",
")"
] | Helper function to perform copy operation to remote server
:param ftp: SFTP handle to perform copy operation(s)
:param local_path: Local path to copy to; can be file or directory
:param remote_path: Remote path to copy to (default: None - Copies file or directory to
home directory directory on the remote server) | [
"Helper",
"function",
"to",
"perform",
"copy",
"operation",
"to",
"remote",
"server"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L299-L326 | train |
riptano/ccm | ccmlib/remote.py | SSHClient.remove | def remove(self, remote_path):
"""
Delete a file or directory recursively on the remote server
:param remote_path: Remote path to remove
"""
# Based on the remote file stats; remove a file or directory recursively
ftp = self.ssh.open_sftp()
if stat.S_ISDIR(ftp.stat(remote_path).st_mode):
self.__remove_dir(ftp, remote_path)
else:
ftp.remove(remote_path)
ftp.close() | python | def remove(self, remote_path):
"""
Delete a file or directory recursively on the remote server
:param remote_path: Remote path to remove
"""
# Based on the remote file stats; remove a file or directory recursively
ftp = self.ssh.open_sftp()
if stat.S_ISDIR(ftp.stat(remote_path).st_mode):
self.__remove_dir(ftp, remote_path)
else:
ftp.remove(remote_path)
ftp.close() | [
"def",
"remove",
"(",
"self",
",",
"remote_path",
")",
":",
"# Based on the remote file stats; remove a file or directory recursively",
"ftp",
"=",
"self",
".",
"ssh",
".",
"open_sftp",
"(",
")",
"if",
"stat",
".",
"S_ISDIR",
"(",
"ftp",
".",
"stat",
"(",
"remote_path",
")",
".",
"st_mode",
")",
":",
"self",
".",
"__remove_dir",
"(",
"ftp",
",",
"remote_path",
")",
"else",
":",
"ftp",
".",
"remove",
"(",
"remote_path",
")",
"ftp",
".",
"close",
"(",
")"
] | Delete a file or directory recursively on the remote server
:param remote_path: Remote path to remove | [
"Delete",
"a",
"file",
"or",
"directory",
"recursively",
"on",
"the",
"remote",
"server"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L328-L340 | train |
riptano/ccm | ccmlib/remote.py | SSHClient.__remove_dir | def __remove_dir(self, ftp, remote_path):
"""
Helper function to perform delete operation on the remote server
:param ftp: SFTP handle to perform delete operation(s)
:param remote_path: Remote path to remove
"""
# Iterate over the remote path and perform remove operations
files = ftp.listdir(remote_path)
for filename in files:
# Attempt to remove the file (if exception then path is directory)
path = remote_path + self.separator + filename
try:
ftp.remove(path)
except IOError:
self.__remove_dir(ftp, path)
# Remove the original directory requested
ftp.rmdir(remote_path) | python | def __remove_dir(self, ftp, remote_path):
"""
Helper function to perform delete operation on the remote server
:param ftp: SFTP handle to perform delete operation(s)
:param remote_path: Remote path to remove
"""
# Iterate over the remote path and perform remove operations
files = ftp.listdir(remote_path)
for filename in files:
# Attempt to remove the file (if exception then path is directory)
path = remote_path + self.separator + filename
try:
ftp.remove(path)
except IOError:
self.__remove_dir(ftp, path)
# Remove the original directory requested
ftp.rmdir(remote_path) | [
"def",
"__remove_dir",
"(",
"self",
",",
"ftp",
",",
"remote_path",
")",
":",
"# Iterate over the remote path and perform remove operations",
"files",
"=",
"ftp",
".",
"listdir",
"(",
"remote_path",
")",
"for",
"filename",
"in",
"files",
":",
"# Attempt to remove the file (if exception then path is directory)",
"path",
"=",
"remote_path",
"+",
"self",
".",
"separator",
"+",
"filename",
"try",
":",
"ftp",
".",
"remove",
"(",
"path",
")",
"except",
"IOError",
":",
"self",
".",
"__remove_dir",
"(",
"ftp",
",",
"path",
")",
"# Remove the original directory requested",
"ftp",
".",
"rmdir",
"(",
"remote_path",
")"
] | Helper function to perform delete operation on the remote server
:param ftp: SFTP handle to perform delete operation(s)
:param remote_path: Remote path to remove | [
"Helper",
"function",
"to",
"perform",
"delete",
"operation",
"on",
"the",
"remote",
"server"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L342-L360 | train |
riptano/ccm | ccmlib/remote.py | RemoteOptionsParser.usage | def usage(self):
"""
Get the usage for the remote exectuion options
:return Usage for the remote execution options
"""
# Retrieve the text for just the arguments
usage = self.parser.format_help().split("optional arguments:")[1]
# Remove any blank lines and return
return "Remote Options:" + os.linesep + \
os.linesep.join([s for s in usage.splitlines() if s]) | python | def usage(self):
"""
Get the usage for the remote exectuion options
:return Usage for the remote execution options
"""
# Retrieve the text for just the arguments
usage = self.parser.format_help().split("optional arguments:")[1]
# Remove any blank lines and return
return "Remote Options:" + os.linesep + \
os.linesep.join([s for s in usage.splitlines() if s]) | [
"def",
"usage",
"(",
"self",
")",
":",
"# Retrieve the text for just the arguments",
"usage",
"=",
"self",
".",
"parser",
".",
"format_help",
"(",
")",
".",
"split",
"(",
"\"optional arguments:\"",
")",
"[",
"1",
"]",
"# Remove any blank lines and return",
"return",
"\"Remote Options:\"",
"+",
"os",
".",
"linesep",
"+",
"os",
".",
"linesep",
".",
"join",
"(",
"[",
"s",
"for",
"s",
"in",
"usage",
".",
"splitlines",
"(",
")",
"if",
"s",
"]",
")"
] | Get the usage for the remote exectuion options
:return Usage for the remote execution options | [
"Get",
"the",
"usage",
"for",
"the",
"remote",
"exectuion",
"options"
] | 275699f79d102b5039b79cc17fa6305dccf18412 | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L490-L501 | train |
mattupstate/flask-jwt | flask_jwt/__init__.py | jwt_required | def jwt_required(realm=None):
"""View decorator that requires a valid JWT token to be present in the request
:param realm: an optional realm
"""
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
return fn(*args, **kwargs)
return decorator
return wrapper | python | def jwt_required(realm=None):
"""View decorator that requires a valid JWT token to be present in the request
:param realm: an optional realm
"""
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
return fn(*args, **kwargs)
return decorator
return wrapper | [
"def",
"jwt_required",
"(",
"realm",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_jwt_required",
"(",
"realm",
"or",
"current_app",
".",
"config",
"[",
"'JWT_DEFAULT_REALM'",
"]",
")",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"decorator",
"return",
"wrapper"
] | View decorator that requires a valid JWT token to be present in the request
:param realm: an optional realm | [
"View",
"decorator",
"that",
"requires",
"a",
"valid",
"JWT",
"token",
"to",
"be",
"present",
"in",
"the",
"request"
] | c27084114e258863b82753fc574a362cd6c62fcd | https://github.com/mattupstate/flask-jwt/blob/c27084114e258863b82753fc574a362cd6c62fcd/flask_jwt/__init__.py#L168-L179 | train |
mattupstate/flask-jwt | flask_jwt/__init__.py | JWT.auth_request_handler | def auth_request_handler(self, callback):
"""Specifies the authentication response handler function.
:param callable callback: the auth request handler function
.. deprecated
"""
warnings.warn("This handler is deprecated. The recommended approach to have control over "
"the authentication resource is to disable the built-in resource by "
"setting JWT_AUTH_URL_RULE=None and registering your own authentication "
"resource directly on your application.", DeprecationWarning, stacklevel=2)
self.auth_request_callback = callback
return callback | python | def auth_request_handler(self, callback):
"""Specifies the authentication response handler function.
:param callable callback: the auth request handler function
.. deprecated
"""
warnings.warn("This handler is deprecated. The recommended approach to have control over "
"the authentication resource is to disable the built-in resource by "
"setting JWT_AUTH_URL_RULE=None and registering your own authentication "
"resource directly on your application.", DeprecationWarning, stacklevel=2)
self.auth_request_callback = callback
return callback | [
"def",
"auth_request_handler",
"(",
"self",
",",
"callback",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This handler is deprecated. The recommended approach to have control over \"",
"\"the authentication resource is to disable the built-in resource by \"",
"\"setting JWT_AUTH_URL_RULE=None and registering your own authentication \"",
"\"resource directly on your application.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"self",
".",
"auth_request_callback",
"=",
"callback",
"return",
"callback"
] | Specifies the authentication response handler function.
:param callable callback: the auth request handler function
.. deprecated | [
"Specifies",
"the",
"authentication",
"response",
"handler",
"function",
"."
] | c27084114e258863b82753fc574a362cd6c62fcd | https://github.com/mattupstate/flask-jwt/blob/c27084114e258863b82753fc574a362cd6c62fcd/flask_jwt/__init__.py#L294-L306 | train |
jwass/mplleaflet | mplleaflet/leaflet_renderer.py | LeafletRenderer._svg_path | def _svg_path(self, pathcodes, data):
"""
Return the SVG path's 'd' element.
"""
def gen_path_elements(pathcodes, data):
counts = {'M': 1, 'L': 1, 'C': 3, 'Z': 0}
it = iter(data)
for code in pathcodes:
yield code
for _ in range(counts[code]):
p = next(it)
yield str(p[0])
yield str(p[1])
return ' '.join(gen_path_elements(pathcodes, data)) | python | def _svg_path(self, pathcodes, data):
"""
Return the SVG path's 'd' element.
"""
def gen_path_elements(pathcodes, data):
counts = {'M': 1, 'L': 1, 'C': 3, 'Z': 0}
it = iter(data)
for code in pathcodes:
yield code
for _ in range(counts[code]):
p = next(it)
yield str(p[0])
yield str(p[1])
return ' '.join(gen_path_elements(pathcodes, data)) | [
"def",
"_svg_path",
"(",
"self",
",",
"pathcodes",
",",
"data",
")",
":",
"def",
"gen_path_elements",
"(",
"pathcodes",
",",
"data",
")",
":",
"counts",
"=",
"{",
"'M'",
":",
"1",
",",
"'L'",
":",
"1",
",",
"'C'",
":",
"3",
",",
"'Z'",
":",
"0",
"}",
"it",
"=",
"iter",
"(",
"data",
")",
"for",
"code",
"in",
"pathcodes",
":",
"yield",
"code",
"for",
"_",
"in",
"range",
"(",
"counts",
"[",
"code",
"]",
")",
":",
"p",
"=",
"next",
"(",
"it",
")",
"yield",
"str",
"(",
"p",
"[",
"0",
"]",
")",
"yield",
"str",
"(",
"p",
"[",
"1",
"]",
")",
"return",
"' '",
".",
"join",
"(",
"gen_path_elements",
"(",
"pathcodes",
",",
"data",
")",
")"
] | Return the SVG path's 'd' element. | [
"Return",
"the",
"SVG",
"path",
"s",
"d",
"element",
"."
] | a83d7b69c56d5507dd7c17f5be377d23a31e84ab | https://github.com/jwass/mplleaflet/blob/a83d7b69c56d5507dd7c17f5be377d23a31e84ab/mplleaflet/leaflet_renderer.py#L69-L84 | train |
jwass/mplleaflet | mplleaflet/_display.py | fig_to_html | def fig_to_html(fig=None, template='base.html', tiles=None, crs=None,
epsg=None, embed_links=False, float_precision=6):
"""
Convert a Matplotlib Figure to a Leaflet map
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
template : string, default 'base.html'
The Jinja2 template to use
tiles : string or tuple
The tiles argument is used to control the map tile source in the
Leaflet map. Several simple shortcuts exist: 'osm', 'mapquest open',
and 'mapbox bright' may be specified to use those tiles.
The argument may be a tuple of two elements. The first element is the
tile URL to use in the map's TileLayer, the second argument is the
attribution to display. See
http://leafletjs.com/reference.html#tilelayer for more information on
formatting the URL.
See also maptiles.mapbox() for specifying Mapbox tiles based on a
Mapbox map ID.
crs : dict, default assumes lon/lat
pyproj definition of the current figure. If None, then it is assumed
the plot is longitude, latitude in X, Y.
epsg : int, default 4326
The EPSG code of the current plot. This can be used in place of the
'crs' parameter.
embed_links : bool, default False
Whether external links (except tiles) shall be explicitly embedded in
the final html.
float_precision : int, default 6
The precision to be used for the floats in the embedded geojson.
Note: only one of 'crs' or 'epsg' may be specified. Both may be None, in
which case the plot is assumed to be longitude / latitude.
Returns
-------
String of html of the resulting webpage
"""
if tiles is None:
tiles = maptiles.osm
elif isinstance(tiles, six.string_types):
if tiles not in maptiles.tiles:
raise ValueError('Unknown tile source "{}"'.format(tiles))
else:
tiles = maptiles.tiles[tiles]
template = env.get_template(template)
if fig is None:
fig = plt.gcf()
dpi = fig.get_dpi()
renderer = LeafletRenderer(crs=crs, epsg=epsg)
exporter = Exporter(renderer)
exporter.run(fig)
attribution = _attribution + ' | ' + tiles[1]
mapid = str(uuid.uuid4()).replace('-', '')
FloatEncoder._formatter = ".{}f".format(float_precision)
gjdata = json.dumps(renderer.geojson(), cls=FloatEncoder)
params = {
'geojson': gjdata,
'width': fig.get_figwidth()*dpi,
'height': fig.get_figheight()*dpi,
'mapid': mapid,
'tile_url': tiles[0],
'attribution': attribution,
'links': [_leaflet_js,_leaflet_css],
'embed_links': embed_links,
}
html = template.render(params)
return html | python | def fig_to_html(fig=None, template='base.html', tiles=None, crs=None,
epsg=None, embed_links=False, float_precision=6):
"""
Convert a Matplotlib Figure to a Leaflet map
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
template : string, default 'base.html'
The Jinja2 template to use
tiles : string or tuple
The tiles argument is used to control the map tile source in the
Leaflet map. Several simple shortcuts exist: 'osm', 'mapquest open',
and 'mapbox bright' may be specified to use those tiles.
The argument may be a tuple of two elements. The first element is the
tile URL to use in the map's TileLayer, the second argument is the
attribution to display. See
http://leafletjs.com/reference.html#tilelayer for more information on
formatting the URL.
See also maptiles.mapbox() for specifying Mapbox tiles based on a
Mapbox map ID.
crs : dict, default assumes lon/lat
pyproj definition of the current figure. If None, then it is assumed
the plot is longitude, latitude in X, Y.
epsg : int, default 4326
The EPSG code of the current plot. This can be used in place of the
'crs' parameter.
embed_links : bool, default False
Whether external links (except tiles) shall be explicitly embedded in
the final html.
float_precision : int, default 6
The precision to be used for the floats in the embedded geojson.
Note: only one of 'crs' or 'epsg' may be specified. Both may be None, in
which case the plot is assumed to be longitude / latitude.
Returns
-------
String of html of the resulting webpage
"""
if tiles is None:
tiles = maptiles.osm
elif isinstance(tiles, six.string_types):
if tiles not in maptiles.tiles:
raise ValueError('Unknown tile source "{}"'.format(tiles))
else:
tiles = maptiles.tiles[tiles]
template = env.get_template(template)
if fig is None:
fig = plt.gcf()
dpi = fig.get_dpi()
renderer = LeafletRenderer(crs=crs, epsg=epsg)
exporter = Exporter(renderer)
exporter.run(fig)
attribution = _attribution + ' | ' + tiles[1]
mapid = str(uuid.uuid4()).replace('-', '')
FloatEncoder._formatter = ".{}f".format(float_precision)
gjdata = json.dumps(renderer.geojson(), cls=FloatEncoder)
params = {
'geojson': gjdata,
'width': fig.get_figwidth()*dpi,
'height': fig.get_figheight()*dpi,
'mapid': mapid,
'tile_url': tiles[0],
'attribution': attribution,
'links': [_leaflet_js,_leaflet_css],
'embed_links': embed_links,
}
html = template.render(params)
return html | [
"def",
"fig_to_html",
"(",
"fig",
"=",
"None",
",",
"template",
"=",
"'base.html'",
",",
"tiles",
"=",
"None",
",",
"crs",
"=",
"None",
",",
"epsg",
"=",
"None",
",",
"embed_links",
"=",
"False",
",",
"float_precision",
"=",
"6",
")",
":",
"if",
"tiles",
"is",
"None",
":",
"tiles",
"=",
"maptiles",
".",
"osm",
"elif",
"isinstance",
"(",
"tiles",
",",
"six",
".",
"string_types",
")",
":",
"if",
"tiles",
"not",
"in",
"maptiles",
".",
"tiles",
":",
"raise",
"ValueError",
"(",
"'Unknown tile source \"{}\"'",
".",
"format",
"(",
"tiles",
")",
")",
"else",
":",
"tiles",
"=",
"maptiles",
".",
"tiles",
"[",
"tiles",
"]",
"template",
"=",
"env",
".",
"get_template",
"(",
"template",
")",
"if",
"fig",
"is",
"None",
":",
"fig",
"=",
"plt",
".",
"gcf",
"(",
")",
"dpi",
"=",
"fig",
".",
"get_dpi",
"(",
")",
"renderer",
"=",
"LeafletRenderer",
"(",
"crs",
"=",
"crs",
",",
"epsg",
"=",
"epsg",
")",
"exporter",
"=",
"Exporter",
"(",
"renderer",
")",
"exporter",
".",
"run",
"(",
"fig",
")",
"attribution",
"=",
"_attribution",
"+",
"' | '",
"+",
"tiles",
"[",
"1",
"]",
"mapid",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"FloatEncoder",
".",
"_formatter",
"=",
"\".{}f\"",
".",
"format",
"(",
"float_precision",
")",
"gjdata",
"=",
"json",
".",
"dumps",
"(",
"renderer",
".",
"geojson",
"(",
")",
",",
"cls",
"=",
"FloatEncoder",
")",
"params",
"=",
"{",
"'geojson'",
":",
"gjdata",
",",
"'width'",
":",
"fig",
".",
"get_figwidth",
"(",
")",
"*",
"dpi",
",",
"'height'",
":",
"fig",
".",
"get_figheight",
"(",
")",
"*",
"dpi",
",",
"'mapid'",
":",
"mapid",
",",
"'tile_url'",
":",
"tiles",
"[",
"0",
"]",
",",
"'attribution'",
":",
"attribution",
",",
"'links'",
":",
"[",
"_leaflet_js",
",",
"_leaflet_css",
"]",
",",
"'embed_links'",
":",
"embed_links",
",",
"}",
"html",
"=",
"template",
".",
"render",
"(",
"params",
")",
"return",
"html"
] | Convert a Matplotlib Figure to a Leaflet map
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
template : string, default 'base.html'
The Jinja2 template to use
tiles : string or tuple
The tiles argument is used to control the map tile source in the
Leaflet map. Several simple shortcuts exist: 'osm', 'mapquest open',
and 'mapbox bright' may be specified to use those tiles.
The argument may be a tuple of two elements. The first element is the
tile URL to use in the map's TileLayer, the second argument is the
attribution to display. See
http://leafletjs.com/reference.html#tilelayer for more information on
formatting the URL.
See also maptiles.mapbox() for specifying Mapbox tiles based on a
Mapbox map ID.
crs : dict, default assumes lon/lat
pyproj definition of the current figure. If None, then it is assumed
the plot is longitude, latitude in X, Y.
epsg : int, default 4326
The EPSG code of the current plot. This can be used in place of the
'crs' parameter.
embed_links : bool, default False
Whether external links (except tiles) shall be explicitly embedded in
the final html.
float_precision : int, default 6
The precision to be used for the floats in the embedded geojson.
Note: only one of 'crs' or 'epsg' may be specified. Both may be None, in
which case the plot is assumed to be longitude / latitude.
Returns
-------
String of html of the resulting webpage | [
"Convert",
"a",
"Matplotlib",
"Figure",
"to",
"a",
"Leaflet",
"map"
] | a83d7b69c56d5507dd7c17f5be377d23a31e84ab | https://github.com/jwass/mplleaflet/blob/a83d7b69c56d5507dd7c17f5be377d23a31e84ab/mplleaflet/_display.py#L27-L107 | train |
jwass/mplleaflet | mplleaflet/_display.py | fig_to_geojson | def fig_to_geojson(fig=None, **kwargs):
"""
Returns a figure's GeoJSON representation as a dictionary
All arguments passed to fig_to_html()
Returns
-------
GeoJSON dictionary
"""
if fig is None:
fig = plt.gcf()
renderer = LeafletRenderer(**kwargs)
exporter = Exporter(renderer)
exporter.run(fig)
return renderer.geojson() | python | def fig_to_geojson(fig=None, **kwargs):
"""
Returns a figure's GeoJSON representation as a dictionary
All arguments passed to fig_to_html()
Returns
-------
GeoJSON dictionary
"""
if fig is None:
fig = plt.gcf()
renderer = LeafletRenderer(**kwargs)
exporter = Exporter(renderer)
exporter.run(fig)
return renderer.geojson() | [
"def",
"fig_to_geojson",
"(",
"fig",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"fig",
"is",
"None",
":",
"fig",
"=",
"plt",
".",
"gcf",
"(",
")",
"renderer",
"=",
"LeafletRenderer",
"(",
"*",
"*",
"kwargs",
")",
"exporter",
"=",
"Exporter",
"(",
"renderer",
")",
"exporter",
".",
"run",
"(",
"fig",
")",
"return",
"renderer",
".",
"geojson",
"(",
")"
] | Returns a figure's GeoJSON representation as a dictionary
All arguments passed to fig_to_html()
Returns
-------
GeoJSON dictionary | [
"Returns",
"a",
"figure",
"s",
"GeoJSON",
"representation",
"as",
"a",
"dictionary"
] | a83d7b69c56d5507dd7c17f5be377d23a31e84ab | https://github.com/jwass/mplleaflet/blob/a83d7b69c56d5507dd7c17f5be377d23a31e84ab/mplleaflet/_display.py#L110-L127 | train |
jwass/mplleaflet | mplleaflet/_display.py | display | def display(fig=None, closefig=True, **kwargs):
"""
Convert a Matplotlib Figure to a Leaflet map. Embed in IPython notebook.
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
closefig : boolean, default True
Close the current Figure
"""
from IPython.display import HTML
if fig is None:
fig = plt.gcf()
if closefig:
plt.close(fig)
html = fig_to_html(fig, **kwargs)
# We embed everything in an iframe.
iframe_html = '<iframe src="data:text/html;base64,{html}" width="{width}" height="{height}"></iframe>'\
.format(html = base64.b64encode(html.encode('utf8')).decode('utf8'),
width = '100%',
height= int(60.*fig.get_figheight()),
)
return HTML(iframe_html) | python | def display(fig=None, closefig=True, **kwargs):
"""
Convert a Matplotlib Figure to a Leaflet map. Embed in IPython notebook.
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
closefig : boolean, default True
Close the current Figure
"""
from IPython.display import HTML
if fig is None:
fig = plt.gcf()
if closefig:
plt.close(fig)
html = fig_to_html(fig, **kwargs)
# We embed everything in an iframe.
iframe_html = '<iframe src="data:text/html;base64,{html}" width="{width}" height="{height}"></iframe>'\
.format(html = base64.b64encode(html.encode('utf8')).decode('utf8'),
width = '100%',
height= int(60.*fig.get_figheight()),
)
return HTML(iframe_html) | [
"def",
"display",
"(",
"fig",
"=",
"None",
",",
"closefig",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"HTML",
"if",
"fig",
"is",
"None",
":",
"fig",
"=",
"plt",
".",
"gcf",
"(",
")",
"if",
"closefig",
":",
"plt",
".",
"close",
"(",
"fig",
")",
"html",
"=",
"fig_to_html",
"(",
"fig",
",",
"*",
"*",
"kwargs",
")",
"# We embed everything in an iframe.",
"iframe_html",
"=",
"'<iframe src=\"data:text/html;base64,{html}\" width=\"{width}\" height=\"{height}\"></iframe>'",
".",
"format",
"(",
"html",
"=",
"base64",
".",
"b64encode",
"(",
"html",
".",
"encode",
"(",
"'utf8'",
")",
")",
".",
"decode",
"(",
"'utf8'",
")",
",",
"width",
"=",
"'100%'",
",",
"height",
"=",
"int",
"(",
"60.",
"*",
"fig",
".",
"get_figheight",
"(",
")",
")",
",",
")",
"return",
"HTML",
"(",
"iframe_html",
")"
] | Convert a Matplotlib Figure to a Leaflet map. Embed in IPython notebook.
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
closefig : boolean, default True
Close the current Figure | [
"Convert",
"a",
"Matplotlib",
"Figure",
"to",
"a",
"Leaflet",
"map",
".",
"Embed",
"in",
"IPython",
"notebook",
"."
] | a83d7b69c56d5507dd7c17f5be377d23a31e84ab | https://github.com/jwass/mplleaflet/blob/a83d7b69c56d5507dd7c17f5be377d23a31e84ab/mplleaflet/_display.py#L140-L165 | train |
jwass/mplleaflet | mplleaflet/_display.py | show | def show(fig=None, path='_map.html', **kwargs):
"""
Convert a Matplotlib Figure to a Leaflet map. Open in a browser
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
path : string, default '_map.html'
Filename where output html will be saved
See fig_to_html() for description of keyword args.
"""
import webbrowser
fullpath = os.path.abspath(path)
with open(fullpath, 'w') as f:
save_html(fig, fileobj=f, **kwargs)
webbrowser.open('file://' + fullpath) | python | def show(fig=None, path='_map.html', **kwargs):
"""
Convert a Matplotlib Figure to a Leaflet map. Open in a browser
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
path : string, default '_map.html'
Filename where output html will be saved
See fig_to_html() for description of keyword args.
"""
import webbrowser
fullpath = os.path.abspath(path)
with open(fullpath, 'w') as f:
save_html(fig, fileobj=f, **kwargs)
webbrowser.open('file://' + fullpath) | [
"def",
"show",
"(",
"fig",
"=",
"None",
",",
"path",
"=",
"'_map.html'",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"webbrowser",
"fullpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"with",
"open",
"(",
"fullpath",
",",
"'w'",
")",
"as",
"f",
":",
"save_html",
"(",
"fig",
",",
"fileobj",
"=",
"f",
",",
"*",
"*",
"kwargs",
")",
"webbrowser",
".",
"open",
"(",
"'file://'",
"+",
"fullpath",
")"
] | Convert a Matplotlib Figure to a Leaflet map. Open in a browser
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
path : string, default '_map.html'
Filename where output html will be saved
See fig_to_html() for description of keyword args. | [
"Convert",
"a",
"Matplotlib",
"Figure",
"to",
"a",
"Leaflet",
"map",
".",
"Open",
"in",
"a",
"browser"
] | a83d7b69c56d5507dd7c17f5be377d23a31e84ab | https://github.com/jwass/mplleaflet/blob/a83d7b69c56d5507dd7c17f5be377d23a31e84ab/mplleaflet/_display.py#L167-L185 | train |
dmsimard/python-cachetclient | contrib/sensu-cachet.py | create_incident | def create_incident(**kwargs):
"""
Creates an incident
"""
incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)
if 'component_id' in kwargs:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
status=kwargs['status'],
component_id=kwargs['component_id'],
component_status=kwargs['component_status'])
else:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
status=kwargs['status']) | python | def create_incident(**kwargs):
"""
Creates an incident
"""
incidents = cachet.Incidents(endpoint=ENDPOINT, api_token=API_TOKEN)
if 'component_id' in kwargs:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
status=kwargs['status'],
component_id=kwargs['component_id'],
component_status=kwargs['component_status'])
else:
return incidents.post(name=kwargs['name'],
message=kwargs['message'],
status=kwargs['status']) | [
"def",
"create_incident",
"(",
"*",
"*",
"kwargs",
")",
":",
"incidents",
"=",
"cachet",
".",
"Incidents",
"(",
"endpoint",
"=",
"ENDPOINT",
",",
"api_token",
"=",
"API_TOKEN",
")",
"if",
"'component_id'",
"in",
"kwargs",
":",
"return",
"incidents",
".",
"post",
"(",
"name",
"=",
"kwargs",
"[",
"'name'",
"]",
",",
"message",
"=",
"kwargs",
"[",
"'message'",
"]",
",",
"status",
"=",
"kwargs",
"[",
"'status'",
"]",
",",
"component_id",
"=",
"kwargs",
"[",
"'component_id'",
"]",
",",
"component_status",
"=",
"kwargs",
"[",
"'component_status'",
"]",
")",
"else",
":",
"return",
"incidents",
".",
"post",
"(",
"name",
"=",
"kwargs",
"[",
"'name'",
"]",
",",
"message",
"=",
"kwargs",
"[",
"'message'",
"]",
",",
"status",
"=",
"kwargs",
"[",
"'status'",
"]",
")"
] | Creates an incident | [
"Creates",
"an",
"incident"
] | 31bbc6d17ba5de088846e1ffae259b6755e672a0 | https://github.com/dmsimard/python-cachetclient/blob/31bbc6d17ba5de088846e1ffae259b6755e672a0/contrib/sensu-cachet.py#L110-L124 | train |
dmsimard/python-cachetclient | contrib/sensu-cachet.py | incident_exists | def incident_exists(name, message, status):
"""
Check if an incident with these attributes already exists
"""
incidents = cachet.Incidents(endpoint=ENDPOINT)
all_incidents = json.loads(incidents.get())
for incident in all_incidents['data']:
if name == incident['name'] and \
status == incident['status'] and \
message.strip() == incident['message'].strip():
return True
return False | python | def incident_exists(name, message, status):
"""
Check if an incident with these attributes already exists
"""
incidents = cachet.Incidents(endpoint=ENDPOINT)
all_incidents = json.loads(incidents.get())
for incident in all_incidents['data']:
if name == incident['name'] and \
status == incident['status'] and \
message.strip() == incident['message'].strip():
return True
return False | [
"def",
"incident_exists",
"(",
"name",
",",
"message",
",",
"status",
")",
":",
"incidents",
"=",
"cachet",
".",
"Incidents",
"(",
"endpoint",
"=",
"ENDPOINT",
")",
"all_incidents",
"=",
"json",
".",
"loads",
"(",
"incidents",
".",
"get",
"(",
")",
")",
"for",
"incident",
"in",
"all_incidents",
"[",
"'data'",
"]",
":",
"if",
"name",
"==",
"incident",
"[",
"'name'",
"]",
"and",
"status",
"==",
"incident",
"[",
"'status'",
"]",
"and",
"message",
".",
"strip",
"(",
")",
"==",
"incident",
"[",
"'message'",
"]",
".",
"strip",
"(",
")",
":",
"return",
"True",
"return",
"False"
] | Check if an incident with these attributes already exists | [
"Check",
"if",
"an",
"incident",
"with",
"these",
"attributes",
"already",
"exists"
] | 31bbc6d17ba5de088846e1ffae259b6755e672a0 | https://github.com/dmsimard/python-cachetclient/blob/31bbc6d17ba5de088846e1ffae259b6755e672a0/contrib/sensu-cachet.py#L127-L138 | train |
dmsimard/python-cachetclient | contrib/sensu-cachet.py | get_component | def get_component(id):
"""
Gets a Cachet component by id
"""
components = cachet.Components(endpoint=ENDPOINT)
component = json.loads(components.get(id=id))
return component['data'] | python | def get_component(id):
"""
Gets a Cachet component by id
"""
components = cachet.Components(endpoint=ENDPOINT)
component = json.loads(components.get(id=id))
return component['data'] | [
"def",
"get_component",
"(",
"id",
")",
":",
"components",
"=",
"cachet",
".",
"Components",
"(",
"endpoint",
"=",
"ENDPOINT",
")",
"component",
"=",
"json",
".",
"loads",
"(",
"components",
".",
"get",
"(",
"id",
"=",
"id",
")",
")",
"return",
"component",
"[",
"'data'",
"]"
] | Gets a Cachet component by id | [
"Gets",
"a",
"Cachet",
"component",
"by",
"id"
] | 31bbc6d17ba5de088846e1ffae259b6755e672a0 | https://github.com/dmsimard/python-cachetclient/blob/31bbc6d17ba5de088846e1ffae259b6755e672a0/contrib/sensu-cachet.py#L141-L147 | train |
dmsimard/python-cachetclient | cachetclient/cachet.py | api_token_required | def api_token_required(f, *args, **kwargs):
"""
Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured.
"""
try:
if args[0].api_token is None:
raise AttributeError('Parameter api_token is required.')
except AttributeError:
raise AttributeError('Parameter api_token is required.')
return f(*args, **kwargs) | python | def api_token_required(f, *args, **kwargs):
"""
Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured.
"""
try:
if args[0].api_token is None:
raise AttributeError('Parameter api_token is required.')
except AttributeError:
raise AttributeError('Parameter api_token is required.')
return f(*args, **kwargs) | [
"def",
"api_token_required",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"args",
"[",
"0",
"]",
".",
"api_token",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"'Parameter api_token is required.'",
")",
"except",
"AttributeError",
":",
"raise",
"AttributeError",
"(",
"'Parameter api_token is required.'",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured. | [
"Decorator",
"helper",
"function",
"to",
"ensure",
"some",
"methods",
"aren",
"t",
"needlessly",
"called",
"without",
"an",
"api_token",
"configured",
"."
] | 31bbc6d17ba5de088846e1ffae259b6755e672a0 | https://github.com/dmsimard/python-cachetclient/blob/31bbc6d17ba5de088846e1ffae259b6755e672a0/cachetclient/cachet.py#L23-L34 | train |
robdmc/behold | behold/logger.py | Behold.is_true | def is_true(self, item=None):
"""
If you are filtering on object values, you need to pass that object here.
"""
if item:
values = [item]
else:
values = []
self._get_item_and_att_names(*values)
return self._passes_all | python | def is_true(self, item=None):
"""
If you are filtering on object values, you need to pass that object here.
"""
if item:
values = [item]
else:
values = []
self._get_item_and_att_names(*values)
return self._passes_all | [
"def",
"is_true",
"(",
"self",
",",
"item",
"=",
"None",
")",
":",
"if",
"item",
":",
"values",
"=",
"[",
"item",
"]",
"else",
":",
"values",
"=",
"[",
"]",
"self",
".",
"_get_item_and_att_names",
"(",
"*",
"values",
")",
"return",
"self",
".",
"_passes_all"
] | If you are filtering on object values, you need to pass that object here. | [
"If",
"you",
"are",
"filtering",
"on",
"object",
"values",
"you",
"need",
"to",
"pass",
"that",
"object",
"here",
"."
] | ac1b7707e2d7472a50d837dda78be1e23af8fce5 | https://github.com/robdmc/behold/blob/ac1b7707e2d7472a50d837dda78be1e23af8fce5/behold/logger.py#L519-L528 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | WebPage.new_from_url | def new_from_url(cls, url, verify=True):
"""
Constructs a new WebPage object for the URL,
using the `requests` module to fetch the HTML.
Parameters
----------
url : str
verify: bool
"""
response = requests.get(url, verify=verify, timeout=2.5)
return cls.new_from_response(response) | python | def new_from_url(cls, url, verify=True):
"""
Constructs a new WebPage object for the URL,
using the `requests` module to fetch the HTML.
Parameters
----------
url : str
verify: bool
"""
response = requests.get(url, verify=verify, timeout=2.5)
return cls.new_from_response(response) | [
"def",
"new_from_url",
"(",
"cls",
",",
"url",
",",
"verify",
"=",
"True",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"verify",
",",
"timeout",
"=",
"2.5",
")",
"return",
"cls",
".",
"new_from_response",
"(",
"response",
")"
] | Constructs a new WebPage object for the URL,
using the `requests` module to fetch the HTML.
Parameters
----------
url : str
verify: bool | [
"Constructs",
"a",
"new",
"WebPage",
"object",
"for",
"the",
"URL",
"using",
"the",
"requests",
"module",
"to",
"fetch",
"the",
"HTML",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L66-L78 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | WebPage.new_from_response | def new_from_response(cls, response):
"""
Constructs a new WebPage object for the response,
using the `BeautifulSoup` module to parse the HTML.
Parameters
----------
response : requests.Response object
"""
return cls(response.url, html=response.text, headers=response.headers) | python | def new_from_response(cls, response):
"""
Constructs a new WebPage object for the response,
using the `BeautifulSoup` module to parse the HTML.
Parameters
----------
response : requests.Response object
"""
return cls(response.url, html=response.text, headers=response.headers) | [
"def",
"new_from_response",
"(",
"cls",
",",
"response",
")",
":",
"return",
"cls",
"(",
"response",
".",
"url",
",",
"html",
"=",
"response",
".",
"text",
",",
"headers",
"=",
"response",
".",
"headers",
")"
] | Constructs a new WebPage object for the response,
using the `BeautifulSoup` module to parse the HTML.
Parameters
----------
response : requests.Response object | [
"Constructs",
"a",
"new",
"WebPage",
"object",
"for",
"the",
"response",
"using",
"the",
"BeautifulSoup",
"module",
"to",
"parse",
"the",
"HTML",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L81-L91 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | Wappalyzer._prepare_app | def _prepare_app(self, app):
"""
Normalize app data, preparing it for the detection phase.
"""
# Ensure these keys' values are lists
for key in ['url', 'html', 'script', 'implies']:
try:
value = app[key]
except KeyError:
app[key] = []
else:
if not isinstance(value, list):
app[key] = [value]
# Ensure these keys exist
for key in ['headers', 'meta']:
try:
value = app[key]
except KeyError:
app[key] = {}
# Ensure the 'meta' key is a dict
obj = app['meta']
if not isinstance(obj, dict):
app['meta'] = {'generator': obj}
# Ensure keys are lowercase
for key in ['headers', 'meta']:
obj = app[key]
app[key] = {k.lower(): v for k, v in obj.items()}
# Prepare regular expression patterns
for key in ['url', 'html', 'script']:
app[key] = [self._prepare_pattern(pattern) for pattern in app[key]]
for key in ['headers', 'meta']:
obj = app[key]
for name, pattern in obj.items():
obj[name] = self._prepare_pattern(obj[name]) | python | def _prepare_app(self, app):
"""
Normalize app data, preparing it for the detection phase.
"""
# Ensure these keys' values are lists
for key in ['url', 'html', 'script', 'implies']:
try:
value = app[key]
except KeyError:
app[key] = []
else:
if not isinstance(value, list):
app[key] = [value]
# Ensure these keys exist
for key in ['headers', 'meta']:
try:
value = app[key]
except KeyError:
app[key] = {}
# Ensure the 'meta' key is a dict
obj = app['meta']
if not isinstance(obj, dict):
app['meta'] = {'generator': obj}
# Ensure keys are lowercase
for key in ['headers', 'meta']:
obj = app[key]
app[key] = {k.lower(): v for k, v in obj.items()}
# Prepare regular expression patterns
for key in ['url', 'html', 'script']:
app[key] = [self._prepare_pattern(pattern) for pattern in app[key]]
for key in ['headers', 'meta']:
obj = app[key]
for name, pattern in obj.items():
obj[name] = self._prepare_pattern(obj[name]) | [
"def",
"_prepare_app",
"(",
"self",
",",
"app",
")",
":",
"# Ensure these keys' values are lists",
"for",
"key",
"in",
"[",
"'url'",
",",
"'html'",
",",
"'script'",
",",
"'implies'",
"]",
":",
"try",
":",
"value",
"=",
"app",
"[",
"key",
"]",
"except",
"KeyError",
":",
"app",
"[",
"key",
"]",
"=",
"[",
"]",
"else",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"app",
"[",
"key",
"]",
"=",
"[",
"value",
"]",
"# Ensure these keys exist",
"for",
"key",
"in",
"[",
"'headers'",
",",
"'meta'",
"]",
":",
"try",
":",
"value",
"=",
"app",
"[",
"key",
"]",
"except",
"KeyError",
":",
"app",
"[",
"key",
"]",
"=",
"{",
"}",
"# Ensure the 'meta' key is a dict",
"obj",
"=",
"app",
"[",
"'meta'",
"]",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"app",
"[",
"'meta'",
"]",
"=",
"{",
"'generator'",
":",
"obj",
"}",
"# Ensure keys are lowercase",
"for",
"key",
"in",
"[",
"'headers'",
",",
"'meta'",
"]",
":",
"obj",
"=",
"app",
"[",
"key",
"]",
"app",
"[",
"key",
"]",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
"}",
"# Prepare regular expression patterns",
"for",
"key",
"in",
"[",
"'url'",
",",
"'html'",
",",
"'script'",
"]",
":",
"app",
"[",
"key",
"]",
"=",
"[",
"self",
".",
"_prepare_pattern",
"(",
"pattern",
")",
"for",
"pattern",
"in",
"app",
"[",
"key",
"]",
"]",
"for",
"key",
"in",
"[",
"'headers'",
",",
"'meta'",
"]",
":",
"obj",
"=",
"app",
"[",
"key",
"]",
"for",
"name",
",",
"pattern",
"in",
"obj",
".",
"items",
"(",
")",
":",
"obj",
"[",
"name",
"]",
"=",
"self",
".",
"_prepare_pattern",
"(",
"obj",
"[",
"name",
"]",
")"
] | Normalize app data, preparing it for the detection phase. | [
"Normalize",
"app",
"data",
"preparing",
"it",
"for",
"the",
"detection",
"phase",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L131-L170 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | Wappalyzer._has_app | def _has_app(self, app, webpage):
"""
Determine whether the web page matches the app signature.
"""
# Search the easiest things first and save the full-text search of the
# HTML for last
for regex in app['url']:
if regex.search(webpage.url):
return True
for name, regex in app['headers'].items():
if name in webpage.headers:
content = webpage.headers[name]
if regex.search(content):
return True
for regex in app['script']:
for script in webpage.scripts:
if regex.search(script):
return True
for name, regex in app['meta'].items():
if name in webpage.meta:
content = webpage.meta[name]
if regex.search(content):
return True
for regex in app['html']:
if regex.search(webpage.html):
return True | python | def _has_app(self, app, webpage):
"""
Determine whether the web page matches the app signature.
"""
# Search the easiest things first and save the full-text search of the
# HTML for last
for regex in app['url']:
if regex.search(webpage.url):
return True
for name, regex in app['headers'].items():
if name in webpage.headers:
content = webpage.headers[name]
if regex.search(content):
return True
for regex in app['script']:
for script in webpage.scripts:
if regex.search(script):
return True
for name, regex in app['meta'].items():
if name in webpage.meta:
content = webpage.meta[name]
if regex.search(content):
return True
for regex in app['html']:
if regex.search(webpage.html):
return True | [
"def",
"_has_app",
"(",
"self",
",",
"app",
",",
"webpage",
")",
":",
"# Search the easiest things first and save the full-text search of the",
"# HTML for last",
"for",
"regex",
"in",
"app",
"[",
"'url'",
"]",
":",
"if",
"regex",
".",
"search",
"(",
"webpage",
".",
"url",
")",
":",
"return",
"True",
"for",
"name",
",",
"regex",
"in",
"app",
"[",
"'headers'",
"]",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"webpage",
".",
"headers",
":",
"content",
"=",
"webpage",
".",
"headers",
"[",
"name",
"]",
"if",
"regex",
".",
"search",
"(",
"content",
")",
":",
"return",
"True",
"for",
"regex",
"in",
"app",
"[",
"'script'",
"]",
":",
"for",
"script",
"in",
"webpage",
".",
"scripts",
":",
"if",
"regex",
".",
"search",
"(",
"script",
")",
":",
"return",
"True",
"for",
"name",
",",
"regex",
"in",
"app",
"[",
"'meta'",
"]",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"webpage",
".",
"meta",
":",
"content",
"=",
"webpage",
".",
"meta",
"[",
"name",
"]",
"if",
"regex",
".",
"search",
"(",
"content",
")",
":",
"return",
"True",
"for",
"regex",
"in",
"app",
"[",
"'html'",
"]",
":",
"if",
"regex",
".",
"search",
"(",
"webpage",
".",
"html",
")",
":",
"return",
"True"
] | Determine whether the web page matches the app signature. | [
"Determine",
"whether",
"the",
"web",
"page",
"matches",
"the",
"app",
"signature",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L189-L219 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | Wappalyzer._get_implied_apps | def _get_implied_apps(self, detected_apps):
"""
Get the set of apps implied by `detected_apps`.
"""
def __get_implied_apps(apps):
_implied_apps = set()
for app in apps:
try:
_implied_apps.update(set(self.apps[app]['implies']))
except KeyError:
pass
return _implied_apps
implied_apps = __get_implied_apps(detected_apps)
all_implied_apps = set()
# Descend recursively until we've found all implied apps
while not all_implied_apps.issuperset(implied_apps):
all_implied_apps.update(implied_apps)
implied_apps = __get_implied_apps(all_implied_apps)
return all_implied_apps | python | def _get_implied_apps(self, detected_apps):
"""
Get the set of apps implied by `detected_apps`.
"""
def __get_implied_apps(apps):
_implied_apps = set()
for app in apps:
try:
_implied_apps.update(set(self.apps[app]['implies']))
except KeyError:
pass
return _implied_apps
implied_apps = __get_implied_apps(detected_apps)
all_implied_apps = set()
# Descend recursively until we've found all implied apps
while not all_implied_apps.issuperset(implied_apps):
all_implied_apps.update(implied_apps)
implied_apps = __get_implied_apps(all_implied_apps)
return all_implied_apps | [
"def",
"_get_implied_apps",
"(",
"self",
",",
"detected_apps",
")",
":",
"def",
"__get_implied_apps",
"(",
"apps",
")",
":",
"_implied_apps",
"=",
"set",
"(",
")",
"for",
"app",
"in",
"apps",
":",
"try",
":",
"_implied_apps",
".",
"update",
"(",
"set",
"(",
"self",
".",
"apps",
"[",
"app",
"]",
"[",
"'implies'",
"]",
")",
")",
"except",
"KeyError",
":",
"pass",
"return",
"_implied_apps",
"implied_apps",
"=",
"__get_implied_apps",
"(",
"detected_apps",
")",
"all_implied_apps",
"=",
"set",
"(",
")",
"# Descend recursively until we've found all implied apps",
"while",
"not",
"all_implied_apps",
".",
"issuperset",
"(",
"implied_apps",
")",
":",
"all_implied_apps",
".",
"update",
"(",
"implied_apps",
")",
"implied_apps",
"=",
"__get_implied_apps",
"(",
"all_implied_apps",
")",
"return",
"all_implied_apps"
] | Get the set of apps implied by `detected_apps`. | [
"Get",
"the",
"set",
"of",
"apps",
"implied",
"by",
"detected_apps",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L221-L242 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | Wappalyzer.get_categories | def get_categories(self, app_name):
"""
Returns a list of the categories for an app name.
"""
cat_nums = self.apps.get(app_name, {}).get("cats", [])
cat_names = [self.categories.get("%s" % cat_num, "")
for cat_num in cat_nums]
return cat_names | python | def get_categories(self, app_name):
"""
Returns a list of the categories for an app name.
"""
cat_nums = self.apps.get(app_name, {}).get("cats", [])
cat_names = [self.categories.get("%s" % cat_num, "")
for cat_num in cat_nums]
return cat_names | [
"def",
"get_categories",
"(",
"self",
",",
"app_name",
")",
":",
"cat_nums",
"=",
"self",
".",
"apps",
".",
"get",
"(",
"app_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"cats\"",
",",
"[",
"]",
")",
"cat_names",
"=",
"[",
"self",
".",
"categories",
".",
"get",
"(",
"\"%s\"",
"%",
"cat_num",
",",
"\"\"",
")",
"for",
"cat_num",
"in",
"cat_nums",
"]",
"return",
"cat_names"
] | Returns a list of the categories for an app name. | [
"Returns",
"a",
"list",
"of",
"the",
"categories",
"for",
"an",
"app",
"name",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L244-L252 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | Wappalyzer.analyze | def analyze(self, webpage):
"""
Return a list of applications that can be detected on the web page.
"""
detected_apps = set()
for app_name, app in self.apps.items():
if self._has_app(app, webpage):
detected_apps.add(app_name)
detected_apps |= self._get_implied_apps(detected_apps)
return detected_apps | python | def analyze(self, webpage):
"""
Return a list of applications that can be detected on the web page.
"""
detected_apps = set()
for app_name, app in self.apps.items():
if self._has_app(app, webpage):
detected_apps.add(app_name)
detected_apps |= self._get_implied_apps(detected_apps)
return detected_apps | [
"def",
"analyze",
"(",
"self",
",",
"webpage",
")",
":",
"detected_apps",
"=",
"set",
"(",
")",
"for",
"app_name",
",",
"app",
"in",
"self",
".",
"apps",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"_has_app",
"(",
"app",
",",
"webpage",
")",
":",
"detected_apps",
".",
"add",
"(",
"app_name",
")",
"detected_apps",
"|=",
"self",
".",
"_get_implied_apps",
"(",
"detected_apps",
")",
"return",
"detected_apps"
] | Return a list of applications that can be detected on the web page. | [
"Return",
"a",
"list",
"of",
"applications",
"that",
"can",
"be",
"detected",
"on",
"the",
"web",
"page",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L254-L266 | train |
chorsley/python-Wappalyzer | Wappalyzer/Wappalyzer.py | Wappalyzer.analyze_with_categories | def analyze_with_categories(self, webpage):
"""
Return a list of applications and categories that can be detected on the web page.
"""
detected_apps = self.analyze(webpage)
categorised_apps = {}
for app_name in detected_apps:
cat_names = self.get_categories(app_name)
categorised_apps[app_name] = {"categories": cat_names}
return categorised_apps | python | def analyze_with_categories(self, webpage):
"""
Return a list of applications and categories that can be detected on the web page.
"""
detected_apps = self.analyze(webpage)
categorised_apps = {}
for app_name in detected_apps:
cat_names = self.get_categories(app_name)
categorised_apps[app_name] = {"categories": cat_names}
return categorised_apps | [
"def",
"analyze_with_categories",
"(",
"self",
",",
"webpage",
")",
":",
"detected_apps",
"=",
"self",
".",
"analyze",
"(",
"webpage",
")",
"categorised_apps",
"=",
"{",
"}",
"for",
"app_name",
"in",
"detected_apps",
":",
"cat_names",
"=",
"self",
".",
"get_categories",
"(",
"app_name",
")",
"categorised_apps",
"[",
"app_name",
"]",
"=",
"{",
"\"categories\"",
":",
"cat_names",
"}",
"return",
"categorised_apps"
] | Return a list of applications and categories that can be detected on the web page. | [
"Return",
"a",
"list",
"of",
"applications",
"and",
"categories",
"that",
"can",
"be",
"detected",
"on",
"the",
"web",
"page",
"."
] | b785e29f12c8032c54279cfa9ce01ead702a386c | https://github.com/chorsley/python-Wappalyzer/blob/b785e29f12c8032c54279cfa9ce01ead702a386c/Wappalyzer/Wappalyzer.py#L268-L279 | train |
user-cont/conu | conu/utils/filesystem.py | Directory.clean | def clean(self):
"""
remove the directory we operated on
:return: None
"""
if self._initialized:
logger.info("brace yourselves, removing %r", self.path)
shutil.rmtree(self.path) | python | def clean(self):
"""
remove the directory we operated on
:return: None
"""
if self._initialized:
logger.info("brace yourselves, removing %r", self.path)
shutil.rmtree(self.path) | [
"def",
"clean",
"(",
"self",
")",
":",
"if",
"self",
".",
"_initialized",
":",
"logger",
".",
"info",
"(",
"\"brace yourselves, removing %r\"",
",",
"self",
".",
"path",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"path",
")"
] | remove the directory we operated on
:return: None | [
"remove",
"the",
"directory",
"we",
"operated",
"on"
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/filesystem.py#L121-L129 | train |
user-cont/conu | conu/utils/filesystem.py | Directory.initialize | def initialize(self):
"""
create the directory if needed and configure it
:return: None
"""
if not self._initialized:
logger.info("initializing %r", self)
if not os.path.exists(self.path):
if self.mode is not None:
os.makedirs(self.path, mode=self.mode)
else:
os.makedirs(self.path)
self._set_mode()
self._add_facl_rules()
self._set_selinux_context()
self._set_ownership()
self._initialized = True
logger.info("initialized")
return
logger.info("%r was already initialized", self) | python | def initialize(self):
"""
create the directory if needed and configure it
:return: None
"""
if not self._initialized:
logger.info("initializing %r", self)
if not os.path.exists(self.path):
if self.mode is not None:
os.makedirs(self.path, mode=self.mode)
else:
os.makedirs(self.path)
self._set_mode()
self._add_facl_rules()
self._set_selinux_context()
self._set_ownership()
self._initialized = True
logger.info("initialized")
return
logger.info("%r was already initialized", self) | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_initialized",
":",
"logger",
".",
"info",
"(",
"\"initializing %r\"",
",",
"self",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"if",
"self",
".",
"mode",
"is",
"not",
"None",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"path",
",",
"mode",
"=",
"self",
".",
"mode",
")",
"else",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"path",
")",
"self",
".",
"_set_mode",
"(",
")",
"self",
".",
"_add_facl_rules",
"(",
")",
"self",
".",
"_set_selinux_context",
"(",
")",
"self",
".",
"_set_ownership",
"(",
")",
"self",
".",
"_initialized",
"=",
"True",
"logger",
".",
"info",
"(",
"\"initialized\"",
")",
"return",
"logger",
".",
"info",
"(",
"\"%r was already initialized\"",
",",
"self",
")"
] | create the directory if needed and configure it
:return: None | [
"create",
"the",
"directory",
"if",
"needed",
"and",
"configure",
"it"
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/filesystem.py#L131-L151 | train |
user-cont/conu | conu/utils/filesystem.py | Directory._set_selinux_context | def _set_selinux_context(self):
"""
Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException
if the command is not present on the system.
:return: None
"""
chcon_command_exists()
# FIXME: do this using python API if possible
if self.selinux_context:
logger.debug("setting SELinux context of %s to %s", self.path, self.selinux_context)
run_cmd(["chcon", self.selinux_context, self.path])
if any([self.selinux_user, self.selinux_role, self.selinux_type, self.selinux_range]):
logger.debug("setting SELinux fields of %s", self.path, self.selinux_context)
# chcon [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...
pairs = [("-u", self.selinux_user), ("-r", self.selinux_role),
("-l", self.selinux_range), ("-t", self.selinux_type)]
c = ["chcon"]
for p in pairs:
if p[1]:
c += p
c += [self.path]
run_cmd(c) | python | def _set_selinux_context(self):
"""
Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException
if the command is not present on the system.
:return: None
"""
chcon_command_exists()
# FIXME: do this using python API if possible
if self.selinux_context:
logger.debug("setting SELinux context of %s to %s", self.path, self.selinux_context)
run_cmd(["chcon", self.selinux_context, self.path])
if any([self.selinux_user, self.selinux_role, self.selinux_type, self.selinux_range]):
logger.debug("setting SELinux fields of %s", self.path, self.selinux_context)
# chcon [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...
pairs = [("-u", self.selinux_user), ("-r", self.selinux_role),
("-l", self.selinux_range), ("-t", self.selinux_type)]
c = ["chcon"]
for p in pairs:
if p[1]:
c += p
c += [self.path]
run_cmd(c) | [
"def",
"_set_selinux_context",
"(",
"self",
")",
":",
"chcon_command_exists",
"(",
")",
"# FIXME: do this using python API if possible",
"if",
"self",
".",
"selinux_context",
":",
"logger",
".",
"debug",
"(",
"\"setting SELinux context of %s to %s\"",
",",
"self",
".",
"path",
",",
"self",
".",
"selinux_context",
")",
"run_cmd",
"(",
"[",
"\"chcon\"",
",",
"self",
".",
"selinux_context",
",",
"self",
".",
"path",
"]",
")",
"if",
"any",
"(",
"[",
"self",
".",
"selinux_user",
",",
"self",
".",
"selinux_role",
",",
"self",
".",
"selinux_type",
",",
"self",
".",
"selinux_range",
"]",
")",
":",
"logger",
".",
"debug",
"(",
"\"setting SELinux fields of %s\"",
",",
"self",
".",
"path",
",",
"self",
".",
"selinux_context",
")",
"# chcon [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...",
"pairs",
"=",
"[",
"(",
"\"-u\"",
",",
"self",
".",
"selinux_user",
")",
",",
"(",
"\"-r\"",
",",
"self",
".",
"selinux_role",
")",
",",
"(",
"\"-l\"",
",",
"self",
".",
"selinux_range",
")",
",",
"(",
"\"-t\"",
",",
"self",
".",
"selinux_type",
")",
"]",
"c",
"=",
"[",
"\"chcon\"",
"]",
"for",
"p",
"in",
"pairs",
":",
"if",
"p",
"[",
"1",
"]",
":",
"c",
"+=",
"p",
"c",
"+=",
"[",
"self",
".",
"path",
"]",
"run_cmd",
"(",
"c",
")"
] | Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException
if the command is not present on the system.
:return: None | [
"Set",
"SELinux",
"context",
"or",
"fields",
"using",
"chcon",
"program",
".",
"Raises",
"CommandDoesNotExistException",
"if",
"the",
"command",
"is",
"not",
"present",
"on",
"the",
"system",
"."
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/filesystem.py#L153-L175 | train |
user-cont/conu | conu/utils/filesystem.py | Directory._set_mode | def _set_mode(self):
"""
set permission bits if needed using python API os.chmod
:return: None
"""
if self.mode is not None:
logger.debug("changing permission bits of %s to %s", self.path, oct(self.mode))
os.chmod(self.path, self.mode) | python | def _set_mode(self):
"""
set permission bits if needed using python API os.chmod
:return: None
"""
if self.mode is not None:
logger.debug("changing permission bits of %s to %s", self.path, oct(self.mode))
os.chmod(self.path, self.mode) | [
"def",
"_set_mode",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"is",
"not",
"None",
":",
"logger",
".",
"debug",
"(",
"\"changing permission bits of %s to %s\"",
",",
"self",
".",
"path",
",",
"oct",
"(",
"self",
".",
"mode",
")",
")",
"os",
".",
"chmod",
"(",
"self",
".",
"path",
",",
"self",
".",
"mode",
")"
] | set permission bits if needed using python API os.chmod
:return: None | [
"set",
"permission",
"bits",
"if",
"needed",
"using",
"python",
"API",
"os",
".",
"chmod"
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/filesystem.py#L192-L200 | train |
user-cont/conu | conu/utils/filesystem.py | Directory._add_facl_rules | def _add_facl_rules(self):
"""
Apply ACL rules on the directory using setfacl program. Raises CommandDoesNotExistException
if the command is not present on the system.
:return: None
"""
setfacl_command_exists()
# we are not using pylibacl b/c it's only for python 2
if self.facl_rules:
logger.debug("adding ACLs %s to %s", self.facl_rules, self.path)
r = ",".join(self.facl_rules)
run_cmd(["setfacl", "-m", r, self.path]) | python | def _add_facl_rules(self):
"""
Apply ACL rules on the directory using setfacl program. Raises CommandDoesNotExistException
if the command is not present on the system.
:return: None
"""
setfacl_command_exists()
# we are not using pylibacl b/c it's only for python 2
if self.facl_rules:
logger.debug("adding ACLs %s to %s", self.facl_rules, self.path)
r = ",".join(self.facl_rules)
run_cmd(["setfacl", "-m", r, self.path]) | [
"def",
"_add_facl_rules",
"(",
"self",
")",
":",
"setfacl_command_exists",
"(",
")",
"# we are not using pylibacl b/c it's only for python 2",
"if",
"self",
".",
"facl_rules",
":",
"logger",
".",
"debug",
"(",
"\"adding ACLs %s to %s\"",
",",
"self",
".",
"facl_rules",
",",
"self",
".",
"path",
")",
"r",
"=",
"\",\"",
".",
"join",
"(",
"self",
".",
"facl_rules",
")",
"run_cmd",
"(",
"[",
"\"setfacl\"",
",",
"\"-m\"",
",",
"r",
",",
"self",
".",
"path",
"]",
")"
] | Apply ACL rules on the directory using setfacl program. Raises CommandDoesNotExistException
if the command is not present on the system.
:return: None | [
"Apply",
"ACL",
"rules",
"on",
"the",
"directory",
"using",
"setfacl",
"program",
".",
"Raises",
"CommandDoesNotExistException",
"if",
"the",
"command",
"is",
"not",
"present",
"on",
"the",
"system",
"."
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/filesystem.py#L202-L214 | train |
user-cont/conu | conu/backend/podman/image.py | PodmanImage.get_volume_options | def get_volume_options(volumes):
"""
Generates volume options to run methods.
:param volumes: tuple or list of tuples in form target x source,target x source,target,mode.
:return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...]
"""
if not isinstance(volumes, list):
volumes = [volumes]
volumes = [Volume.create_from_tuple(v) for v in volumes]
result = []
for v in volumes:
result += ["-v", str(v)]
return result | python | def get_volume_options(volumes):
"""
Generates volume options to run methods.
:param volumes: tuple or list of tuples in form target x source,target x source,target,mode.
:return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...]
"""
if not isinstance(volumes, list):
volumes = [volumes]
volumes = [Volume.create_from_tuple(v) for v in volumes]
result = []
for v in volumes:
result += ["-v", str(v)]
return result | [
"def",
"get_volume_options",
"(",
"volumes",
")",
":",
"if",
"not",
"isinstance",
"(",
"volumes",
",",
"list",
")",
":",
"volumes",
"=",
"[",
"volumes",
"]",
"volumes",
"=",
"[",
"Volume",
".",
"create_from_tuple",
"(",
"v",
")",
"for",
"v",
"in",
"volumes",
"]",
"result",
"=",
"[",
"]",
"for",
"v",
"in",
"volumes",
":",
"result",
"+=",
"[",
"\"-v\"",
",",
"str",
"(",
"v",
")",
"]",
"return",
"result"
] | Generates volume options to run methods.
:param volumes: tuple or list of tuples in form target x source,target x source,target,mode.
:return: list of the form ["-v", "/source:/target", "-v", "/other/source:/destination:z", ...] | [
"Generates",
"volume",
"options",
"to",
"run",
"methods",
"."
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/image.py#L367-L380 | train |
user-cont/conu | conu/backend/podman/image.py | PodmanImage.layers | def layers(self, rev=True):
"""
Get list of PodmanImage for every layer in image
:param rev: get layers rev
:return: list of :class:`conu.PodmanImage`
"""
image_layers = [
PodmanImage(None, identifier=x, pull_policy=PodmanImagePullPolicy.NEVER)
for x in self.get_layer_ids()
]
if not rev:
image_layers.reverse()
return image_layers | python | def layers(self, rev=True):
"""
Get list of PodmanImage for every layer in image
:param rev: get layers rev
:return: list of :class:`conu.PodmanImage`
"""
image_layers = [
PodmanImage(None, identifier=x, pull_policy=PodmanImagePullPolicy.NEVER)
for x in self.get_layer_ids()
]
if not rev:
image_layers.reverse()
return image_layers | [
"def",
"layers",
"(",
"self",
",",
"rev",
"=",
"True",
")",
":",
"image_layers",
"=",
"[",
"PodmanImage",
"(",
"None",
",",
"identifier",
"=",
"x",
",",
"pull_policy",
"=",
"PodmanImagePullPolicy",
".",
"NEVER",
")",
"for",
"x",
"in",
"self",
".",
"get_layer_ids",
"(",
")",
"]",
"if",
"not",
"rev",
":",
"image_layers",
".",
"reverse",
"(",
")",
"return",
"image_layers"
] | Get list of PodmanImage for every layer in image
:param rev: get layers rev
:return: list of :class:`conu.PodmanImage` | [
"Get",
"list",
"of",
"PodmanImage",
"for",
"every",
"layer",
"in",
"image"
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/image.py#L395-L408 | train |
user-cont/conu | conu/backend/podman/image.py | PodmanImage.get_metadata | def get_metadata(self):
"""
Provide metadata about this image.
:return: ImageMetadata, Image metadata instance
"""
if self._metadata is None:
self._metadata = ImageMetadata()
inspect_to_metadata(self._metadata, self.inspect(refresh=True))
return self._metadata | python | def get_metadata(self):
"""
Provide metadata about this image.
:return: ImageMetadata, Image metadata instance
"""
if self._metadata is None:
self._metadata = ImageMetadata()
inspect_to_metadata(self._metadata, self.inspect(refresh=True))
return self._metadata | [
"def",
"get_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"self",
".",
"_metadata",
"=",
"ImageMetadata",
"(",
")",
"inspect_to_metadata",
"(",
"self",
".",
"_metadata",
",",
"self",
".",
"inspect",
"(",
"refresh",
"=",
"True",
")",
")",
"return",
"self",
".",
"_metadata"
] | Provide metadata about this image.
:return: ImageMetadata, Image metadata instance | [
"Provide",
"metadata",
"about",
"this",
"image",
"."
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/image.py#L416-L425 | train |
user-cont/conu | conu/backend/podman/container.py | PodmanContainer.is_running | def is_running(self):
"""
returns True if the container is running
:return: bool
"""
try:
return graceful_get(self.inspect(refresh=True), "State", "Running")
except subprocess.CalledProcessError:
return False | python | def is_running(self):
"""
returns True if the container is running
:return: bool
"""
try:
return graceful_get(self.inspect(refresh=True), "State", "Running")
except subprocess.CalledProcessError:
return False | [
"def",
"is_running",
"(",
"self",
")",
":",
"try",
":",
"return",
"graceful_get",
"(",
"self",
".",
"inspect",
"(",
"refresh",
"=",
"True",
")",
",",
"\"State\"",
",",
"\"Running\"",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"return",
"False"
] | returns True if the container is running
:return: bool | [
"returns",
"True",
"if",
"the",
"container",
"is",
"running"
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/container.py#L125-L134 | train |
user-cont/conu | conu/backend/podman/container.py | PodmanContainer.is_port_open | def is_port_open(self, port, timeout=2):
"""
check if given port is open and receiving connections on container ip_address
:param port: int, container port
:param timeout: int, how many seconds to wait for connection; defaults to 2
:return: True if the connection has been established inside timeout, False otherwise
"""
addresses = self.get_IPv4s()
if not addresses:
return False
return check_port(port, host=addresses[0], timeout=timeout) | python | def is_port_open(self, port, timeout=2):
"""
check if given port is open and receiving connections on container ip_address
:param port: int, container port
:param timeout: int, how many seconds to wait for connection; defaults to 2
:return: True if the connection has been established inside timeout, False otherwise
"""
addresses = self.get_IPv4s()
if not addresses:
return False
return check_port(port, host=addresses[0], timeout=timeout) | [
"def",
"is_port_open",
"(",
"self",
",",
"port",
",",
"timeout",
"=",
"2",
")",
":",
"addresses",
"=",
"self",
".",
"get_IPv4s",
"(",
")",
"if",
"not",
"addresses",
":",
"return",
"False",
"return",
"check_port",
"(",
"port",
",",
"host",
"=",
"addresses",
"[",
"0",
"]",
",",
"timeout",
"=",
"timeout",
")"
] | check if given port is open and receiving connections on container ip_address
:param port: int, container port
:param timeout: int, how many seconds to wait for connection; defaults to 2
:return: True if the connection has been established inside timeout, False otherwise | [
"check",
"if",
"given",
"port",
"is",
"open",
"and",
"receiving",
"connections",
"on",
"container",
"ip_address"
] | 08caae7bb6bdd265b55bb106c3da6a7946a5a352 | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/container.py#L173-L184 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.