id
int32 0
252k
| 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
245,300
|
kallimachos/chios
|
chios/bolditalic/__init__.py
|
css
|
def css(app, env):
"""
Add bolditalic CSS.
:param app: Sphinx application context.
:param env: Sphinx environment context.
"""
srcdir = os.path.abspath(os.path.dirname(__file__))
cssfile = 'bolditalic.css'
csspath = os.path.join(srcdir, cssfile)
buildpath = os.path.join(app.outdir, '_static')
try:
os.makedirs(buildpath)
except OSError:
if not os.path.isdir(buildpath):
raise
copy(csspath, buildpath)
app.add_stylesheet(cssfile)
return
|
python
|
def css(app, env):
"""
Add bolditalic CSS.
:param app: Sphinx application context.
:param env: Sphinx environment context.
"""
srcdir = os.path.abspath(os.path.dirname(__file__))
cssfile = 'bolditalic.css'
csspath = os.path.join(srcdir, cssfile)
buildpath = os.path.join(app.outdir, '_static')
try:
os.makedirs(buildpath)
except OSError:
if not os.path.isdir(buildpath):
raise
copy(csspath, buildpath)
app.add_stylesheet(cssfile)
return
|
[
"def",
"css",
"(",
"app",
",",
"env",
")",
":",
"srcdir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"cssfile",
"=",
"'bolditalic.css'",
"csspath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"srcdir",
",",
"cssfile",
")",
"buildpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app",
".",
"outdir",
",",
"'_static'",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"buildpath",
")",
"except",
"OSError",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"buildpath",
")",
":",
"raise",
"copy",
"(",
"csspath",
",",
"buildpath",
")",
"app",
".",
"add_stylesheet",
"(",
"cssfile",
")",
"return"
] |
Add bolditalic CSS.
:param app: Sphinx application context.
:param env: Sphinx environment context.
|
[
"Add",
"bolditalic",
"CSS",
"."
] |
e14044e4019d57089c625d4ad2f73ccb66b8b7b8
|
https://github.com/kallimachos/chios/blob/e14044e4019d57089c625d4ad2f73ccb66b8b7b8/chios/bolditalic/__init__.py#L31-L49
|
245,301
|
kallimachos/chios
|
chios/bolditalic/__init__.py
|
bolditalic
|
def bolditalic(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""
Add bolditalic role.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called this function.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
node = nodes.inline(rawtext, text)
node.set_class('bolditalic')
return [node], []
|
python
|
def bolditalic(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""
Add bolditalic role.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called this function.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
node = nodes.inline(rawtext, text)
node.set_class('bolditalic')
return [node], []
|
[
"def",
"bolditalic",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"node",
"=",
"nodes",
".",
"inline",
"(",
"rawtext",
",",
"text",
")",
"node",
".",
"set_class",
"(",
"'bolditalic'",
")",
"return",
"[",
"node",
"]",
",",
"[",
"]"
] |
Add bolditalic role.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called this function.
:param options: Directive options for customization.
:param content: The directive content for customization.
|
[
"Add",
"bolditalic",
"role",
"."
] |
e14044e4019d57089c625d4ad2f73ccb66b8b7b8
|
https://github.com/kallimachos/chios/blob/e14044e4019d57089c625d4ad2f73ccb66b8b7b8/chios/bolditalic/__init__.py#L52-L70
|
245,302
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_safe_getmodule
|
def _safe_getmodule(o):
"""Attempts to return the module in which `o` is defined.
"""
from inspect import getmodule
try:
return getmodule(o)
except: # pragma: no cover
#There is nothing we can do about this for now.
msg.err("_safe_getmodule: {}".format(o), 2)
pass
|
python
|
def _safe_getmodule(o):
"""Attempts to return the module in which `o` is defined.
"""
from inspect import getmodule
try:
return getmodule(o)
except: # pragma: no cover
#There is nothing we can do about this for now.
msg.err("_safe_getmodule: {}".format(o), 2)
pass
|
[
"def",
"_safe_getmodule",
"(",
"o",
")",
":",
"from",
"inspect",
"import",
"getmodule",
"try",
":",
"return",
"getmodule",
"(",
"o",
")",
"except",
":",
"# pragma: no cover",
"#There is nothing we can do about this for now.",
"msg",
".",
"err",
"(",
"\"_safe_getmodule: {}\"",
".",
"format",
"(",
"o",
")",
",",
"2",
")",
"pass"
] |
Attempts to return the module in which `o` is defined.
|
[
"Attempts",
"to",
"return",
"the",
"module",
"in",
"which",
"o",
"is",
"defined",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L72-L81
|
245,303
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_safe_getattr
|
def _safe_getattr(o):
"""Gets the attribute from the specified object, taking the acorn decoration
into account.
"""
def getattribute(attr): # pragma: no cover
if hasattr(o, "__acornext__") and o.__acornext__ is not None:
return o.__acornext__.__getattribute__(attr)
elif hasattr(o, "__acorn__") and o.__acorn__ is not None:
#Some of the functions have the original function (when it was not
#extended) in the __acorn__ attribute.
return o.__acorn__.__getattribute__(attr)
else:
return getattr(o, attr)
return getattribute
|
python
|
def _safe_getattr(o):
"""Gets the attribute from the specified object, taking the acorn decoration
into account.
"""
def getattribute(attr): # pragma: no cover
if hasattr(o, "__acornext__") and o.__acornext__ is not None:
return o.__acornext__.__getattribute__(attr)
elif hasattr(o, "__acorn__") and o.__acorn__ is not None:
#Some of the functions have the original function (when it was not
#extended) in the __acorn__ attribute.
return o.__acorn__.__getattribute__(attr)
else:
return getattr(o, attr)
return getattribute
|
[
"def",
"_safe_getattr",
"(",
"o",
")",
":",
"def",
"getattribute",
"(",
"attr",
")",
":",
"# pragma: no cover",
"if",
"hasattr",
"(",
"o",
",",
"\"__acornext__\"",
")",
"and",
"o",
".",
"__acornext__",
"is",
"not",
"None",
":",
"return",
"o",
".",
"__acornext__",
".",
"__getattribute__",
"(",
"attr",
")",
"elif",
"hasattr",
"(",
"o",
",",
"\"__acorn__\"",
")",
"and",
"o",
".",
"__acorn__",
"is",
"not",
"None",
":",
"#Some of the functions have the original function (when it was not",
"#extended) in the __acorn__ attribute.",
"return",
"o",
".",
"__acorn__",
".",
"__getattribute__",
"(",
"attr",
")",
"else",
":",
"return",
"getattr",
"(",
"o",
",",
"attr",
")",
"return",
"getattribute"
] |
Gets the attribute from the specified object, taking the acorn decoration
into account.
|
[
"Gets",
"the",
"attribute",
"from",
"the",
"specified",
"object",
"taking",
"the",
"acorn",
"decoration",
"into",
"account",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L83-L96
|
245,304
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_safe_hasattr
|
def _safe_hasattr(o, attr):
"""Returns True if `o` has the specified attribute. Takes edge cases into
account where packages didn't intend to be used like acorn uses them.
"""
try:
has = hasattr(o, attr)
except: # pragma: no cover
has = False
msg.err("_safe_hasattr: {}.{}".format(o, attr), 2)
pass
return has
|
python
|
def _safe_hasattr(o, attr):
"""Returns True if `o` has the specified attribute. Takes edge cases into
account where packages didn't intend to be used like acorn uses them.
"""
try:
has = hasattr(o, attr)
except: # pragma: no cover
has = False
msg.err("_safe_hasattr: {}.{}".format(o, attr), 2)
pass
return has
|
[
"def",
"_safe_hasattr",
"(",
"o",
",",
"attr",
")",
":",
"try",
":",
"has",
"=",
"hasattr",
"(",
"o",
",",
"attr",
")",
"except",
":",
"# pragma: no cover",
"has",
"=",
"False",
"msg",
".",
"err",
"(",
"\"_safe_hasattr: {}.{}\"",
".",
"format",
"(",
"o",
",",
"attr",
")",
",",
"2",
")",
"pass",
"return",
"has"
] |
Returns True if `o` has the specified attribute. Takes edge cases into
account where packages didn't intend to be used like acorn uses them.
|
[
"Returns",
"True",
"if",
"o",
"has",
"the",
"specified",
"attribute",
".",
"Takes",
"edge",
"cases",
"into",
"account",
"where",
"packages",
"didn",
"t",
"intend",
"to",
"be",
"used",
"like",
"acorn",
"uses",
"them",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L98-L108
|
245,305
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_update_attrs
|
def _update_attrs(nobj, oobj, exceptions=None, acornext=False):
"""Updates the attributes on `nobj` to match those of old, excluding the any
attributes in the exceptions list.
"""
success = True
if (acornext and hasattr(oobj, "__acornext__")
and oobj.__acornext__ is not None): # pragma: no cover
target = oobj.__acornext__
else:
target = oobj
for a, v in _get_members(target):
if hasattr(nobj, a):
#We don't want to overwrite something that acorn has already done.
continue
if a in ["__class__", "__code__", "__closure__"]:# pragma: no cover
#These attributes are not writeable by design.
continue
if exceptions is None or a not in exceptions:
try:
setattr(nobj, a, v)
except TypeError:# pragma: no cover
#Some of the built-in types have __class__ attributes (for
#example) that we can't set on a function type. This catches
#that case and any others.
emsg = "_update_attrs (type): {}.{} => {}"
msg.err(emsg.format(nobj, a, target), 2)
pass
except AttributeError:# pragma: no cover
#Probably a read-only attribute that we are trying to set. Just
#ignore it.
emsg = "_update_attrs (attr): {}.{} => {}"
msg.err(emsg.format(nobj, a, target), 2)
pass
except ValueError:# pragma: no cover
emsg = "_update_attrs (value): {}.{} => {}"
msg.err(emsg.format(nobj, a, target), 2)
success = False
return success
|
python
|
def _update_attrs(nobj, oobj, exceptions=None, acornext=False):
"""Updates the attributes on `nobj` to match those of old, excluding the any
attributes in the exceptions list.
"""
success = True
if (acornext and hasattr(oobj, "__acornext__")
and oobj.__acornext__ is not None): # pragma: no cover
target = oobj.__acornext__
else:
target = oobj
for a, v in _get_members(target):
if hasattr(nobj, a):
#We don't want to overwrite something that acorn has already done.
continue
if a in ["__class__", "__code__", "__closure__"]:# pragma: no cover
#These attributes are not writeable by design.
continue
if exceptions is None or a not in exceptions:
try:
setattr(nobj, a, v)
except TypeError:# pragma: no cover
#Some of the built-in types have __class__ attributes (for
#example) that we can't set on a function type. This catches
#that case and any others.
emsg = "_update_attrs (type): {}.{} => {}"
msg.err(emsg.format(nobj, a, target), 2)
pass
except AttributeError:# pragma: no cover
#Probably a read-only attribute that we are trying to set. Just
#ignore it.
emsg = "_update_attrs (attr): {}.{} => {}"
msg.err(emsg.format(nobj, a, target), 2)
pass
except ValueError:# pragma: no cover
emsg = "_update_attrs (value): {}.{} => {}"
msg.err(emsg.format(nobj, a, target), 2)
success = False
return success
|
[
"def",
"_update_attrs",
"(",
"nobj",
",",
"oobj",
",",
"exceptions",
"=",
"None",
",",
"acornext",
"=",
"False",
")",
":",
"success",
"=",
"True",
"if",
"(",
"acornext",
"and",
"hasattr",
"(",
"oobj",
",",
"\"__acornext__\"",
")",
"and",
"oobj",
".",
"__acornext__",
"is",
"not",
"None",
")",
":",
"# pragma: no cover",
"target",
"=",
"oobj",
".",
"__acornext__",
"else",
":",
"target",
"=",
"oobj",
"for",
"a",
",",
"v",
"in",
"_get_members",
"(",
"target",
")",
":",
"if",
"hasattr",
"(",
"nobj",
",",
"a",
")",
":",
"#We don't want to overwrite something that acorn has already done.",
"continue",
"if",
"a",
"in",
"[",
"\"__class__\"",
",",
"\"__code__\"",
",",
"\"__closure__\"",
"]",
":",
"# pragma: no cover",
"#These attributes are not writeable by design.",
"continue",
"if",
"exceptions",
"is",
"None",
"or",
"a",
"not",
"in",
"exceptions",
":",
"try",
":",
"setattr",
"(",
"nobj",
",",
"a",
",",
"v",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"#Some of the built-in types have __class__ attributes (for",
"#example) that we can't set on a function type. This catches",
"#that case and any others.",
"emsg",
"=",
"\"_update_attrs (type): {}.{} => {}\"",
"msg",
".",
"err",
"(",
"emsg",
".",
"format",
"(",
"nobj",
",",
"a",
",",
"target",
")",
",",
"2",
")",
"pass",
"except",
"AttributeError",
":",
"# pragma: no cover",
"#Probably a read-only attribute that we are trying to set. Just",
"#ignore it.",
"emsg",
"=",
"\"_update_attrs (attr): {}.{} => {}\"",
"msg",
".",
"err",
"(",
"emsg",
".",
"format",
"(",
"nobj",
",",
"a",
",",
"target",
")",
",",
"2",
")",
"pass",
"except",
"ValueError",
":",
"# pragma: no cover",
"emsg",
"=",
"\"_update_attrs (value): {}.{} => {}\"",
"msg",
".",
"err",
"(",
"emsg",
".",
"format",
"(",
"nobj",
",",
"a",
",",
"target",
")",
",",
"2",
")",
"success",
"=",
"False",
"return",
"success"
] |
Updates the attributes on `nobj` to match those of old, excluding the any
attributes in the exceptions list.
|
[
"Updates",
"the",
"attributes",
"on",
"nobj",
"to",
"match",
"those",
"of",
"old",
"excluding",
"the",
"any",
"attributes",
"in",
"the",
"exceptions",
"list",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L110-L150
|
245,306
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_get_name_filter
|
def _get_name_filter(package, context="decorate", reparse=False):
"""Makes sure that the name filters for the specified package have been
loaded.
Args:
package (str): name of the package that this method belongs to.
context (str): one of ['decorate', 'time', 'analyze']; specifies which
section of the configuration settings to check.
"""
global name_filters
pkey = (package, context)
if pkey in name_filters and not reparse:
return name_filters[pkey]
from acorn.config import settings
spack = settings(package)
# The acorn.* sections allow for global settings that affect every package
# that ever gets wrapped.
sections = {
"decorate": ["tracking", "acorn.tracking"],
"time": ["timing", "acorn.timing"],
"analyze": ["analysis", "acorn.analysis"]
}
filters, rfilters = None, None
import re
if context in sections:
# We are interested in the 'filter' and 'rfilter' options if they exist.
filters, rfilters = [], []
ignores, rignores = [], []
for section in sections[context]:
if spack.has_section(section):
options = spack.options(section)
if "filter" in options:
filters.extend(re.split(r"\s*\$\s*", spack.get(section, "filter")))
if "rfilter" in options: # pragma: no cover
#Until now, the fnmatch filters have been the most
#useful. So I don't have any unit tests for regex filters.
pfilters = re.split(r"\s*\$\s*", spack.get(section, "rfilter"))
rfilters.extend([re.compile(p, re.I) for p in pfilters])
if "ignore" in options:
ignores.extend(re.split(r"\s*\$\s*", spack.get(section, "ignore")))
if "rignore" in options: # pragma: no cover
pignores = re.split(r"\s*\$\s*", spack.get(section, "rignore"))
rignores.extend([re.compile(p, re.I) for p in pfilters])
name_filters[pkey] = {
"filters": filters,
"rfilters": rfilters,
"ignores": ignores,
"rignores": rignores
}
else:
name_filters[pkey] = None
return name_filters[pkey]
|
python
|
def _get_name_filter(package, context="decorate", reparse=False):
"""Makes sure that the name filters for the specified package have been
loaded.
Args:
package (str): name of the package that this method belongs to.
context (str): one of ['decorate', 'time', 'analyze']; specifies which
section of the configuration settings to check.
"""
global name_filters
pkey = (package, context)
if pkey in name_filters and not reparse:
return name_filters[pkey]
from acorn.config import settings
spack = settings(package)
# The acorn.* sections allow for global settings that affect every package
# that ever gets wrapped.
sections = {
"decorate": ["tracking", "acorn.tracking"],
"time": ["timing", "acorn.timing"],
"analyze": ["analysis", "acorn.analysis"]
}
filters, rfilters = None, None
import re
if context in sections:
# We are interested in the 'filter' and 'rfilter' options if they exist.
filters, rfilters = [], []
ignores, rignores = [], []
for section in sections[context]:
if spack.has_section(section):
options = spack.options(section)
if "filter" in options:
filters.extend(re.split(r"\s*\$\s*", spack.get(section, "filter")))
if "rfilter" in options: # pragma: no cover
#Until now, the fnmatch filters have been the most
#useful. So I don't have any unit tests for regex filters.
pfilters = re.split(r"\s*\$\s*", spack.get(section, "rfilter"))
rfilters.extend([re.compile(p, re.I) for p in pfilters])
if "ignore" in options:
ignores.extend(re.split(r"\s*\$\s*", spack.get(section, "ignore")))
if "rignore" in options: # pragma: no cover
pignores = re.split(r"\s*\$\s*", spack.get(section, "rignore"))
rignores.extend([re.compile(p, re.I) for p in pfilters])
name_filters[pkey] = {
"filters": filters,
"rfilters": rfilters,
"ignores": ignores,
"rignores": rignores
}
else:
name_filters[pkey] = None
return name_filters[pkey]
|
[
"def",
"_get_name_filter",
"(",
"package",
",",
"context",
"=",
"\"decorate\"",
",",
"reparse",
"=",
"False",
")",
":",
"global",
"name_filters",
"pkey",
"=",
"(",
"package",
",",
"context",
")",
"if",
"pkey",
"in",
"name_filters",
"and",
"not",
"reparse",
":",
"return",
"name_filters",
"[",
"pkey",
"]",
"from",
"acorn",
".",
"config",
"import",
"settings",
"spack",
"=",
"settings",
"(",
"package",
")",
"# The acorn.* sections allow for global settings that affect every package",
"# that ever gets wrapped.",
"sections",
"=",
"{",
"\"decorate\"",
":",
"[",
"\"tracking\"",
",",
"\"acorn.tracking\"",
"]",
",",
"\"time\"",
":",
"[",
"\"timing\"",
",",
"\"acorn.timing\"",
"]",
",",
"\"analyze\"",
":",
"[",
"\"analysis\"",
",",
"\"acorn.analysis\"",
"]",
"}",
"filters",
",",
"rfilters",
"=",
"None",
",",
"None",
"import",
"re",
"if",
"context",
"in",
"sections",
":",
"# We are interested in the 'filter' and 'rfilter' options if they exist.",
"filters",
",",
"rfilters",
"=",
"[",
"]",
",",
"[",
"]",
"ignores",
",",
"rignores",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"section",
"in",
"sections",
"[",
"context",
"]",
":",
"if",
"spack",
".",
"has_section",
"(",
"section",
")",
":",
"options",
"=",
"spack",
".",
"options",
"(",
"section",
")",
"if",
"\"filter\"",
"in",
"options",
":",
"filters",
".",
"extend",
"(",
"re",
".",
"split",
"(",
"r\"\\s*\\$\\s*\"",
",",
"spack",
".",
"get",
"(",
"section",
",",
"\"filter\"",
")",
")",
")",
"if",
"\"rfilter\"",
"in",
"options",
":",
"# pragma: no cover",
"#Until now, the fnmatch filters have been the most",
"#useful. So I don't have any unit tests for regex filters.",
"pfilters",
"=",
"re",
".",
"split",
"(",
"r\"\\s*\\$\\s*\"",
",",
"spack",
".",
"get",
"(",
"section",
",",
"\"rfilter\"",
")",
")",
"rfilters",
".",
"extend",
"(",
"[",
"re",
".",
"compile",
"(",
"p",
",",
"re",
".",
"I",
")",
"for",
"p",
"in",
"pfilters",
"]",
")",
"if",
"\"ignore\"",
"in",
"options",
":",
"ignores",
".",
"extend",
"(",
"re",
".",
"split",
"(",
"r\"\\s*\\$\\s*\"",
",",
"spack",
".",
"get",
"(",
"section",
",",
"\"ignore\"",
")",
")",
")",
"if",
"\"rignore\"",
"in",
"options",
":",
"# pragma: no cover",
"pignores",
"=",
"re",
".",
"split",
"(",
"r\"\\s*\\$\\s*\"",
",",
"spack",
".",
"get",
"(",
"section",
",",
"\"rignore\"",
")",
")",
"rignores",
".",
"extend",
"(",
"[",
"re",
".",
"compile",
"(",
"p",
",",
"re",
".",
"I",
")",
"for",
"p",
"in",
"pfilters",
"]",
")",
"name_filters",
"[",
"pkey",
"]",
"=",
"{",
"\"filters\"",
":",
"filters",
",",
"\"rfilters\"",
":",
"rfilters",
",",
"\"ignores\"",
":",
"ignores",
",",
"\"rignores\"",
":",
"rignores",
"}",
"else",
":",
"name_filters",
"[",
"pkey",
"]",
"=",
"None",
"return",
"name_filters",
"[",
"pkey",
"]"
] |
Makes sure that the name filters for the specified package have been
loaded.
Args:
package (str): name of the package that this method belongs to.
context (str): one of ['decorate', 'time', 'analyze']; specifies which
section of the configuration settings to check.
|
[
"Makes",
"sure",
"that",
"the",
"name",
"filters",
"for",
"the",
"specified",
"package",
"have",
"been",
"loaded",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L167-L222
|
245,307
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_check_args
|
def _check_args(*argl, **argd):
"""Checks the specified argument lists for objects that are trackable.
"""
args = {"_": []}
for item in argl:
args["_"].append(_tracker_str(item))
for key, item in argd.items():
args[key] = _tracker_str(item)
return args
|
python
|
def _check_args(*argl, **argd):
"""Checks the specified argument lists for objects that are trackable.
"""
args = {"_": []}
for item in argl:
args["_"].append(_tracker_str(item))
for key, item in argd.items():
args[key] = _tracker_str(item)
return args
|
[
"def",
"_check_args",
"(",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"args",
"=",
"{",
"\"_\"",
":",
"[",
"]",
"}",
"for",
"item",
"in",
"argl",
":",
"args",
"[",
"\"_\"",
"]",
".",
"append",
"(",
"_tracker_str",
"(",
"item",
")",
")",
"for",
"key",
",",
"item",
"in",
"argd",
".",
"items",
"(",
")",
":",
"args",
"[",
"key",
"]",
"=",
"_tracker_str",
"(",
"item",
")",
"return",
"args"
] |
Checks the specified argument lists for objects that are trackable.
|
[
"Checks",
"the",
"specified",
"argument",
"lists",
"for",
"objects",
"that",
"are",
"trackable",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L301-L311
|
245,308
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_reduced_stack
|
def _reduced_stack(istart=3, iend=5, ipython=True):
"""Returns the reduced function call stack that includes only relevant
function calls (i.e., ignores any that are not part of the specified package
or acorn.
Args:
package (str): name of the package that the logged method belongs to.
"""
import inspect
return [i[istart:iend] for i in inspect.stack() if _decorated_path(i[1])]
|
python
|
def _reduced_stack(istart=3, iend=5, ipython=True):
"""Returns the reduced function call stack that includes only relevant
function calls (i.e., ignores any that are not part of the specified package
or acorn.
Args:
package (str): name of the package that the logged method belongs to.
"""
import inspect
return [i[istart:iend] for i in inspect.stack() if _decorated_path(i[1])]
|
[
"def",
"_reduced_stack",
"(",
"istart",
"=",
"3",
",",
"iend",
"=",
"5",
",",
"ipython",
"=",
"True",
")",
":",
"import",
"inspect",
"return",
"[",
"i",
"[",
"istart",
":",
"iend",
"]",
"for",
"i",
"in",
"inspect",
".",
"stack",
"(",
")",
"if",
"_decorated_path",
"(",
"i",
"[",
"1",
"]",
")",
"]"
] |
Returns the reduced function call stack that includes only relevant
function calls (i.e., ignores any that are not part of the specified package
or acorn.
Args:
package (str): name of the package that the logged method belongs to.
|
[
"Returns",
"the",
"reduced",
"function",
"call",
"stack",
"that",
"includes",
"only",
"relevant",
"function",
"calls",
"(",
"i",
".",
"e",
".",
"ignores",
"any",
"that",
"are",
"not",
"part",
"of",
"the",
"specified",
"package",
"or",
"acorn",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L328-L337
|
245,309
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_pre_create
|
def _pre_create(cls, atdepth, stackdepth, *argl, **argd):
"""Checks whether the the logging should happen based on the specified
parameters. If it should, an initialized entry is returned.
"""
from time import time
if not atdepth:
rstack = _reduced_stack()
reduced = len(rstack)
if msg.will_print(3): # pragma: no cover
sstack = [' | '.join(map(str, r)) for r in rstack]
msg.info("{} => stack ({}): {}".format(cls.__fqdn__, len(rstack),
', '.join(sstack)), 3)
else:
reduced = stackdepth + 10
if reduced <= stackdepth:
args = _check_args(*argl, **argd)
entry = {
"m": "{}.__new__".format(cls.__fqdn__),
"a": args,
"s": time(),
"r": None,
"stack": reduced
}
else:
atdepth = True
entry = None
return (entry, atdepth)
|
python
|
def _pre_create(cls, atdepth, stackdepth, *argl, **argd):
"""Checks whether the the logging should happen based on the specified
parameters. If it should, an initialized entry is returned.
"""
from time import time
if not atdepth:
rstack = _reduced_stack()
reduced = len(rstack)
if msg.will_print(3): # pragma: no cover
sstack = [' | '.join(map(str, r)) for r in rstack]
msg.info("{} => stack ({}): {}".format(cls.__fqdn__, len(rstack),
', '.join(sstack)), 3)
else:
reduced = stackdepth + 10
if reduced <= stackdepth:
args = _check_args(*argl, **argd)
entry = {
"m": "{}.__new__".format(cls.__fqdn__),
"a": args,
"s": time(),
"r": None,
"stack": reduced
}
else:
atdepth = True
entry = None
return (entry, atdepth)
|
[
"def",
"_pre_create",
"(",
"cls",
",",
"atdepth",
",",
"stackdepth",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"from",
"time",
"import",
"time",
"if",
"not",
"atdepth",
":",
"rstack",
"=",
"_reduced_stack",
"(",
")",
"reduced",
"=",
"len",
"(",
"rstack",
")",
"if",
"msg",
".",
"will_print",
"(",
"3",
")",
":",
"# pragma: no cover",
"sstack",
"=",
"[",
"' | '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"r",
")",
")",
"for",
"r",
"in",
"rstack",
"]",
"msg",
".",
"info",
"(",
"\"{} => stack ({}): {}\"",
".",
"format",
"(",
"cls",
".",
"__fqdn__",
",",
"len",
"(",
"rstack",
")",
",",
"', '",
".",
"join",
"(",
"sstack",
")",
")",
",",
"3",
")",
"else",
":",
"reduced",
"=",
"stackdepth",
"+",
"10",
"if",
"reduced",
"<=",
"stackdepth",
":",
"args",
"=",
"_check_args",
"(",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"entry",
"=",
"{",
"\"m\"",
":",
"\"{}.__new__\"",
".",
"format",
"(",
"cls",
".",
"__fqdn__",
")",
",",
"\"a\"",
":",
"args",
",",
"\"s\"",
":",
"time",
"(",
")",
",",
"\"r\"",
":",
"None",
",",
"\"stack\"",
":",
"reduced",
"}",
"else",
":",
"atdepth",
"=",
"True",
"entry",
"=",
"None",
"return",
"(",
"entry",
",",
"atdepth",
")"
] |
Checks whether the the logging should happen based on the specified
parameters. If it should, an initialized entry is returned.
|
[
"Checks",
"whether",
"the",
"the",
"logging",
"should",
"happen",
"based",
"on",
"the",
"specified",
"parameters",
".",
"If",
"it",
"should",
"an",
"initialized",
"entry",
"is",
"returned",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L350-L378
|
245,310
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_post_create
|
def _post_create(atdepth, entry, result):
"""Finishes the entry logging if applicable.
"""
if not atdepth and entry is not None:
if result is not None:
#We need to get these results a UUID that will be saved so that any
#instance methods applied to this object has a parent to refer to.
retid = _tracker_str(result)
entry["r"] = retid
ekey = retid
else: # pragma: no cover
ekey = _tracker_str(cls)
msg.info("{}: {}".format(ekey, entry), 1)
record(ekey, entry)
|
python
|
def _post_create(atdepth, entry, result):
"""Finishes the entry logging if applicable.
"""
if not atdepth and entry is not None:
if result is not None:
#We need to get these results a UUID that will be saved so that any
#instance methods applied to this object has a parent to refer to.
retid = _tracker_str(result)
entry["r"] = retid
ekey = retid
else: # pragma: no cover
ekey = _tracker_str(cls)
msg.info("{}: {}".format(ekey, entry), 1)
record(ekey, entry)
|
[
"def",
"_post_create",
"(",
"atdepth",
",",
"entry",
",",
"result",
")",
":",
"if",
"not",
"atdepth",
"and",
"entry",
"is",
"not",
"None",
":",
"if",
"result",
"is",
"not",
"None",
":",
"#We need to get these results a UUID that will be saved so that any",
"#instance methods applied to this object has a parent to refer to.",
"retid",
"=",
"_tracker_str",
"(",
"result",
")",
"entry",
"[",
"\"r\"",
"]",
"=",
"retid",
"ekey",
"=",
"retid",
"else",
":",
"# pragma: no cover",
"ekey",
"=",
"_tracker_str",
"(",
"cls",
")",
"msg",
".",
"info",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"ekey",
",",
"entry",
")",
",",
"1",
")",
"record",
"(",
"ekey",
",",
"entry",
")"
] |
Finishes the entry logging if applicable.
|
[
"Finishes",
"the",
"entry",
"logging",
"if",
"applicable",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L380-L394
|
245,311
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
creationlog
|
def creationlog(base, package, stackdepth=_def_stackdepth):
"""Decorator for wrapping the creation of class instances that are being logged
by acorn.
Args:
base: base class used to call __new__ for the construction.
package (str): name of (global) package the class belongs to.
stackdepth (int): if the calling stack is less than this depth, than
include the entry in the log; otherwise ignore it.
"""
@staticmethod
def wrapnew(cls, *argl, **argd):
global _atdepth_new, _cstack_new, streamlining
origstream = None
if not (decorating or streamlining):
entry, _atdepth_new = _pre_create(cls, _atdepth_new,
stackdepth, *argl, **argd)
_cstack_new.append(cls)
#See if we need to enable streamlining for this constructor.
fqdn = cls.__fqdn__
if fqdn in _streamlines and _streamlines[fqdn]:
#We only use streamlining for the plotting routines at the
#moment, so it doesn't get hit by the unit tests.
msg.std("Streamlining {}.".format(fqdn), 2)
origstream = streamlining
streamlining = True
try:
if six.PY2:
result = base.__old__(cls, *argl, **argd)
else: # pragma: no cover
#Python 3 changed the way that the constructors behave. In cases
#where a class inherits only from object, and doesn't override
#the __new__ method, the __old__ we replaced was just the one
#belonging to object.
if base.__old__ is object.__new__:
result = base.__old__(cls)
else:
result = base.__old__(cls, *argl, **argd)
except TypeError: # pragma: no cover
#This is a crazy hack! We want this to be dynamic so that it can
#work with any of the packages. If the error message suggests using
#a different constructor, we go ahead and use it.
import sys
xcls, xerr = sys.exc_info()[0:2]
referral = xerr.args[0].split()[-1]
if ".__new__()" in referral:
t = eval(referral.split('.')[0])
result = t.__new__(cls, *argl, **argd)
else:
raise
result = None
if result is not None and hasattr(cls, "__init__"):
try:
cls.__init__(result, *argl, **argd)
except: # pragma: no cover
print(cls, argl, argd)
raise
else: # pragma: no cover
msg.err("Object initialize failed for {}.".format(base.__name__))
#If we don't disable streamlining for the original method that set
#it, then the post call would never be reached.
if origstream is not None:
#We avoid another dict lookup by checking whether we set the
#*local* origstream to something above.
streamlining = origstream
if not (decorating or streamlining):
_cstack_new.pop()
if len(_cstack_new) == 0:
_atdepth_new = False
_post_create(_atdepth_new, entry, result)
return result
return wrapnew
|
python
|
def creationlog(base, package, stackdepth=_def_stackdepth):
"""Decorator for wrapping the creation of class instances that are being logged
by acorn.
Args:
base: base class used to call __new__ for the construction.
package (str): name of (global) package the class belongs to.
stackdepth (int): if the calling stack is less than this depth, than
include the entry in the log; otherwise ignore it.
"""
@staticmethod
def wrapnew(cls, *argl, **argd):
global _atdepth_new, _cstack_new, streamlining
origstream = None
if not (decorating or streamlining):
entry, _atdepth_new = _pre_create(cls, _atdepth_new,
stackdepth, *argl, **argd)
_cstack_new.append(cls)
#See if we need to enable streamlining for this constructor.
fqdn = cls.__fqdn__
if fqdn in _streamlines and _streamlines[fqdn]:
#We only use streamlining for the plotting routines at the
#moment, so it doesn't get hit by the unit tests.
msg.std("Streamlining {}.".format(fqdn), 2)
origstream = streamlining
streamlining = True
try:
if six.PY2:
result = base.__old__(cls, *argl, **argd)
else: # pragma: no cover
#Python 3 changed the way that the constructors behave. In cases
#where a class inherits only from object, and doesn't override
#the __new__ method, the __old__ we replaced was just the one
#belonging to object.
if base.__old__ is object.__new__:
result = base.__old__(cls)
else:
result = base.__old__(cls, *argl, **argd)
except TypeError: # pragma: no cover
#This is a crazy hack! We want this to be dynamic so that it can
#work with any of the packages. If the error message suggests using
#a different constructor, we go ahead and use it.
import sys
xcls, xerr = sys.exc_info()[0:2]
referral = xerr.args[0].split()[-1]
if ".__new__()" in referral:
t = eval(referral.split('.')[0])
result = t.__new__(cls, *argl, **argd)
else:
raise
result = None
if result is not None and hasattr(cls, "__init__"):
try:
cls.__init__(result, *argl, **argd)
except: # pragma: no cover
print(cls, argl, argd)
raise
else: # pragma: no cover
msg.err("Object initialize failed for {}.".format(base.__name__))
#If we don't disable streamlining for the original method that set
#it, then the post call would never be reached.
if origstream is not None:
#We avoid another dict lookup by checking whether we set the
#*local* origstream to something above.
streamlining = origstream
if not (decorating or streamlining):
_cstack_new.pop()
if len(_cstack_new) == 0:
_atdepth_new = False
_post_create(_atdepth_new, entry, result)
return result
return wrapnew
|
[
"def",
"creationlog",
"(",
"base",
",",
"package",
",",
"stackdepth",
"=",
"_def_stackdepth",
")",
":",
"@",
"staticmethod",
"def",
"wrapnew",
"(",
"cls",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"global",
"_atdepth_new",
",",
"_cstack_new",
",",
"streamlining",
"origstream",
"=",
"None",
"if",
"not",
"(",
"decorating",
"or",
"streamlining",
")",
":",
"entry",
",",
"_atdepth_new",
"=",
"_pre_create",
"(",
"cls",
",",
"_atdepth_new",
",",
"stackdepth",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"_cstack_new",
".",
"append",
"(",
"cls",
")",
"#See if we need to enable streamlining for this constructor.",
"fqdn",
"=",
"cls",
".",
"__fqdn__",
"if",
"fqdn",
"in",
"_streamlines",
"and",
"_streamlines",
"[",
"fqdn",
"]",
":",
"#We only use streamlining for the plotting routines at the",
"#moment, so it doesn't get hit by the unit tests.",
"msg",
".",
"std",
"(",
"\"Streamlining {}.\"",
".",
"format",
"(",
"fqdn",
")",
",",
"2",
")",
"origstream",
"=",
"streamlining",
"streamlining",
"=",
"True",
"try",
":",
"if",
"six",
".",
"PY2",
":",
"result",
"=",
"base",
".",
"__old__",
"(",
"cls",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"else",
":",
"# pragma: no cover",
"#Python 3 changed the way that the constructors behave. In cases",
"#where a class inherits only from object, and doesn't override",
"#the __new__ method, the __old__ we replaced was just the one",
"#belonging to object.",
"if",
"base",
".",
"__old__",
"is",
"object",
".",
"__new__",
":",
"result",
"=",
"base",
".",
"__old__",
"(",
"cls",
")",
"else",
":",
"result",
"=",
"base",
".",
"__old__",
"(",
"cls",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"#This is a crazy hack! We want this to be dynamic so that it can",
"#work with any of the packages. If the error message suggests using",
"#a different constructor, we go ahead and use it.",
"import",
"sys",
"xcls",
",",
"xerr",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
":",
"2",
"]",
"referral",
"=",
"xerr",
".",
"args",
"[",
"0",
"]",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"if",
"\".__new__()\"",
"in",
"referral",
":",
"t",
"=",
"eval",
"(",
"referral",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"result",
"=",
"t",
".",
"__new__",
"(",
"cls",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"else",
":",
"raise",
"result",
"=",
"None",
"if",
"result",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"cls",
",",
"\"__init__\"",
")",
":",
"try",
":",
"cls",
".",
"__init__",
"(",
"result",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"except",
":",
"# pragma: no cover",
"print",
"(",
"cls",
",",
"argl",
",",
"argd",
")",
"raise",
"else",
":",
"# pragma: no cover",
"msg",
".",
"err",
"(",
"\"Object initialize failed for {}.\"",
".",
"format",
"(",
"base",
".",
"__name__",
")",
")",
"#If we don't disable streamlining for the original method that set",
"#it, then the post call would never be reached.",
"if",
"origstream",
"is",
"not",
"None",
":",
"#We avoid another dict lookup by checking whether we set the",
"#*local* origstream to something above.",
"streamlining",
"=",
"origstream",
"if",
"not",
"(",
"decorating",
"or",
"streamlining",
")",
":",
"_cstack_new",
".",
"pop",
"(",
")",
"if",
"len",
"(",
"_cstack_new",
")",
"==",
"0",
":",
"_atdepth_new",
"=",
"False",
"_post_create",
"(",
"_atdepth_new",
",",
"entry",
",",
"result",
")",
"return",
"result",
"return",
"wrapnew"
] |
Decorator for wrapping the creation of class instances that are being logged
by acorn.
Args:
base: base class used to call __new__ for the construction.
package (str): name of (global) package the class belongs to.
stackdepth (int): if the calling stack is less than this depth, than
include the entry in the log; otherwise ignore it.
|
[
"Decorator",
"for",
"wrapping",
"the",
"creation",
"of",
"class",
"instances",
"that",
"are",
"being",
"logged",
"by",
"acorn",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L396-L474
|
245,312
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_pre_call
|
def _pre_call(atdepth, parent, fqdn, stackdepth, *argl, **argd):
"""Checks whether the logging should create an entry based on stackdepth. If
so, the entry is created.
"""
from time import time
if not atdepth:
rstack = _reduced_stack()
if "<module>" in rstack[-1]: # pragma: no cover
code = rstack[-1][1]
else:
code = ""
reduced = len(rstack)
if msg.will_print(3): # pragma: no cover
sstack = [' | '.join(map(str, r)) for r in rstack]
msg.info("{} => stack ({}): {}".format(fqdn, len(rstack),
', '.join(sstack)), 3)
else:
reduced = stackdepth + 10
bound = False
if reduced <= stackdepth:
args = _check_args(*argl, **argd)
# At this point, we should start the entry. If the method raises an
# exception, we should keep track of that. If this is an instance
# method, we should get its UUID, if not, then we can just store the
# entry under the full method name.
#There is yet another subtletly here: many packages have a base, static
#method that gets set as an instance method for sub-classes of a certain
#ABC. In that case, parent will be a super-class of the first argument,
#though the types will *not* be identical. Check for overlap in the base
#classes of the first argument. It would be nice if we could easily
#check for bound methods using inspect, but it doesn't work for some of
#the C-extension modules...
if (len(argl) > 0 and parent is not None and inspect.isclass(parent)):
ftype = type(argl[0])
if isinstance(argl[0], parent):
bound = True
elif (inspect.isclass(ftype) and hasattr(ftype, "__bases__") and
inspect.isclass(parent) and hasattr(parent, "__bases__")): # pragma: no cover
common = set(ftype.__bases__) & set(parent.__bases__)
bound = len(common) > 0
if not bound:
#For now, we use the fqdn; later, if the result is not None, we
#will rather index this entry by the returned result, since we
#can also access the fqdn in the entry details.
ekey = fqdn
else:
# It must have the first argument be the instance.
ekey = _tracker_str(argl[0])
#Check whether the logging has been overidden by a configuration option.
if (fqdn not in _logging or _logging[fqdn]):
entry = {
"m": fqdn,
"a": args,
"s": time(),
"r": None,
"c": code,
}
else:
entry = None
else:
entry = None
atdepth = True
ekey = None
return (entry, atdepth, reduced, bound, ekey)
|
python
|
def _pre_call(atdepth, parent, fqdn, stackdepth, *argl, **argd):
"""Checks whether the logging should create an entry based on stackdepth. If
so, the entry is created.
"""
from time import time
if not atdepth:
rstack = _reduced_stack()
if "<module>" in rstack[-1]: # pragma: no cover
code = rstack[-1][1]
else:
code = ""
reduced = len(rstack)
if msg.will_print(3): # pragma: no cover
sstack = [' | '.join(map(str, r)) for r in rstack]
msg.info("{} => stack ({}): {}".format(fqdn, len(rstack),
', '.join(sstack)), 3)
else:
reduced = stackdepth + 10
bound = False
if reduced <= stackdepth:
args = _check_args(*argl, **argd)
# At this point, we should start the entry. If the method raises an
# exception, we should keep track of that. If this is an instance
# method, we should get its UUID, if not, then we can just store the
# entry under the full method name.
#There is yet another subtletly here: many packages have a base, static
#method that gets set as an instance method for sub-classes of a certain
#ABC. In that case, parent will be a super-class of the first argument,
#though the types will *not* be identical. Check for overlap in the base
#classes of the first argument. It would be nice if we could easily
#check for bound methods using inspect, but it doesn't work for some of
#the C-extension modules...
if (len(argl) > 0 and parent is not None and inspect.isclass(parent)):
ftype = type(argl[0])
if isinstance(argl[0], parent):
bound = True
elif (inspect.isclass(ftype) and hasattr(ftype, "__bases__") and
inspect.isclass(parent) and hasattr(parent, "__bases__")): # pragma: no cover
common = set(ftype.__bases__) & set(parent.__bases__)
bound = len(common) > 0
if not bound:
#For now, we use the fqdn; later, if the result is not None, we
#will rather index this entry by the returned result, since we
#can also access the fqdn in the entry details.
ekey = fqdn
else:
# It must have the first argument be the instance.
ekey = _tracker_str(argl[0])
#Check whether the logging has been overidden by a configuration option.
if (fqdn not in _logging or _logging[fqdn]):
entry = {
"m": fqdn,
"a": args,
"s": time(),
"r": None,
"c": code,
}
else:
entry = None
else:
entry = None
atdepth = True
ekey = None
return (entry, atdepth, reduced, bound, ekey)
|
[
"def",
"_pre_call",
"(",
"atdepth",
",",
"parent",
",",
"fqdn",
",",
"stackdepth",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"from",
"time",
"import",
"time",
"if",
"not",
"atdepth",
":",
"rstack",
"=",
"_reduced_stack",
"(",
")",
"if",
"\"<module>\"",
"in",
"rstack",
"[",
"-",
"1",
"]",
":",
"# pragma: no cover",
"code",
"=",
"rstack",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"else",
":",
"code",
"=",
"\"\"",
"reduced",
"=",
"len",
"(",
"rstack",
")",
"if",
"msg",
".",
"will_print",
"(",
"3",
")",
":",
"# pragma: no cover",
"sstack",
"=",
"[",
"' | '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"r",
")",
")",
"for",
"r",
"in",
"rstack",
"]",
"msg",
".",
"info",
"(",
"\"{} => stack ({}): {}\"",
".",
"format",
"(",
"fqdn",
",",
"len",
"(",
"rstack",
")",
",",
"', '",
".",
"join",
"(",
"sstack",
")",
")",
",",
"3",
")",
"else",
":",
"reduced",
"=",
"stackdepth",
"+",
"10",
"bound",
"=",
"False",
"if",
"reduced",
"<=",
"stackdepth",
":",
"args",
"=",
"_check_args",
"(",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"# At this point, we should start the entry. If the method raises an",
"# exception, we should keep track of that. If this is an instance",
"# method, we should get its UUID, if not, then we can just store the",
"# entry under the full method name.",
"#There is yet another subtletly here: many packages have a base, static",
"#method that gets set as an instance method for sub-classes of a certain",
"#ABC. In that case, parent will be a super-class of the first argument,",
"#though the types will *not* be identical. Check for overlap in the base",
"#classes of the first argument. It would be nice if we could easily",
"#check for bound methods using inspect, but it doesn't work for some of",
"#the C-extension modules...",
"if",
"(",
"len",
"(",
"argl",
")",
">",
"0",
"and",
"parent",
"is",
"not",
"None",
"and",
"inspect",
".",
"isclass",
"(",
"parent",
")",
")",
":",
"ftype",
"=",
"type",
"(",
"argl",
"[",
"0",
"]",
")",
"if",
"isinstance",
"(",
"argl",
"[",
"0",
"]",
",",
"parent",
")",
":",
"bound",
"=",
"True",
"elif",
"(",
"inspect",
".",
"isclass",
"(",
"ftype",
")",
"and",
"hasattr",
"(",
"ftype",
",",
"\"__bases__\"",
")",
"and",
"inspect",
".",
"isclass",
"(",
"parent",
")",
"and",
"hasattr",
"(",
"parent",
",",
"\"__bases__\"",
")",
")",
":",
"# pragma: no cover",
"common",
"=",
"set",
"(",
"ftype",
".",
"__bases__",
")",
"&",
"set",
"(",
"parent",
".",
"__bases__",
")",
"bound",
"=",
"len",
"(",
"common",
")",
">",
"0",
"if",
"not",
"bound",
":",
"#For now, we use the fqdn; later, if the result is not None, we",
"#will rather index this entry by the returned result, since we",
"#can also access the fqdn in the entry details.",
"ekey",
"=",
"fqdn",
"else",
":",
"# It must have the first argument be the instance.",
"ekey",
"=",
"_tracker_str",
"(",
"argl",
"[",
"0",
"]",
")",
"#Check whether the logging has been overidden by a configuration option.",
"if",
"(",
"fqdn",
"not",
"in",
"_logging",
"or",
"_logging",
"[",
"fqdn",
"]",
")",
":",
"entry",
"=",
"{",
"\"m\"",
":",
"fqdn",
",",
"\"a\"",
":",
"args",
",",
"\"s\"",
":",
"time",
"(",
")",
",",
"\"r\"",
":",
"None",
",",
"\"c\"",
":",
"code",
",",
"}",
"else",
":",
"entry",
"=",
"None",
"else",
":",
"entry",
"=",
"None",
"atdepth",
"=",
"True",
"ekey",
"=",
"None",
"return",
"(",
"entry",
",",
"atdepth",
",",
"reduced",
",",
"bound",
",",
"ekey",
")"
] |
Checks whether the logging should create an entry based on stackdepth. If
so, the entry is created.
|
[
"Checks",
"whether",
"the",
"logging",
"should",
"create",
"an",
"entry",
"based",
"on",
"stackdepth",
".",
"If",
"so",
"the",
"entry",
"is",
"created",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L487-L556
|
245,313
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_post_call
|
def _post_call(atdepth, package, fqdn, result, entry, bound, ekey, argl, argd):
"""Finishes constructing the log and records it to the database.
"""
from time import time
if not atdepth and entry is not None:
ek = ekey
if result is not None:
retid = _tracker_str(result)
if result is not None and not bound:
ek = retid
entry["r"] = None
else:
entry["r"] = retid
name = fqdn.split('.')[-1]
if filter_name(fqdn, package, "time"):
entry["e"] = time() - entry["s"]
if filter_name(fqdn, package, "analyze"):
entry["z"] = analyze(fqdn, result, argl, argd)
msg.info("{}: {}".format(ek, entry), 1)
# Before we return the result, let's first save this call to the
# database so we have a record of it.
record(ek, entry)
return (ek, entry)
else:
return (None, None)
|
python
|
def _post_call(atdepth, package, fqdn, result, entry, bound, ekey, argl, argd):
"""Finishes constructing the log and records it to the database.
"""
from time import time
if not atdepth and entry is not None:
ek = ekey
if result is not None:
retid = _tracker_str(result)
if result is not None and not bound:
ek = retid
entry["r"] = None
else:
entry["r"] = retid
name = fqdn.split('.')[-1]
if filter_name(fqdn, package, "time"):
entry["e"] = time() - entry["s"]
if filter_name(fqdn, package, "analyze"):
entry["z"] = analyze(fqdn, result, argl, argd)
msg.info("{}: {}".format(ek, entry), 1)
# Before we return the result, let's first save this call to the
# database so we have a record of it.
record(ek, entry)
return (ek, entry)
else:
return (None, None)
|
[
"def",
"_post_call",
"(",
"atdepth",
",",
"package",
",",
"fqdn",
",",
"result",
",",
"entry",
",",
"bound",
",",
"ekey",
",",
"argl",
",",
"argd",
")",
":",
"from",
"time",
"import",
"time",
"if",
"not",
"atdepth",
"and",
"entry",
"is",
"not",
"None",
":",
"ek",
"=",
"ekey",
"if",
"result",
"is",
"not",
"None",
":",
"retid",
"=",
"_tracker_str",
"(",
"result",
")",
"if",
"result",
"is",
"not",
"None",
"and",
"not",
"bound",
":",
"ek",
"=",
"retid",
"entry",
"[",
"\"r\"",
"]",
"=",
"None",
"else",
":",
"entry",
"[",
"\"r\"",
"]",
"=",
"retid",
"name",
"=",
"fqdn",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"if",
"filter_name",
"(",
"fqdn",
",",
"package",
",",
"\"time\"",
")",
":",
"entry",
"[",
"\"e\"",
"]",
"=",
"time",
"(",
")",
"-",
"entry",
"[",
"\"s\"",
"]",
"if",
"filter_name",
"(",
"fqdn",
",",
"package",
",",
"\"analyze\"",
")",
":",
"entry",
"[",
"\"z\"",
"]",
"=",
"analyze",
"(",
"fqdn",
",",
"result",
",",
"argl",
",",
"argd",
")",
"msg",
".",
"info",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"ek",
",",
"entry",
")",
",",
"1",
")",
"# Before we return the result, let's first save this call to the",
"# database so we have a record of it.",
"record",
"(",
"ek",
",",
"entry",
")",
"return",
"(",
"ek",
",",
"entry",
")",
"else",
":",
"return",
"(",
"None",
",",
"None",
")"
] |
Finishes constructing the log and records it to the database.
|
[
"Finishes",
"constructing",
"the",
"log",
"and",
"records",
"it",
"to",
"the",
"database",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L558-L584
|
245,314
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
post
|
def post(fqdn, package, result, entry, bound, ekey, *argl, **argd):
"""Adds logging for the post-call result of calling the method externally.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
package (str): name of the package we are logging for. Usually the first
element of `fqdn.split('.')`.
result: returned from calling the method we are logging.
entry (dict): one of the values returned by :func:`pre`.
bound (bool): true if the method is bound.
ekey (str): key under which to store the entry in the database.
"""
global _atdepth_call, _cstack_call
_cstack_call.pop()
if len(_cstack_call) == 0:
_atdepth_call = False
r = _post_call(_atdepth_call, package, fqdn, result,
entry, bound, ekey, argl, argd)
return r
|
python
|
def post(fqdn, package, result, entry, bound, ekey, *argl, **argd):
"""Adds logging for the post-call result of calling the method externally.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
package (str): name of the package we are logging for. Usually the first
element of `fqdn.split('.')`.
result: returned from calling the method we are logging.
entry (dict): one of the values returned by :func:`pre`.
bound (bool): true if the method is bound.
ekey (str): key under which to store the entry in the database.
"""
global _atdepth_call, _cstack_call
_cstack_call.pop()
if len(_cstack_call) == 0:
_atdepth_call = False
r = _post_call(_atdepth_call, package, fqdn, result,
entry, bound, ekey, argl, argd)
return r
|
[
"def",
"post",
"(",
"fqdn",
",",
"package",
",",
"result",
",",
"entry",
",",
"bound",
",",
"ekey",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"global",
"_atdepth_call",
",",
"_cstack_call",
"_cstack_call",
".",
"pop",
"(",
")",
"if",
"len",
"(",
"_cstack_call",
")",
"==",
"0",
":",
"_atdepth_call",
"=",
"False",
"r",
"=",
"_post_call",
"(",
"_atdepth_call",
",",
"package",
",",
"fqdn",
",",
"result",
",",
"entry",
",",
"bound",
",",
"ekey",
",",
"argl",
",",
"argd",
")",
"return",
"r"
] |
Adds logging for the post-call result of calling the method externally.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
package (str): name of the package we are logging for. Usually the first
element of `fqdn.split('.')`.
result: returned from calling the method we are logging.
entry (dict): one of the values returned by :func:`pre`.
bound (bool): true if the method is bound.
ekey (str): key under which to store the entry in the database.
|
[
"Adds",
"logging",
"for",
"the",
"post",
"-",
"call",
"result",
"of",
"calling",
"the",
"method",
"externally",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L586-L604
|
245,315
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
pre
|
def pre(fqdn, parent, stackdepth, *argl, **argd):
"""Adds logging for a call to the specified function that is being handled
by an external module.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
parent: *object* that the function belongs to.
stackdepth (int): maximum stack depth before entries are ignored.
argl (list): positional arguments passed to the function call.
argd (dict): keyword arguments passed to the function call.
"""
global _atdepth_call, _cstack_call
#We add +1 to stackdepth because this method had to be called in
#addition to the wrapper method, so we would be off by 1.
pcres = _pre_call(_atdepth_call, parent, fqdn, stackdepth+1,
*argl, **argd)
entry, _atdepth_call, reduced, bound, ekey = pcres
_cstack_call.append(fqdn)
return (entry, bound, ekey)
|
python
|
def pre(fqdn, parent, stackdepth, *argl, **argd):
"""Adds logging for a call to the specified function that is being handled
by an external module.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
parent: *object* that the function belongs to.
stackdepth (int): maximum stack depth before entries are ignored.
argl (list): positional arguments passed to the function call.
argd (dict): keyword arguments passed to the function call.
"""
global _atdepth_call, _cstack_call
#We add +1 to stackdepth because this method had to be called in
#addition to the wrapper method, so we would be off by 1.
pcres = _pre_call(_atdepth_call, parent, fqdn, stackdepth+1,
*argl, **argd)
entry, _atdepth_call, reduced, bound, ekey = pcres
_cstack_call.append(fqdn)
return (entry, bound, ekey)
|
[
"def",
"pre",
"(",
"fqdn",
",",
"parent",
",",
"stackdepth",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"global",
"_atdepth_call",
",",
"_cstack_call",
"#We add +1 to stackdepth because this method had to be called in",
"#addition to the wrapper method, so we would be off by 1.",
"pcres",
"=",
"_pre_call",
"(",
"_atdepth_call",
",",
"parent",
",",
"fqdn",
",",
"stackdepth",
"+",
"1",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
"entry",
",",
"_atdepth_call",
",",
"reduced",
",",
"bound",
",",
"ekey",
"=",
"pcres",
"_cstack_call",
".",
"append",
"(",
"fqdn",
")",
"return",
"(",
"entry",
",",
"bound",
",",
"ekey",
")"
] |
Adds logging for a call to the specified function that is being handled
by an external module.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
parent: *object* that the function belongs to.
stackdepth (int): maximum stack depth before entries are ignored.
argl (list): positional arguments passed to the function call.
argd (dict): keyword arguments passed to the function call.
|
[
"Adds",
"logging",
"for",
"a",
"call",
"to",
"the",
"specified",
"function",
"that",
"is",
"being",
"handled",
"by",
"an",
"external",
"module",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L606-L624
|
245,316
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_create_extension
|
def _create_extension(o, otype, fqdn, pmodule):
"""Creates an extension object to represent `o` that can have attributes
set, but which behaves identically to the given object.
Args:
o: object to create an extension for; no checks are performed to see if
extension is actually required.
otype (str): object types; one of ["classes", "functions", "methods",
"modules"].
fqdn (str): fully qualified name of the package that the object belongs
to.
pmodule: the parent module (or class) that `o` belongs to; used for setting
the special __module__ attribute.
"""
import types
xdict = {"__acornext__": o,
"__doc__": o.__doc__}
if otype == "classes":
classname = o.__name__
try:
if fqdn in _explicit_subclasses:
xclass = eval(_explicit_subclasses[fqdn])
xclass.__acornext__ = o
else:
xclass = type(classname, (o, ), xdict)
xclass.__module__ = o.__module__
return xclass
except TypeError:
#This happens when a class is final, meaning that it is not allowed
#to be subclassed.
_final_objs.append(id(o))
return o
elif (otype in ["functions", "descriptors", "unknowns"] or
(otype == "builtins" and (isinstance(o, types.BuiltinFunctionType) or
isinstance(o, types.BuiltinMethodType)))):
#The unknowns type is for objects that don't match any of the
#inspect.is* function calls, but still have a __call__ method (such as
#the numpy.ufunc class instances). These can still be wrapped by another
#function.
def xwrapper(*args, **kwargs):
try:
return o(*args, **kwargs)
except:
#see issue #4.
targs = list(map(type, args))
kargs = list(kwargs.keys())
msg.err("xwrapper: {}({}, {})".format(o, targs, kargs), 2)
pass
#Set the docstring and original object attributes.
for attr, val in xdict.items():
setattr(xwrapper, attr, val)
#We want to get the members dictionary. For classes, using
#:meth:`inspect.getmembers` produces stack overflow errors. Instead, we
#reference the __dict__ directly. However, for built-in methods and
#functions, there is no __dict__, so we use `inspect.getmembers`.
failed = False
setattr(xwrapper, "__getattribute__", _safe_getattr(xwrapper))
#We want the new function to be identical to the old except that
#it's __call__ method, which we overrode above.
failed = not _update_attrs(xwrapper, o, ["__call__"])
if otype in ["descriptors", "unknowns"] and inspect.ismodule(pmodule):
if hasattr(o, "__objclass__"): # pragma: no cover
setattr(xwrapper, "__module__", pmodule.__name__)
elif hasattr(o, "__class__") and o.__class__ is not None:
setattr(xwrapper, "__module__", pmodule.__name__)
if not failed:
return xwrapper
|
python
|
def _create_extension(o, otype, fqdn, pmodule):
"""Creates an extension object to represent `o` that can have attributes
set, but which behaves identically to the given object.
Args:
o: object to create an extension for; no checks are performed to see if
extension is actually required.
otype (str): object types; one of ["classes", "functions", "methods",
"modules"].
fqdn (str): fully qualified name of the package that the object belongs
to.
pmodule: the parent module (or class) that `o` belongs to; used for setting
the special __module__ attribute.
"""
import types
xdict = {"__acornext__": o,
"__doc__": o.__doc__}
if otype == "classes":
classname = o.__name__
try:
if fqdn in _explicit_subclasses:
xclass = eval(_explicit_subclasses[fqdn])
xclass.__acornext__ = o
else:
xclass = type(classname, (o, ), xdict)
xclass.__module__ = o.__module__
return xclass
except TypeError:
#This happens when a class is final, meaning that it is not allowed
#to be subclassed.
_final_objs.append(id(o))
return o
elif (otype in ["functions", "descriptors", "unknowns"] or
(otype == "builtins" and (isinstance(o, types.BuiltinFunctionType) or
isinstance(o, types.BuiltinMethodType)))):
#The unknowns type is for objects that don't match any of the
#inspect.is* function calls, but still have a __call__ method (such as
#the numpy.ufunc class instances). These can still be wrapped by another
#function.
def xwrapper(*args, **kwargs):
try:
return o(*args, **kwargs)
except:
#see issue #4.
targs = list(map(type, args))
kargs = list(kwargs.keys())
msg.err("xwrapper: {}({}, {})".format(o, targs, kargs), 2)
pass
#Set the docstring and original object attributes.
for attr, val in xdict.items():
setattr(xwrapper, attr, val)
#We want to get the members dictionary. For classes, using
#:meth:`inspect.getmembers` produces stack overflow errors. Instead, we
#reference the __dict__ directly. However, for built-in methods and
#functions, there is no __dict__, so we use `inspect.getmembers`.
failed = False
setattr(xwrapper, "__getattribute__", _safe_getattr(xwrapper))
#We want the new function to be identical to the old except that
#it's __call__ method, which we overrode above.
failed = not _update_attrs(xwrapper, o, ["__call__"])
if otype in ["descriptors", "unknowns"] and inspect.ismodule(pmodule):
if hasattr(o, "__objclass__"): # pragma: no cover
setattr(xwrapper, "__module__", pmodule.__name__)
elif hasattr(o, "__class__") and o.__class__ is not None:
setattr(xwrapper, "__module__", pmodule.__name__)
if not failed:
return xwrapper
|
[
"def",
"_create_extension",
"(",
"o",
",",
"otype",
",",
"fqdn",
",",
"pmodule",
")",
":",
"import",
"types",
"xdict",
"=",
"{",
"\"__acornext__\"",
":",
"o",
",",
"\"__doc__\"",
":",
"o",
".",
"__doc__",
"}",
"if",
"otype",
"==",
"\"classes\"",
":",
"classname",
"=",
"o",
".",
"__name__",
"try",
":",
"if",
"fqdn",
"in",
"_explicit_subclasses",
":",
"xclass",
"=",
"eval",
"(",
"_explicit_subclasses",
"[",
"fqdn",
"]",
")",
"xclass",
".",
"__acornext__",
"=",
"o",
"else",
":",
"xclass",
"=",
"type",
"(",
"classname",
",",
"(",
"o",
",",
")",
",",
"xdict",
")",
"xclass",
".",
"__module__",
"=",
"o",
".",
"__module__",
"return",
"xclass",
"except",
"TypeError",
":",
"#This happens when a class is final, meaning that it is not allowed",
"#to be subclassed.",
"_final_objs",
".",
"append",
"(",
"id",
"(",
"o",
")",
")",
"return",
"o",
"elif",
"(",
"otype",
"in",
"[",
"\"functions\"",
",",
"\"descriptors\"",
",",
"\"unknowns\"",
"]",
"or",
"(",
"otype",
"==",
"\"builtins\"",
"and",
"(",
"isinstance",
"(",
"o",
",",
"types",
".",
"BuiltinFunctionType",
")",
"or",
"isinstance",
"(",
"o",
",",
"types",
".",
"BuiltinMethodType",
")",
")",
")",
")",
":",
"#The unknowns type is for objects that don't match any of the",
"#inspect.is* function calls, but still have a __call__ method (such as",
"#the numpy.ufunc class instances). These can still be wrapped by another",
"#function.",
"def",
"xwrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"o",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"#see issue #4.",
"targs",
"=",
"list",
"(",
"map",
"(",
"type",
",",
"args",
")",
")",
"kargs",
"=",
"list",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"msg",
".",
"err",
"(",
"\"xwrapper: {}({}, {})\"",
".",
"format",
"(",
"o",
",",
"targs",
",",
"kargs",
")",
",",
"2",
")",
"pass",
"#Set the docstring and original object attributes.",
"for",
"attr",
",",
"val",
"in",
"xdict",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"xwrapper",
",",
"attr",
",",
"val",
")",
"#We want to get the members dictionary. For classes, using",
"#:meth:`inspect.getmembers` produces stack overflow errors. Instead, we",
"#reference the __dict__ directly. However, for built-in methods and",
"#functions, there is no __dict__, so we use `inspect.getmembers`.",
"failed",
"=",
"False",
"setattr",
"(",
"xwrapper",
",",
"\"__getattribute__\"",
",",
"_safe_getattr",
"(",
"xwrapper",
")",
")",
"#We want the new function to be identical to the old except that",
"#it's __call__ method, which we overrode above.",
"failed",
"=",
"not",
"_update_attrs",
"(",
"xwrapper",
",",
"o",
",",
"[",
"\"__call__\"",
"]",
")",
"if",
"otype",
"in",
"[",
"\"descriptors\"",
",",
"\"unknowns\"",
"]",
"and",
"inspect",
".",
"ismodule",
"(",
"pmodule",
")",
":",
"if",
"hasattr",
"(",
"o",
",",
"\"__objclass__\"",
")",
":",
"# pragma: no cover",
"setattr",
"(",
"xwrapper",
",",
"\"__module__\"",
",",
"pmodule",
".",
"__name__",
")",
"elif",
"hasattr",
"(",
"o",
",",
"\"__class__\"",
")",
"and",
"o",
".",
"__class__",
"is",
"not",
"None",
":",
"setattr",
"(",
"xwrapper",
",",
"\"__module__\"",
",",
"pmodule",
".",
"__name__",
")",
"if",
"not",
"failed",
":",
"return",
"xwrapper"
] |
Creates an extension object to represent `o` that can have attributes
set, but which behaves identically to the given object.
Args:
o: object to create an extension for; no checks are performed to see if
extension is actually required.
otype (str): object types; one of ["classes", "functions", "methods",
"modules"].
fqdn (str): fully qualified name of the package that the object belongs
to.
pmodule: the parent module (or class) that `o` belongs to; used for setting
the special __module__ attribute.
|
[
"Creates",
"an",
"extension",
"object",
"to",
"represent",
"o",
"that",
"can",
"have",
"attributes",
"set",
"but",
"which",
"behaves",
"identically",
"to",
"the",
"given",
"object",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L739-L811
|
245,317
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_extend_object
|
def _extend_object(parent, n, o, otype, fqdn):
"""Extends the specified object if it needs to be extended. The method
attempts to add an attribute to the object; if it fails, a new object is
created that inherits all of `o` attributes, but is now a regular object
that can have attributes set.
Args:
parent: has `n` in its `__dict__` attribute.
n (str): object name attribute.
o (list): object instances to be extended.
otype (str): object types; one of ["classes", "functions", "methods",
"modules"].
fqdn (str): fully qualified name of the package that the object belongs
to.
"""
from inspect import ismodule, isclass
pmodule = parent if ismodule(parent) or isclass(parent) else None
try:
#The __acornext__ attribute references the original, unextended
#object; if the object didn't need extended, then __acornext__ is
#none.
if otype == "methods":
setattr(o.__func__, "__acornext__", None)
else:
setattr(o, "__acornext__", None)
fqdn = _fqdn(o, recheck=True, pmodule=pmodule)
return o
except (TypeError, AttributeError):
#We have a built-in or extension type.
okey = id(o)
if okey not in _extended_objs:
#We need to generate an extension for this object and store it
#in the extensions dict.
xobj = _create_extension(o, otype, fqdn, pmodule)
fqdn = _fqdn(xobj, recheck=True, pmodule=pmodule)
if xobj is not None:
_extended_objs[okey] = xobj
#else: we can't handle this kind of object; it just won't be
#logged...
try:
setattr(parent, n, _extended_objs[okey])
return _extended_objs[okey]
except KeyError: # pragma: no cover
msg.warn("Object extension failed: {} ({}).".format(o, otype))
|
python
|
def _extend_object(parent, n, o, otype, fqdn):
"""Extends the specified object if it needs to be extended. The method
attempts to add an attribute to the object; if it fails, a new object is
created that inherits all of `o` attributes, but is now a regular object
that can have attributes set.
Args:
parent: has `n` in its `__dict__` attribute.
n (str): object name attribute.
o (list): object instances to be extended.
otype (str): object types; one of ["classes", "functions", "methods",
"modules"].
fqdn (str): fully qualified name of the package that the object belongs
to.
"""
from inspect import ismodule, isclass
pmodule = parent if ismodule(parent) or isclass(parent) else None
try:
#The __acornext__ attribute references the original, unextended
#object; if the object didn't need extended, then __acornext__ is
#none.
if otype == "methods":
setattr(o.__func__, "__acornext__", None)
else:
setattr(o, "__acornext__", None)
fqdn = _fqdn(o, recheck=True, pmodule=pmodule)
return o
except (TypeError, AttributeError):
#We have a built-in or extension type.
okey = id(o)
if okey not in _extended_objs:
#We need to generate an extension for this object and store it
#in the extensions dict.
xobj = _create_extension(o, otype, fqdn, pmodule)
fqdn = _fqdn(xobj, recheck=True, pmodule=pmodule)
if xobj is not None:
_extended_objs[okey] = xobj
#else: we can't handle this kind of object; it just won't be
#logged...
try:
setattr(parent, n, _extended_objs[okey])
return _extended_objs[okey]
except KeyError: # pragma: no cover
msg.warn("Object extension failed: {} ({}).".format(o, otype))
|
[
"def",
"_extend_object",
"(",
"parent",
",",
"n",
",",
"o",
",",
"otype",
",",
"fqdn",
")",
":",
"from",
"inspect",
"import",
"ismodule",
",",
"isclass",
"pmodule",
"=",
"parent",
"if",
"ismodule",
"(",
"parent",
")",
"or",
"isclass",
"(",
"parent",
")",
"else",
"None",
"try",
":",
"#The __acornext__ attribute references the original, unextended",
"#object; if the object didn't need extended, then __acornext__ is",
"#none.",
"if",
"otype",
"==",
"\"methods\"",
":",
"setattr",
"(",
"o",
".",
"__func__",
",",
"\"__acornext__\"",
",",
"None",
")",
"else",
":",
"setattr",
"(",
"o",
",",
"\"__acornext__\"",
",",
"None",
")",
"fqdn",
"=",
"_fqdn",
"(",
"o",
",",
"recheck",
"=",
"True",
",",
"pmodule",
"=",
"pmodule",
")",
"return",
"o",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"#We have a built-in or extension type. ",
"okey",
"=",
"id",
"(",
"o",
")",
"if",
"okey",
"not",
"in",
"_extended_objs",
":",
"#We need to generate an extension for this object and store it",
"#in the extensions dict.",
"xobj",
"=",
"_create_extension",
"(",
"o",
",",
"otype",
",",
"fqdn",
",",
"pmodule",
")",
"fqdn",
"=",
"_fqdn",
"(",
"xobj",
",",
"recheck",
"=",
"True",
",",
"pmodule",
"=",
"pmodule",
")",
"if",
"xobj",
"is",
"not",
"None",
":",
"_extended_objs",
"[",
"okey",
"]",
"=",
"xobj",
"#else: we can't handle this kind of object; it just won't be",
"#logged...",
"try",
":",
"setattr",
"(",
"parent",
",",
"n",
",",
"_extended_objs",
"[",
"okey",
"]",
")",
"return",
"_extended_objs",
"[",
"okey",
"]",
"except",
"KeyError",
":",
"# pragma: no cover",
"msg",
".",
"warn",
"(",
"\"Object extension failed: {} ({}).\"",
".",
"format",
"(",
"o",
",",
"otype",
")",
")"
] |
Extends the specified object if it needs to be extended. The method
attempts to add an attribute to the object; if it fails, a new object is
created that inherits all of `o` attributes, but is now a regular object
that can have attributes set.
Args:
parent: has `n` in its `__dict__` attribute.
n (str): object name attribute.
o (list): object instances to be extended.
otype (str): object types; one of ["classes", "functions", "methods",
"modules"].
fqdn (str): fully qualified name of the package that the object belongs
to.
|
[
"Extends",
"the",
"specified",
"object",
"if",
"it",
"needs",
"to",
"be",
"extended",
".",
"The",
"method",
"attempts",
"to",
"add",
"an",
"attribute",
"to",
"the",
"object",
";",
"if",
"it",
"fails",
"a",
"new",
"object",
"is",
"created",
"that",
"inherits",
"all",
"of",
"o",
"attributes",
"but",
"is",
"now",
"a",
"regular",
"object",
"that",
"can",
"have",
"attributes",
"set",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L851-L895
|
245,318
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_fqdn
|
def _fqdn(o, oset=True, recheck=False, pmodule=None):
"""Returns the fully qualified name of the object.
Args:
o (type): instance of the object's type.
oset (bool): when True, the fqdn will also be set on the object as attribute
`__fqdn__`.
recheck (bool): for sub-classes, sometimes the super class has already had
its __fqdn__ attribute set; in that case, we want to recheck the
object's name. This usually only gets used during object extension.
"""
if id(o) in _set_failures or o is None:
return None
if recheck or not _safe_hasattr(o, "__fqdn__"):
import inspect
if not hasattr(o, "__name__"):
msg.warn("Skipped object {}: no __name__ attribute.".format(o), 3)
return
result = None
if hasattr(o, "__acornext__") and o.__acornext__ is not None:
otarget = o.__acornext__
else:
otarget = o
omod = _safe_getmodule(otarget) or pmodule
if (omod is None and hasattr(otarget, "__objclass__") and
otarget.__objclass__ is not None): # pragma: no cover
omod = _safe_getmodule(otarget.__objclass__)
parts = ("<unknown>" if omod is None else omod.__name__,
otarget.__objclass__.__name__,
otarget.__name__)
#msg.std("FQDN: objclass => {}".format(parts), 4)
result = "{}.{}.{}".format(*parts)
elif (omod is None and hasattr(otarget, "__class__") and
otarget.__class__ is not None):
omod = _safe_getmodule(otarget.__class__)
parts = ("<unknown>" if omod is None else omod.__name__,
otarget.__class__.__name__,
otarget.__name__)
#msg.std("FQDN: class => {}".format(parts), 4)
result = "{}.{}.{}".format(*parts)
elif omod is not otarget:
parts = (_fqdn(omod, False), otarget.__name__)
#msg.std("FQDN: o => {}".format(parts), 4)
result = "{}.{}".format(*parts)
else:
result = otarget.__name__
if oset:
_safe_setattr(o, "__fqdn__", result)
return result
if _safe_hasattr(o, "__fqdn__"):
return o.__fqdn__
|
python
|
def _fqdn(o, oset=True, recheck=False, pmodule=None):
"""Returns the fully qualified name of the object.
Args:
o (type): instance of the object's type.
oset (bool): when True, the fqdn will also be set on the object as attribute
`__fqdn__`.
recheck (bool): for sub-classes, sometimes the super class has already had
its __fqdn__ attribute set; in that case, we want to recheck the
object's name. This usually only gets used during object extension.
"""
if id(o) in _set_failures or o is None:
return None
if recheck or not _safe_hasattr(o, "__fqdn__"):
import inspect
if not hasattr(o, "__name__"):
msg.warn("Skipped object {}: no __name__ attribute.".format(o), 3)
return
result = None
if hasattr(o, "__acornext__") and o.__acornext__ is not None:
otarget = o.__acornext__
else:
otarget = o
omod = _safe_getmodule(otarget) or pmodule
if (omod is None and hasattr(otarget, "__objclass__") and
otarget.__objclass__ is not None): # pragma: no cover
omod = _safe_getmodule(otarget.__objclass__)
parts = ("<unknown>" if omod is None else omod.__name__,
otarget.__objclass__.__name__,
otarget.__name__)
#msg.std("FQDN: objclass => {}".format(parts), 4)
result = "{}.{}.{}".format(*parts)
elif (omod is None and hasattr(otarget, "__class__") and
otarget.__class__ is not None):
omod = _safe_getmodule(otarget.__class__)
parts = ("<unknown>" if omod is None else omod.__name__,
otarget.__class__.__name__,
otarget.__name__)
#msg.std("FQDN: class => {}".format(parts), 4)
result = "{}.{}.{}".format(*parts)
elif omod is not otarget:
parts = (_fqdn(omod, False), otarget.__name__)
#msg.std("FQDN: o => {}".format(parts), 4)
result = "{}.{}".format(*parts)
else:
result = otarget.__name__
if oset:
_safe_setattr(o, "__fqdn__", result)
return result
if _safe_hasattr(o, "__fqdn__"):
return o.__fqdn__
|
[
"def",
"_fqdn",
"(",
"o",
",",
"oset",
"=",
"True",
",",
"recheck",
"=",
"False",
",",
"pmodule",
"=",
"None",
")",
":",
"if",
"id",
"(",
"o",
")",
"in",
"_set_failures",
"or",
"o",
"is",
"None",
":",
"return",
"None",
"if",
"recheck",
"or",
"not",
"_safe_hasattr",
"(",
"o",
",",
"\"__fqdn__\"",
")",
":",
"import",
"inspect",
"if",
"not",
"hasattr",
"(",
"o",
",",
"\"__name__\"",
")",
":",
"msg",
".",
"warn",
"(",
"\"Skipped object {}: no __name__ attribute.\"",
".",
"format",
"(",
"o",
")",
",",
"3",
")",
"return",
"result",
"=",
"None",
"if",
"hasattr",
"(",
"o",
",",
"\"__acornext__\"",
")",
"and",
"o",
".",
"__acornext__",
"is",
"not",
"None",
":",
"otarget",
"=",
"o",
".",
"__acornext__",
"else",
":",
"otarget",
"=",
"o",
"omod",
"=",
"_safe_getmodule",
"(",
"otarget",
")",
"or",
"pmodule",
"if",
"(",
"omod",
"is",
"None",
"and",
"hasattr",
"(",
"otarget",
",",
"\"__objclass__\"",
")",
"and",
"otarget",
".",
"__objclass__",
"is",
"not",
"None",
")",
":",
"# pragma: no cover",
"omod",
"=",
"_safe_getmodule",
"(",
"otarget",
".",
"__objclass__",
")",
"parts",
"=",
"(",
"\"<unknown>\"",
"if",
"omod",
"is",
"None",
"else",
"omod",
".",
"__name__",
",",
"otarget",
".",
"__objclass__",
".",
"__name__",
",",
"otarget",
".",
"__name__",
")",
"#msg.std(\"FQDN: objclass => {}\".format(parts), 4)",
"result",
"=",
"\"{}.{}.{}\"",
".",
"format",
"(",
"*",
"parts",
")",
"elif",
"(",
"omod",
"is",
"None",
"and",
"hasattr",
"(",
"otarget",
",",
"\"__class__\"",
")",
"and",
"otarget",
".",
"__class__",
"is",
"not",
"None",
")",
":",
"omod",
"=",
"_safe_getmodule",
"(",
"otarget",
".",
"__class__",
")",
"parts",
"=",
"(",
"\"<unknown>\"",
"if",
"omod",
"is",
"None",
"else",
"omod",
".",
"__name__",
",",
"otarget",
".",
"__class__",
".",
"__name__",
",",
"otarget",
".",
"__name__",
")",
"#msg.std(\"FQDN: class => {}\".format(parts), 4)",
"result",
"=",
"\"{}.{}.{}\"",
".",
"format",
"(",
"*",
"parts",
")",
"elif",
"omod",
"is",
"not",
"otarget",
":",
"parts",
"=",
"(",
"_fqdn",
"(",
"omod",
",",
"False",
")",
",",
"otarget",
".",
"__name__",
")",
"#msg.std(\"FQDN: o => {}\".format(parts), 4)",
"result",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"*",
"parts",
")",
"else",
":",
"result",
"=",
"otarget",
".",
"__name__",
"if",
"oset",
":",
"_safe_setattr",
"(",
"o",
",",
"\"__fqdn__\"",
",",
"result",
")",
"return",
"result",
"if",
"_safe_hasattr",
"(",
"o",
",",
"\"__fqdn__\"",
")",
":",
"return",
"o",
".",
"__fqdn__"
] |
Returns the fully qualified name of the object.
Args:
o (type): instance of the object's type.
oset (bool): when True, the fqdn will also be set on the object as attribute
`__fqdn__`.
recheck (bool): for sub-classes, sometimes the super class has already had
its __fqdn__ attribute set; in that case, we want to recheck the
object's name. This usually only gets used during object extension.
|
[
"Returns",
"the",
"fully",
"qualified",
"name",
"of",
"the",
"object",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1063-L1118
|
245,319
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_get_stack_depth
|
def _get_stack_depth(package, fqdn, defdepth=_def_stackdepth):
"""Loads the stack depth settings from the config file for the specified
package.
Args:
package (str): name of the package to get stack depth info for.
fqdn (str): fully qualified domain name of the member in the package.
defdepth (int): default depth when one has not been configured.
"""
global _stack_config
if package not in _stack_config:
from acorn.config import settings
spack = settings(package)
_stack_config[package] = {}
secname = "logging.depth"
if spack.has_section(secname):
for ofqdn in spack.options(secname):
_stack_config[package][ofqdn] = spack.getint(secname, ofqdn)
usedef = True
if fqdn in _stack_config[package]:
result = _stack_config[package][fqdn]
usedef = False
elif "*" in _stack_config[package]: # pragma: no cover
result = _stack_config[package]["*"]
usedef = False
else:
result = defdepth
if not usedef:
msg.gen("Using {} for {} stack depth.".format(result, fqdn), 3)
return result
|
python
|
def _get_stack_depth(package, fqdn, defdepth=_def_stackdepth):
"""Loads the stack depth settings from the config file for the specified
package.
Args:
package (str): name of the package to get stack depth info for.
fqdn (str): fully qualified domain name of the member in the package.
defdepth (int): default depth when one has not been configured.
"""
global _stack_config
if package not in _stack_config:
from acorn.config import settings
spack = settings(package)
_stack_config[package] = {}
secname = "logging.depth"
if spack.has_section(secname):
for ofqdn in spack.options(secname):
_stack_config[package][ofqdn] = spack.getint(secname, ofqdn)
usedef = True
if fqdn in _stack_config[package]:
result = _stack_config[package][fqdn]
usedef = False
elif "*" in _stack_config[package]: # pragma: no cover
result = _stack_config[package]["*"]
usedef = False
else:
result = defdepth
if not usedef:
msg.gen("Using {} for {} stack depth.".format(result, fqdn), 3)
return result
|
[
"def",
"_get_stack_depth",
"(",
"package",
",",
"fqdn",
",",
"defdepth",
"=",
"_def_stackdepth",
")",
":",
"global",
"_stack_config",
"if",
"package",
"not",
"in",
"_stack_config",
":",
"from",
"acorn",
".",
"config",
"import",
"settings",
"spack",
"=",
"settings",
"(",
"package",
")",
"_stack_config",
"[",
"package",
"]",
"=",
"{",
"}",
"secname",
"=",
"\"logging.depth\"",
"if",
"spack",
".",
"has_section",
"(",
"secname",
")",
":",
"for",
"ofqdn",
"in",
"spack",
".",
"options",
"(",
"secname",
")",
":",
"_stack_config",
"[",
"package",
"]",
"[",
"ofqdn",
"]",
"=",
"spack",
".",
"getint",
"(",
"secname",
",",
"ofqdn",
")",
"usedef",
"=",
"True",
"if",
"fqdn",
"in",
"_stack_config",
"[",
"package",
"]",
":",
"result",
"=",
"_stack_config",
"[",
"package",
"]",
"[",
"fqdn",
"]",
"usedef",
"=",
"False",
"elif",
"\"*\"",
"in",
"_stack_config",
"[",
"package",
"]",
":",
"# pragma: no cover",
"result",
"=",
"_stack_config",
"[",
"package",
"]",
"[",
"\"*\"",
"]",
"usedef",
"=",
"False",
"else",
":",
"result",
"=",
"defdepth",
"if",
"not",
"usedef",
":",
"msg",
".",
"gen",
"(",
"\"Using {} for {} stack depth.\"",
".",
"format",
"(",
"result",
",",
"fqdn",
")",
",",
"3",
")",
"return",
"result"
] |
Loads the stack depth settings from the config file for the specified
package.
Args:
package (str): name of the package to get stack depth info for.
fqdn (str): fully qualified domain name of the member in the package.
defdepth (int): default depth when one has not been configured.
|
[
"Loads",
"the",
"stack",
"depth",
"settings",
"from",
"the",
"config",
"file",
"for",
"the",
"specified",
"package",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1124-L1156
|
245,320
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_load_subclasses
|
def _load_subclasses(package):
"""Loads the subclass settings for the specified package so that we can
decorate the classes correctly.
"""
global _explicit_subclasses
from acorn.config import settings
spack = settings(package)
if spack is not None:
if spack.has_section("subclass"):
_explicit_subclasses.update(dict(spack.items("subclass")))
|
python
|
def _load_subclasses(package):
"""Loads the subclass settings for the specified package so that we can
decorate the classes correctly.
"""
global _explicit_subclasses
from acorn.config import settings
spack = settings(package)
if spack is not None:
if spack.has_section("subclass"):
_explicit_subclasses.update(dict(spack.items("subclass")))
|
[
"def",
"_load_subclasses",
"(",
"package",
")",
":",
"global",
"_explicit_subclasses",
"from",
"acorn",
".",
"config",
"import",
"settings",
"spack",
"=",
"settings",
"(",
"package",
")",
"if",
"spack",
"is",
"not",
"None",
":",
"if",
"spack",
".",
"has_section",
"(",
"\"subclass\"",
")",
":",
"_explicit_subclasses",
".",
"update",
"(",
"dict",
"(",
"spack",
".",
"items",
"(",
"\"subclass\"",
")",
")",
")"
] |
Loads the subclass settings for the specified package so that we can
decorate the classes correctly.
|
[
"Loads",
"the",
"subclass",
"settings",
"for",
"the",
"specified",
"package",
"so",
"that",
"we",
"can",
"decorate",
"the",
"classes",
"correctly",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1278-L1287
|
245,321
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
_load_callwraps
|
def _load_callwraps(packname, package):
"""Loads the special call wrapping settings for functions in the specified
package. This allows the result of the original method call to be cast as a
different type, or passed to a different constructor before returning from
the wrapped function.
Args:
packname (str): name of the package to get config settings for.
package: actual package object.
"""
global _callwraps
from acorn.config import settings
from acorn.logging.descriptors import _obj_getattr
spack = settings(packname)
if spack is not None:
if spack.has_section("callwrap"):
wrappings = dict(spack.items("callwrap"))
for fqdn, target in wrappings.items():
caller = _obj_getattr(package, target)
_callwraps[fqdn] = caller
|
python
|
def _load_callwraps(packname, package):
"""Loads the special call wrapping settings for functions in the specified
package. This allows the result of the original method call to be cast as a
different type, or passed to a different constructor before returning from
the wrapped function.
Args:
packname (str): name of the package to get config settings for.
package: actual package object.
"""
global _callwraps
from acorn.config import settings
from acorn.logging.descriptors import _obj_getattr
spack = settings(packname)
if spack is not None:
if spack.has_section("callwrap"):
wrappings = dict(spack.items("callwrap"))
for fqdn, target in wrappings.items():
caller = _obj_getattr(package, target)
_callwraps[fqdn] = caller
|
[
"def",
"_load_callwraps",
"(",
"packname",
",",
"package",
")",
":",
"global",
"_callwraps",
"from",
"acorn",
".",
"config",
"import",
"settings",
"from",
"acorn",
".",
"logging",
".",
"descriptors",
"import",
"_obj_getattr",
"spack",
"=",
"settings",
"(",
"packname",
")",
"if",
"spack",
"is",
"not",
"None",
":",
"if",
"spack",
".",
"has_section",
"(",
"\"callwrap\"",
")",
":",
"wrappings",
"=",
"dict",
"(",
"spack",
".",
"items",
"(",
"\"callwrap\"",
")",
")",
"for",
"fqdn",
",",
"target",
"in",
"wrappings",
".",
"items",
"(",
")",
":",
"caller",
"=",
"_obj_getattr",
"(",
"package",
",",
"target",
")",
"_callwraps",
"[",
"fqdn",
"]",
"=",
"caller"
] |
Loads the special call wrapping settings for functions in the specified
package. This allows the result of the original method call to be cast as a
different type, or passed to a different constructor before returning from
the wrapped function.
Args:
packname (str): name of the package to get config settings for.
package: actual package object.
|
[
"Loads",
"the",
"special",
"call",
"wrapping",
"settings",
"for",
"functions",
"in",
"the",
"specified",
"package",
".",
"This",
"allows",
"the",
"result",
"of",
"the",
"original",
"method",
"call",
"to",
"be",
"cast",
"as",
"a",
"different",
"type",
"or",
"passed",
"to",
"a",
"different",
"constructor",
"before",
"returning",
"from",
"the",
"wrapped",
"function",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1342-L1361
|
245,322
|
rosenbrockc/acorn
|
acorn/logging/decoration.py
|
decorate
|
def decorate(package):
"""Decorates all the methods in the specified package to have logging
enabled according to the configuration for the package.
"""
from os import sep
global _decor_count, _decorated_packs, _decorated_o, _pack_paths
global decorating
if "acorn" not in _decorated_packs:
_decorated_packs.append("acorn")
packpath = "acorn{}".format(sep)
if packpath not in _pack_paths:
#We initialize _pack_paths to include common packages that people
#use without decorating. Otherwise those slow *way* down and the
#notebook becomes unusable.
_pack_paths.append(packpath)
npack = package.__name__
#Since scipy includes numpy (for example), we don't want to run the numpy
#decoration twice if the person also chooses to import numpy. In that case,
#we just skip it; the memory references in scipy point to the same numpy
#modules and libraries.
if npack not in _decorated_packs:
_decor_count[npack] = [0, 0, 0]
_decorated_o[npack] = {}
_load_subclasses(npack)
packsplit = _split_object(package, package.__name__)
origdecor = decorating
decorating = True
for ot, ol in packsplit.items():
for name, obj in ol:
decorate_obj(package, name, obj, ot)
#Now that we have actually decorated all the objects, we can load the
#call wraps to point to the new decorated objects.
_load_callwraps(npack, package)
_load_streamlines(npack, package)
_load_logging(npack, package)
decorating = origdecor
_decorated_packs.append(npack)
_pack_paths.append("{}{}".format(npack, sep))
msg.info("{}: {} (Decor/Skip/NA)".format(npack, _decor_count[npack]))
|
python
|
def decorate(package):
"""Decorates all the methods in the specified package to have logging
enabled according to the configuration for the package.
"""
from os import sep
global _decor_count, _decorated_packs, _decorated_o, _pack_paths
global decorating
if "acorn" not in _decorated_packs:
_decorated_packs.append("acorn")
packpath = "acorn{}".format(sep)
if packpath not in _pack_paths:
#We initialize _pack_paths to include common packages that people
#use without decorating. Otherwise those slow *way* down and the
#notebook becomes unusable.
_pack_paths.append(packpath)
npack = package.__name__
#Since scipy includes numpy (for example), we don't want to run the numpy
#decoration twice if the person also chooses to import numpy. In that case,
#we just skip it; the memory references in scipy point to the same numpy
#modules and libraries.
if npack not in _decorated_packs:
_decor_count[npack] = [0, 0, 0]
_decorated_o[npack] = {}
_load_subclasses(npack)
packsplit = _split_object(package, package.__name__)
origdecor = decorating
decorating = True
for ot, ol in packsplit.items():
for name, obj in ol:
decorate_obj(package, name, obj, ot)
#Now that we have actually decorated all the objects, we can load the
#call wraps to point to the new decorated objects.
_load_callwraps(npack, package)
_load_streamlines(npack, package)
_load_logging(npack, package)
decorating = origdecor
_decorated_packs.append(npack)
_pack_paths.append("{}{}".format(npack, sep))
msg.info("{}: {} (Decor/Skip/NA)".format(npack, _decor_count[npack]))
|
[
"def",
"decorate",
"(",
"package",
")",
":",
"from",
"os",
"import",
"sep",
"global",
"_decor_count",
",",
"_decorated_packs",
",",
"_decorated_o",
",",
"_pack_paths",
"global",
"decorating",
"if",
"\"acorn\"",
"not",
"in",
"_decorated_packs",
":",
"_decorated_packs",
".",
"append",
"(",
"\"acorn\"",
")",
"packpath",
"=",
"\"acorn{}\"",
".",
"format",
"(",
"sep",
")",
"if",
"packpath",
"not",
"in",
"_pack_paths",
":",
"#We initialize _pack_paths to include common packages that people",
"#use without decorating. Otherwise those slow *way* down and the",
"#notebook becomes unusable.",
"_pack_paths",
".",
"append",
"(",
"packpath",
")",
"npack",
"=",
"package",
".",
"__name__",
"#Since scipy includes numpy (for example), we don't want to run the numpy",
"#decoration twice if the person also chooses to import numpy. In that case,",
"#we just skip it; the memory references in scipy point to the same numpy",
"#modules and libraries.",
"if",
"npack",
"not",
"in",
"_decorated_packs",
":",
"_decor_count",
"[",
"npack",
"]",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"_decorated_o",
"[",
"npack",
"]",
"=",
"{",
"}",
"_load_subclasses",
"(",
"npack",
")",
"packsplit",
"=",
"_split_object",
"(",
"package",
",",
"package",
".",
"__name__",
")",
"origdecor",
"=",
"decorating",
"decorating",
"=",
"True",
"for",
"ot",
",",
"ol",
"in",
"packsplit",
".",
"items",
"(",
")",
":",
"for",
"name",
",",
"obj",
"in",
"ol",
":",
"decorate_obj",
"(",
"package",
",",
"name",
",",
"obj",
",",
"ot",
")",
"#Now that we have actually decorated all the objects, we can load the",
"#call wraps to point to the new decorated objects.",
"_load_callwraps",
"(",
"npack",
",",
"package",
")",
"_load_streamlines",
"(",
"npack",
",",
"package",
")",
"_load_logging",
"(",
"npack",
",",
"package",
")",
"decorating",
"=",
"origdecor",
"_decorated_packs",
".",
"append",
"(",
"npack",
")",
"_pack_paths",
".",
"append",
"(",
"\"{}{}\"",
".",
"format",
"(",
"npack",
",",
"sep",
")",
")",
"msg",
".",
"info",
"(",
"\"{}: {} (Decor/Skip/NA)\"",
".",
"format",
"(",
"npack",
",",
"_decor_count",
"[",
"npack",
"]",
")",
")"
] |
Decorates all the methods in the specified package to have logging
enabled according to the configuration for the package.
|
[
"Decorates",
"all",
"the",
"methods",
"in",
"the",
"specified",
"package",
"to",
"have",
"logging",
"enabled",
"according",
"to",
"the",
"configuration",
"for",
"the",
"package",
"."
] |
9a44d1a1ad8bfc2c54a6b56d9efe54433a797820
|
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L1375-L1417
|
245,323
|
twidi/py-dataql
|
dataql/parsers/mixins.py
|
NamedArgsParserMixin.visit_named_arg
|
def visit_named_arg(self, _, children):
"""Named argument of a filter.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: name of the arg
- 1: for ``WS`` (whitespace): ``None``.
- 2: operator
- 3: for ``WS`` (whitespace): ``None``.
- 4: value of the named arg
Returns
-------
.resources.NamedArg
Instance of ``.resources.NamedArg``.
Example
-------
>>> NamedArgsParserMixin(r'foo= 1', default_rule='NAMED_ARG').data
foo=1
>>> NamedArgsParserMixin(r'bar="BAZ"', default_rule='NAMED_ARG').data
bar="BAZ"
>>> NamedArgsParserMixin(r'quz=null', default_rule='NAMED_ARG').data
quz=None
>>> NamedArgsParserMixin(r'foo:TRUE', default_rule='NAMED_ARG').data
foo=True
>>> NamedArgsParserMixin(r'bar=False', default_rule='NAMED_ARG').data
bar=False
"""
return self.NamedArg(
arg=children[0],
arg_type=children[2],
value=children[4],
)
|
python
|
def visit_named_arg(self, _, children):
"""Named argument of a filter.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: name of the arg
- 1: for ``WS`` (whitespace): ``None``.
- 2: operator
- 3: for ``WS`` (whitespace): ``None``.
- 4: value of the named arg
Returns
-------
.resources.NamedArg
Instance of ``.resources.NamedArg``.
Example
-------
>>> NamedArgsParserMixin(r'foo= 1', default_rule='NAMED_ARG').data
foo=1
>>> NamedArgsParserMixin(r'bar="BAZ"', default_rule='NAMED_ARG').data
bar="BAZ"
>>> NamedArgsParserMixin(r'quz=null', default_rule='NAMED_ARG').data
quz=None
>>> NamedArgsParserMixin(r'foo:TRUE', default_rule='NAMED_ARG').data
foo=True
>>> NamedArgsParserMixin(r'bar=False', default_rule='NAMED_ARG').data
bar=False
"""
return self.NamedArg(
arg=children[0],
arg_type=children[2],
value=children[4],
)
|
[
"def",
"visit_named_arg",
"(",
"self",
",",
"_",
",",
"children",
")",
":",
"return",
"self",
".",
"NamedArg",
"(",
"arg",
"=",
"children",
"[",
"0",
"]",
",",
"arg_type",
"=",
"children",
"[",
"2",
"]",
",",
"value",
"=",
"children",
"[",
"4",
"]",
",",
")"
] |
Named argument of a filter.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: name of the arg
- 1: for ``WS`` (whitespace): ``None``.
- 2: operator
- 3: for ``WS`` (whitespace): ``None``.
- 4: value of the named arg
Returns
-------
.resources.NamedArg
Instance of ``.resources.NamedArg``.
Example
-------
>>> NamedArgsParserMixin(r'foo= 1', default_rule='NAMED_ARG').data
foo=1
>>> NamedArgsParserMixin(r'bar="BAZ"', default_rule='NAMED_ARG').data
bar="BAZ"
>>> NamedArgsParserMixin(r'quz=null', default_rule='NAMED_ARG').data
quz=None
>>> NamedArgsParserMixin(r'foo:TRUE', default_rule='NAMED_ARG').data
foo=True
>>> NamedArgsParserMixin(r'bar=False', default_rule='NAMED_ARG').data
bar=False
|
[
"Named",
"argument",
"of",
"a",
"filter",
"."
] |
5841a3fd559829193ed709c255166085bdde1c52
|
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/parsers/mixins.py#L179-L217
|
245,324
|
twidi/py-dataql
|
dataql/parsers/mixins.py
|
FiltersParserMixin.visit_filter
|
def visit_filter(self, _, children):
"""A filter, with optional arguments.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: string, name of the filter.
- 1: list of instances of ``.resources.NamedArg``
Returns
-------
.resources.Filter
An instance of ``.resources.Filter`` with a name and a list of arguments.
The list of arguments will be ``None`` if no parenthesis.
Example
-------
>>> FiltersParserMixin(r'foo', default_rule='FILTER').data
.foo
>>> FiltersParserMixin(r'foo()', default_rule='FILTER').data
.foo()
>>> FiltersParserMixin(r'foo(1)', default_rule='FILTER').data
.foo(1)
>>> FiltersParserMixin(r'foo(1, bar="baz")', default_rule='FILTER').data
.foo(1, bar="baz")
"""
return self.Filter(
name=children[0],
args=children[1],
)
|
python
|
def visit_filter(self, _, children):
"""A filter, with optional arguments.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: string, name of the filter.
- 1: list of instances of ``.resources.NamedArg``
Returns
-------
.resources.Filter
An instance of ``.resources.Filter`` with a name and a list of arguments.
The list of arguments will be ``None`` if no parenthesis.
Example
-------
>>> FiltersParserMixin(r'foo', default_rule='FILTER').data
.foo
>>> FiltersParserMixin(r'foo()', default_rule='FILTER').data
.foo()
>>> FiltersParserMixin(r'foo(1)', default_rule='FILTER').data
.foo(1)
>>> FiltersParserMixin(r'foo(1, bar="baz")', default_rule='FILTER').data
.foo(1, bar="baz")
"""
return self.Filter(
name=children[0],
args=children[1],
)
|
[
"def",
"visit_filter",
"(",
"self",
",",
"_",
",",
"children",
")",
":",
"return",
"self",
".",
"Filter",
"(",
"name",
"=",
"children",
"[",
"0",
"]",
",",
"args",
"=",
"children",
"[",
"1",
"]",
",",
")"
] |
A filter, with optional arguments.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: string, name of the filter.
- 1: list of instances of ``.resources.NamedArg``
Returns
-------
.resources.Filter
An instance of ``.resources.Filter`` with a name and a list of arguments.
The list of arguments will be ``None`` if no parenthesis.
Example
-------
>>> FiltersParserMixin(r'foo', default_rule='FILTER').data
.foo
>>> FiltersParserMixin(r'foo()', default_rule='FILTER').data
.foo()
>>> FiltersParserMixin(r'foo(1)', default_rule='FILTER').data
.foo(1)
>>> FiltersParserMixin(r'foo(1, bar="baz")', default_rule='FILTER').data
.foo(1, bar="baz")
|
[
"A",
"filter",
"with",
"optional",
"arguments",
"."
] |
5841a3fd559829193ed709c255166085bdde1c52
|
https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/parsers/mixins.py#L855-L888
|
245,325
|
jmoiron/gaspar
|
gaspar/producers.py
|
Producer.setup_zmq
|
def setup_zmq(self):
"""Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket."""
self.context = zmq.Context()
self.push = self.context.socket(zmq.PUSH)
self.push_port = self.push.bind_to_random_port("tcp://%s" % self.host)
# start a listener for the pull socket
eventlet.spawn(self.zmq_pull)
eventlet.sleep(0)
|
python
|
def setup_zmq(self):
"""Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket."""
self.context = zmq.Context()
self.push = self.context.socket(zmq.PUSH)
self.push_port = self.push.bind_to_random_port("tcp://%s" % self.host)
# start a listener for the pull socket
eventlet.spawn(self.zmq_pull)
eventlet.sleep(0)
|
[
"def",
"setup_zmq",
"(",
"self",
")",
":",
"self",
".",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"self",
".",
"push",
"=",
"self",
".",
"context",
".",
"socket",
"(",
"zmq",
".",
"PUSH",
")",
"self",
".",
"push_port",
"=",
"self",
".",
"push",
".",
"bind_to_random_port",
"(",
"\"tcp://%s\"",
"%",
"self",
".",
"host",
")",
"# start a listener for the pull socket",
"eventlet",
".",
"spawn",
"(",
"self",
".",
"zmq_pull",
")",
"eventlet",
".",
"sleep",
"(",
"0",
")"
] |
Set up a PUSH and a PULL socket. The PUSH socket will push out
requests to the workers. The PULL socket will receive responses from
the workers and reply through the server socket.
|
[
"Set",
"up",
"a",
"PUSH",
"and",
"a",
"PULL",
"socket",
".",
"The",
"PUSH",
"socket",
"will",
"push",
"out",
"requests",
"to",
"the",
"workers",
".",
"The",
"PULL",
"socket",
"will",
"receive",
"responses",
"from",
"the",
"workers",
"and",
"reply",
"through",
"the",
"server",
"socket",
"."
] |
cc9d7403a4d86382b10a7e96c6d0a020cc5e1b12
|
https://github.com/jmoiron/gaspar/blob/cc9d7403a4d86382b10a7e96c6d0a020cc5e1b12/gaspar/producers.py#L50-L59
|
245,326
|
jmoiron/gaspar
|
gaspar/producers.py
|
Producer.start
|
def start(self, blocking=True):
"""Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control ."""
self.setup_zmq()
if blocking:
self.serve()
else:
eventlet.spawn(self.serve)
# ensure that self.serve runs now as calling code will
# expect start() to have started the server even non-blk
eventlet.sleep(0)
|
python
|
def start(self, blocking=True):
"""Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control ."""
self.setup_zmq()
if blocking:
self.serve()
else:
eventlet.spawn(self.serve)
# ensure that self.serve runs now as calling code will
# expect start() to have started the server even non-blk
eventlet.sleep(0)
|
[
"def",
"start",
"(",
"self",
",",
"blocking",
"=",
"True",
")",
":",
"self",
".",
"setup_zmq",
"(",
")",
"if",
"blocking",
":",
"self",
".",
"serve",
"(",
")",
"else",
":",
"eventlet",
".",
"spawn",
"(",
"self",
".",
"serve",
")",
"# ensure that self.serve runs now as calling code will",
"# expect start() to have started the server even non-blk",
"eventlet",
".",
"sleep",
"(",
"0",
")"
] |
Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control .
|
[
"Start",
"the",
"producer",
".",
"This",
"will",
"eventually",
"fire",
"the",
"server_start",
"and",
"running",
"events",
"in",
"sequence",
"which",
"signify",
"that",
"the",
"incoming",
"TCP",
"request",
"socket",
"is",
"running",
"and",
"the",
"workers",
"have",
"been",
"forked",
"respectively",
".",
"If",
"blocking",
"is",
"False",
"control",
"."
] |
cc9d7403a4d86382b10a7e96c6d0a020cc5e1b12
|
https://github.com/jmoiron/gaspar/blob/cc9d7403a4d86382b10a7e96c6d0a020cc5e1b12/gaspar/producers.py#L93-L105
|
245,327
|
emory-libraries/eulcommon
|
eulcommon/djangoextras/taskresult/models.py
|
TaskResult.status_icon
|
def status_icon(self):
'glyphicon for task status; requires bootstrap'
icon = self.status_icon_map.get(self.status.lower(),
self.unknown_icon)
style = self.status_style.get(self.status.lower(), '')
return mark_safe(
'<span class="glyphicon %s %s" aria-hidden="true"></span>' %
(icon, style))
|
python
|
def status_icon(self):
'glyphicon for task status; requires bootstrap'
icon = self.status_icon_map.get(self.status.lower(),
self.unknown_icon)
style = self.status_style.get(self.status.lower(), '')
return mark_safe(
'<span class="glyphicon %s %s" aria-hidden="true"></span>' %
(icon, style))
|
[
"def",
"status_icon",
"(",
"self",
")",
":",
"icon",
"=",
"self",
".",
"status_icon_map",
".",
"get",
"(",
"self",
".",
"status",
".",
"lower",
"(",
")",
",",
"self",
".",
"unknown_icon",
")",
"style",
"=",
"self",
".",
"status_style",
".",
"get",
"(",
"self",
".",
"status",
".",
"lower",
"(",
")",
",",
"''",
")",
"return",
"mark_safe",
"(",
"'<span class=\"glyphicon %s %s\" aria-hidden=\"true\"></span>'",
"%",
"(",
"icon",
",",
"style",
")",
")"
] |
glyphicon for task status; requires bootstrap
|
[
"glyphicon",
"for",
"task",
"status",
";",
"requires",
"bootstrap"
] |
dc63a9b3b5e38205178235e0d716d1b28158d3a9
|
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/djangoextras/taskresult/models.py#L76-L83
|
245,328
|
ronaldguillen/wave
|
wave/utils/formatting.py
|
remove_trailing_string
|
def remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content
|
python
|
def remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content
|
[
"def",
"remove_trailing_string",
"(",
"content",
",",
"trailing",
")",
":",
"if",
"content",
".",
"endswith",
"(",
"trailing",
")",
"and",
"content",
"!=",
"trailing",
":",
"return",
"content",
"[",
":",
"-",
"len",
"(",
"trailing",
")",
"]",
"return",
"content"
] |
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
|
[
"Strip",
"trailing",
"component",
"trailing",
"from",
"content",
"if",
"it",
"exists",
".",
"Used",
"when",
"generating",
"names",
"from",
"view",
"classes",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L15-L22
|
245,329
|
ronaldguillen/wave
|
wave/utils/formatting.py
|
dedent
|
def dedent(content):
"""
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line.
"""
content = force_text(content)
whitespace_counts = [len(line) - len(line.lstrip(' '))
for line in content.splitlines()[1:] if line.lstrip()]
# unindent the content if needed
if whitespace_counts:
whitespace_pattern = '^' + (' ' * min(whitespace_counts))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
return content.strip()
|
python
|
def dedent(content):
"""
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line.
"""
content = force_text(content)
whitespace_counts = [len(line) - len(line.lstrip(' '))
for line in content.splitlines()[1:] if line.lstrip()]
# unindent the content if needed
if whitespace_counts:
whitespace_pattern = '^' + (' ' * min(whitespace_counts))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
return content.strip()
|
[
"def",
"dedent",
"(",
"content",
")",
":",
"content",
"=",
"force_text",
"(",
"content",
")",
"whitespace_counts",
"=",
"[",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
"' '",
")",
")",
"for",
"line",
"in",
"content",
".",
"splitlines",
"(",
")",
"[",
"1",
":",
"]",
"if",
"line",
".",
"lstrip",
"(",
")",
"]",
"# unindent the content if needed",
"if",
"whitespace_counts",
":",
"whitespace_pattern",
"=",
"'^'",
"+",
"(",
"' '",
"*",
"min",
"(",
"whitespace_counts",
")",
")",
"content",
"=",
"re",
".",
"sub",
"(",
"re",
".",
"compile",
"(",
"whitespace_pattern",
",",
"re",
".",
"MULTILINE",
")",
",",
"''",
",",
"content",
")",
"return",
"content",
".",
"strip",
"(",
")"
] |
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line.
|
[
"Remove",
"leading",
"indent",
"from",
"a",
"block",
"of",
"text",
".",
"Used",
"when",
"generating",
"descriptions",
"from",
"docstrings",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L25-L43
|
245,330
|
ronaldguillen/wave
|
wave/utils/formatting.py
|
camelcase_to_spaces
|
def camelcase_to_spaces(content):
"""
Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes.
"""
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
content = re.sub(camelcase_boundry, ' \\1', content).strip()
return ' '.join(content.split('_')).title()
|
python
|
def camelcase_to_spaces(content):
"""
Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes.
"""
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
content = re.sub(camelcase_boundry, ' \\1', content).strip()
return ' '.join(content.split('_')).title()
|
[
"def",
"camelcase_to_spaces",
"(",
"content",
")",
":",
"camelcase_boundry",
"=",
"'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'",
"content",
"=",
"re",
".",
"sub",
"(",
"camelcase_boundry",
",",
"' \\\\1'",
",",
"content",
")",
".",
"strip",
"(",
")",
"return",
"' '",
".",
"join",
"(",
"content",
".",
"split",
"(",
"'_'",
")",
")",
".",
"title",
"(",
")"
] |
Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes.
|
[
"Translate",
"CamelCaseNames",
"to",
"Camel",
"Case",
"Names",
".",
"Used",
"when",
"generating",
"names",
"from",
"view",
"classes",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L46-L53
|
245,331
|
ronaldguillen/wave
|
wave/utils/formatting.py
|
markup_description
|
def markup_description(description):
"""
Apply HTML markup to the given description.
"""
if apply_markdown:
description = apply_markdown(description)
else:
description = escape(description).replace('\n', '<br />')
description = '<p>' + description + '</p>'
return mark_safe(description)
|
python
|
def markup_description(description):
"""
Apply HTML markup to the given description.
"""
if apply_markdown:
description = apply_markdown(description)
else:
description = escape(description).replace('\n', '<br />')
description = '<p>' + description + '</p>'
return mark_safe(description)
|
[
"def",
"markup_description",
"(",
"description",
")",
":",
"if",
"apply_markdown",
":",
"description",
"=",
"apply_markdown",
"(",
"description",
")",
"else",
":",
"description",
"=",
"escape",
"(",
"description",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'<br />'",
")",
"description",
"=",
"'<p>'",
"+",
"description",
"+",
"'</p>'",
"return",
"mark_safe",
"(",
"description",
")"
] |
Apply HTML markup to the given description.
|
[
"Apply",
"HTML",
"markup",
"to",
"the",
"given",
"description",
"."
] |
20bb979c917f7634d8257992e6d449dc751256a9
|
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/utils/formatting.py#L56-L65
|
245,332
|
limpyd/redis-limpyd-jobs
|
limpyd_jobs/utils.py
|
import_class
|
def import_class(class_uri):
"""
Import a class by string 'from.path.module.class'
"""
parts = class_uri.split('.')
class_name = parts.pop()
module_uri = '.'.join(parts)
try:
module = import_module(module_uri)
except ImportError as e:
# maybe we are still in a module, test going up one level
try:
module = import_class(module_uri)
except Exception:
# if failure raise the original exception
raise e
return getattr(module, class_name)
|
python
|
def import_class(class_uri):
"""
Import a class by string 'from.path.module.class'
"""
parts = class_uri.split('.')
class_name = parts.pop()
module_uri = '.'.join(parts)
try:
module = import_module(module_uri)
except ImportError as e:
# maybe we are still in a module, test going up one level
try:
module = import_class(module_uri)
except Exception:
# if failure raise the original exception
raise e
return getattr(module, class_name)
|
[
"def",
"import_class",
"(",
"class_uri",
")",
":",
"parts",
"=",
"class_uri",
".",
"split",
"(",
"'.'",
")",
"class_name",
"=",
"parts",
".",
"pop",
"(",
")",
"module_uri",
"=",
"'.'",
".",
"join",
"(",
"parts",
")",
"try",
":",
"module",
"=",
"import_module",
"(",
"module_uri",
")",
"except",
"ImportError",
"as",
"e",
":",
"# maybe we are still in a module, test going up one level",
"try",
":",
"module",
"=",
"import_class",
"(",
"module_uri",
")",
"except",
"Exception",
":",
"# if failure raise the original exception",
"raise",
"e",
"return",
"getattr",
"(",
"module",
",",
"class_name",
")"
] |
Import a class by string 'from.path.module.class'
|
[
"Import",
"a",
"class",
"by",
"string",
"from",
".",
"path",
".",
"module",
".",
"class"
] |
264c71029bad4377d6132bf8bb9c55c44f3b03a2
|
https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/utils.py#L55-L74
|
245,333
|
SeabornGames/Meta
|
seaborn_meta/class_name.py
|
class_name_to_instant_name
|
def class_name_to_instant_name(name):
""" This will convert from 'ParentName_ChildName' to
'parent_name.child_name' """
name = name.replace('/', '_')
ret = name[0].lower()
for i in range(1, len(name)):
if name[i] == '_':
ret += '.'
elif '9' < name[i] < 'a' and name[i - 1] != '_':
ret += '_' + name[i].lower()
else:
ret += name[i].lower()
return ret
|
python
|
def class_name_to_instant_name(name):
""" This will convert from 'ParentName_ChildName' to
'parent_name.child_name' """
name = name.replace('/', '_')
ret = name[0].lower()
for i in range(1, len(name)):
if name[i] == '_':
ret += '.'
elif '9' < name[i] < 'a' and name[i - 1] != '_':
ret += '_' + name[i].lower()
else:
ret += name[i].lower()
return ret
|
[
"def",
"class_name_to_instant_name",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"ret",
"=",
"name",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"name",
")",
")",
":",
"if",
"name",
"[",
"i",
"]",
"==",
"'_'",
":",
"ret",
"+=",
"'.'",
"elif",
"'9'",
"<",
"name",
"[",
"i",
"]",
"<",
"'a'",
"and",
"name",
"[",
"i",
"-",
"1",
"]",
"!=",
"'_'",
":",
"ret",
"+=",
"'_'",
"+",
"name",
"[",
"i",
"]",
".",
"lower",
"(",
")",
"else",
":",
"ret",
"+=",
"name",
"[",
"i",
"]",
".",
"lower",
"(",
")",
"return",
"ret"
] |
This will convert from 'ParentName_ChildName' to
'parent_name.child_name'
|
[
"This",
"will",
"convert",
"from",
"ParentName_ChildName",
"to",
"parent_name",
".",
"child_name"
] |
f2a38ad8bcc5ac177e537645853593225895df46
|
https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/class_name.py#L8-L20
|
245,334
|
Othernet-Project/chainable-validators
|
validators/helpers.py
|
OR
|
def OR(*fns):
""" Validate with any of the chainable valdator functions """
if len(fns) < 2:
raise TypeError('At least two functions must be passed')
@chainable
def validator(v):
for fn in fns:
last = None
try:
return fn(v)
except ValueError as err:
last = err
if last:
raise last
return validator
|
python
|
def OR(*fns):
""" Validate with any of the chainable valdator functions """
if len(fns) < 2:
raise TypeError('At least two functions must be passed')
@chainable
def validator(v):
for fn in fns:
last = None
try:
return fn(v)
except ValueError as err:
last = err
if last:
raise last
return validator
|
[
"def",
"OR",
"(",
"*",
"fns",
")",
":",
"if",
"len",
"(",
"fns",
")",
"<",
"2",
":",
"raise",
"TypeError",
"(",
"'At least two functions must be passed'",
")",
"@",
"chainable",
"def",
"validator",
"(",
"v",
")",
":",
"for",
"fn",
"in",
"fns",
":",
"last",
"=",
"None",
"try",
":",
"return",
"fn",
"(",
"v",
")",
"except",
"ValueError",
"as",
"err",
":",
"last",
"=",
"err",
"if",
"last",
":",
"raise",
"last",
"return",
"validator"
] |
Validate with any of the chainable valdator functions
|
[
"Validate",
"with",
"any",
"of",
"the",
"chainable",
"valdator",
"functions"
] |
8c0afebfaaa131440ffb2a960b9b38978f00d88f
|
https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/helpers.py#L16-L31
|
245,335
|
Othernet-Project/chainable-validators
|
validators/helpers.py
|
NOT
|
def NOT(fn):
""" Reverse the effect of a chainable validator function """
@chainable
def validator(v):
try:
fn(v)
except ValueError:
return v
raise ValueError('invalid')
return validator
|
python
|
def NOT(fn):
""" Reverse the effect of a chainable validator function """
@chainable
def validator(v):
try:
fn(v)
except ValueError:
return v
raise ValueError('invalid')
return validator
|
[
"def",
"NOT",
"(",
"fn",
")",
":",
"@",
"chainable",
"def",
"validator",
"(",
"v",
")",
":",
"try",
":",
"fn",
"(",
"v",
")",
"except",
"ValueError",
":",
"return",
"v",
"raise",
"ValueError",
"(",
"'invalid'",
")",
"return",
"validator"
] |
Reverse the effect of a chainable validator function
|
[
"Reverse",
"the",
"effect",
"of",
"a",
"chainable",
"validator",
"function"
] |
8c0afebfaaa131440ffb2a960b9b38978f00d88f
|
https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/helpers.py#L34-L43
|
245,336
|
Othernet-Project/chainable-validators
|
validators/helpers.py
|
spec_validator
|
def spec_validator(spec, key=operator.itemgetter):
""" Take a spec in dict form, and return a function that validates objects
The spec maps each object's key to a chain of validator functions.
The ``key`` argument can be used to customize the way value matching a spec
key from the object. By default, it uses ``operator.itemgetter``. It should
be assigned a function that takes a key value and returns a function that
returns the vale from an object that is passed to it.
"""
spec = {k: (key(k), make_chain(v)) for k, v in spec.items()}
def validator(obj):
errors = {}
for k, v in spec.items():
getter, chain = v
val = getter(obj)
try:
chain(val)
except ValueError as err:
errors[k] = err
return errors
return validator
|
python
|
def spec_validator(spec, key=operator.itemgetter):
""" Take a spec in dict form, and return a function that validates objects
The spec maps each object's key to a chain of validator functions.
The ``key`` argument can be used to customize the way value matching a spec
key from the object. By default, it uses ``operator.itemgetter``. It should
be assigned a function that takes a key value and returns a function that
returns the vale from an object that is passed to it.
"""
spec = {k: (key(k), make_chain(v)) for k, v in spec.items()}
def validator(obj):
errors = {}
for k, v in spec.items():
getter, chain = v
val = getter(obj)
try:
chain(val)
except ValueError as err:
errors[k] = err
return errors
return validator
|
[
"def",
"spec_validator",
"(",
"spec",
",",
"key",
"=",
"operator",
".",
"itemgetter",
")",
":",
"spec",
"=",
"{",
"k",
":",
"(",
"key",
"(",
"k",
")",
",",
"make_chain",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"spec",
".",
"items",
"(",
")",
"}",
"def",
"validator",
"(",
"obj",
")",
":",
"errors",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"spec",
".",
"items",
"(",
")",
":",
"getter",
",",
"chain",
"=",
"v",
"val",
"=",
"getter",
"(",
"obj",
")",
"try",
":",
"chain",
"(",
"val",
")",
"except",
"ValueError",
"as",
"err",
":",
"errors",
"[",
"k",
"]",
"=",
"err",
"return",
"errors",
"return",
"validator"
] |
Take a spec in dict form, and return a function that validates objects
The spec maps each object's key to a chain of validator functions.
The ``key`` argument can be used to customize the way value matching a spec
key from the object. By default, it uses ``operator.itemgetter``. It should
be assigned a function that takes a key value and returns a function that
returns the vale from an object that is passed to it.
|
[
"Take",
"a",
"spec",
"in",
"dict",
"form",
"and",
"return",
"a",
"function",
"that",
"validates",
"objects"
] |
8c0afebfaaa131440ffb2a960b9b38978f00d88f
|
https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/helpers.py#L46-L69
|
245,337
|
deformio/python-deform
|
pydeform/client.py
|
Client.auth
|
def auth(self, auth_type, auth_key, project_id=None):
"""Creates authenticated client.
Parameters:
* `auth_type` - Authentication type. Use `session` for auth
by session key. Use `token` for auth by token.
* `auth_key` - Authentication `session key` or `token`.
* `project_id` - Project identifier. Must be provided for
`token` authentication. Default is `None`.
Returns:
* Instance of [SessionAuthClient](#sessionauthclient) if
`auth_type` is `session`.
* Instance of [ProjectClient](#projectclient) if
`auth_type` is `token`
Raises:
* ValueError: if `project_id` parameter was not provided
Examples:
For auth with `session` you should obtain session key by
[Client.user.login](#clientuserlogin) providing
your account's email and password:
```python
client = Client(host='deform.io')
session_client = client.auth(
'session',
client.user.login(
email='email@example.com',
password='password'
),
)
print session_client
<pydeform.client.SessionAuthClient object at 0x10c585650>
```
Authentication with `token` example:
```python
client = Client(host='deform.io')
token_client = client.auth(
'token',
auth_key='token-value',
project_id='some-project',
)
print token_client
<pydeform.client.ProjectClient object at 0x11c585650>
```
"""
if auth_type == 'session':
return SessionAuthClient(
auth_header=get_session_http_auth_header(auth_key),
host=self.host,
port=self.port,
secure=self.secure,
requests_session=self.requests_session,
request_defaults=self.request_defaults,
api_base_path=self.api_base_path,
)
elif auth_type == 'token':
if not project_id:
msg = 'You should provide project_id for token authentication'
raise ValueError(msg)
return ProjectClient(
base_uri=get_base_uri(
project=project_id,
host=self.host,
port=self.port,
secure=self.secure,
api_base_path=self.api_base_path
),
auth_header=get_token_http_auth_header(auth_key),
requests_session=self.requests_session,
request_defaults=self.request_defaults,
)
|
python
|
def auth(self, auth_type, auth_key, project_id=None):
"""Creates authenticated client.
Parameters:
* `auth_type` - Authentication type. Use `session` for auth
by session key. Use `token` for auth by token.
* `auth_key` - Authentication `session key` or `token`.
* `project_id` - Project identifier. Must be provided for
`token` authentication. Default is `None`.
Returns:
* Instance of [SessionAuthClient](#sessionauthclient) if
`auth_type` is `session`.
* Instance of [ProjectClient](#projectclient) if
`auth_type` is `token`
Raises:
* ValueError: if `project_id` parameter was not provided
Examples:
For auth with `session` you should obtain session key by
[Client.user.login](#clientuserlogin) providing
your account's email and password:
```python
client = Client(host='deform.io')
session_client = client.auth(
'session',
client.user.login(
email='email@example.com',
password='password'
),
)
print session_client
<pydeform.client.SessionAuthClient object at 0x10c585650>
```
Authentication with `token` example:
```python
client = Client(host='deform.io')
token_client = client.auth(
'token',
auth_key='token-value',
project_id='some-project',
)
print token_client
<pydeform.client.ProjectClient object at 0x11c585650>
```
"""
if auth_type == 'session':
return SessionAuthClient(
auth_header=get_session_http_auth_header(auth_key),
host=self.host,
port=self.port,
secure=self.secure,
requests_session=self.requests_session,
request_defaults=self.request_defaults,
api_base_path=self.api_base_path,
)
elif auth_type == 'token':
if not project_id:
msg = 'You should provide project_id for token authentication'
raise ValueError(msg)
return ProjectClient(
base_uri=get_base_uri(
project=project_id,
host=self.host,
port=self.port,
secure=self.secure,
api_base_path=self.api_base_path
),
auth_header=get_token_http_auth_header(auth_key),
requests_session=self.requests_session,
request_defaults=self.request_defaults,
)
|
[
"def",
"auth",
"(",
"self",
",",
"auth_type",
",",
"auth_key",
",",
"project_id",
"=",
"None",
")",
":",
"if",
"auth_type",
"==",
"'session'",
":",
"return",
"SessionAuthClient",
"(",
"auth_header",
"=",
"get_session_http_auth_header",
"(",
"auth_key",
")",
",",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"secure",
"=",
"self",
".",
"secure",
",",
"requests_session",
"=",
"self",
".",
"requests_session",
",",
"request_defaults",
"=",
"self",
".",
"request_defaults",
",",
"api_base_path",
"=",
"self",
".",
"api_base_path",
",",
")",
"elif",
"auth_type",
"==",
"'token'",
":",
"if",
"not",
"project_id",
":",
"msg",
"=",
"'You should provide project_id for token authentication'",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"ProjectClient",
"(",
"base_uri",
"=",
"get_base_uri",
"(",
"project",
"=",
"project_id",
",",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
",",
"secure",
"=",
"self",
".",
"secure",
",",
"api_base_path",
"=",
"self",
".",
"api_base_path",
")",
",",
"auth_header",
"=",
"get_token_http_auth_header",
"(",
"auth_key",
")",
",",
"requests_session",
"=",
"self",
".",
"requests_session",
",",
"request_defaults",
"=",
"self",
".",
"request_defaults",
",",
")"
] |
Creates authenticated client.
Parameters:
* `auth_type` - Authentication type. Use `session` for auth
by session key. Use `token` for auth by token.
* `auth_key` - Authentication `session key` or `token`.
* `project_id` - Project identifier. Must be provided for
`token` authentication. Default is `None`.
Returns:
* Instance of [SessionAuthClient](#sessionauthclient) if
`auth_type` is `session`.
* Instance of [ProjectClient](#projectclient) if
`auth_type` is `token`
Raises:
* ValueError: if `project_id` parameter was not provided
Examples:
For auth with `session` you should obtain session key by
[Client.user.login](#clientuserlogin) providing
your account's email and password:
```python
client = Client(host='deform.io')
session_client = client.auth(
'session',
client.user.login(
email='email@example.com',
password='password'
),
)
print session_client
<pydeform.client.SessionAuthClient object at 0x10c585650>
```
Authentication with `token` example:
```python
client = Client(host='deform.io')
token_client = client.auth(
'token',
auth_key='token-value',
project_id='some-project',
)
print token_client
<pydeform.client.ProjectClient object at 0x11c585650>
```
|
[
"Creates",
"authenticated",
"client",
"."
] |
c1edc7572881b83a4981b2dd39898527e518bd1f
|
https://github.com/deformio/python-deform/blob/c1edc7572881b83a4981b2dd39898527e518bd1f/pydeform/client.py#L85-L165
|
245,338
|
kolypto/py-exdoc
|
exdoc/py/__init__.py
|
getdoc
|
def getdoc(obj):
""" Get object docstring
:rtype: str
"""
inspect_got_doc = inspect.getdoc(obj)
if inspect_got_doc in (object.__init__.__doc__, object.__doc__):
return '' # We never want this builtin stuff
return (inspect_got_doc or '').strip()
|
python
|
def getdoc(obj):
""" Get object docstring
:rtype: str
"""
inspect_got_doc = inspect.getdoc(obj)
if inspect_got_doc in (object.__init__.__doc__, object.__doc__):
return '' # We never want this builtin stuff
return (inspect_got_doc or '').strip()
|
[
"def",
"getdoc",
"(",
"obj",
")",
":",
"inspect_got_doc",
"=",
"inspect",
".",
"getdoc",
"(",
"obj",
")",
"if",
"inspect_got_doc",
"in",
"(",
"object",
".",
"__init__",
".",
"__doc__",
",",
"object",
".",
"__doc__",
")",
":",
"return",
"''",
"# We never want this builtin stuff",
"return",
"(",
"inspect_got_doc",
"or",
"''",
")",
".",
"strip",
"(",
")"
] |
Get object docstring
:rtype: str
|
[
"Get",
"object",
"docstring"
] |
516526c01c203271410e7d7340024ef9f0bfa46a
|
https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L11-L19
|
245,339
|
kolypto/py-exdoc
|
exdoc/py/__init__.py
|
_get_callable
|
def _get_callable(obj, of_class = None):
""" Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that this method is a member of
:type of_class: class|None
:return: (qualname, Callable|None, Class|None). Callable is None for classes without __init__()
:rtype: (str, Callable|None, Class|None)
"""
# Cases
o = obj
if inspect.isclass(obj):
try:
o = obj.__init__
of_class = obj
except AttributeError:
pass
# Finish
return qualname(obj), o, of_class
|
python
|
def _get_callable(obj, of_class = None):
""" Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that this method is a member of
:type of_class: class|None
:return: (qualname, Callable|None, Class|None). Callable is None for classes without __init__()
:rtype: (str, Callable|None, Class|None)
"""
# Cases
o = obj
if inspect.isclass(obj):
try:
o = obj.__init__
of_class = obj
except AttributeError:
pass
# Finish
return qualname(obj), o, of_class
|
[
"def",
"_get_callable",
"(",
"obj",
",",
"of_class",
"=",
"None",
")",
":",
"# Cases",
"o",
"=",
"obj",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"try",
":",
"o",
"=",
"obj",
".",
"__init__",
"of_class",
"=",
"obj",
"except",
"AttributeError",
":",
"pass",
"# Finish",
"return",
"qualname",
"(",
"obj",
")",
",",
"o",
",",
"of_class"
] |
Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that this method is a member of
:type of_class: class|None
:return: (qualname, Callable|None, Class|None). Callable is None for classes without __init__()
:rtype: (str, Callable|None, Class|None)
|
[
"Get",
"callable",
"for",
"an",
"object",
"and",
"its",
"full",
"name",
"."
] |
516526c01c203271410e7d7340024ef9f0bfa46a
|
https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L22-L51
|
245,340
|
kolypto/py-exdoc
|
exdoc/py/__init__.py
|
_doc_parse
|
def _doc_parse(doc, module=None, qualname=None):
""" Parse docstring into a dict
:rtype: data.FDocstring
"""
# Build the rex
known_tags = {
'param': 'arg',
'type': 'arg-type',
'return': 'ret',
'returns': 'ret',
'rtype': 'ret-type',
'exception': 'exc',
'except': 'exc',
'raise': 'exc',
'raises': 'exc',
}
tag_rex = re.compile(r'^\s*:(' + '|'.join(map(re.escape, known_tags)) + r')\s*(\S+)?\s*:', re.MULTILINE)
# Match tags
collect_args = {}
collect_ret = {}
doc_args = []
doc_exc = []
for m in reversed(list(tag_rex.finditer(doc))):
# Fetch data
tag, arg = m.groups()
tag = known_tags[tag] # Normalized tag name
# Fetch docstring part
value = doc[m.end():].strip() # Copy text after the tag
doc = doc[:m.start()].strip() # truncate the string
# Handle tag: collect data
if tag == 'exc':
doc_exc.append(data.ExceptionDoc(arg, value))
elif tag in ('ret', 'ret-type'):
# Collect fields 1 by 1
collect_ret[{'ret': 'doc', 'ret-type': 'type'}[tag]] = value
elif tag in ('arg', 'arg-type'):
# Init new collection
if arg not in collect_args:
doc_args.append(arg) # add name for now, then map() replace with classes
collect_args[arg] = {}
# Collect fields 1 by 1
collect_args[arg][{'arg': 'doc', 'arg-type': 'type'}[tag]] = value
else:
raise AssertionError('Unknown tag type: {}'.format(tag))
# Merge collected data
doc_ret = data.ValueDoc(**collect_ret) if collect_ret else None
doc_args = map(lambda name: data.ArgumentDoc(name=name, **collect_args[name]), collect_args)
# Finish
return data.FDocstring(module=module, qualname=qualname, doc=doc, args=doc_args, exc=doc_exc, ret=doc_ret)
|
python
|
def _doc_parse(doc, module=None, qualname=None):
""" Parse docstring into a dict
:rtype: data.FDocstring
"""
# Build the rex
known_tags = {
'param': 'arg',
'type': 'arg-type',
'return': 'ret',
'returns': 'ret',
'rtype': 'ret-type',
'exception': 'exc',
'except': 'exc',
'raise': 'exc',
'raises': 'exc',
}
tag_rex = re.compile(r'^\s*:(' + '|'.join(map(re.escape, known_tags)) + r')\s*(\S+)?\s*:', re.MULTILINE)
# Match tags
collect_args = {}
collect_ret = {}
doc_args = []
doc_exc = []
for m in reversed(list(tag_rex.finditer(doc))):
# Fetch data
tag, arg = m.groups()
tag = known_tags[tag] # Normalized tag name
# Fetch docstring part
value = doc[m.end():].strip() # Copy text after the tag
doc = doc[:m.start()].strip() # truncate the string
# Handle tag: collect data
if tag == 'exc':
doc_exc.append(data.ExceptionDoc(arg, value))
elif tag in ('ret', 'ret-type'):
# Collect fields 1 by 1
collect_ret[{'ret': 'doc', 'ret-type': 'type'}[tag]] = value
elif tag in ('arg', 'arg-type'):
# Init new collection
if arg not in collect_args:
doc_args.append(arg) # add name for now, then map() replace with classes
collect_args[arg] = {}
# Collect fields 1 by 1
collect_args[arg][{'arg': 'doc', 'arg-type': 'type'}[tag]] = value
else:
raise AssertionError('Unknown tag type: {}'.format(tag))
# Merge collected data
doc_ret = data.ValueDoc(**collect_ret) if collect_ret else None
doc_args = map(lambda name: data.ArgumentDoc(name=name, **collect_args[name]), collect_args)
# Finish
return data.FDocstring(module=module, qualname=qualname, doc=doc, args=doc_args, exc=doc_exc, ret=doc_ret)
|
[
"def",
"_doc_parse",
"(",
"doc",
",",
"module",
"=",
"None",
",",
"qualname",
"=",
"None",
")",
":",
"# Build the rex",
"known_tags",
"=",
"{",
"'param'",
":",
"'arg'",
",",
"'type'",
":",
"'arg-type'",
",",
"'return'",
":",
"'ret'",
",",
"'returns'",
":",
"'ret'",
",",
"'rtype'",
":",
"'ret-type'",
",",
"'exception'",
":",
"'exc'",
",",
"'except'",
":",
"'exc'",
",",
"'raise'",
":",
"'exc'",
",",
"'raises'",
":",
"'exc'",
",",
"}",
"tag_rex",
"=",
"re",
".",
"compile",
"(",
"r'^\\s*:('",
"+",
"'|'",
".",
"join",
"(",
"map",
"(",
"re",
".",
"escape",
",",
"known_tags",
")",
")",
"+",
"r')\\s*(\\S+)?\\s*:'",
",",
"re",
".",
"MULTILINE",
")",
"# Match tags",
"collect_args",
"=",
"{",
"}",
"collect_ret",
"=",
"{",
"}",
"doc_args",
"=",
"[",
"]",
"doc_exc",
"=",
"[",
"]",
"for",
"m",
"in",
"reversed",
"(",
"list",
"(",
"tag_rex",
".",
"finditer",
"(",
"doc",
")",
")",
")",
":",
"# Fetch data",
"tag",
",",
"arg",
"=",
"m",
".",
"groups",
"(",
")",
"tag",
"=",
"known_tags",
"[",
"tag",
"]",
"# Normalized tag name",
"# Fetch docstring part",
"value",
"=",
"doc",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
".",
"strip",
"(",
")",
"# Copy text after the tag",
"doc",
"=",
"doc",
"[",
":",
"m",
".",
"start",
"(",
")",
"]",
".",
"strip",
"(",
")",
"# truncate the string",
"# Handle tag: collect data",
"if",
"tag",
"==",
"'exc'",
":",
"doc_exc",
".",
"append",
"(",
"data",
".",
"ExceptionDoc",
"(",
"arg",
",",
"value",
")",
")",
"elif",
"tag",
"in",
"(",
"'ret'",
",",
"'ret-type'",
")",
":",
"# Collect fields 1 by 1",
"collect_ret",
"[",
"{",
"'ret'",
":",
"'doc'",
",",
"'ret-type'",
":",
"'type'",
"}",
"[",
"tag",
"]",
"]",
"=",
"value",
"elif",
"tag",
"in",
"(",
"'arg'",
",",
"'arg-type'",
")",
":",
"# Init new collection",
"if",
"arg",
"not",
"in",
"collect_args",
":",
"doc_args",
".",
"append",
"(",
"arg",
")",
"# add name for now, then map() replace with classes",
"collect_args",
"[",
"arg",
"]",
"=",
"{",
"}",
"# Collect fields 1 by 1",
"collect_args",
"[",
"arg",
"]",
"[",
"{",
"'arg'",
":",
"'doc'",
",",
"'arg-type'",
":",
"'type'",
"}",
"[",
"tag",
"]",
"]",
"=",
"value",
"else",
":",
"raise",
"AssertionError",
"(",
"'Unknown tag type: {}'",
".",
"format",
"(",
"tag",
")",
")",
"# Merge collected data",
"doc_ret",
"=",
"data",
".",
"ValueDoc",
"(",
"*",
"*",
"collect_ret",
")",
"if",
"collect_ret",
"else",
"None",
"doc_args",
"=",
"map",
"(",
"lambda",
"name",
":",
"data",
".",
"ArgumentDoc",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"collect_args",
"[",
"name",
"]",
")",
",",
"collect_args",
")",
"# Finish",
"return",
"data",
".",
"FDocstring",
"(",
"module",
"=",
"module",
",",
"qualname",
"=",
"qualname",
",",
"doc",
"=",
"doc",
",",
"args",
"=",
"doc_args",
",",
"exc",
"=",
"doc_exc",
",",
"ret",
"=",
"doc_ret",
")"
] |
Parse docstring into a dict
:rtype: data.FDocstring
|
[
"Parse",
"docstring",
"into",
"a",
"dict"
] |
516526c01c203271410e7d7340024ef9f0bfa46a
|
https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L54-L109
|
245,341
|
kolypto/py-exdoc
|
exdoc/py/__init__.py
|
_argspec
|
def _argspec(func):
""" For a callable, get the full argument spec
:type func: Callable
:rtype: list[data.ArgumentSpec]
"""
assert isinstance(func, collections.Callable), 'Argument must be a callable'
try: sp = inspect.getargspec(func) if six.PY2 else inspect.getfullargspec(func)
except TypeError:
# inspect.getargspec() fails for built-in functions
return []
# Collect arguments with defaults
ret = []
defaults_start = len(sp.args) - len(sp.defaults) if sp.defaults else len(sp.args)
for i, name in enumerate(sp.args):
arg = data.ArgumentSpec(name)
if i >= defaults_start:
arg['default'] = sp.defaults[i - defaults_start]
ret.append(arg)
# *args, **kwargs
if sp.varargs:
ret.append(data.ArgumentSpec(sp.varargs, varargs=True))
if six.PY2:
if sp.keywords:
ret.append(data.ArgumentSpec(sp.keywords, keywords=True))
else:
if sp.varkw:
ret.append(data.ArgumentSpec(sp.varkw, keywords=True))
# TODO: support Python 3: kwonlyargs, kwonlydefaults, annotations
# Finish
return ret
|
python
|
def _argspec(func):
""" For a callable, get the full argument spec
:type func: Callable
:rtype: list[data.ArgumentSpec]
"""
assert isinstance(func, collections.Callable), 'Argument must be a callable'
try: sp = inspect.getargspec(func) if six.PY2 else inspect.getfullargspec(func)
except TypeError:
# inspect.getargspec() fails for built-in functions
return []
# Collect arguments with defaults
ret = []
defaults_start = len(sp.args) - len(sp.defaults) if sp.defaults else len(sp.args)
for i, name in enumerate(sp.args):
arg = data.ArgumentSpec(name)
if i >= defaults_start:
arg['default'] = sp.defaults[i - defaults_start]
ret.append(arg)
# *args, **kwargs
if sp.varargs:
ret.append(data.ArgumentSpec(sp.varargs, varargs=True))
if six.PY2:
if sp.keywords:
ret.append(data.ArgumentSpec(sp.keywords, keywords=True))
else:
if sp.varkw:
ret.append(data.ArgumentSpec(sp.varkw, keywords=True))
# TODO: support Python 3: kwonlyargs, kwonlydefaults, annotations
# Finish
return ret
|
[
"def",
"_argspec",
"(",
"func",
")",
":",
"assert",
"isinstance",
"(",
"func",
",",
"collections",
".",
"Callable",
")",
",",
"'Argument must be a callable'",
"try",
":",
"sp",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"six",
".",
"PY2",
"else",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
"except",
"TypeError",
":",
"# inspect.getargspec() fails for built-in functions",
"return",
"[",
"]",
"# Collect arguments with defaults",
"ret",
"=",
"[",
"]",
"defaults_start",
"=",
"len",
"(",
"sp",
".",
"args",
")",
"-",
"len",
"(",
"sp",
".",
"defaults",
")",
"if",
"sp",
".",
"defaults",
"else",
"len",
"(",
"sp",
".",
"args",
")",
"for",
"i",
",",
"name",
"in",
"enumerate",
"(",
"sp",
".",
"args",
")",
":",
"arg",
"=",
"data",
".",
"ArgumentSpec",
"(",
"name",
")",
"if",
"i",
">=",
"defaults_start",
":",
"arg",
"[",
"'default'",
"]",
"=",
"sp",
".",
"defaults",
"[",
"i",
"-",
"defaults_start",
"]",
"ret",
".",
"append",
"(",
"arg",
")",
"# *args, **kwargs",
"if",
"sp",
".",
"varargs",
":",
"ret",
".",
"append",
"(",
"data",
".",
"ArgumentSpec",
"(",
"sp",
".",
"varargs",
",",
"varargs",
"=",
"True",
")",
")",
"if",
"six",
".",
"PY2",
":",
"if",
"sp",
".",
"keywords",
":",
"ret",
".",
"append",
"(",
"data",
".",
"ArgumentSpec",
"(",
"sp",
".",
"keywords",
",",
"keywords",
"=",
"True",
")",
")",
"else",
":",
"if",
"sp",
".",
"varkw",
":",
"ret",
".",
"append",
"(",
"data",
".",
"ArgumentSpec",
"(",
"sp",
".",
"varkw",
",",
"keywords",
"=",
"True",
")",
")",
"# TODO: support Python 3: kwonlyargs, kwonlydefaults, annotations",
"# Finish",
"return",
"ret"
] |
For a callable, get the full argument spec
:type func: Callable
:rtype: list[data.ArgumentSpec]
|
[
"For",
"a",
"callable",
"get",
"the",
"full",
"argument",
"spec"
] |
516526c01c203271410e7d7340024ef9f0bfa46a
|
https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L121-L156
|
245,342
|
kolypto/py-exdoc
|
exdoc/py/__init__.py
|
doc
|
def doc(obj, of_class=None):
""" Get parsed documentation for an object as a dict.
This includes arguments spec, as well as the parsed data from the docstring.
```python
from exdoc import doc
```
The `doc()` function simply fetches documentation for an object, which can be
* Module
* Class
* Function or method
* Property
The resulting dictionary includes argument specification, as well as parsed docstring:
```python
def f(a, b=1, *args):
''' Simple function
: param a: First
: type a: int
: param b: Second
: type b: int
: param args: More numbers
: returns: nothing interesting
: rtype: bool
: raises ValueError: hopeless condition
'''
from exdoc import doc
doc(f) # ->
{
'module': '__main__',
'name': 'f',
'qualname': 'f', # qualified name: e.g. <class>.<method>
'signature': 'f(a, b=1, *args)',
'qsignature': 'f(a, b=1, *args)', # qualified signature
'doc': 'Simple function',
'clsdoc': '', # doc from the class (used for constructors)
# Exceptions
'exc': [
{'doc': 'hopeless condition', 'name': 'ValueError'}
],
# Return value
'ret': {'doc': 'nothing interesting', 'type': 'bool'},
# Arguments
'args': [
{'doc': 'First', 'name': 'a', 'type': 'int'},
{'default': 1, 'doc': 'Second', 'name': 'b', 'type': 'int'},
{'doc': 'More numbers', 'name': '*args', 'type': None}
],
}
```
Note: in Python 3, when documenting a method of a class, pass the class to the `doc()` function as the second argument:
```python
doc(cls.method, cls)
```
This is necessary because in Python3 methods are not bound like they used to. Now, they are just functions.
:type obj: ModuleType|type|Callable|property
:param of_class: A class whose method is being documented.
:type of_class: class|None
:rtype: Docstring|FDocstring
"""
# Special care about properties
if isinstance(obj, property):
docstr = doc(obj.fget)
# Some hacks for properties
docstr.signature = docstr.qsignature= obj.fget.__name__
docstr.args = docstr.args[1:]
return docstr
# Module
module = inspect.getmodule(obj)
if module:
module = module.__name__
# Not callable: e.g. modules
if not callable(obj):
if hasattr(obj, '__name__'):
return data.Docstring(qualname=obj.__name__, doc=getdoc(obj))
else:
return None
# Callables
qualname, fun, of_class = _get_callable(obj, of_class)
docstr = _docspec(fun, module=module, qualname=qualname, of_class=of_class)
# Class? Get doc
if inspect.isclass(obj):
# Get class doc
clsdoc = getdoc(obj)
# Parse docstring and merge into constructor doc
if clsdoc:
# Parse docstring
clsdoc = _doc_parse(clsdoc, module=module, qualname=qualname)
# Store clsdoc always
docstr.clsdoc = clsdoc.doc
# Merge exceptions list
docstr.exc.extend(clsdoc.exc)
# If constructor does not have it's own docstr -- copy it from the clsdoc
if not docstr.doc:
docstr.doc = docstr.clsdoc
# Merge arguments: type, doc
for a_class in clsdoc.args:
for a_constructor in docstr.args:
if a_class.name.lstrip('*') == a_constructor.name.lstrip('*'):
a_constructor.type = a_class.type
a_constructor.doc = a_class.doc
# Finish
return docstr
|
python
|
def doc(obj, of_class=None):
""" Get parsed documentation for an object as a dict.
This includes arguments spec, as well as the parsed data from the docstring.
```python
from exdoc import doc
```
The `doc()` function simply fetches documentation for an object, which can be
* Module
* Class
* Function or method
* Property
The resulting dictionary includes argument specification, as well as parsed docstring:
```python
def f(a, b=1, *args):
''' Simple function
: param a: First
: type a: int
: param b: Second
: type b: int
: param args: More numbers
: returns: nothing interesting
: rtype: bool
: raises ValueError: hopeless condition
'''
from exdoc import doc
doc(f) # ->
{
'module': '__main__',
'name': 'f',
'qualname': 'f', # qualified name: e.g. <class>.<method>
'signature': 'f(a, b=1, *args)',
'qsignature': 'f(a, b=1, *args)', # qualified signature
'doc': 'Simple function',
'clsdoc': '', # doc from the class (used for constructors)
# Exceptions
'exc': [
{'doc': 'hopeless condition', 'name': 'ValueError'}
],
# Return value
'ret': {'doc': 'nothing interesting', 'type': 'bool'},
# Arguments
'args': [
{'doc': 'First', 'name': 'a', 'type': 'int'},
{'default': 1, 'doc': 'Second', 'name': 'b', 'type': 'int'},
{'doc': 'More numbers', 'name': '*args', 'type': None}
],
}
```
Note: in Python 3, when documenting a method of a class, pass the class to the `doc()` function as the second argument:
```python
doc(cls.method, cls)
```
This is necessary because in Python3 methods are not bound like they used to. Now, they are just functions.
:type obj: ModuleType|type|Callable|property
:param of_class: A class whose method is being documented.
:type of_class: class|None
:rtype: Docstring|FDocstring
"""
# Special care about properties
if isinstance(obj, property):
docstr = doc(obj.fget)
# Some hacks for properties
docstr.signature = docstr.qsignature= obj.fget.__name__
docstr.args = docstr.args[1:]
return docstr
# Module
module = inspect.getmodule(obj)
if module:
module = module.__name__
# Not callable: e.g. modules
if not callable(obj):
if hasattr(obj, '__name__'):
return data.Docstring(qualname=obj.__name__, doc=getdoc(obj))
else:
return None
# Callables
qualname, fun, of_class = _get_callable(obj, of_class)
docstr = _docspec(fun, module=module, qualname=qualname, of_class=of_class)
# Class? Get doc
if inspect.isclass(obj):
# Get class doc
clsdoc = getdoc(obj)
# Parse docstring and merge into constructor doc
if clsdoc:
# Parse docstring
clsdoc = _doc_parse(clsdoc, module=module, qualname=qualname)
# Store clsdoc always
docstr.clsdoc = clsdoc.doc
# Merge exceptions list
docstr.exc.extend(clsdoc.exc)
# If constructor does not have it's own docstr -- copy it from the clsdoc
if not docstr.doc:
docstr.doc = docstr.clsdoc
# Merge arguments: type, doc
for a_class in clsdoc.args:
for a_constructor in docstr.args:
if a_class.name.lstrip('*') == a_constructor.name.lstrip('*'):
a_constructor.type = a_class.type
a_constructor.doc = a_class.doc
# Finish
return docstr
|
[
"def",
"doc",
"(",
"obj",
",",
"of_class",
"=",
"None",
")",
":",
"# Special care about properties",
"if",
"isinstance",
"(",
"obj",
",",
"property",
")",
":",
"docstr",
"=",
"doc",
"(",
"obj",
".",
"fget",
")",
"# Some hacks for properties",
"docstr",
".",
"signature",
"=",
"docstr",
".",
"qsignature",
"=",
"obj",
".",
"fget",
".",
"__name__",
"docstr",
".",
"args",
"=",
"docstr",
".",
"args",
"[",
"1",
":",
"]",
"return",
"docstr",
"# Module",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"obj",
")",
"if",
"module",
":",
"module",
"=",
"module",
".",
"__name__",
"# Not callable: e.g. modules",
"if",
"not",
"callable",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__name__'",
")",
":",
"return",
"data",
".",
"Docstring",
"(",
"qualname",
"=",
"obj",
".",
"__name__",
",",
"doc",
"=",
"getdoc",
"(",
"obj",
")",
")",
"else",
":",
"return",
"None",
"# Callables",
"qualname",
",",
"fun",
",",
"of_class",
"=",
"_get_callable",
"(",
"obj",
",",
"of_class",
")",
"docstr",
"=",
"_docspec",
"(",
"fun",
",",
"module",
"=",
"module",
",",
"qualname",
"=",
"qualname",
",",
"of_class",
"=",
"of_class",
")",
"# Class? Get doc",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"# Get class doc",
"clsdoc",
"=",
"getdoc",
"(",
"obj",
")",
"# Parse docstring and merge into constructor doc",
"if",
"clsdoc",
":",
"# Parse docstring",
"clsdoc",
"=",
"_doc_parse",
"(",
"clsdoc",
",",
"module",
"=",
"module",
",",
"qualname",
"=",
"qualname",
")",
"# Store clsdoc always",
"docstr",
".",
"clsdoc",
"=",
"clsdoc",
".",
"doc",
"# Merge exceptions list",
"docstr",
".",
"exc",
".",
"extend",
"(",
"clsdoc",
".",
"exc",
")",
"# If constructor does not have it's own docstr -- copy it from the clsdoc",
"if",
"not",
"docstr",
".",
"doc",
":",
"docstr",
".",
"doc",
"=",
"docstr",
".",
"clsdoc",
"# Merge arguments: type, doc",
"for",
"a_class",
"in",
"clsdoc",
".",
"args",
":",
"for",
"a_constructor",
"in",
"docstr",
".",
"args",
":",
"if",
"a_class",
".",
"name",
".",
"lstrip",
"(",
"'*'",
")",
"==",
"a_constructor",
".",
"name",
".",
"lstrip",
"(",
"'*'",
")",
":",
"a_constructor",
".",
"type",
"=",
"a_class",
".",
"type",
"a_constructor",
".",
"doc",
"=",
"a_class",
".",
"doc",
"# Finish",
"return",
"docstr"
] |
Get parsed documentation for an object as a dict.
This includes arguments spec, as well as the parsed data from the docstring.
```python
from exdoc import doc
```
The `doc()` function simply fetches documentation for an object, which can be
* Module
* Class
* Function or method
* Property
The resulting dictionary includes argument specification, as well as parsed docstring:
```python
def f(a, b=1, *args):
''' Simple function
: param a: First
: type a: int
: param b: Second
: type b: int
: param args: More numbers
: returns: nothing interesting
: rtype: bool
: raises ValueError: hopeless condition
'''
from exdoc import doc
doc(f) # ->
{
'module': '__main__',
'name': 'f',
'qualname': 'f', # qualified name: e.g. <class>.<method>
'signature': 'f(a, b=1, *args)',
'qsignature': 'f(a, b=1, *args)', # qualified signature
'doc': 'Simple function',
'clsdoc': '', # doc from the class (used for constructors)
# Exceptions
'exc': [
{'doc': 'hopeless condition', 'name': 'ValueError'}
],
# Return value
'ret': {'doc': 'nothing interesting', 'type': 'bool'},
# Arguments
'args': [
{'doc': 'First', 'name': 'a', 'type': 'int'},
{'default': 1, 'doc': 'Second', 'name': 'b', 'type': 'int'},
{'doc': 'More numbers', 'name': '*args', 'type': None}
],
}
```
Note: in Python 3, when documenting a method of a class, pass the class to the `doc()` function as the second argument:
```python
doc(cls.method, cls)
```
This is necessary because in Python3 methods are not bound like they used to. Now, they are just functions.
:type obj: ModuleType|type|Callable|property
:param of_class: A class whose method is being documented.
:type of_class: class|None
:rtype: Docstring|FDocstring
|
[
"Get",
"parsed",
"documentation",
"for",
"an",
"object",
"as",
"a",
"dict",
"."
] |
516526c01c203271410e7d7340024ef9f0bfa46a
|
https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L184-L306
|
245,343
|
kolypto/py-exdoc
|
exdoc/py/__init__.py
|
subclasses
|
def subclasses(cls, leaves=False):
""" List all subclasses of the given class, including itself.
If `leaves=True`, only returns classes which have no subclasses themselves.
:type cls: type
:param leaves: Only return leaf classes
:type leaves: bool
:rtype: list[type]
"""
stack = [cls]
subcls = []
while stack:
c = stack.pop()
c_subs = c.__subclasses__()
stack.extend(c_subs)
if not leaves or not c_subs:
subcls.append(c)
return subcls
|
python
|
def subclasses(cls, leaves=False):
""" List all subclasses of the given class, including itself.
If `leaves=True`, only returns classes which have no subclasses themselves.
:type cls: type
:param leaves: Only return leaf classes
:type leaves: bool
:rtype: list[type]
"""
stack = [cls]
subcls = []
while stack:
c = stack.pop()
c_subs = c.__subclasses__()
stack.extend(c_subs)
if not leaves or not c_subs:
subcls.append(c)
return subcls
|
[
"def",
"subclasses",
"(",
"cls",
",",
"leaves",
"=",
"False",
")",
":",
"stack",
"=",
"[",
"cls",
"]",
"subcls",
"=",
"[",
"]",
"while",
"stack",
":",
"c",
"=",
"stack",
".",
"pop",
"(",
")",
"c_subs",
"=",
"c",
".",
"__subclasses__",
"(",
")",
"stack",
".",
"extend",
"(",
"c_subs",
")",
"if",
"not",
"leaves",
"or",
"not",
"c_subs",
":",
"subcls",
".",
"append",
"(",
"c",
")",
"return",
"subcls"
] |
List all subclasses of the given class, including itself.
If `leaves=True`, only returns classes which have no subclasses themselves.
:type cls: type
:param leaves: Only return leaf classes
:type leaves: bool
:rtype: list[type]
|
[
"List",
"all",
"subclasses",
"of",
"the",
"given",
"class",
"including",
"itself",
"."
] |
516526c01c203271410e7d7340024ef9f0bfa46a
|
https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L339-L357
|
245,344
|
GemHQ/round-py
|
round/wallets.py
|
generate
|
def generate(passphrase, trees=['primary']):
"""Generate a seed for the primary tree of a Gem wallet.
You may choose to store the passphrase for a user so the user doesn't have
to type it in every time. This is okay (although the security risks should
be obvious) but Gem strongly discourages storing even the encrypted private
seed, and storing both the passphrase and the private seed is completely
insane. Don't do it.
Args:
passphrase (str): The passphrase that will be used to encrypt the seed
before it's send to Gem. Key-stretching is done with PBDKF2 and
encryption is done with nacl's SecretBox.
trees (list of str): A list of names to generate trees for. For User
Wallets this will be ['primary'], for Application Wallets it will be
['primary', 'backup'].
Returns:
A dict of dicts containing the serialized public master node, and
a sub-dict with the encrypted private seed for each tree in `trees`.
"""
seeds, multi_wallet = MultiWallet.generate(trees, entropy=True)
result = {}
for tree in trees:
result[tree] = dict(private_seed=seeds[tree],
public_seed=multi_wallet.public_wif(tree),
encrypted_seed=PassphraseBox.encrypt(passphrase,
seeds[tree]))
return result
|
python
|
def generate(passphrase, trees=['primary']):
"""Generate a seed for the primary tree of a Gem wallet.
You may choose to store the passphrase for a user so the user doesn't have
to type it in every time. This is okay (although the security risks should
be obvious) but Gem strongly discourages storing even the encrypted private
seed, and storing both the passphrase and the private seed is completely
insane. Don't do it.
Args:
passphrase (str): The passphrase that will be used to encrypt the seed
before it's send to Gem. Key-stretching is done with PBDKF2 and
encryption is done with nacl's SecretBox.
trees (list of str): A list of names to generate trees for. For User
Wallets this will be ['primary'], for Application Wallets it will be
['primary', 'backup'].
Returns:
A dict of dicts containing the serialized public master node, and
a sub-dict with the encrypted private seed for each tree in `trees`.
"""
seeds, multi_wallet = MultiWallet.generate(trees, entropy=True)
result = {}
for tree in trees:
result[tree] = dict(private_seed=seeds[tree],
public_seed=multi_wallet.public_wif(tree),
encrypted_seed=PassphraseBox.encrypt(passphrase,
seeds[tree]))
return result
|
[
"def",
"generate",
"(",
"passphrase",
",",
"trees",
"=",
"[",
"'primary'",
"]",
")",
":",
"seeds",
",",
"multi_wallet",
"=",
"MultiWallet",
".",
"generate",
"(",
"trees",
",",
"entropy",
"=",
"True",
")",
"result",
"=",
"{",
"}",
"for",
"tree",
"in",
"trees",
":",
"result",
"[",
"tree",
"]",
"=",
"dict",
"(",
"private_seed",
"=",
"seeds",
"[",
"tree",
"]",
",",
"public_seed",
"=",
"multi_wallet",
".",
"public_wif",
"(",
"tree",
")",
",",
"encrypted_seed",
"=",
"PassphraseBox",
".",
"encrypt",
"(",
"passphrase",
",",
"seeds",
"[",
"tree",
"]",
")",
")",
"return",
"result"
] |
Generate a seed for the primary tree of a Gem wallet.
You may choose to store the passphrase for a user so the user doesn't have
to type it in every time. This is okay (although the security risks should
be obvious) but Gem strongly discourages storing even the encrypted private
seed, and storing both the passphrase and the private seed is completely
insane. Don't do it.
Args:
passphrase (str): The passphrase that will be used to encrypt the seed
before it's send to Gem. Key-stretching is done with PBDKF2 and
encryption is done with nacl's SecretBox.
trees (list of str): A list of names to generate trees for. For User
Wallets this will be ['primary'], for Application Wallets it will be
['primary', 'backup'].
Returns:
A dict of dicts containing the serialized public master node, and
a sub-dict with the encrypted private seed for each tree in `trees`.
|
[
"Generate",
"a",
"seed",
"for",
"the",
"primary",
"tree",
"of",
"a",
"Gem",
"wallet",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L26-L55
|
245,345
|
GemHQ/round-py
|
round/wallets.py
|
Wallets.create
|
def create(self, name, passphrase=None, wallet_data=None):
"""Create a new Wallet object and add it to this Wallets collection.
This is only available in this library for Application wallets. Users
must add additional wallets in their User Console
Args:
name (str): wallet name
passphrase (str, optional): A passphrase with which to encrypt a user
wallet. If not supplied, wallet_data is mandatory.
wallet_data (dict): Output from wallets.generate.
For User Wallets, only the primary tree is used.
For Application Wallets, the primary and backup trees are used.
Returns:
A tuple of the (backup_private_seed, round.Wallet).
"""
if not self.application:
raise RoundError("User accounts are limited to one wallet. Make an "
"account or shoot us an email <dev@gem.co> if you "
"have a compelling use case for more.")
if not passphrase and not wallet_data:
raise ValueError("Usage: wallets.create(name, passphrase [, "
"wallet_data])")
elif passphrase:
wallet_data = generate(passphrase,
trees=(['primary', 'backup'] if (
self.application) else ['primary']))
wallet = dict(
primary_private_seed=wallet_data['primary']['encrypted_seed'],
primary_public_seed=wallet_data['primary']['public_seed'],
name=name)
if self.application:
wallet['backup_public_seed'] = wallet_data['backup']['public_seed']
resource = self.resource.create(wallet)
wallet = self.wrap(resource)
return (wallet_data['backup']['private_seed'], self.add(wallet)) if (
self.application) else self.add(wallet)
|
python
|
def create(self, name, passphrase=None, wallet_data=None):
"""Create a new Wallet object and add it to this Wallets collection.
This is only available in this library for Application wallets. Users
must add additional wallets in their User Console
Args:
name (str): wallet name
passphrase (str, optional): A passphrase with which to encrypt a user
wallet. If not supplied, wallet_data is mandatory.
wallet_data (dict): Output from wallets.generate.
For User Wallets, only the primary tree is used.
For Application Wallets, the primary and backup trees are used.
Returns:
A tuple of the (backup_private_seed, round.Wallet).
"""
if not self.application:
raise RoundError("User accounts are limited to one wallet. Make an "
"account or shoot us an email <dev@gem.co> if you "
"have a compelling use case for more.")
if not passphrase and not wallet_data:
raise ValueError("Usage: wallets.create(name, passphrase [, "
"wallet_data])")
elif passphrase:
wallet_data = generate(passphrase,
trees=(['primary', 'backup'] if (
self.application) else ['primary']))
wallet = dict(
primary_private_seed=wallet_data['primary']['encrypted_seed'],
primary_public_seed=wallet_data['primary']['public_seed'],
name=name)
if self.application:
wallet['backup_public_seed'] = wallet_data['backup']['public_seed']
resource = self.resource.create(wallet)
wallet = self.wrap(resource)
return (wallet_data['backup']['private_seed'], self.add(wallet)) if (
self.application) else self.add(wallet)
|
[
"def",
"create",
"(",
"self",
",",
"name",
",",
"passphrase",
"=",
"None",
",",
"wallet_data",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"application",
":",
"raise",
"RoundError",
"(",
"\"User accounts are limited to one wallet. Make an \"",
"\"account or shoot us an email <dev@gem.co> if you \"",
"\"have a compelling use case for more.\"",
")",
"if",
"not",
"passphrase",
"and",
"not",
"wallet_data",
":",
"raise",
"ValueError",
"(",
"\"Usage: wallets.create(name, passphrase [, \"",
"\"wallet_data])\"",
")",
"elif",
"passphrase",
":",
"wallet_data",
"=",
"generate",
"(",
"passphrase",
",",
"trees",
"=",
"(",
"[",
"'primary'",
",",
"'backup'",
"]",
"if",
"(",
"self",
".",
"application",
")",
"else",
"[",
"'primary'",
"]",
")",
")",
"wallet",
"=",
"dict",
"(",
"primary_private_seed",
"=",
"wallet_data",
"[",
"'primary'",
"]",
"[",
"'encrypted_seed'",
"]",
",",
"primary_public_seed",
"=",
"wallet_data",
"[",
"'primary'",
"]",
"[",
"'public_seed'",
"]",
",",
"name",
"=",
"name",
")",
"if",
"self",
".",
"application",
":",
"wallet",
"[",
"'backup_public_seed'",
"]",
"=",
"wallet_data",
"[",
"'backup'",
"]",
"[",
"'public_seed'",
"]",
"resource",
"=",
"self",
".",
"resource",
".",
"create",
"(",
"wallet",
")",
"wallet",
"=",
"self",
".",
"wrap",
"(",
"resource",
")",
"return",
"(",
"wallet_data",
"[",
"'backup'",
"]",
"[",
"'private_seed'",
"]",
",",
"self",
".",
"add",
"(",
"wallet",
")",
")",
"if",
"(",
"self",
".",
"application",
")",
"else",
"self",
".",
"add",
"(",
"wallet",
")"
] |
Create a new Wallet object and add it to this Wallets collection.
This is only available in this library for Application wallets. Users
must add additional wallets in their User Console
Args:
name (str): wallet name
passphrase (str, optional): A passphrase with which to encrypt a user
wallet. If not supplied, wallet_data is mandatory.
wallet_data (dict): Output from wallets.generate.
For User Wallets, only the primary tree is used.
For Application Wallets, the primary and backup trees are used.
Returns:
A tuple of the (backup_private_seed, round.Wallet).
|
[
"Create",
"a",
"new",
"Wallet",
"object",
"and",
"add",
"it",
"to",
"this",
"Wallets",
"collection",
".",
"This",
"is",
"only",
"available",
"in",
"this",
"library",
"for",
"Application",
"wallets",
".",
"Users",
"must",
"add",
"additional",
"wallets",
"in",
"their",
"User",
"Console"
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L78-L116
|
245,346
|
GemHQ/round-py
|
round/wallets.py
|
Wallet.unlock
|
def unlock(self, passphrase, encrypted_seed=None):
"""Unlock the Wallet by decrypting the primary_private_seed with the
supplied passphrase. Once unlocked, the private seed is accessible in
memory and calls to `account.pay` will succeed. This is a necessary step
for creating transactions.
Args:
passphrase (str): The passphrase the User used to encrypt this wallet.
encrypted_seed (dict): A dictionary of the form
{'ciphertext': longhexvalue,
'iterations': integer of pbkdf2 derivations,
'nonce': 24-byte hex value
'salt': 16-byte hex value}
this dict represents an private seed (not a master key) encrypted
with the `passphrase` using pbkdf2. You can obtain this value with
wallet.generate. If this value is supplied, it overwrites (locally
only) the encrypted primary_private_seed value, allowing you to load
in a primary key that you didn't store with Gem. Note that the key
MUST match the pubkey that this wallet was created with.
Returns:
self
"""
wallet = self.resource
if not encrypted_seed:
encrypted_seed = wallet.primary_private_seed
try:
if encrypted_seed['nonce']:
primary_seed = NaclPassphraseBox.decrypt(
passphrase, encrypted_seed)
else:
primary_seed = PassphraseBox.decrypt(
passphrase, encrypted_seed)
except:
raise InvalidPassphraseError()
self.multi_wallet = MultiWallet(
private_seeds={'primary': primary_seed},
public={'cosigner': wallet.cosigner_public_seed,
'backup': wallet.backup_public_seed})
return self
|
python
|
def unlock(self, passphrase, encrypted_seed=None):
"""Unlock the Wallet by decrypting the primary_private_seed with the
supplied passphrase. Once unlocked, the private seed is accessible in
memory and calls to `account.pay` will succeed. This is a necessary step
for creating transactions.
Args:
passphrase (str): The passphrase the User used to encrypt this wallet.
encrypted_seed (dict): A dictionary of the form
{'ciphertext': longhexvalue,
'iterations': integer of pbkdf2 derivations,
'nonce': 24-byte hex value
'salt': 16-byte hex value}
this dict represents an private seed (not a master key) encrypted
with the `passphrase` using pbkdf2. You can obtain this value with
wallet.generate. If this value is supplied, it overwrites (locally
only) the encrypted primary_private_seed value, allowing you to load
in a primary key that you didn't store with Gem. Note that the key
MUST match the pubkey that this wallet was created with.
Returns:
self
"""
wallet = self.resource
if not encrypted_seed:
encrypted_seed = wallet.primary_private_seed
try:
if encrypted_seed['nonce']:
primary_seed = NaclPassphraseBox.decrypt(
passphrase, encrypted_seed)
else:
primary_seed = PassphraseBox.decrypt(
passphrase, encrypted_seed)
except:
raise InvalidPassphraseError()
self.multi_wallet = MultiWallet(
private_seeds={'primary': primary_seed},
public={'cosigner': wallet.cosigner_public_seed,
'backup': wallet.backup_public_seed})
return self
|
[
"def",
"unlock",
"(",
"self",
",",
"passphrase",
",",
"encrypted_seed",
"=",
"None",
")",
":",
"wallet",
"=",
"self",
".",
"resource",
"if",
"not",
"encrypted_seed",
":",
"encrypted_seed",
"=",
"wallet",
".",
"primary_private_seed",
"try",
":",
"if",
"encrypted_seed",
"[",
"'nonce'",
"]",
":",
"primary_seed",
"=",
"NaclPassphraseBox",
".",
"decrypt",
"(",
"passphrase",
",",
"encrypted_seed",
")",
"else",
":",
"primary_seed",
"=",
"PassphraseBox",
".",
"decrypt",
"(",
"passphrase",
",",
"encrypted_seed",
")",
"except",
":",
"raise",
"InvalidPassphraseError",
"(",
")",
"self",
".",
"multi_wallet",
"=",
"MultiWallet",
"(",
"private_seeds",
"=",
"{",
"'primary'",
":",
"primary_seed",
"}",
",",
"public",
"=",
"{",
"'cosigner'",
":",
"wallet",
".",
"cosigner_public_seed",
",",
"'backup'",
":",
"wallet",
".",
"backup_public_seed",
"}",
")",
"return",
"self"
] |
Unlock the Wallet by decrypting the primary_private_seed with the
supplied passphrase. Once unlocked, the private seed is accessible in
memory and calls to `account.pay` will succeed. This is a necessary step
for creating transactions.
Args:
passphrase (str): The passphrase the User used to encrypt this wallet.
encrypted_seed (dict): A dictionary of the form
{'ciphertext': longhexvalue,
'iterations': integer of pbkdf2 derivations,
'nonce': 24-byte hex value
'salt': 16-byte hex value}
this dict represents an private seed (not a master key) encrypted
with the `passphrase` using pbkdf2. You can obtain this value with
wallet.generate. If this value is supplied, it overwrites (locally
only) the encrypted primary_private_seed value, allowing you to load
in a primary key that you didn't store with Gem. Note that the key
MUST match the pubkey that this wallet was created with.
Returns:
self
|
[
"Unlock",
"the",
"Wallet",
"by",
"decrypting",
"the",
"primary_private_seed",
"with",
"the",
"supplied",
"passphrase",
".",
"Once",
"unlocked",
"the",
"private",
"seed",
"is",
"accessible",
"in",
"memory",
"and",
"calls",
"to",
"account",
".",
"pay",
"will",
"succeed",
".",
"This",
"is",
"a",
"necessary",
"step",
"for",
"creating",
"transactions",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L165-L204
|
245,347
|
GemHQ/round-py
|
round/wallets.py
|
Wallet.get_accounts
|
def get_accounts(self, fetch=False):
"""Return this Wallet's accounts object, populating it if fetch is True."""
return Accounts(self.resource.accounts, self.client, wallet=self, populate=fetch)
|
python
|
def get_accounts(self, fetch=False):
"""Return this Wallet's accounts object, populating it if fetch is True."""
return Accounts(self.resource.accounts, self.client, wallet=self, populate=fetch)
|
[
"def",
"get_accounts",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"Accounts",
"(",
"self",
".",
"resource",
".",
"accounts",
",",
"self",
".",
"client",
",",
"wallet",
"=",
"self",
",",
"populate",
"=",
"fetch",
")"
] |
Return this Wallet's accounts object, populating it if fetch is True.
|
[
"Return",
"this",
"Wallet",
"s",
"accounts",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L234-L236
|
245,348
|
GemHQ/round-py
|
round/wallets.py
|
Wallet.account
|
def account(self, key=None, address=None, name=None):
"""Query for an account by key, address, or name."""
if key:
return self.client.account(key, wallet=self)
if address:
q = dict(address=address)
elif name:
q = dict(name=name)
else:
raise TypeError("Missing param: key, address, or name is required.")
return Account(
self.resource.account_query(q).get(), self.client, wallet=self)
|
python
|
def account(self, key=None, address=None, name=None):
"""Query for an account by key, address, or name."""
if key:
return self.client.account(key, wallet=self)
if address:
q = dict(address=address)
elif name:
q = dict(name=name)
else:
raise TypeError("Missing param: key, address, or name is required.")
return Account(
self.resource.account_query(q).get(), self.client, wallet=self)
|
[
"def",
"account",
"(",
"self",
",",
"key",
"=",
"None",
",",
"address",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"key",
":",
"return",
"self",
".",
"client",
".",
"account",
"(",
"key",
",",
"wallet",
"=",
"self",
")",
"if",
"address",
":",
"q",
"=",
"dict",
"(",
"address",
"=",
"address",
")",
"elif",
"name",
":",
"q",
"=",
"dict",
"(",
"name",
"=",
"name",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Missing param: key, address, or name is required.\"",
")",
"return",
"Account",
"(",
"self",
".",
"resource",
".",
"account_query",
"(",
"q",
")",
".",
"get",
"(",
")",
",",
"self",
".",
"client",
",",
"wallet",
"=",
"self",
")"
] |
Query for an account by key, address, or name.
|
[
"Query",
"for",
"an",
"account",
"by",
"key",
"address",
"or",
"name",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L242-L254
|
245,349
|
GemHQ/round-py
|
round/wallets.py
|
Wallet.dump_addresses
|
def dump_addresses(self, network, filename=None):
"""Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network`
"""
addrs = [addr.data for a in self.accounts.values() if a.network == network
for addr in a.addresses]
if filename:
from json import dump
with open(filename, 'w') as f:
dump(addrs, f)
return addrs
|
python
|
def dump_addresses(self, network, filename=None):
"""Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network`
"""
addrs = [addr.data for a in self.accounts.values() if a.network == network
for addr in a.addresses]
if filename:
from json import dump
with open(filename, 'w') as f:
dump(addrs, f)
return addrs
|
[
"def",
"dump_addresses",
"(",
"self",
",",
"network",
",",
"filename",
"=",
"None",
")",
":",
"addrs",
"=",
"[",
"addr",
".",
"data",
"for",
"a",
"in",
"self",
".",
"accounts",
".",
"values",
"(",
")",
"if",
"a",
".",
"network",
"==",
"network",
"for",
"addr",
"in",
"a",
".",
"addresses",
"]",
"if",
"filename",
":",
"from",
"json",
"import",
"dump",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"dump",
"(",
"addrs",
",",
"f",
")",
"return",
"addrs"
] |
Return a list of address dictionaries for each address in all of the
accounts in this wallet of the network specified by `network`
|
[
"Return",
"a",
"list",
"of",
"address",
"dictionaries",
"for",
"each",
"address",
"in",
"all",
"of",
"the",
"accounts",
"in",
"this",
"wallet",
"of",
"the",
"network",
"specified",
"by",
"network"
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L256-L267
|
245,350
|
GemHQ/round-py
|
round/wallets.py
|
Wallet.get_subscriptions
|
def get_subscriptions(self, fetch=False):
"""Return this Wallet's subscriptions object, populating it if fetch is True."""
return Subscriptions(
self.resource.subscriptions, self.client, populate=fetch)
|
python
|
def get_subscriptions(self, fetch=False):
"""Return this Wallet's subscriptions object, populating it if fetch is True."""
return Subscriptions(
self.resource.subscriptions, self.client, populate=fetch)
|
[
"def",
"get_subscriptions",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"Subscriptions",
"(",
"self",
".",
"resource",
".",
"subscriptions",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
")"
] |
Return this Wallet's subscriptions object, populating it if fetch is True.
|
[
"Return",
"this",
"Wallet",
"s",
"subscriptions",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L275-L278
|
245,351
|
GemHQ/round-py
|
round/wallets.py
|
Wallet.signatures
|
def signatures(self, transaction):
"""Sign a transaction.
Args:
transaction (coinop.Transaction)
Returns:
A list of signature dicts of the form
[ {'primary': 'base58signaturestring'},
... ]
"""
# TODO: output.metadata['type']['change']
if not self.multi_wallet:
raise DecryptionError("This wallet must be unlocked with "
"wallet.unlock(passphrase)")
return self.multi_wallet.signatures(transaction)
|
python
|
def signatures(self, transaction):
"""Sign a transaction.
Args:
transaction (coinop.Transaction)
Returns:
A list of signature dicts of the form
[ {'primary': 'base58signaturestring'},
... ]
"""
# TODO: output.metadata['type']['change']
if not self.multi_wallet:
raise DecryptionError("This wallet must be unlocked with "
"wallet.unlock(passphrase)")
return self.multi_wallet.signatures(transaction)
|
[
"def",
"signatures",
"(",
"self",
",",
"transaction",
")",
":",
"# TODO: output.metadata['type']['change']",
"if",
"not",
"self",
".",
"multi_wallet",
":",
"raise",
"DecryptionError",
"(",
"\"This wallet must be unlocked with \"",
"\"wallet.unlock(passphrase)\"",
")",
"return",
"self",
".",
"multi_wallet",
".",
"signatures",
"(",
"transaction",
")"
] |
Sign a transaction.
Args:
transaction (coinop.Transaction)
Returns:
A list of signature dicts of the form
[ {'primary': 'base58signaturestring'},
... ]
|
[
"Sign",
"a",
"transaction",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L431-L447
|
245,352
|
quasipedia/swaggery
|
swaggery/utils.py
|
map_exception_codes
|
def map_exception_codes():
'''Helper function to intialise CODES_TO_EXCEPTIONS.'''
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code: e for _, e in werkex}
|
python
|
def map_exception_codes():
'''Helper function to intialise CODES_TO_EXCEPTIONS.'''
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code: e for _, e in werkex}
|
[
"def",
"map_exception_codes",
"(",
")",
":",
"werkex",
"=",
"inspect",
".",
"getmembers",
"(",
"exceptions",
",",
"lambda",
"x",
":",
"getattr",
"(",
"x",
",",
"'code'",
",",
"None",
")",
")",
"return",
"{",
"e",
".",
"code",
":",
"e",
"for",
"_",
",",
"e",
"in",
"werkex",
"}"
] |
Helper function to intialise CODES_TO_EXCEPTIONS.
|
[
"Helper",
"function",
"to",
"intialise",
"CODES_TO_EXCEPTIONS",
"."
] |
89a2e1b2bebbc511c781c9e63972f65aef73cc2f
|
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L98-L101
|
245,353
|
quasipedia/swaggery
|
swaggery/utils.py
|
extract_pathvars
|
def extract_pathvars(callback):
'''Extract the path variables from an Resource operation.
Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]}
'''
mandatory = []
optional = []
# We loop on the signature because the order of the parameters is
# important, and signature is an OrderedDict, while annotations is a
# regular dictionary
for pname in callback.signature.parameters.keys():
try:
anno = callback.__annotations__[pname]
except KeyError: # unannotated params, like "cls" or "request"
continue
if anno[0] != Ptypes.path:
continue
# At this point we are only considering path variables, but
# we have to generate different (present/absent) if these
# parameters have a default.
if callback.signature.parameters[pname].default == inspect._empty:
mandatory.append(pname)
else:
optional.append(pname)
return {'mandatory': mandatory, 'optional': optional}
|
python
|
def extract_pathvars(callback):
'''Extract the path variables from an Resource operation.
Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]}
'''
mandatory = []
optional = []
# We loop on the signature because the order of the parameters is
# important, and signature is an OrderedDict, while annotations is a
# regular dictionary
for pname in callback.signature.parameters.keys():
try:
anno = callback.__annotations__[pname]
except KeyError: # unannotated params, like "cls" or "request"
continue
if anno[0] != Ptypes.path:
continue
# At this point we are only considering path variables, but
# we have to generate different (present/absent) if these
# parameters have a default.
if callback.signature.parameters[pname].default == inspect._empty:
mandatory.append(pname)
else:
optional.append(pname)
return {'mandatory': mandatory, 'optional': optional}
|
[
"def",
"extract_pathvars",
"(",
"callback",
")",
":",
"mandatory",
"=",
"[",
"]",
"optional",
"=",
"[",
"]",
"# We loop on the signature because the order of the parameters is",
"# important, and signature is an OrderedDict, while annotations is a",
"# regular dictionary",
"for",
"pname",
"in",
"callback",
".",
"signature",
".",
"parameters",
".",
"keys",
"(",
")",
":",
"try",
":",
"anno",
"=",
"callback",
".",
"__annotations__",
"[",
"pname",
"]",
"except",
"KeyError",
":",
"# unannotated params, like \"cls\" or \"request\"",
"continue",
"if",
"anno",
"[",
"0",
"]",
"!=",
"Ptypes",
".",
"path",
":",
"continue",
"# At this point we are only considering path variables, but",
"# we have to generate different (present/absent) if these",
"# parameters have a default.",
"if",
"callback",
".",
"signature",
".",
"parameters",
"[",
"pname",
"]",
".",
"default",
"==",
"inspect",
".",
"_empty",
":",
"mandatory",
".",
"append",
"(",
"pname",
")",
"else",
":",
"optional",
".",
"append",
"(",
"pname",
")",
"return",
"{",
"'mandatory'",
":",
"mandatory",
",",
"'optional'",
":",
"optional",
"}"
] |
Extract the path variables from an Resource operation.
Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]}
|
[
"Extract",
"the",
"path",
"variables",
"from",
"an",
"Resource",
"operation",
"."
] |
89a2e1b2bebbc511c781c9e63972f65aef73cc2f
|
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L117-L141
|
245,354
|
quasipedia/swaggery
|
swaggery/utils.py
|
inject_extra_args
|
def inject_extra_args(callback, request, kwargs):
'''Inject extra arguments from header, body, form.'''
# TODO: this is a temporary pach, should be managed via honouring the
# mimetype in the request header....
annots = dict(callback.__annotations__)
del annots['return']
for param_name, (param_type, _) in annots.items():
if param_type == Ptypes.path:
continue # Already parsed by werkzeug
elif param_type == Ptypes.body:
value = getattr(request, PTYPE_TO_REQUEST_PROPERTY[param_type])
# TODO: The JSON conversion should be dependant from request
# header type, really...
value = json.loads(value.decode('utf-8'))
else:
get = lambda attr: getattr(request, attr).get(param_name, None)
value = get(PTYPE_TO_REQUEST_PROPERTY[param_type])
if value is not None:
kwargs[param_name] = value
|
python
|
def inject_extra_args(callback, request, kwargs):
'''Inject extra arguments from header, body, form.'''
# TODO: this is a temporary pach, should be managed via honouring the
# mimetype in the request header....
annots = dict(callback.__annotations__)
del annots['return']
for param_name, (param_type, _) in annots.items():
if param_type == Ptypes.path:
continue # Already parsed by werkzeug
elif param_type == Ptypes.body:
value = getattr(request, PTYPE_TO_REQUEST_PROPERTY[param_type])
# TODO: The JSON conversion should be dependant from request
# header type, really...
value = json.loads(value.decode('utf-8'))
else:
get = lambda attr: getattr(request, attr).get(param_name, None)
value = get(PTYPE_TO_REQUEST_PROPERTY[param_type])
if value is not None:
kwargs[param_name] = value
|
[
"def",
"inject_extra_args",
"(",
"callback",
",",
"request",
",",
"kwargs",
")",
":",
"# TODO: this is a temporary pach, should be managed via honouring the",
"# mimetype in the request header....",
"annots",
"=",
"dict",
"(",
"callback",
".",
"__annotations__",
")",
"del",
"annots",
"[",
"'return'",
"]",
"for",
"param_name",
",",
"(",
"param_type",
",",
"_",
")",
"in",
"annots",
".",
"items",
"(",
")",
":",
"if",
"param_type",
"==",
"Ptypes",
".",
"path",
":",
"continue",
"# Already parsed by werkzeug",
"elif",
"param_type",
"==",
"Ptypes",
".",
"body",
":",
"value",
"=",
"getattr",
"(",
"request",
",",
"PTYPE_TO_REQUEST_PROPERTY",
"[",
"param_type",
"]",
")",
"# TODO: The JSON conversion should be dependant from request",
"# header type, really...",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"else",
":",
"get",
"=",
"lambda",
"attr",
":",
"getattr",
"(",
"request",
",",
"attr",
")",
".",
"get",
"(",
"param_name",
",",
"None",
")",
"value",
"=",
"get",
"(",
"PTYPE_TO_REQUEST_PROPERTY",
"[",
"param_type",
"]",
")",
"if",
"value",
"is",
"not",
"None",
":",
"kwargs",
"[",
"param_name",
"]",
"=",
"value"
] |
Inject extra arguments from header, body, form.
|
[
"Inject",
"extra",
"arguments",
"from",
"header",
"body",
"form",
"."
] |
89a2e1b2bebbc511c781c9e63972f65aef73cc2f
|
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L155-L173
|
245,355
|
quasipedia/swaggery
|
swaggery/utils.py
|
filter_annotations_by_ptype
|
def filter_annotations_by_ptype(function, ptype):
'''Filter an annotation by only leaving the parameters of type "ptype".'''
ret = {}
for k, v in function.__annotations__.items():
if k == 'return':
continue
pt, _ = v
if pt == ptype:
ret[k] = v
return ret
|
python
|
def filter_annotations_by_ptype(function, ptype):
'''Filter an annotation by only leaving the parameters of type "ptype".'''
ret = {}
for k, v in function.__annotations__.items():
if k == 'return':
continue
pt, _ = v
if pt == ptype:
ret[k] = v
return ret
|
[
"def",
"filter_annotations_by_ptype",
"(",
"function",
",",
"ptype",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"function",
".",
"__annotations__",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'return'",
":",
"continue",
"pt",
",",
"_",
"=",
"v",
"if",
"pt",
"==",
"ptype",
":",
"ret",
"[",
"k",
"]",
"=",
"v",
"return",
"ret"
] |
Filter an annotation by only leaving the parameters of type "ptype".
|
[
"Filter",
"an",
"annotation",
"by",
"only",
"leaving",
"the",
"parameters",
"of",
"type",
"ptype",
"."
] |
89a2e1b2bebbc511c781c9e63972f65aef73cc2f
|
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/utils.py#L183-L192
|
245,356
|
Tsjerk/simopt
|
simopt.py
|
option2tuple
|
def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = opt[1], opt[2:]
else:
tup = opt[0], opt[1:]
return tup
|
python
|
def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = opt[1], opt[2:]
else:
tup = opt[0], opt[1:]
return tup
|
[
"def",
"option2tuple",
"(",
"opt",
")",
":",
"if",
"isinstance",
"(",
"opt",
"[",
"0",
"]",
",",
"int",
")",
":",
"tup",
"=",
"opt",
"[",
"1",
"]",
",",
"opt",
"[",
"2",
":",
"]",
"else",
":",
"tup",
"=",
"opt",
"[",
"0",
"]",
",",
"opt",
"[",
"1",
":",
"]",
"return",
"tup"
] |
Return a tuple of option, taking possible presence of level into account
|
[
"Return",
"a",
"tuple",
"of",
"option",
"taking",
"possible",
"presence",
"of",
"level",
"into",
"account"
] |
fa63360492af35ccb92116000325b2bbf5961703
|
https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L191-L199
|
245,357
|
Tsjerk/simopt
|
simopt.py
|
opt_func
|
def opt_func(options, check_mandatory=True):
"""
Restore argument checks for functions that takes options dicts as arguments
Functions that take the option dictionary produced by :meth:`Options.parse`
as `kwargs` loose the argument checking usually performed by the python
interpretor. They also loose the ability to take default values for
their keyword arguments. Such function is basically unusable without the
full dictionary produced by the option parser.
This is a decorator that restores argument checking and default values
assignment on the basis of an :class:`Options` instance.
options = Options([
(0, "-f", "input", str, 1, None, MULTI, "Input file"),
(0, "-o", "output", str, 1, None, MA, "Output file"),
(0, "-p", "topology", str, 1, None, 0, "Optional topology"),
])
@opt_func(options)
def process_things(**arguments):
# Do something
return
# The function can be called with the arguments
# from the argument parser
arguments = options.parse()
process_things(**arguments)
# It can be called with only part of the arguments,
# the other arguments will be set to their default as defined by
# the Options instance
process_things(output='output.gro')
# If the function is called with an unknown argument, the decorator
# raises a TypeError
process_things(unknown=None)
# Likewise, if the function is called without the mandatory arguments,
# the decorator raises a TypeError
process_things(topology='topology.top')
# The check for mandatory arguments can be deactivated
@opt_func(options, check_mandatory=False)
def process_things(**arguments):
# Do things
return
Note that the decorator cannot be used on functions that accept Other
arguments than the one defined in the :class:`Options` instance. Also, the
arguments have to be given as keyword arguments. Positional arguments
will cause the decorator to raise a `TypeError`.
"""
# A function `my_function` decorated with `opt_func` is replaced by
# `opt_func(options)(my_function)`. This is equivalent to
# `validate_arguments(my_function)` using the `options` argument provided
# to the decorator. A call to `my_function` results in a call to
# `opt_func(options)(my_function)(*args, **kwargs)`
# ^^^^^^^^^^^^^^^^^^ validate_arguments
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ wrap
def validate_arguments(func):
@functools.wraps(func)
def wrap(*args, **kwargs):
if args:
raise TypeError('{0.__name__}() takes 0 positional arguments '
'but {1} was given'.format(func, len(args)))
keys = set(kwargs.keys())
missing = options.mandatory_keys - keys
if missing and check_mandatory:
raise TypeError('{0.__name__}() is missing the following '
'mandatory keyword arguments: {1}'
.format(func, ', '.join(missing)))
arguments = options._default_dict()
unknown = keys - set(arguments.keys())
if unknown:
raise TypeError('{0.__name__}() received the following '
'unexpected arguments: {1}'
.format(func, ', '.join(unknown)))
arguments.update(**kwargs)
return func(**arguments)
return wrap
return validate_arguments
|
python
|
def opt_func(options, check_mandatory=True):
"""
Restore argument checks for functions that takes options dicts as arguments
Functions that take the option dictionary produced by :meth:`Options.parse`
as `kwargs` loose the argument checking usually performed by the python
interpretor. They also loose the ability to take default values for
their keyword arguments. Such function is basically unusable without the
full dictionary produced by the option parser.
This is a decorator that restores argument checking and default values
assignment on the basis of an :class:`Options` instance.
options = Options([
(0, "-f", "input", str, 1, None, MULTI, "Input file"),
(0, "-o", "output", str, 1, None, MA, "Output file"),
(0, "-p", "topology", str, 1, None, 0, "Optional topology"),
])
@opt_func(options)
def process_things(**arguments):
# Do something
return
# The function can be called with the arguments
# from the argument parser
arguments = options.parse()
process_things(**arguments)
# It can be called with only part of the arguments,
# the other arguments will be set to their default as defined by
# the Options instance
process_things(output='output.gro')
# If the function is called with an unknown argument, the decorator
# raises a TypeError
process_things(unknown=None)
# Likewise, if the function is called without the mandatory arguments,
# the decorator raises a TypeError
process_things(topology='topology.top')
# The check for mandatory arguments can be deactivated
@opt_func(options, check_mandatory=False)
def process_things(**arguments):
# Do things
return
Note that the decorator cannot be used on functions that accept Other
arguments than the one defined in the :class:`Options` instance. Also, the
arguments have to be given as keyword arguments. Positional arguments
will cause the decorator to raise a `TypeError`.
"""
# A function `my_function` decorated with `opt_func` is replaced by
# `opt_func(options)(my_function)`. This is equivalent to
# `validate_arguments(my_function)` using the `options` argument provided
# to the decorator. A call to `my_function` results in a call to
# `opt_func(options)(my_function)(*args, **kwargs)`
# ^^^^^^^^^^^^^^^^^^ validate_arguments
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ wrap
def validate_arguments(func):
@functools.wraps(func)
def wrap(*args, **kwargs):
if args:
raise TypeError('{0.__name__}() takes 0 positional arguments '
'but {1} was given'.format(func, len(args)))
keys = set(kwargs.keys())
missing = options.mandatory_keys - keys
if missing and check_mandatory:
raise TypeError('{0.__name__}() is missing the following '
'mandatory keyword arguments: {1}'
.format(func, ', '.join(missing)))
arguments = options._default_dict()
unknown = keys - set(arguments.keys())
if unknown:
raise TypeError('{0.__name__}() received the following '
'unexpected arguments: {1}'
.format(func, ', '.join(unknown)))
arguments.update(**kwargs)
return func(**arguments)
return wrap
return validate_arguments
|
[
"def",
"opt_func",
"(",
"options",
",",
"check_mandatory",
"=",
"True",
")",
":",
"# A function `my_function` decorated with `opt_func` is replaced by",
"# `opt_func(options)(my_function)`. This is equivalent to",
"# `validate_arguments(my_function)` using the `options` argument provided",
"# to the decorator. A call to `my_function` results in a call to",
"# `opt_func(options)(my_function)(*args, **kwargs)`",
"# ^^^^^^^^^^^^^^^^^^ validate_arguments",
"# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ wrap",
"def",
"validate_arguments",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"raise",
"TypeError",
"(",
"'{0.__name__}() takes 0 positional arguments '",
"'but {1} was given'",
".",
"format",
"(",
"func",
",",
"len",
"(",
"args",
")",
")",
")",
"keys",
"=",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"missing",
"=",
"options",
".",
"mandatory_keys",
"-",
"keys",
"if",
"missing",
"and",
"check_mandatory",
":",
"raise",
"TypeError",
"(",
"'{0.__name__}() is missing the following '",
"'mandatory keyword arguments: {1}'",
".",
"format",
"(",
"func",
",",
"', '",
".",
"join",
"(",
"missing",
")",
")",
")",
"arguments",
"=",
"options",
".",
"_default_dict",
"(",
")",
"unknown",
"=",
"keys",
"-",
"set",
"(",
"arguments",
".",
"keys",
"(",
")",
")",
"if",
"unknown",
":",
"raise",
"TypeError",
"(",
"'{0.__name__}() received the following '",
"'unexpected arguments: {1}'",
".",
"format",
"(",
"func",
",",
"', '",
".",
"join",
"(",
"unknown",
")",
")",
")",
"arguments",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"return",
"func",
"(",
"*",
"*",
"arguments",
")",
"return",
"wrap",
"return",
"validate_arguments"
] |
Restore argument checks for functions that takes options dicts as arguments
Functions that take the option dictionary produced by :meth:`Options.parse`
as `kwargs` loose the argument checking usually performed by the python
interpretor. They also loose the ability to take default values for
their keyword arguments. Such function is basically unusable without the
full dictionary produced by the option parser.
This is a decorator that restores argument checking and default values
assignment on the basis of an :class:`Options` instance.
options = Options([
(0, "-f", "input", str, 1, None, MULTI, "Input file"),
(0, "-o", "output", str, 1, None, MA, "Output file"),
(0, "-p", "topology", str, 1, None, 0, "Optional topology"),
])
@opt_func(options)
def process_things(**arguments):
# Do something
return
# The function can be called with the arguments
# from the argument parser
arguments = options.parse()
process_things(**arguments)
# It can be called with only part of the arguments,
# the other arguments will be set to their default as defined by
# the Options instance
process_things(output='output.gro')
# If the function is called with an unknown argument, the decorator
# raises a TypeError
process_things(unknown=None)
# Likewise, if the function is called without the mandatory arguments,
# the decorator raises a TypeError
process_things(topology='topology.top')
# The check for mandatory arguments can be deactivated
@opt_func(options, check_mandatory=False)
def process_things(**arguments):
# Do things
return
Note that the decorator cannot be used on functions that accept Other
arguments than the one defined in the :class:`Options` instance. Also, the
arguments have to be given as keyword arguments. Positional arguments
will cause the decorator to raise a `TypeError`.
|
[
"Restore",
"argument",
"checks",
"for",
"functions",
"that",
"takes",
"options",
"dicts",
"as",
"arguments"
] |
fa63360492af35ccb92116000325b2bbf5961703
|
https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L202-L283
|
245,358
|
Tsjerk/simopt
|
simopt.py
|
Options._default_dict
|
def _default_dict(self):
"""Return a dictionary with the default for each option."""
options = {}
for attr, _, _, default, multi, _ in self._optiondict.values():
if multi and default is None:
options[attr] = []
else:
options[attr] = default
return options
|
python
|
def _default_dict(self):
"""Return a dictionary with the default for each option."""
options = {}
for attr, _, _, default, multi, _ in self._optiondict.values():
if multi and default is None:
options[attr] = []
else:
options[attr] = default
return options
|
[
"def",
"_default_dict",
"(",
"self",
")",
":",
"options",
"=",
"{",
"}",
"for",
"attr",
",",
"_",
",",
"_",
",",
"default",
",",
"multi",
",",
"_",
"in",
"self",
".",
"_optiondict",
".",
"values",
"(",
")",
":",
"if",
"multi",
"and",
"default",
"is",
"None",
":",
"options",
"[",
"attr",
"]",
"=",
"[",
"]",
"else",
":",
"options",
"[",
"attr",
"]",
"=",
"default",
"return",
"options"
] |
Return a dictionary with the default for each option.
|
[
"Return",
"a",
"dictionary",
"with",
"the",
"default",
"for",
"each",
"option",
"."
] |
fa63360492af35ccb92116000325b2bbf5961703
|
https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L87-L95
|
245,359
|
Tsjerk/simopt
|
simopt.py
|
Options.help
|
def help(self, args=None, userlevel=9):
"""Make a string from the option list"""
out = [main.__file__+"\n"]
if args is not None:
parsed = self.parse(args, ignore_help=True)
else:
parsed = self._default_dict()
for thing in self.options:
if type(thing) == str:
out.append(" "+thing)
elif thing[0] <= userlevel:
out.append(" %10s %s ( %s )" % (thing[1], thing[-1], str(parsed[thing[2]])))
return "\n".join(out)+"\n"
|
python
|
def help(self, args=None, userlevel=9):
"""Make a string from the option list"""
out = [main.__file__+"\n"]
if args is not None:
parsed = self.parse(args, ignore_help=True)
else:
parsed = self._default_dict()
for thing in self.options:
if type(thing) == str:
out.append(" "+thing)
elif thing[0] <= userlevel:
out.append(" %10s %s ( %s )" % (thing[1], thing[-1], str(parsed[thing[2]])))
return "\n".join(out)+"\n"
|
[
"def",
"help",
"(",
"self",
",",
"args",
"=",
"None",
",",
"userlevel",
"=",
"9",
")",
":",
"out",
"=",
"[",
"main",
".",
"__file__",
"+",
"\"\\n\"",
"]",
"if",
"args",
"is",
"not",
"None",
":",
"parsed",
"=",
"self",
".",
"parse",
"(",
"args",
",",
"ignore_help",
"=",
"True",
")",
"else",
":",
"parsed",
"=",
"self",
".",
"_default_dict",
"(",
")",
"for",
"thing",
"in",
"self",
".",
"options",
":",
"if",
"type",
"(",
"thing",
")",
"==",
"str",
":",
"out",
".",
"append",
"(",
"\" \"",
"+",
"thing",
")",
"elif",
"thing",
"[",
"0",
"]",
"<=",
"userlevel",
":",
"out",
".",
"append",
"(",
"\" %10s %s ( %s )\"",
"%",
"(",
"thing",
"[",
"1",
"]",
",",
"thing",
"[",
"-",
"1",
"]",
",",
"str",
"(",
"parsed",
"[",
"thing",
"[",
"2",
"]",
"]",
")",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"out",
")",
"+",
"\"\\n\""
] |
Make a string from the option list
|
[
"Make",
"a",
"string",
"from",
"the",
"option",
"list"
] |
fa63360492af35ccb92116000325b2bbf5961703
|
https://github.com/Tsjerk/simopt/blob/fa63360492af35ccb92116000325b2bbf5961703/simopt.py#L118-L133
|
245,360
|
tlatsas/wigiki
|
wigiki/builder.py
|
Builder.page_list
|
def page_list(cls, pages, base_url='/'):
"""transform a list of page titles in a list of html links"""
plist = []
for page in pages:
url = "<a href=\"{}{}\">{}</a>".format(base_url, cls.slugify(page), page)
plist.append(url)
return plist
|
python
|
def page_list(cls, pages, base_url='/'):
"""transform a list of page titles in a list of html links"""
plist = []
for page in pages:
url = "<a href=\"{}{}\">{}</a>".format(base_url, cls.slugify(page), page)
plist.append(url)
return plist
|
[
"def",
"page_list",
"(",
"cls",
",",
"pages",
",",
"base_url",
"=",
"'/'",
")",
":",
"plist",
"=",
"[",
"]",
"for",
"page",
"in",
"pages",
":",
"url",
"=",
"\"<a href=\\\"{}{}\\\">{}</a>\"",
".",
"format",
"(",
"base_url",
",",
"cls",
".",
"slugify",
"(",
"page",
")",
",",
"page",
")",
"plist",
".",
"append",
"(",
"url",
")",
"return",
"plist"
] |
transform a list of page titles in a list of html links
|
[
"transform",
"a",
"list",
"of",
"page",
"titles",
"in",
"a",
"list",
"of",
"html",
"links"
] |
baf9c5a6523a9b90db7572330d04e3e199391273
|
https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/builder.py#L14-L20
|
245,361
|
tlatsas/wigiki
|
wigiki/builder.py
|
Builder.slugify
|
def slugify(cls, s):
"""Return the slug version of the string ``s``"""
slug = re.sub("[^0-9a-zA-Z-]", "-", s)
return re.sub("-{2,}", "-", slug).strip('-')
|
python
|
def slugify(cls, s):
"""Return the slug version of the string ``s``"""
slug = re.sub("[^0-9a-zA-Z-]", "-", s)
return re.sub("-{2,}", "-", slug).strip('-')
|
[
"def",
"slugify",
"(",
"cls",
",",
"s",
")",
":",
"slug",
"=",
"re",
".",
"sub",
"(",
"\"[^0-9a-zA-Z-]\"",
",",
"\"-\"",
",",
"s",
")",
"return",
"re",
".",
"sub",
"(",
"\"-{2,}\"",
",",
"\"-\"",
",",
"slug",
")",
".",
"strip",
"(",
"'-'",
")"
] |
Return the slug version of the string ``s``
|
[
"Return",
"the",
"slug",
"version",
"of",
"the",
"string",
"s"
] |
baf9c5a6523a9b90db7572330d04e3e199391273
|
https://github.com/tlatsas/wigiki/blob/baf9c5a6523a9b90db7572330d04e3e199391273/wigiki/builder.py#L24-L27
|
245,362
|
disqus/nose-socket-whitelist
|
src/socketwhitelist/plugins.py
|
SocketWhitelistPlugin.is_whitelisted
|
def is_whitelisted(self, addrinfo):
"""
Returns if a result of ``socket.getaddrinfo`` is in the socket address
whitelist.
"""
# For details about the ``getaddrinfo`` struct, see the Python docs:
# http://docs.python.org/library/socket.html#socket.getaddrinfo
family, socktype, proto, canonname, sockaddr = addrinfo
address, port = sockaddr[:2]
return address in self.socket_address_whitelist
|
python
|
def is_whitelisted(self, addrinfo):
"""
Returns if a result of ``socket.getaddrinfo`` is in the socket address
whitelist.
"""
# For details about the ``getaddrinfo`` struct, see the Python docs:
# http://docs.python.org/library/socket.html#socket.getaddrinfo
family, socktype, proto, canonname, sockaddr = addrinfo
address, port = sockaddr[:2]
return address in self.socket_address_whitelist
|
[
"def",
"is_whitelisted",
"(",
"self",
",",
"addrinfo",
")",
":",
"# For details about the ``getaddrinfo`` struct, see the Python docs:",
"# http://docs.python.org/library/socket.html#socket.getaddrinfo",
"family",
",",
"socktype",
",",
"proto",
",",
"canonname",
",",
"sockaddr",
"=",
"addrinfo",
"address",
",",
"port",
"=",
"sockaddr",
"[",
":",
"2",
"]",
"return",
"address",
"in",
"self",
".",
"socket_address_whitelist"
] |
Returns if a result of ``socket.getaddrinfo`` is in the socket address
whitelist.
|
[
"Returns",
"if",
"a",
"result",
"of",
"socket",
".",
"getaddrinfo",
"is",
"in",
"the",
"socket",
"address",
"whitelist",
"."
] |
062f9bac079a01f74a94abda977c9a28ad472f39
|
https://github.com/disqus/nose-socket-whitelist/blob/062f9bac079a01f74a94abda977c9a28ad472f39/src/socketwhitelist/plugins.py#L94-L103
|
245,363
|
disqus/nose-socket-whitelist
|
src/socketwhitelist/plugins.py
|
LoggingSocketWhitelistPlugin.report
|
def report(self):
"""
Performs rollups, prints report of sockets opened.
"""
aggregations = dict(
(test, Counter().rollup(values))
for test, values in self.socket_warnings.items()
)
total = sum(
len(warnings)
for warnings in self.socket_warnings.values()
)
def format_test_statistics(test, counter):
return "%s:\n%s" % (
test,
'\n'.join(
' - %s: %s' % (socket, count)
for socket, count in counter.items()
)
)
def format_statistics(aggregations):
return '\n'.join(
format_test_statistics(test, counter)
for test, counter in aggregations.items()
)
# Only print the report if there are actually things to report.
if aggregations:
print('=' * 70, file=self.stream)
print(
'NON-WHITELISTED SOCKETS OPENED: %s' % total,
file=self.stream,
)
print('-' * 70, file=self.stream)
print(format_statistics(aggregations), file=self.stream)
|
python
|
def report(self):
"""
Performs rollups, prints report of sockets opened.
"""
aggregations = dict(
(test, Counter().rollup(values))
for test, values in self.socket_warnings.items()
)
total = sum(
len(warnings)
for warnings in self.socket_warnings.values()
)
def format_test_statistics(test, counter):
return "%s:\n%s" % (
test,
'\n'.join(
' - %s: %s' % (socket, count)
for socket, count in counter.items()
)
)
def format_statistics(aggregations):
return '\n'.join(
format_test_statistics(test, counter)
for test, counter in aggregations.items()
)
# Only print the report if there are actually things to report.
if aggregations:
print('=' * 70, file=self.stream)
print(
'NON-WHITELISTED SOCKETS OPENED: %s' % total,
file=self.stream,
)
print('-' * 70, file=self.stream)
print(format_statistics(aggregations), file=self.stream)
|
[
"def",
"report",
"(",
"self",
")",
":",
"aggregations",
"=",
"dict",
"(",
"(",
"test",
",",
"Counter",
"(",
")",
".",
"rollup",
"(",
"values",
")",
")",
"for",
"test",
",",
"values",
"in",
"self",
".",
"socket_warnings",
".",
"items",
"(",
")",
")",
"total",
"=",
"sum",
"(",
"len",
"(",
"warnings",
")",
"for",
"warnings",
"in",
"self",
".",
"socket_warnings",
".",
"values",
"(",
")",
")",
"def",
"format_test_statistics",
"(",
"test",
",",
"counter",
")",
":",
"return",
"\"%s:\\n%s\"",
"%",
"(",
"test",
",",
"'\\n'",
".",
"join",
"(",
"' - %s: %s'",
"%",
"(",
"socket",
",",
"count",
")",
"for",
"socket",
",",
"count",
"in",
"counter",
".",
"items",
"(",
")",
")",
")",
"def",
"format_statistics",
"(",
"aggregations",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"format_test_statistics",
"(",
"test",
",",
"counter",
")",
"for",
"test",
",",
"counter",
"in",
"aggregations",
".",
"items",
"(",
")",
")",
"# Only print the report if there are actually things to report.",
"if",
"aggregations",
":",
"print",
"(",
"'='",
"*",
"70",
",",
"file",
"=",
"self",
".",
"stream",
")",
"print",
"(",
"'NON-WHITELISTED SOCKETS OPENED: %s'",
"%",
"total",
",",
"file",
"=",
"self",
".",
"stream",
",",
")",
"print",
"(",
"'-'",
"*",
"70",
",",
"file",
"=",
"self",
".",
"stream",
")",
"print",
"(",
"format_statistics",
"(",
"aggregations",
")",
",",
"file",
"=",
"self",
".",
"stream",
")"
] |
Performs rollups, prints report of sockets opened.
|
[
"Performs",
"rollups",
"prints",
"report",
"of",
"sockets",
"opened",
"."
] |
062f9bac079a01f74a94abda977c9a28ad472f39
|
https://github.com/disqus/nose-socket-whitelist/blob/062f9bac079a01f74a94abda977c9a28ad472f39/src/socketwhitelist/plugins.py#L146-L182
|
245,364
|
pip-services3-python/pip-services3-components-python
|
pip_services3_components/count/CachedCounters.py
|
CachedCounters.get_all
|
def get_all(self):
"""
Gets all captured counters.
:return: a list with counters.
"""
self._lock.acquire()
try:
return list(self._cache.values())
finally:
self._lock.release()
|
python
|
def get_all(self):
"""
Gets all captured counters.
:return: a list with counters.
"""
self._lock.acquire()
try:
return list(self._cache.values())
finally:
self._lock.release()
|
[
"def",
"get_all",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"list",
"(",
"self",
".",
"_cache",
".",
"values",
"(",
")",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
Gets all captured counters.
:return: a list with counters.
|
[
"Gets",
"all",
"captured",
"counters",
"."
] |
1de9c1bb544cf1891111e9a5f5d67653f62c9b52
|
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L129-L139
|
245,365
|
pip-services3-python/pip-services3-components-python
|
pip_services3_components/count/CachedCounters.py
|
CachedCounters.get
|
def get(self, name, typ):
"""
Gets a counter specified by its name.
It counter does not exist or its type doesn't match the specified type
it creates a new one.
:param name: a counter name to retrieve.
:param typ: a counter type.
:return: an existing or newly created counter of the specified type.
"""
if name == None or len(name) == 0:
raise Exception("Counter name was not set")
self._lock.acquire()
try:
counter = self._cache[name] if name in self._cache else None
if counter == None or counter.type != typ:
counter = Counter(name, typ)
self._cache[name] = counter
return counter
finally:
self._lock.release()
|
python
|
def get(self, name, typ):
"""
Gets a counter specified by its name.
It counter does not exist or its type doesn't match the specified type
it creates a new one.
:param name: a counter name to retrieve.
:param typ: a counter type.
:return: an existing or newly created counter of the specified type.
"""
if name == None or len(name) == 0:
raise Exception("Counter name was not set")
self._lock.acquire()
try:
counter = self._cache[name] if name in self._cache else None
if counter == None or counter.type != typ:
counter = Counter(name, typ)
self._cache[name] = counter
return counter
finally:
self._lock.release()
|
[
"def",
"get",
"(",
"self",
",",
"name",
",",
"typ",
")",
":",
"if",
"name",
"==",
"None",
"or",
"len",
"(",
"name",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Counter name was not set\"",
")",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"counter",
"=",
"self",
".",
"_cache",
"[",
"name",
"]",
"if",
"name",
"in",
"self",
".",
"_cache",
"else",
"None",
"if",
"counter",
"==",
"None",
"or",
"counter",
".",
"type",
"!=",
"typ",
":",
"counter",
"=",
"Counter",
"(",
"name",
",",
"typ",
")",
"self",
".",
"_cache",
"[",
"name",
"]",
"=",
"counter",
"return",
"counter",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
Gets a counter specified by its name.
It counter does not exist or its type doesn't match the specified type
it creates a new one.
:param name: a counter name to retrieve.
:param typ: a counter type.
:return: an existing or newly created counter of the specified type.
|
[
"Gets",
"a",
"counter",
"specified",
"by",
"its",
"name",
".",
"It",
"counter",
"does",
"not",
"exist",
"or",
"its",
"type",
"doesn",
"t",
"match",
"the",
"specified",
"type",
"it",
"creates",
"a",
"new",
"one",
"."
] |
1de9c1bb544cf1891111e9a5f5d67653f62c9b52
|
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L142-L167
|
245,366
|
lambdalisue/maidenhair
|
src/maidenhair/parsers/base.py
|
BaseParser.load
|
def load(self, filename, **kwargs):
"""
Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array
"""
with open(filename, 'r') as f:
return self.parse(f, **kwargs)
|
python
|
def load(self, filename, **kwargs):
"""
Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array
"""
with open(filename, 'r') as f:
return self.parse(f, **kwargs)
|
[
"def",
"load",
"(",
"self",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"self",
".",
"parse",
"(",
"f",
",",
"*",
"*",
"kwargs",
")"
] |
Parse a file specified with the filename and return an numpy array
Parameters
----------
filename : string
A path of a file
Returns
-------
ndarray
An instance of numpy array
|
[
"Parse",
"a",
"file",
"specified",
"with",
"the",
"filename",
"and",
"return",
"an",
"numpy",
"array"
] |
d5095c1087d1f4d71cc57410492151d2803a9f0d
|
https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/parsers/base.py#L33-L49
|
245,367
|
madisona/django-image-helper
|
image_helper/fields.py
|
_get_thumbnail_filename
|
def _get_thumbnail_filename(filename, append_text="-thumbnail"):
"""
Returns a thumbnail version of the file name.
"""
name, ext = os.path.splitext(filename)
return ''.join([name, append_text, ext])
|
python
|
def _get_thumbnail_filename(filename, append_text="-thumbnail"):
"""
Returns a thumbnail version of the file name.
"""
name, ext = os.path.splitext(filename)
return ''.join([name, append_text, ext])
|
[
"def",
"_get_thumbnail_filename",
"(",
"filename",
",",
"append_text",
"=",
"\"-thumbnail\"",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"return",
"''",
".",
"join",
"(",
"[",
"name",
",",
"append_text",
",",
"ext",
"]",
")"
] |
Returns a thumbnail version of the file name.
|
[
"Returns",
"a",
"thumbnail",
"version",
"of",
"the",
"file",
"name",
"."
] |
2dbad297486bf5e50d86f12f85e51da31e50ac22
|
https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L16-L21
|
245,368
|
madisona/django-image-helper
|
image_helper/fields.py
|
SizedImageField.contribute_to_class
|
def contribute_to_class(self, cls, name):
"""
Makes sure thumbnail gets set when image field initialized.
"""
super(SizedImageField, self).contribute_to_class(cls, name)
signals.post_init.connect(self._set_thumbnail, sender=cls)
|
python
|
def contribute_to_class(self, cls, name):
"""
Makes sure thumbnail gets set when image field initialized.
"""
super(SizedImageField, self).contribute_to_class(cls, name)
signals.post_init.connect(self._set_thumbnail, sender=cls)
|
[
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
")",
":",
"super",
"(",
"SizedImageField",
",",
"self",
")",
".",
"contribute_to_class",
"(",
"cls",
",",
"name",
")",
"signals",
".",
"post_init",
".",
"connect",
"(",
"self",
".",
"_set_thumbnail",
",",
"sender",
"=",
"cls",
")"
] |
Makes sure thumbnail gets set when image field initialized.
|
[
"Makes",
"sure",
"thumbnail",
"gets",
"set",
"when",
"image",
"field",
"initialized",
"."
] |
2dbad297486bf5e50d86f12f85e51da31e50ac22
|
https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L97-L102
|
245,369
|
madisona/django-image-helper
|
image_helper/fields.py
|
SizedImageField.pre_save
|
def pre_save(self, model_instance, add):
"""
Resizes, commits image to storage, and returns field's value just before saving.
"""
file = getattr(model_instance, self.attname)
if file and not file._committed:
file.name = self._clean_file_name(model_instance, file.name)
file.file = self._resize_image(model_instance, file)
file.save(file.name, file, save=False)
return file
|
python
|
def pre_save(self, model_instance, add):
"""
Resizes, commits image to storage, and returns field's value just before saving.
"""
file = getattr(model_instance, self.attname)
if file and not file._committed:
file.name = self._clean_file_name(model_instance, file.name)
file.file = self._resize_image(model_instance, file)
file.save(file.name, file, save=False)
return file
|
[
"def",
"pre_save",
"(",
"self",
",",
"model_instance",
",",
"add",
")",
":",
"file",
"=",
"getattr",
"(",
"model_instance",
",",
"self",
".",
"attname",
")",
"if",
"file",
"and",
"not",
"file",
".",
"_committed",
":",
"file",
".",
"name",
"=",
"self",
".",
"_clean_file_name",
"(",
"model_instance",
",",
"file",
".",
"name",
")",
"file",
".",
"file",
"=",
"self",
".",
"_resize_image",
"(",
"model_instance",
",",
"file",
")",
"file",
".",
"save",
"(",
"file",
".",
"name",
",",
"file",
",",
"save",
"=",
"False",
")",
"return",
"file"
] |
Resizes, commits image to storage, and returns field's value just before saving.
|
[
"Resizes",
"commits",
"image",
"to",
"storage",
"and",
"returns",
"field",
"s",
"value",
"just",
"before",
"saving",
"."
] |
2dbad297486bf5e50d86f12f85e51da31e50ac22
|
https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L104-L113
|
245,370
|
madisona/django-image-helper
|
image_helper/fields.py
|
SizedImageField._clean_file_name
|
def _clean_file_name(self, model_instance, filename):
"""
We need to make sure we know the full file name before we save the thumbnail so
we can be sure the name doesn't change on save.
This method gets the available filename and returns just the file part.
"""
available_name = self.storage.get_available_name(
self.generate_filename(model_instance, filename))
return os.path.basename(available_name)
|
python
|
def _clean_file_name(self, model_instance, filename):
"""
We need to make sure we know the full file name before we save the thumbnail so
we can be sure the name doesn't change on save.
This method gets the available filename and returns just the file part.
"""
available_name = self.storage.get_available_name(
self.generate_filename(model_instance, filename))
return os.path.basename(available_name)
|
[
"def",
"_clean_file_name",
"(",
"self",
",",
"model_instance",
",",
"filename",
")",
":",
"available_name",
"=",
"self",
".",
"storage",
".",
"get_available_name",
"(",
"self",
".",
"generate_filename",
"(",
"model_instance",
",",
"filename",
")",
")",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"available_name",
")"
] |
We need to make sure we know the full file name before we save the thumbnail so
we can be sure the name doesn't change on save.
This method gets the available filename and returns just the file part.
|
[
"We",
"need",
"to",
"make",
"sure",
"we",
"know",
"the",
"full",
"file",
"name",
"before",
"we",
"save",
"the",
"thumbnail",
"so",
"we",
"can",
"be",
"sure",
"the",
"name",
"doesn",
"t",
"change",
"on",
"save",
"."
] |
2dbad297486bf5e50d86f12f85e51da31e50ac22
|
https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L115-L124
|
245,371
|
madisona/django-image-helper
|
image_helper/fields.py
|
SizedImageField._create_thumbnail
|
def _create_thumbnail(self, model_instance, thumbnail, image_name):
"""
Resizes and saves the thumbnail image
"""
thumbnail = self._do_resize(thumbnail, self.thumbnail_size)
full_image_name = self.generate_filename(model_instance, image_name)
thumbnail_filename = _get_thumbnail_filename(full_image_name)
thumb = self._get_simple_uploaded_file(thumbnail, thumbnail_filename)
self.storage.save(thumbnail_filename, thumb)
|
python
|
def _create_thumbnail(self, model_instance, thumbnail, image_name):
"""
Resizes and saves the thumbnail image
"""
thumbnail = self._do_resize(thumbnail, self.thumbnail_size)
full_image_name = self.generate_filename(model_instance, image_name)
thumbnail_filename = _get_thumbnail_filename(full_image_name)
thumb = self._get_simple_uploaded_file(thumbnail, thumbnail_filename)
self.storage.save(thumbnail_filename, thumb)
|
[
"def",
"_create_thumbnail",
"(",
"self",
",",
"model_instance",
",",
"thumbnail",
",",
"image_name",
")",
":",
"thumbnail",
"=",
"self",
".",
"_do_resize",
"(",
"thumbnail",
",",
"self",
".",
"thumbnail_size",
")",
"full_image_name",
"=",
"self",
".",
"generate_filename",
"(",
"model_instance",
",",
"image_name",
")",
"thumbnail_filename",
"=",
"_get_thumbnail_filename",
"(",
"full_image_name",
")",
"thumb",
"=",
"self",
".",
"_get_simple_uploaded_file",
"(",
"thumbnail",
",",
"thumbnail_filename",
")",
"self",
".",
"storage",
".",
"save",
"(",
"thumbnail_filename",
",",
"thumb",
")"
] |
Resizes and saves the thumbnail image
|
[
"Resizes",
"and",
"saves",
"the",
"thumbnail",
"image"
] |
2dbad297486bf5e50d86f12f85e51da31e50ac22
|
https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L126-L134
|
245,372
|
madisona/django-image-helper
|
image_helper/fields.py
|
SizedImageField._set_thumbnail
|
def _set_thumbnail(self, instance=None, **kwargs):
"""
Sets a `thumbnail` attribute on the image field class.
On thumbnail you can access name, url, path attributes
"""
image_field = getattr(instance, self.name)
if image_field:
thumbnail_filename = _get_thumbnail_filename(image_field.name)
thumbnail_field = ThumbnailField(thumbnail_filename, self.storage)
setattr(image_field, 'thumbnail', thumbnail_field)
|
python
|
def _set_thumbnail(self, instance=None, **kwargs):
"""
Sets a `thumbnail` attribute on the image field class.
On thumbnail you can access name, url, path attributes
"""
image_field = getattr(instance, self.name)
if image_field:
thumbnail_filename = _get_thumbnail_filename(image_field.name)
thumbnail_field = ThumbnailField(thumbnail_filename, self.storage)
setattr(image_field, 'thumbnail', thumbnail_field)
|
[
"def",
"_set_thumbnail",
"(",
"self",
",",
"instance",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"image_field",
"=",
"getattr",
"(",
"instance",
",",
"self",
".",
"name",
")",
"if",
"image_field",
":",
"thumbnail_filename",
"=",
"_get_thumbnail_filename",
"(",
"image_field",
".",
"name",
")",
"thumbnail_field",
"=",
"ThumbnailField",
"(",
"thumbnail_filename",
",",
"self",
".",
"storage",
")",
"setattr",
"(",
"image_field",
",",
"'thumbnail'",
",",
"thumbnail_field",
")"
] |
Sets a `thumbnail` attribute on the image field class.
On thumbnail you can access name, url, path attributes
|
[
"Sets",
"a",
"thumbnail",
"attribute",
"on",
"the",
"image",
"field",
"class",
".",
"On",
"thumbnail",
"you",
"can",
"access",
"name",
"url",
"path",
"attributes"
] |
2dbad297486bf5e50d86f12f85e51da31e50ac22
|
https://github.com/madisona/django-image-helper/blob/2dbad297486bf5e50d86f12f85e51da31e50ac22/image_helper/fields.py#L160-L170
|
245,373
|
GemHQ/round-py
|
round/applications.py
|
Applications.create
|
def create(self, **kwargs):
"""Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
"""
resource = self.resource.create(kwargs)
if 'admin_token' in kwargs:
resource.context.authorize('Gem-Application',
api_token=resource.api_token,
admin_token=kwargs['admin_token'])
app = self.wrap(resource)
return self.add(app)
|
python
|
def create(self, **kwargs):
"""Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
"""
resource = self.resource.create(kwargs)
if 'admin_token' in kwargs:
resource.context.authorize('Gem-Application',
api_token=resource.api_token,
admin_token=kwargs['admin_token'])
app = self.wrap(resource)
return self.add(app)
|
[
"def",
"create",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"self",
".",
"resource",
".",
"create",
"(",
"kwargs",
")",
"if",
"'admin_token'",
"in",
"kwargs",
":",
"resource",
".",
"context",
".",
"authorize",
"(",
"'Gem-Application'",
",",
"api_token",
"=",
"resource",
".",
"api_token",
",",
"admin_token",
"=",
"kwargs",
"[",
"'admin_token'",
"]",
")",
"app",
"=",
"self",
".",
"wrap",
"(",
"resource",
")",
"return",
"self",
".",
"add",
"(",
"app",
")"
] |
Create a new Application.
Args:
**kwargs: Arbitrary keyword arguments, including:
name (str): A name for the new Application.
Returns:
A round.Application object if successful.
|
[
"Create",
"a",
"new",
"Application",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L21-L37
|
245,374
|
GemHQ/round-py
|
round/applications.py
|
Application.get_mfa
|
def get_mfa(self):
"""Return the currently-valid MFA token for this application."""
token = str(self.totp.now())
# PyOTP doesn't pre-pad tokens shorter than 6 characters
# ROTP does, so we have to.
while len(token) < 6:
token = '0{}'.format(token)
return token
|
python
|
def get_mfa(self):
"""Return the currently-valid MFA token for this application."""
token = str(self.totp.now())
# PyOTP doesn't pre-pad tokens shorter than 6 characters
# ROTP does, so we have to.
while len(token) < 6:
token = '0{}'.format(token)
return token
|
[
"def",
"get_mfa",
"(",
"self",
")",
":",
"token",
"=",
"str",
"(",
"self",
".",
"totp",
".",
"now",
"(",
")",
")",
"# PyOTP doesn't pre-pad tokens shorter than 6 characters",
"# ROTP does, so we have to.",
"while",
"len",
"(",
"token",
")",
"<",
"6",
":",
"token",
"=",
"'0{}'",
".",
"format",
"(",
"token",
")",
"return",
"token"
] |
Return the currently-valid MFA token for this application.
|
[
"Return",
"the",
"currently",
"-",
"valid",
"MFA",
"token",
"for",
"this",
"application",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L63-L70
|
245,375
|
GemHQ/round-py
|
round/applications.py
|
Application.reset
|
def reset(self, *args):
"""Resets any of the tokens for this Application.
Note that you may have to reauthenticate afterwards.
Usage:
application.reset('api_token')
application.reset('api_token', 'totp_secret')
Args:
*args (list of str): one or more of
['api_token', 'subscription_token', 'totp_secret']
Returns:
The Application.
"""
self.resource = self.resource.reset(list(args))
return self
|
python
|
def reset(self, *args):
"""Resets any of the tokens for this Application.
Note that you may have to reauthenticate afterwards.
Usage:
application.reset('api_token')
application.reset('api_token', 'totp_secret')
Args:
*args (list of str): one or more of
['api_token', 'subscription_token', 'totp_secret']
Returns:
The Application.
"""
self.resource = self.resource.reset(list(args))
return self
|
[
"def",
"reset",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"resource",
"=",
"self",
".",
"resource",
".",
"reset",
"(",
"list",
"(",
"args",
")",
")",
"return",
"self"
] |
Resets any of the tokens for this Application.
Note that you may have to reauthenticate afterwards.
Usage:
application.reset('api_token')
application.reset('api_token', 'totp_secret')
Args:
*args (list of str): one or more of
['api_token', 'subscription_token', 'totp_secret']
Returns:
The Application.
|
[
"Resets",
"any",
"of",
"the",
"tokens",
"for",
"this",
"Application",
".",
"Note",
"that",
"you",
"may",
"have",
"to",
"reauthenticate",
"afterwards",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L72-L88
|
245,376
|
GemHQ/round-py
|
round/applications.py
|
Application.get_users
|
def get_users(self, fetch=True):
"""Return this Applications's users object, populating it if fetch
is True."""
return Users(self.resource.users, self.client, populate=fetch)
|
python
|
def get_users(self, fetch=True):
"""Return this Applications's users object, populating it if fetch
is True."""
return Users(self.resource.users, self.client, populate=fetch)
|
[
"def",
"get_users",
"(",
"self",
",",
"fetch",
"=",
"True",
")",
":",
"return",
"Users",
"(",
"self",
".",
"resource",
".",
"users",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
")"
] |
Return this Applications's users object, populating it if fetch
is True.
|
[
"Return",
"this",
"Applications",
"s",
"users",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L96-L99
|
245,377
|
GemHQ/round-py
|
round/applications.py
|
Application.get_wallets
|
def get_wallets(self, fetch=False):
"""Return this Applications's wallets object, populating it if fetch
is True."""
return Wallets(
self.resource.wallets, self.client, populate=fetch, application=self)
|
python
|
def get_wallets(self, fetch=False):
"""Return this Applications's wallets object, populating it if fetch
is True."""
return Wallets(
self.resource.wallets, self.client, populate=fetch, application=self)
|
[
"def",
"get_wallets",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"Wallets",
"(",
"self",
".",
"resource",
".",
"wallets",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
",",
"application",
"=",
"self",
")"
] |
Return this Applications's wallets object, populating it if fetch
is True.
|
[
"Return",
"this",
"Applications",
"s",
"wallets",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L107-L111
|
245,378
|
GemHQ/round-py
|
round/applications.py
|
Application.get_netki_domains
|
def get_netki_domains(self, fetch=False):
"""Return the Applications NetkiDomains object, populating it if fetch
is True."""
return NetkiDomains(
self.resource.netki_domains, self.client, populate=fetch)
|
python
|
def get_netki_domains(self, fetch=False):
"""Return the Applications NetkiDomains object, populating it if fetch
is True."""
return NetkiDomains(
self.resource.netki_domains, self.client, populate=fetch)
|
[
"def",
"get_netki_domains",
"(",
"self",
",",
"fetch",
"=",
"False",
")",
":",
"return",
"NetkiDomains",
"(",
"self",
".",
"resource",
".",
"netki_domains",
",",
"self",
".",
"client",
",",
"populate",
"=",
"fetch",
")"
] |
Return the Applications NetkiDomains object, populating it if fetch
is True.
|
[
"Return",
"the",
"Applications",
"NetkiDomains",
"object",
"populating",
"it",
"if",
"fetch",
"is",
"True",
"."
] |
d0838f849cd260b1eb5df67ed3c6f2fe56c91c21
|
https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/applications.py#L135-L139
|
245,379
|
johnnoone/facts
|
facts/grafts/system_grafts.py
|
os_info
|
def os_info():
"""Returns os data.
"""
return {
'uname': dict(platform.uname()._asdict()),
'path': os.environ.get('PATH', '').split(':'),
'shell': os.environ.get('SHELL', '/bin/sh'),
}
|
python
|
def os_info():
"""Returns os data.
"""
return {
'uname': dict(platform.uname()._asdict()),
'path': os.environ.get('PATH', '').split(':'),
'shell': os.environ.get('SHELL', '/bin/sh'),
}
|
[
"def",
"os_info",
"(",
")",
":",
"return",
"{",
"'uname'",
":",
"dict",
"(",
"platform",
".",
"uname",
"(",
")",
".",
"_asdict",
"(",
")",
")",
",",
"'path'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
".",
"split",
"(",
"':'",
")",
",",
"'shell'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'SHELL'",
",",
"'/bin/sh'",
")",
",",
"}"
] |
Returns os data.
|
[
"Returns",
"os",
"data",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L26-L33
|
245,380
|
johnnoone/facts
|
facts/grafts/system_grafts.py
|
network_info
|
def network_info():
"""Returns hostname, ipv4 and ipv6.
"""
def extract(host, family):
return socket.getaddrinfo(host, None, family)[0][4][0]
host = socket.gethostname()
response = {
'hostname': host,
'ipv4': None,
'ipv6': None
}
with suppress(IndexError, socket.gaierror):
response['ipv4'] = extract(host, socket.AF_INET)
with suppress(IndexError, socket.gaierror):
response['ipv6'] = extract(host, socket.AF_INET6)
return response
|
python
|
def network_info():
"""Returns hostname, ipv4 and ipv6.
"""
def extract(host, family):
return socket.getaddrinfo(host, None, family)[0][4][0]
host = socket.gethostname()
response = {
'hostname': host,
'ipv4': None,
'ipv6': None
}
with suppress(IndexError, socket.gaierror):
response['ipv4'] = extract(host, socket.AF_INET)
with suppress(IndexError, socket.gaierror):
response['ipv6'] = extract(host, socket.AF_INET6)
return response
|
[
"def",
"network_info",
"(",
")",
":",
"def",
"extract",
"(",
"host",
",",
"family",
")",
":",
"return",
"socket",
".",
"getaddrinfo",
"(",
"host",
",",
"None",
",",
"family",
")",
"[",
"0",
"]",
"[",
"4",
"]",
"[",
"0",
"]",
"host",
"=",
"socket",
".",
"gethostname",
"(",
")",
"response",
"=",
"{",
"'hostname'",
":",
"host",
",",
"'ipv4'",
":",
"None",
",",
"'ipv6'",
":",
"None",
"}",
"with",
"suppress",
"(",
"IndexError",
",",
"socket",
".",
"gaierror",
")",
":",
"response",
"[",
"'ipv4'",
"]",
"=",
"extract",
"(",
"host",
",",
"socket",
".",
"AF_INET",
")",
"with",
"suppress",
"(",
"IndexError",
",",
"socket",
".",
"gaierror",
")",
":",
"response",
"[",
"'ipv6'",
"]",
"=",
"extract",
"(",
"host",
",",
"socket",
".",
"AF_INET6",
")",
"return",
"response"
] |
Returns hostname, ipv4 and ipv6.
|
[
"Returns",
"hostname",
"ipv4",
"and",
"ipv6",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L60-L76
|
245,381
|
johnnoone/facts
|
facts/grafts/system_grafts.py
|
mac_addr_info
|
def mac_addr_info():
"""Returns mac address.
"""
mac = get_mac()
if mac == get_mac(): # not random generated
hexa = '%012x' % mac
value = ':'.join(hexa[i:i+2] for i in range(0, 12, 2))
else:
value = None
return {'mac': value}
|
python
|
def mac_addr_info():
"""Returns mac address.
"""
mac = get_mac()
if mac == get_mac(): # not random generated
hexa = '%012x' % mac
value = ':'.join(hexa[i:i+2] for i in range(0, 12, 2))
else:
value = None
return {'mac': value}
|
[
"def",
"mac_addr_info",
"(",
")",
":",
"mac",
"=",
"get_mac",
"(",
")",
"if",
"mac",
"==",
"get_mac",
"(",
")",
":",
"# not random generated",
"hexa",
"=",
"'%012x'",
"%",
"mac",
"value",
"=",
"':'",
".",
"join",
"(",
"hexa",
"[",
"i",
":",
"i",
"+",
"2",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"12",
",",
"2",
")",
")",
"else",
":",
"value",
"=",
"None",
"return",
"{",
"'mac'",
":",
"value",
"}"
] |
Returns mac address.
|
[
"Returns",
"mac",
"address",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L80-L89
|
245,382
|
johnnoone/facts
|
facts/grafts/system_grafts.py
|
interfaces_info
|
def interfaces_info():
"""Returns interfaces data.
"""
def replace(value):
if value == netifaces.AF_LINK:
return 'link'
if value == netifaces.AF_INET:
return 'ipv4'
if value == netifaces.AF_INET6:
return 'ipv6'
return value
results = {}
for iface in netifaces.interfaces():
addrs = netifaces.ifaddresses(iface)
results[iface] = {replace(k): v for k, v in addrs.items()}
return results
|
python
|
def interfaces_info():
"""Returns interfaces data.
"""
def replace(value):
if value == netifaces.AF_LINK:
return 'link'
if value == netifaces.AF_INET:
return 'ipv4'
if value == netifaces.AF_INET6:
return 'ipv6'
return value
results = {}
for iface in netifaces.interfaces():
addrs = netifaces.ifaddresses(iface)
results[iface] = {replace(k): v for k, v in addrs.items()}
return results
|
[
"def",
"interfaces_info",
"(",
")",
":",
"def",
"replace",
"(",
"value",
")",
":",
"if",
"value",
"==",
"netifaces",
".",
"AF_LINK",
":",
"return",
"'link'",
"if",
"value",
"==",
"netifaces",
".",
"AF_INET",
":",
"return",
"'ipv4'",
"if",
"value",
"==",
"netifaces",
".",
"AF_INET6",
":",
"return",
"'ipv6'",
"return",
"value",
"results",
"=",
"{",
"}",
"for",
"iface",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
":",
"addrs",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"iface",
")",
"results",
"[",
"iface",
"]",
"=",
"{",
"replace",
"(",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"addrs",
".",
"items",
"(",
")",
"}",
"return",
"results"
] |
Returns interfaces data.
|
[
"Returns",
"interfaces",
"data",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L104-L121
|
245,383
|
johnnoone/facts
|
facts/grafts/system_grafts.py
|
gateways_info
|
def gateways_info():
"""Returns gateways data.
"""
data = netifaces.gateways()
results = {'default': {}}
with suppress(KeyError):
results['ipv4'] = data[netifaces.AF_INET]
results['default']['ipv4'] = data['default'][netifaces.AF_INET]
with suppress(KeyError):
results['ipv6'] = data[netifaces.AF_INET6]
results['default']['ipv6'] = data['default'][netifaces.AF_INET6]
return results
|
python
|
def gateways_info():
"""Returns gateways data.
"""
data = netifaces.gateways()
results = {'default': {}}
with suppress(KeyError):
results['ipv4'] = data[netifaces.AF_INET]
results['default']['ipv4'] = data['default'][netifaces.AF_INET]
with suppress(KeyError):
results['ipv6'] = data[netifaces.AF_INET6]
results['default']['ipv6'] = data['default'][netifaces.AF_INET6]
return results
|
[
"def",
"gateways_info",
"(",
")",
":",
"data",
"=",
"netifaces",
".",
"gateways",
"(",
")",
"results",
"=",
"{",
"'default'",
":",
"{",
"}",
"}",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"results",
"[",
"'ipv4'",
"]",
"=",
"data",
"[",
"netifaces",
".",
"AF_INET",
"]",
"results",
"[",
"'default'",
"]",
"[",
"'ipv4'",
"]",
"=",
"data",
"[",
"'default'",
"]",
"[",
"netifaces",
".",
"AF_INET",
"]",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"results",
"[",
"'ipv6'",
"]",
"=",
"data",
"[",
"netifaces",
".",
"AF_INET6",
"]",
"results",
"[",
"'default'",
"]",
"[",
"'ipv6'",
"]",
"=",
"data",
"[",
"'default'",
"]",
"[",
"netifaces",
".",
"AF_INET6",
"]",
"return",
"results"
] |
Returns gateways data.
|
[
"Returns",
"gateways",
"data",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L125-L138
|
245,384
|
johnnoone/facts
|
facts/grafts/system_grafts.py
|
memory_data
|
def memory_data():
"""Returns memory data.
"""
vm = psutil.virtual_memory()
sw = psutil.swap_memory()
return {
'virtual': {
'total': mark(vm.total, 'bytes'),
'free': mark(vm.free, 'bytes'),
'percent': mark(vm.percent, 'percentage')
},
'swap': {
'total': mark(sw.total, 'bytes'),
'free': mark(sw.free, 'bytes'),
'percent': mark(sw.percent, 'percentage')
},
}
|
python
|
def memory_data():
"""Returns memory data.
"""
vm = psutil.virtual_memory()
sw = psutil.swap_memory()
return {
'virtual': {
'total': mark(vm.total, 'bytes'),
'free': mark(vm.free, 'bytes'),
'percent': mark(vm.percent, 'percentage')
},
'swap': {
'total': mark(sw.total, 'bytes'),
'free': mark(sw.free, 'bytes'),
'percent': mark(sw.percent, 'percentage')
},
}
|
[
"def",
"memory_data",
"(",
")",
":",
"vm",
"=",
"psutil",
".",
"virtual_memory",
"(",
")",
"sw",
"=",
"psutil",
".",
"swap_memory",
"(",
")",
"return",
"{",
"'virtual'",
":",
"{",
"'total'",
":",
"mark",
"(",
"vm",
".",
"total",
",",
"'bytes'",
")",
",",
"'free'",
":",
"mark",
"(",
"vm",
".",
"free",
",",
"'bytes'",
")",
",",
"'percent'",
":",
"mark",
"(",
"vm",
".",
"percent",
",",
"'percentage'",
")",
"}",
",",
"'swap'",
":",
"{",
"'total'",
":",
"mark",
"(",
"sw",
".",
"total",
",",
"'bytes'",
")",
",",
"'free'",
":",
"mark",
"(",
"sw",
".",
"free",
",",
"'bytes'",
")",
",",
"'percent'",
":",
"mark",
"(",
"sw",
".",
"percent",
",",
"'percentage'",
")",
"}",
",",
"}"
] |
Returns memory data.
|
[
"Returns",
"memory",
"data",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L152-L169
|
245,385
|
johnnoone/facts
|
facts/grafts/system_grafts.py
|
devices_data
|
def devices_data():
"""Returns devices data.
"""
response = {}
for part in psutil.disk_partitions():
device = part.device
response[device] = {
'device': device,
'mountpoint': part.mountpoint,
'fstype': part.fstype,
'opts': part.opts,
}
if part.mountpoint:
usage = psutil.disk_usage(part.mountpoint)
response[device]['usage'] = {
'size': mark(usage.total, 'bytes'),
'used': mark(usage.used, 'bytes'),
'free': mark(usage.free, 'bytes'),
'percent': mark(usage.percent, 'percentage')
}
return response
|
python
|
def devices_data():
"""Returns devices data.
"""
response = {}
for part in psutil.disk_partitions():
device = part.device
response[device] = {
'device': device,
'mountpoint': part.mountpoint,
'fstype': part.fstype,
'opts': part.opts,
}
if part.mountpoint:
usage = psutil.disk_usage(part.mountpoint)
response[device]['usage'] = {
'size': mark(usage.total, 'bytes'),
'used': mark(usage.used, 'bytes'),
'free': mark(usage.free, 'bytes'),
'percent': mark(usage.percent, 'percentage')
}
return response
|
[
"def",
"devices_data",
"(",
")",
":",
"response",
"=",
"{",
"}",
"for",
"part",
"in",
"psutil",
".",
"disk_partitions",
"(",
")",
":",
"device",
"=",
"part",
".",
"device",
"response",
"[",
"device",
"]",
"=",
"{",
"'device'",
":",
"device",
",",
"'mountpoint'",
":",
"part",
".",
"mountpoint",
",",
"'fstype'",
":",
"part",
".",
"fstype",
",",
"'opts'",
":",
"part",
".",
"opts",
",",
"}",
"if",
"part",
".",
"mountpoint",
":",
"usage",
"=",
"psutil",
".",
"disk_usage",
"(",
"part",
".",
"mountpoint",
")",
"response",
"[",
"device",
"]",
"[",
"'usage'",
"]",
"=",
"{",
"'size'",
":",
"mark",
"(",
"usage",
".",
"total",
",",
"'bytes'",
")",
",",
"'used'",
":",
"mark",
"(",
"usage",
".",
"used",
",",
"'bytes'",
")",
",",
"'free'",
":",
"mark",
"(",
"usage",
".",
"free",
",",
"'bytes'",
")",
",",
"'percent'",
":",
"mark",
"(",
"usage",
".",
"percent",
",",
"'percentage'",
")",
"}",
"return",
"response"
] |
Returns devices data.
|
[
"Returns",
"devices",
"data",
"."
] |
82d38a46c15d9c01200445526f4c0d1825fc1e51
|
https://github.com/johnnoone/facts/blob/82d38a46c15d9c01200445526f4c0d1825fc1e51/facts/grafts/system_grafts.py#L173-L193
|
245,386
|
mugurbil/gnm
|
examples/simple_2D/simple_2D.py
|
integrator
|
def integrator(integrand,xmin,xmax,n_points,factor=2):
'''
Creating theoretical curve for 2D model functions
integrator function
'''
integral_vector = np.empty([n_points+1])
dx = (xmax-xmin)/n_points
# integrate
for i in xrange(n_points+1):
xnow = xmin + i * dx
integral, error = integrate.quad(rotate(integrand,
xnow), xmin*factor, xmax*factor)
integral_vector[i] = integral
# normalize
normalization = np.average(integral_vector)*(xmax-xmin)
normalized_vector = integral_vector/normalization
return normalized_vector
|
python
|
def integrator(integrand,xmin,xmax,n_points,factor=2):
'''
Creating theoretical curve for 2D model functions
integrator function
'''
integral_vector = np.empty([n_points+1])
dx = (xmax-xmin)/n_points
# integrate
for i in xrange(n_points+1):
xnow = xmin + i * dx
integral, error = integrate.quad(rotate(integrand,
xnow), xmin*factor, xmax*factor)
integral_vector[i] = integral
# normalize
normalization = np.average(integral_vector)*(xmax-xmin)
normalized_vector = integral_vector/normalization
return normalized_vector
|
[
"def",
"integrator",
"(",
"integrand",
",",
"xmin",
",",
"xmax",
",",
"n_points",
",",
"factor",
"=",
"2",
")",
":",
"integral_vector",
"=",
"np",
".",
"empty",
"(",
"[",
"n_points",
"+",
"1",
"]",
")",
"dx",
"=",
"(",
"xmax",
"-",
"xmin",
")",
"/",
"n_points",
"# integrate",
"for",
"i",
"in",
"xrange",
"(",
"n_points",
"+",
"1",
")",
":",
"xnow",
"=",
"xmin",
"+",
"i",
"*",
"dx",
"integral",
",",
"error",
"=",
"integrate",
".",
"quad",
"(",
"rotate",
"(",
"integrand",
",",
"xnow",
")",
",",
"xmin",
"*",
"factor",
",",
"xmax",
"*",
"factor",
")",
"integral_vector",
"[",
"i",
"]",
"=",
"integral",
"# normalize",
"normalization",
"=",
"np",
".",
"average",
"(",
"integral_vector",
")",
"*",
"(",
"xmax",
"-",
"xmin",
")",
"normalized_vector",
"=",
"integral_vector",
"/",
"normalization",
"return",
"normalized_vector"
] |
Creating theoretical curve for 2D model functions
integrator function
|
[
"Creating",
"theoretical",
"curve",
"for",
"2D",
"model",
"functions",
"integrator",
"function"
] |
4f9711fb9d78cc02820c25234bc3ab9615014f11
|
https://github.com/mugurbil/gnm/blob/4f9711fb9d78cc02820c25234bc3ab9615014f11/examples/simple_2D/simple_2D.py#L94-L110
|
245,387
|
mugurbil/gnm
|
examples/simple_2D/simple_2D.py
|
rotate
|
def rotate(f,x,theta=0):
'''
Returns a function that takes as input the 1D vector along the angle
given a function that takes in 2D input
'''
f_R = lambda b: f(np.array([[x*np.cos(theta)-b*np.sin(theta)],
[x*np.sin(theta)+b*np.cos(theta)]]))
return f_R
|
python
|
def rotate(f,x,theta=0):
'''
Returns a function that takes as input the 1D vector along the angle
given a function that takes in 2D input
'''
f_R = lambda b: f(np.array([[x*np.cos(theta)-b*np.sin(theta)],
[x*np.sin(theta)+b*np.cos(theta)]]))
return f_R
|
[
"def",
"rotate",
"(",
"f",
",",
"x",
",",
"theta",
"=",
"0",
")",
":",
"f_R",
"=",
"lambda",
"b",
":",
"f",
"(",
"np",
".",
"array",
"(",
"[",
"[",
"x",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"-",
"b",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
"x",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
"+",
"b",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
"]",
"]",
")",
")",
"return",
"f_R"
] |
Returns a function that takes as input the 1D vector along the angle
given a function that takes in 2D input
|
[
"Returns",
"a",
"function",
"that",
"takes",
"as",
"input",
"the",
"1D",
"vector",
"along",
"the",
"angle",
"given",
"a",
"function",
"that",
"takes",
"in",
"2D",
"input"
] |
4f9711fb9d78cc02820c25234bc3ab9615014f11
|
https://github.com/mugurbil/gnm/blob/4f9711fb9d78cc02820c25234bc3ab9615014f11/examples/simple_2D/simple_2D.py#L112-L119
|
245,388
|
django-py/django-doberman
|
doberman/auth.py
|
AccessAttempt.check_failed_login
|
def check_failed_login(self):
"""
'Private method', check failed logins, it's used for wath_login decorator
"""
last_attempt = self.get_last_failed_access_attempt()
if not last_attempt:
# create a new entry
user_access = self._FailedAccessAttemptModel(ip_address=self.ip)
elif last_attempt:
user_access = last_attempt
if self.request.method == 'POST':
if self.username is None:
raise DobermanImproperlyConfigured(
"Bad username form field, if you are using a custom field please configure: "
"DOBERMAN_USERNAME_FORM_FIELD via settings."
)
if self.response.status_code != 302:
user_access.user_agent = self.request.META.get('HTTP_USER_AGENT', '<unknown user agent>')[:255]
user_access.username = self.username
user_access.failed_attempts += 1
user_access.params_get = self.request.GET
user_access.params_post = self.request.POST
if user_access.failed_attempts >= self.max_failed_attempts:
user_access.is_locked = True
user_access.save()
elif self.response.status_code == 302 and not user_access.is_locked:
user_access.is_expired = True
user_access.save()
return user_access
|
python
|
def check_failed_login(self):
"""
'Private method', check failed logins, it's used for wath_login decorator
"""
last_attempt = self.get_last_failed_access_attempt()
if not last_attempt:
# create a new entry
user_access = self._FailedAccessAttemptModel(ip_address=self.ip)
elif last_attempt:
user_access = last_attempt
if self.request.method == 'POST':
if self.username is None:
raise DobermanImproperlyConfigured(
"Bad username form field, if you are using a custom field please configure: "
"DOBERMAN_USERNAME_FORM_FIELD via settings."
)
if self.response.status_code != 302:
user_access.user_agent = self.request.META.get('HTTP_USER_AGENT', '<unknown user agent>')[:255]
user_access.username = self.username
user_access.failed_attempts += 1
user_access.params_get = self.request.GET
user_access.params_post = self.request.POST
if user_access.failed_attempts >= self.max_failed_attempts:
user_access.is_locked = True
user_access.save()
elif self.response.status_code == 302 and not user_access.is_locked:
user_access.is_expired = True
user_access.save()
return user_access
|
[
"def",
"check_failed_login",
"(",
"self",
")",
":",
"last_attempt",
"=",
"self",
".",
"get_last_failed_access_attempt",
"(",
")",
"if",
"not",
"last_attempt",
":",
"# create a new entry",
"user_access",
"=",
"self",
".",
"_FailedAccessAttemptModel",
"(",
"ip_address",
"=",
"self",
".",
"ip",
")",
"elif",
"last_attempt",
":",
"user_access",
"=",
"last_attempt",
"if",
"self",
".",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"self",
".",
"username",
"is",
"None",
":",
"raise",
"DobermanImproperlyConfigured",
"(",
"\"Bad username form field, if you are using a custom field please configure: \"",
"\"DOBERMAN_USERNAME_FORM_FIELD via settings.\"",
")",
"if",
"self",
".",
"response",
".",
"status_code",
"!=",
"302",
":",
"user_access",
".",
"user_agent",
"=",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_USER_AGENT'",
",",
"'<unknown user agent>'",
")",
"[",
":",
"255",
"]",
"user_access",
".",
"username",
"=",
"self",
".",
"username",
"user_access",
".",
"failed_attempts",
"+=",
"1",
"user_access",
".",
"params_get",
"=",
"self",
".",
"request",
".",
"GET",
"user_access",
".",
"params_post",
"=",
"self",
".",
"request",
".",
"POST",
"if",
"user_access",
".",
"failed_attempts",
">=",
"self",
".",
"max_failed_attempts",
":",
"user_access",
".",
"is_locked",
"=",
"True",
"user_access",
".",
"save",
"(",
")",
"elif",
"self",
".",
"response",
".",
"status_code",
"==",
"302",
"and",
"not",
"user_access",
".",
"is_locked",
":",
"user_access",
".",
"is_expired",
"=",
"True",
"user_access",
".",
"save",
"(",
")",
"return",
"user_access"
] |
'Private method', check failed logins, it's used for wath_login decorator
|
[
"Private",
"method",
"check",
"failed",
"logins",
"it",
"s",
"used",
"for",
"wath_login",
"decorator"
] |
2e5959737a1b64234ed5a179c93f96a0de1c3e5c
|
https://github.com/django-py/django-doberman/blob/2e5959737a1b64234ed5a179c93f96a0de1c3e5c/doberman/auth.py#L59-L95
|
245,389
|
riccardocagnasso/useless
|
src/useless/PE/__init__.py
|
PE_File.optional_data_directories
|
def optional_data_directories(self):
"""
Data directories entries are somewhat wierd.
First of all they have no direct type information in it, the type
is assumed from the position inside the table. For this reason
there are often "null" entries, with all fields set to zero.
Here we parse all the entries, assign the correct type via position
and then filter out the "null" ones.
Even if the algorithm itself if quite simple, figuring it required
a huge amount of time staring at PE/COFF specification with a 8O
like expression thinking "WTF? WTF! WTF? WHY?!"
"""
base_offset = self.pe_header_offset +\
COFF_Header.get_size() +\
OptionalHeader_StandardFields.get_size() +\
OptionalHeader_WindowsFields.get_size()
for i in range(0, self.optional_windows_fields.NumberOfRvaAndSizes):
offset = base_offset + i*OptionalHeader_DataDirectory.get_size()
header = OptionalHeader_DataDirectory(self.stream, offset, i)
if not header.is_empty():
yield header
|
python
|
def optional_data_directories(self):
"""
Data directories entries are somewhat wierd.
First of all they have no direct type information in it, the type
is assumed from the position inside the table. For this reason
there are often "null" entries, with all fields set to zero.
Here we parse all the entries, assign the correct type via position
and then filter out the "null" ones.
Even if the algorithm itself if quite simple, figuring it required
a huge amount of time staring at PE/COFF specification with a 8O
like expression thinking "WTF? WTF! WTF? WHY?!"
"""
base_offset = self.pe_header_offset +\
COFF_Header.get_size() +\
OptionalHeader_StandardFields.get_size() +\
OptionalHeader_WindowsFields.get_size()
for i in range(0, self.optional_windows_fields.NumberOfRvaAndSizes):
offset = base_offset + i*OptionalHeader_DataDirectory.get_size()
header = OptionalHeader_DataDirectory(self.stream, offset, i)
if not header.is_empty():
yield header
|
[
"def",
"optional_data_directories",
"(",
"self",
")",
":",
"base_offset",
"=",
"self",
".",
"pe_header_offset",
"+",
"COFF_Header",
".",
"get_size",
"(",
")",
"+",
"OptionalHeader_StandardFields",
".",
"get_size",
"(",
")",
"+",
"OptionalHeader_WindowsFields",
".",
"get_size",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"optional_windows_fields",
".",
"NumberOfRvaAndSizes",
")",
":",
"offset",
"=",
"base_offset",
"+",
"i",
"*",
"OptionalHeader_DataDirectory",
".",
"get_size",
"(",
")",
"header",
"=",
"OptionalHeader_DataDirectory",
"(",
"self",
".",
"stream",
",",
"offset",
",",
"i",
")",
"if",
"not",
"header",
".",
"is_empty",
"(",
")",
":",
"yield",
"header"
] |
Data directories entries are somewhat wierd.
First of all they have no direct type information in it, the type
is assumed from the position inside the table. For this reason
there are often "null" entries, with all fields set to zero.
Here we parse all the entries, assign the correct type via position
and then filter out the "null" ones.
Even if the algorithm itself if quite simple, figuring it required
a huge amount of time staring at PE/COFF specification with a 8O
like expression thinking "WTF? WTF! WTF? WHY?!"
|
[
"Data",
"directories",
"entries",
"are",
"somewhat",
"wierd",
"."
] |
5167aab82958f653148e3689c9a7e548d4fa2cba
|
https://github.com/riccardocagnasso/useless/blob/5167aab82958f653148e3689c9a7e548d4fa2cba/src/useless/PE/__init__.py#L63-L88
|
245,390
|
riccardocagnasso/useless
|
src/useless/PE/__init__.py
|
PE_File.resolve_rva
|
def resolve_rva(self, rva):
"""
RVAs are supposed to be used with the image of the file in memory.
There's no direct algorithm to calculate the offset of an RVA in
the file.
What we do here is to find the section that contains the RVA and
then we calculate the offset between the RVA of the section
and the offset of the section in the file. With this offset, we can
compute the position of the RVA in the file
"""
containing_section = self.get_section_of_rva(rva)
in_section_offset = containing_section.PointerToRawData -\
containing_section.VirtualAddress
return in_section_offset + rva
|
python
|
def resolve_rva(self, rva):
"""
RVAs are supposed to be used with the image of the file in memory.
There's no direct algorithm to calculate the offset of an RVA in
the file.
What we do here is to find the section that contains the RVA and
then we calculate the offset between the RVA of the section
and the offset of the section in the file. With this offset, we can
compute the position of the RVA in the file
"""
containing_section = self.get_section_of_rva(rva)
in_section_offset = containing_section.PointerToRawData -\
containing_section.VirtualAddress
return in_section_offset + rva
|
[
"def",
"resolve_rva",
"(",
"self",
",",
"rva",
")",
":",
"containing_section",
"=",
"self",
".",
"get_section_of_rva",
"(",
"rva",
")",
"in_section_offset",
"=",
"containing_section",
".",
"PointerToRawData",
"-",
"containing_section",
".",
"VirtualAddress",
"return",
"in_section_offset",
"+",
"rva"
] |
RVAs are supposed to be used with the image of the file in memory.
There's no direct algorithm to calculate the offset of an RVA in
the file.
What we do here is to find the section that contains the RVA and
then we calculate the offset between the RVA of the section
and the offset of the section in the file. With this offset, we can
compute the position of the RVA in the file
|
[
"RVAs",
"are",
"supposed",
"to",
"be",
"used",
"with",
"the",
"image",
"of",
"the",
"file",
"in",
"memory",
".",
"There",
"s",
"no",
"direct",
"algorithm",
"to",
"calculate",
"the",
"offset",
"of",
"an",
"RVA",
"in",
"the",
"file",
"."
] |
5167aab82958f653148e3689c9a7e548d4fa2cba
|
https://github.com/riccardocagnasso/useless/blob/5167aab82958f653148e3689c9a7e548d4fa2cba/src/useless/PE/__init__.py#L109-L125
|
245,391
|
riccardocagnasso/useless
|
src/useless/PE/__init__.py
|
PE_File.dir_import_table
|
def dir_import_table(self):
"""
import table is terminated by a all-null entry, so we have to
check for that
"""
import_header = list(self.optional_data_directories)[1]
import_offset = self.resolve_rva(import_header.VirtualAddress)
i = 0
while True:
offset = import_offset + i*Import_DirectoryTable.get_size()
idt = Import_DirectoryTable(self.stream, offset, self)
if idt.is_empty():
break
else:
yield idt
i += 1
|
python
|
def dir_import_table(self):
"""
import table is terminated by a all-null entry, so we have to
check for that
"""
import_header = list(self.optional_data_directories)[1]
import_offset = self.resolve_rva(import_header.VirtualAddress)
i = 0
while True:
offset = import_offset + i*Import_DirectoryTable.get_size()
idt = Import_DirectoryTable(self.stream, offset, self)
if idt.is_empty():
break
else:
yield idt
i += 1
|
[
"def",
"dir_import_table",
"(",
"self",
")",
":",
"import_header",
"=",
"list",
"(",
"self",
".",
"optional_data_directories",
")",
"[",
"1",
"]",
"import_offset",
"=",
"self",
".",
"resolve_rva",
"(",
"import_header",
".",
"VirtualAddress",
")",
"i",
"=",
"0",
"while",
"True",
":",
"offset",
"=",
"import_offset",
"+",
"i",
"*",
"Import_DirectoryTable",
".",
"get_size",
"(",
")",
"idt",
"=",
"Import_DirectoryTable",
"(",
"self",
".",
"stream",
",",
"offset",
",",
"self",
")",
"if",
"idt",
".",
"is_empty",
"(",
")",
":",
"break",
"else",
":",
"yield",
"idt",
"i",
"+=",
"1"
] |
import table is terminated by a all-null entry, so we have to
check for that
|
[
"import",
"table",
"is",
"terminated",
"by",
"a",
"all",
"-",
"null",
"entry",
"so",
"we",
"have",
"to",
"check",
"for",
"that"
] |
5167aab82958f653148e3689c9a7e548d4fa2cba
|
https://github.com/riccardocagnasso/useless/blob/5167aab82958f653148e3689c9a7e548d4fa2cba/src/useless/PE/__init__.py#L135-L153
|
245,392
|
kemingy/cnprep
|
cnprep/zh2num.py
|
get_number
|
def get_number(message, limit=4):
"""
convert Chinese to pinyin and extract useful numbers
attention:
1. only for integer
2. before apply this method, the message should be preprocessed
input:
message: the message you want to extract numbers from.
limit: limit the length of number sequence
"""
words = pinyin.get_pinyin(message).split('-')
numbers = []
tmp = ''
count = 0
for w in words:
if re.search(r'\W', w, re.A):
for s in list(w):
if s in special_char.keys():
count += 1
tmp += special_char[s]
else:
if count >= limit:
numbers.append(tmp)
count = 0
tmp = ''
elif w in pinyin2number.keys():
count += 1
tmp += pinyin2number[w]
else:
if count >= limit:
numbers.append(tmp)
count = 0
tmp = ''
if count >= limit:
numbers.append(tmp)
return numbers
|
python
|
def get_number(message, limit=4):
"""
convert Chinese to pinyin and extract useful numbers
attention:
1. only for integer
2. before apply this method, the message should be preprocessed
input:
message: the message you want to extract numbers from.
limit: limit the length of number sequence
"""
words = pinyin.get_pinyin(message).split('-')
numbers = []
tmp = ''
count = 0
for w in words:
if re.search(r'\W', w, re.A):
for s in list(w):
if s in special_char.keys():
count += 1
tmp += special_char[s]
else:
if count >= limit:
numbers.append(tmp)
count = 0
tmp = ''
elif w in pinyin2number.keys():
count += 1
tmp += pinyin2number[w]
else:
if count >= limit:
numbers.append(tmp)
count = 0
tmp = ''
if count >= limit:
numbers.append(tmp)
return numbers
|
[
"def",
"get_number",
"(",
"message",
",",
"limit",
"=",
"4",
")",
":",
"words",
"=",
"pinyin",
".",
"get_pinyin",
"(",
"message",
")",
".",
"split",
"(",
"'-'",
")",
"numbers",
"=",
"[",
"]",
"tmp",
"=",
"''",
"count",
"=",
"0",
"for",
"w",
"in",
"words",
":",
"if",
"re",
".",
"search",
"(",
"r'\\W'",
",",
"w",
",",
"re",
".",
"A",
")",
":",
"for",
"s",
"in",
"list",
"(",
"w",
")",
":",
"if",
"s",
"in",
"special_char",
".",
"keys",
"(",
")",
":",
"count",
"+=",
"1",
"tmp",
"+=",
"special_char",
"[",
"s",
"]",
"else",
":",
"if",
"count",
">=",
"limit",
":",
"numbers",
".",
"append",
"(",
"tmp",
")",
"count",
"=",
"0",
"tmp",
"=",
"''",
"elif",
"w",
"in",
"pinyin2number",
".",
"keys",
"(",
")",
":",
"count",
"+=",
"1",
"tmp",
"+=",
"pinyin2number",
"[",
"w",
"]",
"else",
":",
"if",
"count",
">=",
"limit",
":",
"numbers",
".",
"append",
"(",
"tmp",
")",
"count",
"=",
"0",
"tmp",
"=",
"''",
"if",
"count",
">=",
"limit",
":",
"numbers",
".",
"append",
"(",
"tmp",
")",
"return",
"numbers"
] |
convert Chinese to pinyin and extract useful numbers
attention:
1. only for integer
2. before apply this method, the message should be preprocessed
input:
message: the message you want to extract numbers from.
limit: limit the length of number sequence
|
[
"convert",
"Chinese",
"to",
"pinyin",
"and",
"extract",
"useful",
"numbers"
] |
076ea185167adb7e652bea3b81fb6830e162e880
|
https://github.com/kemingy/cnprep/blob/076ea185167adb7e652bea3b81fb6830e162e880/cnprep/zh2num.py#L73-L110
|
245,393
|
lwcook/horsetail-matching
|
horsetailmatching/densitymatching.py
|
DensityMatching.evalMetric
|
def evalMetric(self, x, method=None):
'''Evaluates the density matching metric at a given design point.
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:return: metric_value - value of the metric evaluated at the design
point given by x
:rtype: float
*Example Usage*::
>>> def myFunc(x, u): return x[0]*x[1] + u
>>> u1 = UniformParameter()
>>> theDM = DensityMatching(myFunc, u)
>>> x0 = [1, 2]
>>> theDM.evalMetric(x0)
'''
return super(DensityMatching, self).evalMetric(x, method)
|
python
|
def evalMetric(self, x, method=None):
'''Evaluates the density matching metric at a given design point.
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:return: metric_value - value of the metric evaluated at the design
point given by x
:rtype: float
*Example Usage*::
>>> def myFunc(x, u): return x[0]*x[1] + u
>>> u1 = UniformParameter()
>>> theDM = DensityMatching(myFunc, u)
>>> x0 = [1, 2]
>>> theDM.evalMetric(x0)
'''
return super(DensityMatching, self).evalMetric(x, method)
|
[
"def",
"evalMetric",
"(",
"self",
",",
"x",
",",
"method",
"=",
"None",
")",
":",
"return",
"super",
"(",
"DensityMatching",
",",
"self",
")",
".",
"evalMetric",
"(",
"x",
",",
"method",
")"
] |
Evaluates the density matching metric at a given design point.
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:return: metric_value - value of the metric evaluated at the design
point given by x
:rtype: float
*Example Usage*::
>>> def myFunc(x, u): return x[0]*x[1] + u
>>> u1 = UniformParameter()
>>> theDM = DensityMatching(myFunc, u)
>>> x0 = [1, 2]
>>> theDM.evalMetric(x0)
|
[
"Evaluates",
"the",
"density",
"matching",
"metric",
"at",
"a",
"given",
"design",
"point",
"."
] |
f3d5f8d01249debbca978f412ce4eae017458119
|
https://github.com/lwcook/horsetail-matching/blob/f3d5f8d01249debbca978f412ce4eae017458119/horsetailmatching/densitymatching.py#L114-L134
|
245,394
|
lwcook/horsetail-matching
|
horsetailmatching/densitymatching.py
|
DensityMatching.getPDF
|
def getPDF(self):
'''Function that gets vectors of the pdf and target at the last design
evaluated.
:return: tuple of q values, pdf values, target values
'''
if hasattr(self, '_qplot'):
return self._qplot, self._hplot, self._tplot
else:
raise ValueError('''The metric has not been evaluated at any
design point so the PDF cannot get obtained''')
|
python
|
def getPDF(self):
'''Function that gets vectors of the pdf and target at the last design
evaluated.
:return: tuple of q values, pdf values, target values
'''
if hasattr(self, '_qplot'):
return self._qplot, self._hplot, self._tplot
else:
raise ValueError('''The metric has not been evaluated at any
design point so the PDF cannot get obtained''')
|
[
"def",
"getPDF",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_qplot'",
")",
":",
"return",
"self",
".",
"_qplot",
",",
"self",
".",
"_hplot",
",",
"self",
".",
"_tplot",
"else",
":",
"raise",
"ValueError",
"(",
"'''The metric has not been evaluated at any\n design point so the PDF cannot get obtained'''",
")"
] |
Function that gets vectors of the pdf and target at the last design
evaluated.
:return: tuple of q values, pdf values, target values
|
[
"Function",
"that",
"gets",
"vectors",
"of",
"the",
"pdf",
"and",
"target",
"at",
"the",
"last",
"design",
"evaluated",
"."
] |
f3d5f8d01249debbca978f412ce4eae017458119
|
https://github.com/lwcook/horsetail-matching/blob/f3d5f8d01249debbca978f412ce4eae017458119/horsetailmatching/densitymatching.py#L152-L165
|
245,395
|
radjkarl/fancyTools
|
fancytools/plot/errorBand.py
|
errorBand
|
def errorBand(x, yAvg, yStd, yDensity, plt, n_colors=None):
"""
plot error-band around avg
where colour equals to point density
"""
dmn = yDensity.min()
dmx = yDensity.max()
if n_colors is None:
n_colors = dmx - dmn + 1
print(n_colors)
cm = plt.cm.get_cmap('Blues', lut=n_colors)
# normalize (0...1):
relDensity = (yDensity - dmn) / (dmx - dmn)
# limit the number of densities to n_colors:
bins = np.linspace(0, 1, n_colors - 1)
inds = np.digitize(relDensity, bins)
i0 = 0
try:
while True:
# define area length as those of the same alpha value
v0 = inds[i0]
am = np.argmax(inds[i0:] != v0)
if am == 0:
i1 = len(inds)
else:
i1 = i0 + am
r = slice(i0, i1 + 1)
col = cm(v0)
# create polygon of color=density around average:
plt.fill_between(x[r], yAvg[r] - yStd[r], yAvg[r] + yStd[r],
alpha=1,
edgecolor=col, # '#3F7F4C',
facecolor=col, # '#7EFF99',
linewidth=1)
i0 = i1
except IndexError:
pass
plt.plot(x, yAvg, 'k', color='#3F7F4C')
# show colorbar in plot:
sm = plt.cm.ScalarMappable(cmap=cm, norm=plt.Normalize(vmin=dmn, vmax=dmx))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
plt.colorbar(sm)
plt.legend()
|
python
|
def errorBand(x, yAvg, yStd, yDensity, plt, n_colors=None):
"""
plot error-band around avg
where colour equals to point density
"""
dmn = yDensity.min()
dmx = yDensity.max()
if n_colors is None:
n_colors = dmx - dmn + 1
print(n_colors)
cm = plt.cm.get_cmap('Blues', lut=n_colors)
# normalize (0...1):
relDensity = (yDensity - dmn) / (dmx - dmn)
# limit the number of densities to n_colors:
bins = np.linspace(0, 1, n_colors - 1)
inds = np.digitize(relDensity, bins)
i0 = 0
try:
while True:
# define area length as those of the same alpha value
v0 = inds[i0]
am = np.argmax(inds[i0:] != v0)
if am == 0:
i1 = len(inds)
else:
i1 = i0 + am
r = slice(i0, i1 + 1)
col = cm(v0)
# create polygon of color=density around average:
plt.fill_between(x[r], yAvg[r] - yStd[r], yAvg[r] + yStd[r],
alpha=1,
edgecolor=col, # '#3F7F4C',
facecolor=col, # '#7EFF99',
linewidth=1)
i0 = i1
except IndexError:
pass
plt.plot(x, yAvg, 'k', color='#3F7F4C')
# show colorbar in plot:
sm = plt.cm.ScalarMappable(cmap=cm, norm=plt.Normalize(vmin=dmn, vmax=dmx))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
plt.colorbar(sm)
plt.legend()
|
[
"def",
"errorBand",
"(",
"x",
",",
"yAvg",
",",
"yStd",
",",
"yDensity",
",",
"plt",
",",
"n_colors",
"=",
"None",
")",
":",
"dmn",
"=",
"yDensity",
".",
"min",
"(",
")",
"dmx",
"=",
"yDensity",
".",
"max",
"(",
")",
"if",
"n_colors",
"is",
"None",
":",
"n_colors",
"=",
"dmx",
"-",
"dmn",
"+",
"1",
"print",
"(",
"n_colors",
")",
"cm",
"=",
"plt",
".",
"cm",
".",
"get_cmap",
"(",
"'Blues'",
",",
"lut",
"=",
"n_colors",
")",
"# normalize (0...1):",
"relDensity",
"=",
"(",
"yDensity",
"-",
"dmn",
")",
"/",
"(",
"dmx",
"-",
"dmn",
")",
"# limit the number of densities to n_colors:",
"bins",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"n_colors",
"-",
"1",
")",
"inds",
"=",
"np",
".",
"digitize",
"(",
"relDensity",
",",
"bins",
")",
"i0",
"=",
"0",
"try",
":",
"while",
"True",
":",
"# define area length as those of the same alpha value",
"v0",
"=",
"inds",
"[",
"i0",
"]",
"am",
"=",
"np",
".",
"argmax",
"(",
"inds",
"[",
"i0",
":",
"]",
"!=",
"v0",
")",
"if",
"am",
"==",
"0",
":",
"i1",
"=",
"len",
"(",
"inds",
")",
"else",
":",
"i1",
"=",
"i0",
"+",
"am",
"r",
"=",
"slice",
"(",
"i0",
",",
"i1",
"+",
"1",
")",
"col",
"=",
"cm",
"(",
"v0",
")",
"# create polygon of color=density around average:",
"plt",
".",
"fill_between",
"(",
"x",
"[",
"r",
"]",
",",
"yAvg",
"[",
"r",
"]",
"-",
"yStd",
"[",
"r",
"]",
",",
"yAvg",
"[",
"r",
"]",
"+",
"yStd",
"[",
"r",
"]",
",",
"alpha",
"=",
"1",
",",
"edgecolor",
"=",
"col",
",",
"# '#3F7F4C',",
"facecolor",
"=",
"col",
",",
"# '#7EFF99',",
"linewidth",
"=",
"1",
")",
"i0",
"=",
"i1",
"except",
"IndexError",
":",
"pass",
"plt",
".",
"plot",
"(",
"x",
",",
"yAvg",
",",
"'k'",
",",
"color",
"=",
"'#3F7F4C'",
")",
"# show colorbar in plot:",
"sm",
"=",
"plt",
".",
"cm",
".",
"ScalarMappable",
"(",
"cmap",
"=",
"cm",
",",
"norm",
"=",
"plt",
".",
"Normalize",
"(",
"vmin",
"=",
"dmn",
",",
"vmax",
"=",
"dmx",
")",
")",
"# fake up the array of the scalar mappable. Urgh...",
"sm",
".",
"_A",
"=",
"[",
"]",
"plt",
".",
"colorbar",
"(",
"sm",
")",
"plt",
".",
"legend",
"(",
")"
] |
plot error-band around avg
where colour equals to point density
|
[
"plot",
"error",
"-",
"band",
"around",
"avg",
"where",
"colour",
"equals",
"to",
"point",
"density"
] |
4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b
|
https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/plot/errorBand.py#L8-L58
|
245,396
|
rameshg87/pyremotevbox
|
pyremotevbox/ZSI/twisted/client.py
|
getPage
|
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
scheme, host, port, path = client._parse(url)
factory = client.HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
if contextFactory is None:
raise RuntimeError, 'must provide a contextFactory'
conn = reactor.connectSSL(host, port, factory, contextFactory)
else:
conn = reactor.connectTCP(host, port, factory)
return factory
|
python
|
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
scheme, host, port, path = client._parse(url)
factory = client.HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
if contextFactory is None:
raise RuntimeError, 'must provide a contextFactory'
conn = reactor.connectSSL(host, port, factory, contextFactory)
else:
conn = reactor.connectTCP(host, port, factory)
return factory
|
[
"def",
"getPage",
"(",
"url",
",",
"contextFactory",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scheme",
",",
"host",
",",
"port",
",",
"path",
"=",
"client",
".",
"_parse",
"(",
"url",
")",
"factory",
"=",
"client",
".",
"HTTPClientFactory",
"(",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"scheme",
"==",
"'https'",
":",
"if",
"contextFactory",
"is",
"None",
":",
"raise",
"RuntimeError",
",",
"'must provide a contextFactory'",
"conn",
"=",
"reactor",
".",
"connectSSL",
"(",
"host",
",",
"port",
",",
"factory",
",",
"contextFactory",
")",
"else",
":",
"conn",
"=",
"reactor",
".",
"connectTCP",
"(",
"host",
",",
"port",
",",
"factory",
")",
"return",
"factory"
] |
Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
|
[
"Download",
"a",
"web",
"page",
"as",
"a",
"string",
"."
] |
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
|
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/twisted/client.py#L41-L58
|
245,397
|
rameshg87/pyremotevbox
|
pyremotevbox/ZSI/twisted/client.py
|
Binding.Send
|
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None,
**kw):
"""Returns a ProcessingChain which needs to be passed to Receive if
Send is being called consecutively.
"""
url = url or self.url
cookies = None
if chain is not None:
cookies = chain.flow.cookies
d = {}
d.update(self.nsdict)
d.update(nsdict)
if soapaction is not None:
self.addHTTPHeader('SOAPAction', soapaction)
chain = self.factory.newInstance()
soapdata = chain.processRequest(pyobj, nsdict=nsdict,
soapaction=soapaction, **kw)
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
f = getPage(str(url), contextFactory=self.contextFactory,
postdata=soapdata, agent=self.agent,
method='POST', headers=self.getHTTPHeaders(),
cookies=cookies)
if isinstance(f, Failure):
return f
chain.flow = f
self.chain = chain
return chain
|
python
|
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None,
**kw):
"""Returns a ProcessingChain which needs to be passed to Receive if
Send is being called consecutively.
"""
url = url or self.url
cookies = None
if chain is not None:
cookies = chain.flow.cookies
d = {}
d.update(self.nsdict)
d.update(nsdict)
if soapaction is not None:
self.addHTTPHeader('SOAPAction', soapaction)
chain = self.factory.newInstance()
soapdata = chain.processRequest(pyobj, nsdict=nsdict,
soapaction=soapaction, **kw)
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
f = getPage(str(url), contextFactory=self.contextFactory,
postdata=soapdata, agent=self.agent,
method='POST', headers=self.getHTTPHeaders(),
cookies=cookies)
if isinstance(f, Failure):
return f
chain.flow = f
self.chain = chain
return chain
|
[
"def",
"Send",
"(",
"self",
",",
"url",
",",
"opname",
",",
"pyobj",
",",
"nsdict",
"=",
"{",
"}",
",",
"soapaction",
"=",
"None",
",",
"chain",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"url",
"=",
"url",
"or",
"self",
".",
"url",
"cookies",
"=",
"None",
"if",
"chain",
"is",
"not",
"None",
":",
"cookies",
"=",
"chain",
".",
"flow",
".",
"cookies",
"d",
"=",
"{",
"}",
"d",
".",
"update",
"(",
"self",
".",
"nsdict",
")",
"d",
".",
"update",
"(",
"nsdict",
")",
"if",
"soapaction",
"is",
"not",
"None",
":",
"self",
".",
"addHTTPHeader",
"(",
"'SOAPAction'",
",",
"soapaction",
")",
"chain",
"=",
"self",
".",
"factory",
".",
"newInstance",
"(",
")",
"soapdata",
"=",
"chain",
".",
"processRequest",
"(",
"pyobj",
",",
"nsdict",
"=",
"nsdict",
",",
"soapaction",
"=",
"soapaction",
",",
"*",
"*",
"kw",
")",
"if",
"self",
".",
"trace",
":",
"print",
">>",
"self",
".",
"trace",
",",
"\"_\"",
"*",
"33",
",",
"time",
".",
"ctime",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"\"REQUEST:\"",
"print",
">>",
"self",
".",
"trace",
",",
"soapdata",
"f",
"=",
"getPage",
"(",
"str",
"(",
"url",
")",
",",
"contextFactory",
"=",
"self",
".",
"contextFactory",
",",
"postdata",
"=",
"soapdata",
",",
"agent",
"=",
"self",
".",
"agent",
",",
"method",
"=",
"'POST'",
",",
"headers",
"=",
"self",
".",
"getHTTPHeaders",
"(",
")",
",",
"cookies",
"=",
"cookies",
")",
"if",
"isinstance",
"(",
"f",
",",
"Failure",
")",
":",
"return",
"f",
"chain",
".",
"flow",
"=",
"f",
"self",
".",
"chain",
"=",
"chain",
"return",
"chain"
] |
Returns a ProcessingChain which needs to be passed to Receive if
Send is being called consecutively.
|
[
"Returns",
"a",
"ProcessingChain",
"which",
"needs",
"to",
"be",
"passed",
"to",
"Receive",
"if",
"Send",
"is",
"being",
"called",
"consecutively",
"."
] |
123dffff27da57c8faa3ac1dd4c68b1cf4558b1a
|
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/twisted/client.py#L246-L281
|
245,398
|
quasipedia/swaggery
|
swaggery/responses.py
|
AsyncResponse.stream_array
|
def stream_array(self, generator):
'''Helper function to stream content as an array of JSON values.'''
def chunkify(generator):
log.debug('Data Stream STARTED')
yield '['.encode()
# In order to have commas only after the first value, we take the
# first value of the generator manually
try:
yield jsonify(next(generator)).encode()
except StopIteration:
pass
while True:
try:
bit = next(generator)
except StopIteration:
yield ']'.encode()
break
else:
yield ',\n'.encode()
yield jsonify(bit).encode()
log.debug('Data Stream ENDED')
return chunkify(generator)
|
python
|
def stream_array(self, generator):
'''Helper function to stream content as an array of JSON values.'''
def chunkify(generator):
log.debug('Data Stream STARTED')
yield '['.encode()
# In order to have commas only after the first value, we take the
# first value of the generator manually
try:
yield jsonify(next(generator)).encode()
except StopIteration:
pass
while True:
try:
bit = next(generator)
except StopIteration:
yield ']'.encode()
break
else:
yield ',\n'.encode()
yield jsonify(bit).encode()
log.debug('Data Stream ENDED')
return chunkify(generator)
|
[
"def",
"stream_array",
"(",
"self",
",",
"generator",
")",
":",
"def",
"chunkify",
"(",
"generator",
")",
":",
"log",
".",
"debug",
"(",
"'Data Stream STARTED'",
")",
"yield",
"'['",
".",
"encode",
"(",
")",
"# In order to have commas only after the first value, we take the",
"# first value of the generator manually",
"try",
":",
"yield",
"jsonify",
"(",
"next",
"(",
"generator",
")",
")",
".",
"encode",
"(",
")",
"except",
"StopIteration",
":",
"pass",
"while",
"True",
":",
"try",
":",
"bit",
"=",
"next",
"(",
"generator",
")",
"except",
"StopIteration",
":",
"yield",
"']'",
".",
"encode",
"(",
")",
"break",
"else",
":",
"yield",
"',\\n'",
".",
"encode",
"(",
")",
"yield",
"jsonify",
"(",
"bit",
")",
".",
"encode",
"(",
")",
"log",
".",
"debug",
"(",
"'Data Stream ENDED'",
")",
"return",
"chunkify",
"(",
"generator",
")"
] |
Helper function to stream content as an array of JSON values.
|
[
"Helper",
"function",
"to",
"stream",
"content",
"as",
"an",
"array",
"of",
"JSON",
"values",
"."
] |
89a2e1b2bebbc511c781c9e63972f65aef73cc2f
|
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/responses.py#L30-L51
|
245,399
|
quasipedia/swaggery
|
swaggery/responses.py
|
BadResponse.process_500
|
def process_500(self, request, exception):
'''Internal server error.'''
id_ = str(uuid.uuid4())[:6].upper()
msg = 'Internal server error: 500. Unique error identifier is {}'
msg = msg.format(id_)
log.error('HTTP 500 [Message - {}]: {}'.format(id_, msg))
log.error('HTTP 500 [Arguments - {}]: {}'.format(id_, request.args))
log.exception('HTTP 500 [Traceback - {}]:'.format(id_))
return msg
|
python
|
def process_500(self, request, exception):
'''Internal server error.'''
id_ = str(uuid.uuid4())[:6].upper()
msg = 'Internal server error: 500. Unique error identifier is {}'
msg = msg.format(id_)
log.error('HTTP 500 [Message - {}]: {}'.format(id_, msg))
log.error('HTTP 500 [Arguments - {}]: {}'.format(id_, request.args))
log.exception('HTTP 500 [Traceback - {}]:'.format(id_))
return msg
|
[
"def",
"process_500",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"id_",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"[",
":",
"6",
"]",
".",
"upper",
"(",
")",
"msg",
"=",
"'Internal server error: 500. Unique error identifier is {}'",
"msg",
"=",
"msg",
".",
"format",
"(",
"id_",
")",
"log",
".",
"error",
"(",
"'HTTP 500 [Message - {}]: {}'",
".",
"format",
"(",
"id_",
",",
"msg",
")",
")",
"log",
".",
"error",
"(",
"'HTTP 500 [Arguments - {}]: {}'",
".",
"format",
"(",
"id_",
",",
"request",
".",
"args",
")",
")",
"log",
".",
"exception",
"(",
"'HTTP 500 [Traceback - {}]:'",
".",
"format",
"(",
"id_",
")",
")",
"return",
"msg"
] |
Internal server error.
|
[
"Internal",
"server",
"error",
"."
] |
89a2e1b2bebbc511c781c9e63972f65aef73cc2f
|
https://github.com/quasipedia/swaggery/blob/89a2e1b2bebbc511c781c9e63972f65aef73cc2f/swaggery/responses.py#L80-L88
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.