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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Autodesk/aomi | aomi/model/resource.py | Resource.diff_write_only | def diff_write_only(resource):
"""A different implementation of diff that is
used for those Vault resources that are write-only
such as AWS root configs"""
if resource.present and not resource.existing:
return ADD
elif not resource.present and resource.existing:
return DEL
elif resource.present and resource.existing:
return OVERWRITE
return NOOP | python | def diff_write_only(resource):
"""A different implementation of diff that is
used for those Vault resources that are write-only
such as AWS root configs"""
if resource.present and not resource.existing:
return ADD
elif not resource.present and resource.existing:
return DEL
elif resource.present and resource.existing:
return OVERWRITE
return NOOP | [
"def",
"diff_write_only",
"(",
"resource",
")",
":",
"if",
"resource",
".",
"present",
"and",
"not",
"resource",
".",
"existing",
":",
"return",
"ADD",
"elif",
"not",
"resource",
".",
"present",
"and",
"resource",
".",
"existing",
":",
"return",
"DEL",
"el... | A different implementation of diff that is
used for those Vault resources that are write-only
such as AWS root configs | [
"A",
"different",
"implementation",
"of",
"diff",
"that",
"is",
"used",
"for",
"those",
"Vault",
"resources",
"that",
"are",
"write",
"-",
"only",
"such",
"as",
"AWS",
"root",
"configs"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L239-L250 | train | 44,500 |
Autodesk/aomi | aomi/model/resource.py | Resource.read | def read(self, client):
"""Read from Vault while handling non surprising errors."""
val = None
if self.no_resource:
return val
LOG.debug("Reading from %s", self)
try:
val = client.read(self.path)
except hvac.exceptions.InvalidRequest as vault_exception:
if str(vault_exception).startswith('no handler for route'):
val = None
return val | python | def read(self, client):
"""Read from Vault while handling non surprising errors."""
val = None
if self.no_resource:
return val
LOG.debug("Reading from %s", self)
try:
val = client.read(self.path)
except hvac.exceptions.InvalidRequest as vault_exception:
if str(vault_exception).startswith('no handler for route'):
val = None
return val | [
"def",
"read",
"(",
"self",
",",
"client",
")",
":",
"val",
"=",
"None",
"if",
"self",
".",
"no_resource",
":",
"return",
"val",
"LOG",
".",
"debug",
"(",
"\"Reading from %s\"",
",",
"self",
")",
"try",
":",
"val",
"=",
"client",
".",
"read",
"(",
... | Read from Vault while handling non surprising errors. | [
"Read",
"from",
"Vault",
"while",
"handling",
"non",
"surprising",
"errors",
"."
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L253-L266 | train | 44,501 |
Autodesk/aomi | aomi/model/resource.py | Resource.write | def write(self, client):
"""Write to Vault while handling non-surprising errors."""
val = None
if not self.no_resource:
val = client.write(self.path, **self.obj())
return val | python | def write(self, client):
"""Write to Vault while handling non-surprising errors."""
val = None
if not self.no_resource:
val = client.write(self.path, **self.obj())
return val | [
"def",
"write",
"(",
"self",
",",
"client",
")",
":",
"val",
"=",
"None",
"if",
"not",
"self",
".",
"no_resource",
":",
"val",
"=",
"client",
".",
"write",
"(",
"self",
".",
"path",
",",
"*",
"*",
"self",
".",
"obj",
"(",
")",
")",
"return",
"v... | Write to Vault while handling non-surprising errors. | [
"Write",
"to",
"Vault",
"while",
"handling",
"non",
"-",
"surprising",
"errors",
"."
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L269-L275 | train | 44,502 |
Autodesk/aomi | aomi/validation.py | find_file | def find_file(name, directory):
"""Searches up from a directory looking for a file"""
path_bits = directory.split(os.sep)
for i in range(0, len(path_bits) - 1):
check_path = path_bits[0:len(path_bits) - i]
check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name)
if os.path.exists(check_file):
return abspath(check_file)
return None | python | def find_file(name, directory):
"""Searches up from a directory looking for a file"""
path_bits = directory.split(os.sep)
for i in range(0, len(path_bits) - 1):
check_path = path_bits[0:len(path_bits) - i]
check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name)
if os.path.exists(check_file):
return abspath(check_file)
return None | [
"def",
"find_file",
"(",
"name",
",",
"directory",
")",
":",
"path_bits",
"=",
"directory",
".",
"split",
"(",
"os",
".",
"sep",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"path_bits",
")",
"-",
"1",
")",
":",
"check_path",
"=",
"... | Searches up from a directory looking for a file | [
"Searches",
"up",
"from",
"a",
"directory",
"looking",
"for",
"a",
"file"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L14-L23 | train | 44,503 |
Autodesk/aomi | aomi/validation.py | in_file | def in_file(string, search_file):
"""Looks in a file for a string."""
handle = open(search_file, 'r')
for line in handle.readlines():
if string in line:
return True
return False | python | def in_file(string, search_file):
"""Looks in a file for a string."""
handle = open(search_file, 'r')
for line in handle.readlines():
if string in line:
return True
return False | [
"def",
"in_file",
"(",
"string",
",",
"search_file",
")",
":",
"handle",
"=",
"open",
"(",
"search_file",
",",
"'r'",
")",
"for",
"line",
"in",
"handle",
".",
"readlines",
"(",
")",
":",
"if",
"string",
"in",
"line",
":",
"return",
"True",
"return",
... | Looks in a file for a string. | [
"Looks",
"in",
"a",
"file",
"for",
"a",
"string",
"."
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L26-L33 | train | 44,504 |
Autodesk/aomi | aomi/validation.py | gitignore | def gitignore(opt):
"""Will check directories upwards from the Secretfile in order
to ensure the gitignore file is set properly"""
directory = os.path.dirname(abspath(opt.secretfile))
gitignore_file = find_file('.gitignore', directory)
if gitignore_file:
secrets_path = subdir_path(abspath(opt.secrets), gitignore_file)
if secrets_path:
if not in_file(secrets_path, gitignore_file):
e_msg = "The path %s was not found in %s" \
% (secrets_path, gitignore_file)
raise aomi.exceptions.AomiFile(e_msg)
else:
LOG.debug("Using a non-relative secret directory")
else:
raise aomi.exceptions.AomiFile("You should really have a .gitignore") | python | def gitignore(opt):
"""Will check directories upwards from the Secretfile in order
to ensure the gitignore file is set properly"""
directory = os.path.dirname(abspath(opt.secretfile))
gitignore_file = find_file('.gitignore', directory)
if gitignore_file:
secrets_path = subdir_path(abspath(opt.secrets), gitignore_file)
if secrets_path:
if not in_file(secrets_path, gitignore_file):
e_msg = "The path %s was not found in %s" \
% (secrets_path, gitignore_file)
raise aomi.exceptions.AomiFile(e_msg)
else:
LOG.debug("Using a non-relative secret directory")
else:
raise aomi.exceptions.AomiFile("You should really have a .gitignore") | [
"def",
"gitignore",
"(",
"opt",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"abspath",
"(",
"opt",
".",
"secretfile",
")",
")",
"gitignore_file",
"=",
"find_file",
"(",
"'.gitignore'",
",",
"directory",
")",
"if",
"gitignore_file",
... | Will check directories upwards from the Secretfile in order
to ensure the gitignore file is set properly | [
"Will",
"check",
"directories",
"upwards",
"from",
"the",
"Secretfile",
"in",
"order",
"to",
"ensure",
"the",
"gitignore",
"file",
"is",
"set",
"properly"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L36-L52 | train | 44,505 |
Autodesk/aomi | aomi/validation.py | secret_file | def secret_file(filename):
"""Will check the permissions of things which really
should be secret files"""
filestat = os.stat(abspath(filename))
if stat.S_ISREG(filestat.st_mode) == 0 and \
stat.S_ISLNK(filestat.st_mode) == 0:
e_msg = "Secret file %s must be a real file or symlink" % filename
raise aomi.exceptions.AomiFile(e_msg)
if platform.system() != "Windows":
if filestat.st_mode & stat.S_IROTH or \
filestat.st_mode & stat.S_IWOTH or \
filestat.st_mode & stat.S_IWGRP:
e_msg = "Secret file %s has too loose permissions" % filename
raise aomi.exceptions.AomiFile(e_msg) | python | def secret_file(filename):
"""Will check the permissions of things which really
should be secret files"""
filestat = os.stat(abspath(filename))
if stat.S_ISREG(filestat.st_mode) == 0 and \
stat.S_ISLNK(filestat.st_mode) == 0:
e_msg = "Secret file %s must be a real file or symlink" % filename
raise aomi.exceptions.AomiFile(e_msg)
if platform.system() != "Windows":
if filestat.st_mode & stat.S_IROTH or \
filestat.st_mode & stat.S_IWOTH or \
filestat.st_mode & stat.S_IWGRP:
e_msg = "Secret file %s has too loose permissions" % filename
raise aomi.exceptions.AomiFile(e_msg) | [
"def",
"secret_file",
"(",
"filename",
")",
":",
"filestat",
"=",
"os",
".",
"stat",
"(",
"abspath",
"(",
"filename",
")",
")",
"if",
"stat",
".",
"S_ISREG",
"(",
"filestat",
".",
"st_mode",
")",
"==",
"0",
"and",
"stat",
".",
"S_ISLNK",
"(",
"filest... | Will check the permissions of things which really
should be secret files | [
"Will",
"check",
"the",
"permissions",
"of",
"things",
"which",
"really",
"should",
"be",
"secret",
"files"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L55-L69 | train | 44,506 |
Autodesk/aomi | aomi/validation.py | validate_obj | def validate_obj(keys, obj):
"""Super simple "object" validation."""
msg = ''
for k in keys:
if isinstance(k, str):
if k not in obj or (not isinstance(obj[k], list) and not obj[k]):
if msg:
msg = "%s," % msg
msg = "%s%s" % (msg, k)
elif isinstance(k, list):
found = False
for k_a in k:
if k_a in obj:
found = True
if not found:
if msg:
msg = "%s," % msg
msg = "%s(%s" % (msg, ','.join(k))
if msg:
msg = "%s missing" % msg
return msg | python | def validate_obj(keys, obj):
"""Super simple "object" validation."""
msg = ''
for k in keys:
if isinstance(k, str):
if k not in obj or (not isinstance(obj[k], list) and not obj[k]):
if msg:
msg = "%s," % msg
msg = "%s%s" % (msg, k)
elif isinstance(k, list):
found = False
for k_a in k:
if k_a in obj:
found = True
if not found:
if msg:
msg = "%s," % msg
msg = "%s(%s" % (msg, ','.join(k))
if msg:
msg = "%s missing" % msg
return msg | [
"def",
"validate_obj",
"(",
"keys",
",",
"obj",
")",
":",
"msg",
"=",
"''",
"for",
"k",
"in",
"keys",
":",
"if",
"isinstance",
"(",
"k",
",",
"str",
")",
":",
"if",
"k",
"not",
"in",
"obj",
"or",
"(",
"not",
"isinstance",
"(",
"obj",
"[",
"k",
... | Super simple "object" validation. | [
"Super",
"simple",
"object",
"validation",
"."
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L72-L97 | train | 44,507 |
Autodesk/aomi | aomi/validation.py | check_obj | def check_obj(keys, name, obj):
"""Do basic validation on an object"""
msg = validate_obj(keys, obj)
if msg:
raise aomi.exceptions.AomiData("object check : %s in %s" % (msg, name)) | python | def check_obj(keys, name, obj):
"""Do basic validation on an object"""
msg = validate_obj(keys, obj)
if msg:
raise aomi.exceptions.AomiData("object check : %s in %s" % (msg, name)) | [
"def",
"check_obj",
"(",
"keys",
",",
"name",
",",
"obj",
")",
":",
"msg",
"=",
"validate_obj",
"(",
"keys",
",",
"obj",
")",
"if",
"msg",
":",
"raise",
"aomi",
".",
"exceptions",
".",
"AomiData",
"(",
"\"object check : %s in %s\"",
"%",
"(",
"msg",
",... | Do basic validation on an object | [
"Do",
"basic",
"validation",
"on",
"an",
"object"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L114-L119 | train | 44,508 |
Autodesk/aomi | aomi/validation.py | sanitize_mount | def sanitize_mount(mount):
"""Returns a quote-unquote sanitized mount path"""
sanitized_mount = mount
if sanitized_mount.startswith('/'):
sanitized_mount = sanitized_mount[1:]
if sanitized_mount.endswith('/'):
sanitized_mount = sanitized_mount[:-1]
sanitized_mount = sanitized_mount.replace('//', '/')
return sanitized_mount | python | def sanitize_mount(mount):
"""Returns a quote-unquote sanitized mount path"""
sanitized_mount = mount
if sanitized_mount.startswith('/'):
sanitized_mount = sanitized_mount[1:]
if sanitized_mount.endswith('/'):
sanitized_mount = sanitized_mount[:-1]
sanitized_mount = sanitized_mount.replace('//', '/')
return sanitized_mount | [
"def",
"sanitize_mount",
"(",
"mount",
")",
":",
"sanitized_mount",
"=",
"mount",
"if",
"sanitized_mount",
".",
"startswith",
"(",
"'/'",
")",
":",
"sanitized_mount",
"=",
"sanitized_mount",
"[",
"1",
":",
"]",
"if",
"sanitized_mount",
".",
"endswith",
"(",
... | Returns a quote-unquote sanitized mount path | [
"Returns",
"a",
"quote",
"-",
"unquote",
"sanitized",
"mount",
"path"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L122-L132 | train | 44,509 |
Autodesk/aomi | aomi/validation.py | gpg_fingerprint | def gpg_fingerprint(key):
"""Validates a GPG key fingerprint
This handles both pre and post GPG 2.1"""
if (len(key) == 8 and re.match(r'^[0-9A-F]{8}$', key)) or \
(len(key) == 40 and re.match(r'^[0-9A-F]{40}$', key)):
return
raise aomi.exceptions.Validation('Invalid GPG Fingerprint') | python | def gpg_fingerprint(key):
"""Validates a GPG key fingerprint
This handles both pre and post GPG 2.1"""
if (len(key) == 8 and re.match(r'^[0-9A-F]{8}$', key)) or \
(len(key) == 40 and re.match(r'^[0-9A-F]{40}$', key)):
return
raise aomi.exceptions.Validation('Invalid GPG Fingerprint') | [
"def",
"gpg_fingerprint",
"(",
"key",
")",
":",
"if",
"(",
"len",
"(",
"key",
")",
"==",
"8",
"and",
"re",
".",
"match",
"(",
"r'^[0-9A-F]{8}$'",
",",
"key",
")",
")",
"or",
"(",
"len",
"(",
"key",
")",
"==",
"40",
"and",
"re",
".",
"match",
"(... | Validates a GPG key fingerprint
This handles both pre and post GPG 2.1 | [
"Validates",
"a",
"GPG",
"key",
"fingerprint"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L135-L143 | train | 44,510 |
Autodesk/aomi | aomi/validation.py | is_unicode_string | def is_unicode_string(string):
"""Validates that we are some kinda unicode string"""
try:
if sys.version_info >= (3, 0):
# isn't a python 3 str actually unicode
if not isinstance(string, str):
string.decode('utf-8')
else:
string.decode('utf-8')
except UnicodeError:
raise aomi.exceptions.Validation('Not a unicode string') | python | def is_unicode_string(string):
"""Validates that we are some kinda unicode string"""
try:
if sys.version_info >= (3, 0):
# isn't a python 3 str actually unicode
if not isinstance(string, str):
string.decode('utf-8')
else:
string.decode('utf-8')
except UnicodeError:
raise aomi.exceptions.Validation('Not a unicode string') | [
"def",
"is_unicode_string",
"(",
"string",
")",
":",
"try",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"# isn't a python 3 str actually unicode",
"if",
"not",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"string",
".",... | Validates that we are some kinda unicode string | [
"Validates",
"that",
"we",
"are",
"some",
"kinda",
"unicode",
"string"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L146-L157 | train | 44,511 |
Autodesk/aomi | aomi/validation.py | is_unicode | def is_unicode(string):
"""Validates that the object itself is some kinda string"""
str_type = str(type(string))
if str_type.find('str') > 0 or str_type.find('unicode') > 0:
return True
return False | python | def is_unicode(string):
"""Validates that the object itself is some kinda string"""
str_type = str(type(string))
if str_type.find('str') > 0 or str_type.find('unicode') > 0:
return True
return False | [
"def",
"is_unicode",
"(",
"string",
")",
":",
"str_type",
"=",
"str",
"(",
"type",
"(",
"string",
")",
")",
"if",
"str_type",
".",
"find",
"(",
"'str'",
")",
">",
"0",
"or",
"str_type",
".",
"find",
"(",
"'unicode'",
")",
">",
"0",
":",
"return",
... | Validates that the object itself is some kinda string | [
"Validates",
"that",
"the",
"object",
"itself",
"is",
"some",
"kinda",
"string"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L160-L167 | train | 44,512 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.get_sectionsf | def get_sectionsf(self, *args, **kwargs):
"""
Decorator method to extract sections from a function docstring
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_sections` method. Note, that the first argument
will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its sections
via the :meth:`get_sections` method"""
def func(f):
doc = f.__doc__
self.get_sections(doc or '', *args, **kwargs)
return f
return func | python | def get_sectionsf(self, *args, **kwargs):
"""
Decorator method to extract sections from a function docstring
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_sections` method. Note, that the first argument
will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its sections
via the :meth:`get_sections` method"""
def func(f):
doc = f.__doc__
self.get_sections(doc or '', *args, **kwargs)
return f
return func | [
"def",
"get_sectionsf",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"func",
"(",
"f",
")",
":",
"doc",
"=",
"f",
".",
"__doc__",
"self",
".",
"get_sections",
"(",
"doc",
"or",
"''",
",",
"*",
"args",
",",
"*",
"*",
... | Decorator method to extract sections from a function docstring
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_sections` method. Note, that the first argument
will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its sections
via the :meth:`get_sections` method | [
"Decorator",
"method",
"to",
"extract",
"sections",
"from",
"a",
"function",
"docstring"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L350-L369 | train | 44,513 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.delete_params_s | def delete_params_s(s, params):
"""
Delete the given parameters from a string
Same as :meth:`delete_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters section
params: list of str
The names of the parameters to delete
Returns
-------
str
The modified string `s` without the descriptions of `params`
"""
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params)
return re.sub(patt, '', '\n' + s.strip() + '\n').strip() | python | def delete_params_s(s, params):
"""
Delete the given parameters from a string
Same as :meth:`delete_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters section
params: list of str
The names of the parameters to delete
Returns
-------
str
The modified string `s` without the descriptions of `params`
"""
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params)
return re.sub(patt, '', '\n' + s.strip() + '\n').strip() | [
"def",
"delete_params_s",
"(",
"s",
",",
"params",
")",
":",
"patt",
"=",
"'(?s)'",
"+",
"'|'",
".",
"join",
"(",
"'(?<=\\n)'",
"+",
"s",
"+",
"'\\s*:.+?\\n(?=\\S+|$)'",
"for",
"s",
"in",
"params",
")",
"return",
"re",
".",
"sub",
"(",
"patt",
",",
"... | Delete the given parameters from a string
Same as :meth:`delete_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters section
params: list of str
The names of the parameters to delete
Returns
-------
str
The modified string `s` without the descriptions of `params` | [
"Delete",
"the",
"given",
"parameters",
"from",
"a",
"string"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L498-L519 | train | 44,514 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.delete_types_s | def delete_types_s(s, types):
"""
Delete the given types from a string
Same as :meth:`delete_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to delete
Returns
-------
str
The modified string `s` without the descriptions of `types`
"""
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\n.+?\n(?=\S+|$)' for s in types)
return re.sub(patt, '', '\n' + s.strip() + '\n',).strip() | python | def delete_types_s(s, types):
"""
Delete the given types from a string
Same as :meth:`delete_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to delete
Returns
-------
str
The modified string `s` without the descriptions of `types`
"""
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\n.+?\n(?=\S+|$)' for s in types)
return re.sub(patt, '', '\n' + s.strip() + '\n',).strip() | [
"def",
"delete_types_s",
"(",
"s",
",",
"types",
")",
":",
"patt",
"=",
"'(?s)'",
"+",
"'|'",
".",
"join",
"(",
"'(?<=\\n)'",
"+",
"s",
"+",
"'\\n.+?\\n(?=\\S+|$)'",
"for",
"s",
"in",
"types",
")",
"return",
"re",
".",
"sub",
"(",
"patt",
",",
"''",
... | Delete the given types from a string
Same as :meth:`delete_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to delete
Returns
-------
str
The modified string `s` without the descriptions of `types` | [
"Delete",
"the",
"given",
"types",
"from",
"a",
"string"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L618-L639 | train | 44,515 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.keep_params_s | def keep_params_s(s, params):
"""
Keep the given parameters from a string
Same as :meth:`keep_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters like section
params: list of str
The parameter names to keep
Returns
-------
str
The modified string `s` with only the descriptions of `params`
"""
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params)
return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip() | python | def keep_params_s(s, params):
"""
Keep the given parameters from a string
Same as :meth:`keep_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters like section
params: list of str
The parameter names to keep
Returns
-------
str
The modified string `s` with only the descriptions of `params`
"""
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params)
return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip() | [
"def",
"keep_params_s",
"(",
"s",
",",
"params",
")",
":",
"patt",
"=",
"'(?s)'",
"+",
"'|'",
".",
"join",
"(",
"'(?<=\\n)'",
"+",
"s",
"+",
"'\\s*:.+?\\n(?=\\S+|$)'",
"for",
"s",
"in",
"params",
")",
"return",
"''",
".",
"join",
"(",
"re",
".",
"fin... | Keep the given parameters from a string
Same as :meth:`keep_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters like section
params: list of str
The parameter names to keep
Returns
-------
str
The modified string `s` with only the descriptions of `params` | [
"Keep",
"the",
"given",
"parameters",
"from",
"a",
"string"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L730-L751 | train | 44,516 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.keep_types_s | def keep_types_s(s, types):
"""
Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to keep
Returns
-------
str
The modified string `s` with only the descriptions of `types`
"""
patt = '|'.join('(?<=\n)' + s + '\n(?s).+?\n(?=\S+|$)' for s in types)
return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip() | python | def keep_types_s(s, types):
"""
Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to keep
Returns
-------
str
The modified string `s` with only the descriptions of `types`
"""
patt = '|'.join('(?<=\n)' + s + '\n(?s).+?\n(?=\S+|$)' for s in types)
return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip() | [
"def",
"keep_types_s",
"(",
"s",
",",
"types",
")",
":",
"patt",
"=",
"'|'",
".",
"join",
"(",
"'(?<=\\n)'",
"+",
"s",
"+",
"'\\n(?s).+?\\n(?=\\S+|$)'",
"for",
"s",
"in",
"types",
")",
"return",
"''",
".",
"join",
"(",
"re",
".",
"findall",
"(",
"pat... | Keep the given types from a string
Same as :meth:`keep_types` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the returns like section
types: list of str
The type identifiers to keep
Returns
-------
str
The modified string `s` with only the descriptions of `types` | [
"Keep",
"the",
"given",
"types",
"from",
"a",
"string"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L836-L856 | train | 44,517 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.save_docstring | def save_docstring(self, key):
"""
Descriptor method to save a docstring from a function
Like the :meth:`get_sectionsf` method this method serves as a
descriptor for functions but saves the entire docstring"""
def func(f):
self.params[key] = f.__doc__ or ''
return f
return func | python | def save_docstring(self, key):
"""
Descriptor method to save a docstring from a function
Like the :meth:`get_sectionsf` method this method serves as a
descriptor for functions but saves the entire docstring"""
def func(f):
self.params[key] = f.__doc__ or ''
return f
return func | [
"def",
"save_docstring",
"(",
"self",
",",
"key",
")",
":",
"def",
"func",
"(",
"f",
")",
":",
"self",
".",
"params",
"[",
"key",
"]",
"=",
"f",
".",
"__doc__",
"or",
"''",
"return",
"f",
"return",
"func"
] | Descriptor method to save a docstring from a function
Like the :meth:`get_sectionsf` method this method serves as a
descriptor for functions but saves the entire docstring | [
"Descriptor",
"method",
"to",
"save",
"a",
"docstring",
"from",
"a",
"function"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L858-L867 | train | 44,518 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.get_summary | def get_summary(self, s, base=None):
"""
Get the summary of the given docstring
This method extracts the summary from the given docstring `s` which is
basicly the part until two newlines appear
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the summary shall be stored in the :attr:`params`
attribute. If not None, the summary will be stored in
``base + '.summary'``. Otherwise, it will not be stored at all
Returns
-------
str
The extracted summary"""
summary = summary_patt.search(s).group()
if base is not None:
self.params[base + '.summary'] = summary
return summary | python | def get_summary(self, s, base=None):
"""
Get the summary of the given docstring
This method extracts the summary from the given docstring `s` which is
basicly the part until two newlines appear
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the summary shall be stored in the :attr:`params`
attribute. If not None, the summary will be stored in
``base + '.summary'``. Otherwise, it will not be stored at all
Returns
-------
str
The extracted summary"""
summary = summary_patt.search(s).group()
if base is not None:
self.params[base + '.summary'] = summary
return summary | [
"def",
"get_summary",
"(",
"self",
",",
"s",
",",
"base",
"=",
"None",
")",
":",
"summary",
"=",
"summary_patt",
".",
"search",
"(",
"s",
")",
".",
"group",
"(",
")",
"if",
"base",
"is",
"not",
"None",
":",
"self",
".",
"params",
"[",
"base",
"+"... | Get the summary of the given docstring
This method extracts the summary from the given docstring `s` which is
basicly the part until two newlines appear
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the summary shall be stored in the :attr:`params`
attribute. If not None, the summary will be stored in
``base + '.summary'``. Otherwise, it will not be stored at all
Returns
-------
str
The extracted summary | [
"Get",
"the",
"summary",
"of",
"the",
"given",
"docstring"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L869-L892 | train | 44,519 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.get_summaryf | def get_summaryf(self, *args, **kwargs):
"""
Extract the summary from a function docstring
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_summary` method. Note, that the first argument
will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_summary` method"""
def func(f):
doc = f.__doc__
self.get_summary(doc or '', *args, **kwargs)
return f
return func | python | def get_summaryf(self, *args, **kwargs):
"""
Extract the summary from a function docstring
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_summary` method. Note, that the first argument
will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_summary` method"""
def func(f):
doc = f.__doc__
self.get_summary(doc or '', *args, **kwargs)
return f
return func | [
"def",
"get_summaryf",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"func",
"(",
"f",
")",
":",
"doc",
"=",
"f",
".",
"__doc__",
"self",
".",
"get_summary",
"(",
"doc",
"or",
"''",
",",
"*",
"args",
",",
"*",
"*",
... | Extract the summary from a function docstring
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_summary` method. Note, that the first argument
will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_summary` method | [
"Extract",
"the",
"summary",
"from",
"a",
"function",
"docstring"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L894-L913 | train | 44,520 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.get_extended_summary | def get_extended_summary(self, s, base=None):
"""Get the extended summary from a docstring
This here is the extended summary
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the summary shall be stored in the :attr:`params`
attribute. If not None, the summary will be stored in
``base + '.summary_ext'``. Otherwise, it will not be stored at
all
Returns
-------
str
The extracted extended summary"""
# Remove the summary and dedent
s = self._remove_summary(s)
ret = ''
if not self._all_sections_patt.match(s):
m = self._extended_summary_patt.match(s)
if m is not None:
ret = m.group().strip()
if base is not None:
self.params[base + '.summary_ext'] = ret
return ret | python | def get_extended_summary(self, s, base=None):
"""Get the extended summary from a docstring
This here is the extended summary
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the summary shall be stored in the :attr:`params`
attribute. If not None, the summary will be stored in
``base + '.summary_ext'``. Otherwise, it will not be stored at
all
Returns
-------
str
The extracted extended summary"""
# Remove the summary and dedent
s = self._remove_summary(s)
ret = ''
if not self._all_sections_patt.match(s):
m = self._extended_summary_patt.match(s)
if m is not None:
ret = m.group().strip()
if base is not None:
self.params[base + '.summary_ext'] = ret
return ret | [
"def",
"get_extended_summary",
"(",
"self",
",",
"s",
",",
"base",
"=",
"None",
")",
":",
"# Remove the summary and dedent",
"s",
"=",
"self",
".",
"_remove_summary",
"(",
"s",
")",
"ret",
"=",
"''",
"if",
"not",
"self",
".",
"_all_sections_patt",
".",
"ma... | Get the extended summary from a docstring
This here is the extended summary
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the summary shall be stored in the :attr:`params`
attribute. If not None, the summary will be stored in
``base + '.summary_ext'``. Otherwise, it will not be stored at
all
Returns
-------
str
The extracted extended summary | [
"Get",
"the",
"extended",
"summary",
"from",
"a",
"docstring"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L915-L943 | train | 44,521 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.get_extended_summaryf | def get_extended_summaryf(self, *args, **kwargs):
"""Extract the extended summary from a function docstring
This function can be used as a decorator to extract the extended
summary of a function docstring (similar to :meth:`get_sectionsf`).
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_extended_summary` method. Note, that the first
argument will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_extended_summary` method"""
def func(f):
doc = f.__doc__
self.get_extended_summary(doc or '', *args, **kwargs)
return f
return func | python | def get_extended_summaryf(self, *args, **kwargs):
"""Extract the extended summary from a function docstring
This function can be used as a decorator to extract the extended
summary of a function docstring (similar to :meth:`get_sectionsf`).
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_extended_summary` method. Note, that the first
argument will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_extended_summary` method"""
def func(f):
doc = f.__doc__
self.get_extended_summary(doc or '', *args, **kwargs)
return f
return func | [
"def",
"get_extended_summaryf",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"func",
"(",
"f",
")",
":",
"doc",
"=",
"f",
".",
"__doc__",
"self",
".",
"get_extended_summary",
"(",
"doc",
"or",
"''",
",",
"*",
"args",
","... | Extract the extended summary from a function docstring
This function can be used as a decorator to extract the extended
summary of a function docstring (similar to :meth:`get_sectionsf`).
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_extended_summary` method. Note, that the first
argument will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_extended_summary` method | [
"Extract",
"the",
"extended",
"summary",
"from",
"a",
"function",
"docstring"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L945-L966 | train | 44,522 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.get_full_description | def get_full_description(self, s, base=None):
"""Get the full description from a docstring
This here and the line above is the full description (i.e. the
combination of the :meth:`get_summary` and the
:meth:`get_extended_summary`) output
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the description shall be stored in the
:attr:`params` attribute. If not None, the summary will be stored
in ``base + '.full_desc'``. Otherwise, it will not be stored
at all
Returns
-------
str
The extracted full description"""
summary = self.get_summary(s)
extended_summary = self.get_extended_summary(s)
ret = (summary + '\n\n' + extended_summary).strip()
if base is not None:
self.params[base + '.full_desc'] = ret
return ret | python | def get_full_description(self, s, base=None):
"""Get the full description from a docstring
This here and the line above is the full description (i.e. the
combination of the :meth:`get_summary` and the
:meth:`get_extended_summary`) output
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the description shall be stored in the
:attr:`params` attribute. If not None, the summary will be stored
in ``base + '.full_desc'``. Otherwise, it will not be stored
at all
Returns
-------
str
The extracted full description"""
summary = self.get_summary(s)
extended_summary = self.get_extended_summary(s)
ret = (summary + '\n\n' + extended_summary).strip()
if base is not None:
self.params[base + '.full_desc'] = ret
return ret | [
"def",
"get_full_description",
"(",
"self",
",",
"s",
",",
"base",
"=",
"None",
")",
":",
"summary",
"=",
"self",
".",
"get_summary",
"(",
"s",
")",
"extended_summary",
"=",
"self",
".",
"get_extended_summary",
"(",
"s",
")",
"ret",
"=",
"(",
"summary",
... | Get the full description from a docstring
This here and the line above is the full description (i.e. the
combination of the :meth:`get_summary` and the
:meth:`get_extended_summary`) output
Parameters
----------
s: str
The docstring to use
base: str or None
A key under which the description shall be stored in the
:attr:`params` attribute. If not None, the summary will be stored
in ``base + '.full_desc'``. Otherwise, it will not be stored
at all
Returns
-------
str
The extracted full description | [
"Get",
"the",
"full",
"description",
"from",
"a",
"docstring"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L968-L994 | train | 44,523 |
Chilipp/docrep | docrep/__init__.py | DocstringProcessor.get_full_descriptionf | def get_full_descriptionf(self, *args, **kwargs):
"""Extract the full description from a function docstring
This function can be used as a decorator to extract the full
descriptions of a function docstring (similar to
:meth:`get_sectionsf`).
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_full_description` method. Note, that the first
argument will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_full_description` method"""
def func(f):
doc = f.__doc__
self.get_full_description(doc or '', *args, **kwargs)
return f
return func | python | def get_full_descriptionf(self, *args, **kwargs):
"""Extract the full description from a function docstring
This function can be used as a decorator to extract the full
descriptions of a function docstring (similar to
:meth:`get_sectionsf`).
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_full_description` method. Note, that the first
argument will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_full_description` method"""
def func(f):
doc = f.__doc__
self.get_full_description(doc or '', *args, **kwargs)
return f
return func | [
"def",
"get_full_descriptionf",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"func",
"(",
"f",
")",
":",
"doc",
"=",
"f",
".",
"__doc__",
"self",
".",
"get_full_description",
"(",
"doc",
"or",
"''",
",",
"*",
"args",
","... | Extract the full description from a function docstring
This function can be used as a decorator to extract the full
descriptions of a function docstring (similar to
:meth:`get_sectionsf`).
Parameters
----------
``*args`` and ``**kwargs``
See the :meth:`get_full_description` method. Note, that the first
argument will be the docstring of the specified function
Returns
-------
function
Wrapper that takes a function as input and registers its summary
via the :meth:`get_full_description` method | [
"Extract",
"the",
"full",
"description",
"from",
"a",
"function",
"docstring"
] | 637971f76e1a6e1c70e36dcd1b02bbc37ba02487 | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L996-L1018 | train | 44,524 |
pylover/pymlconf | pymlconf/models.py | Mergable.make_mergable_if_possible | def make_mergable_if_possible(cls, data, context):
"""
Makes an object mergable if possible. Returns the virgin object if
cannot convert it to a mergable instance.
:returns: :class:`.Mergable` or type(data)
"""
if isinstance(data, dict):
return MergableDict(data=data, context=context)
elif isiterable(data):
return MergableList(
data=[cls.make_mergable_if_possible(i, context) for i in data],
context=context
)
else:
return data | python | def make_mergable_if_possible(cls, data, context):
"""
Makes an object mergable if possible. Returns the virgin object if
cannot convert it to a mergable instance.
:returns: :class:`.Mergable` or type(data)
"""
if isinstance(data, dict):
return MergableDict(data=data, context=context)
elif isiterable(data):
return MergableList(
data=[cls.make_mergable_if_possible(i, context) for i in data],
context=context
)
else:
return data | [
"def",
"make_mergable_if_possible",
"(",
"cls",
",",
"data",
",",
"context",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"MergableDict",
"(",
"data",
"=",
"data",
",",
"context",
"=",
"context",
")",
"elif",
"isiterable",
... | Makes an object mergable if possible. Returns the virgin object if
cannot convert it to a mergable instance.
:returns: :class:`.Mergable` or type(data) | [
"Makes",
"an",
"object",
"mergable",
"if",
"possible",
".",
"Returns",
"the",
"virgin",
"object",
"if",
"cannot",
"convert",
"it",
"to",
"a",
"mergable",
"instance",
"."
] | a187dc3924dffc4d9992a369c7964599c6e201c1 | https://github.com/pylover/pymlconf/blob/a187dc3924dffc4d9992a369c7964599c6e201c1/pymlconf/models.py#L63-L79 | train | 44,525 |
pylover/pymlconf | pymlconf/models.py | Mergable.merge | def merge(self, *args):
"""
Merges this instance with new instances, in-place.
:param \\*args: Configuration values to merge with current instance.
:type \\*args: iterable
"""
for data in args:
if isinstance(data, str):
to_merge = load_string(data, self.context)
if not to_merge:
continue
else:
to_merge = data
if not self.can_merge(to_merge):
raise TypeError(
'Cannot merge myself:%s with %s. data: %s' \
% (type(self), type(data), data)
)
self._merge(to_merge) | python | def merge(self, *args):
"""
Merges this instance with new instances, in-place.
:param \\*args: Configuration values to merge with current instance.
:type \\*args: iterable
"""
for data in args:
if isinstance(data, str):
to_merge = load_string(data, self.context)
if not to_merge:
continue
else:
to_merge = data
if not self.can_merge(to_merge):
raise TypeError(
'Cannot merge myself:%s with %s. data: %s' \
% (type(self), type(data), data)
)
self._merge(to_merge) | [
"def",
"merge",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"data",
"in",
"args",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"to_merge",
"=",
"load_string",
"(",
"data",
",",
"self",
".",
"context",
")",
"if",
"not",
"to_merge"... | Merges this instance with new instances, in-place.
:param \\*args: Configuration values to merge with current instance.
:type \\*args: iterable | [
"Merges",
"this",
"instance",
"with",
"new",
"instances",
"in",
"-",
"place",
"."
] | a187dc3924dffc4d9992a369c7964599c6e201c1 | https://github.com/pylover/pymlconf/blob/a187dc3924dffc4d9992a369c7964599c6e201c1/pymlconf/models.py#L81-L103 | train | 44,526 |
pylover/pymlconf | pymlconf/models.py | Root.load_file | def load_file(self, filename):
"""
load file which contains yaml configuration entries.and merge it by
current instance
:param files: files to load and merge into existing configuration
instance
:type files: list
"""
if not path.exists(filename):
raise FileNotFoundError(filename)
loaded_yaml = load_yaml(filename, self.context)
if loaded_yaml:
self.merge(loaded_yaml) | python | def load_file(self, filename):
"""
load file which contains yaml configuration entries.and merge it by
current instance
:param files: files to load and merge into existing configuration
instance
:type files: list
"""
if not path.exists(filename):
raise FileNotFoundError(filename)
loaded_yaml = load_yaml(filename, self.context)
if loaded_yaml:
self.merge(loaded_yaml) | [
"def",
"load_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"FileNotFoundError",
"(",
"filename",
")",
"loaded_yaml",
"=",
"load_yaml",
"(",
"filename",
",",
"self",
".",
"context",
... | load file which contains yaml configuration entries.and merge it by
current instance
:param files: files to load and merge into existing configuration
instance
:type files: list | [
"load",
"file",
"which",
"contains",
"yaml",
"configuration",
"entries",
".",
"and",
"merge",
"it",
"by",
"current",
"instance"
] | a187dc3924dffc4d9992a369c7964599c6e201c1 | https://github.com/pylover/pymlconf/blob/a187dc3924dffc4d9992a369c7964599c6e201c1/pymlconf/models.py#L195-L210 | train | 44,527 |
pylover/pymlconf | pymlconf/models.py | DeferredRoot.initialize | def initialize(self, init_value, context=None, force=False):
"""
Initialize the configuration manager
:param force: force initialization even if it's already initialized
:return:
"""
if not force and self._instance is not None:
raise ConfigurationAlreadyInitializedError(
'Configuration manager object is already initialized.'
)
self.__class__._instance = Root(init_value, context=context) | python | def initialize(self, init_value, context=None, force=False):
"""
Initialize the configuration manager
:param force: force initialization even if it's already initialized
:return:
"""
if not force and self._instance is not None:
raise ConfigurationAlreadyInitializedError(
'Configuration manager object is already initialized.'
)
self.__class__._instance = Root(init_value, context=context) | [
"def",
"initialize",
"(",
"self",
",",
"init_value",
",",
"context",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"self",
".",
"_instance",
"is",
"not",
"None",
":",
"raise",
"ConfigurationAlreadyInitializedError",
"(",
"... | Initialize the configuration manager
:param force: force initialization even if it's already initialized
:return: | [
"Initialize",
"the",
"configuration",
"manager"
] | a187dc3924dffc4d9992a369c7964599c6e201c1 | https://github.com/pylover/pymlconf/blob/a187dc3924dffc4d9992a369c7964599c6e201c1/pymlconf/models.py#L237-L250 | train | 44,528 |
Autodesk/aomi | aomi/template.py | grok_filter_name | def grok_filter_name(element):
"""Extracts the name, which may be embedded, for a Jinja2
filter node"""
e_name = None
if element.name == 'default':
if isinstance(element.node, jinja2.nodes.Getattr):
e_name = element.node.node.name
else:
e_name = element.node.name
return e_name | python | def grok_filter_name(element):
"""Extracts the name, which may be embedded, for a Jinja2
filter node"""
e_name = None
if element.name == 'default':
if isinstance(element.node, jinja2.nodes.Getattr):
e_name = element.node.node.name
else:
e_name = element.node.name
return e_name | [
"def",
"grok_filter_name",
"(",
"element",
")",
":",
"e_name",
"=",
"None",
"if",
"element",
".",
"name",
"==",
"'default'",
":",
"if",
"isinstance",
"(",
"element",
".",
"node",
",",
"jinja2",
".",
"nodes",
".",
"Getattr",
")",
":",
"e_name",
"=",
"el... | Extracts the name, which may be embedded, for a Jinja2
filter node | [
"Extracts",
"the",
"name",
"which",
"may",
"be",
"embedded",
"for",
"a",
"Jinja2",
"filter",
"node"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L21-L31 | train | 44,529 |
Autodesk/aomi | aomi/template.py | grok_for_node | def grok_for_node(element, default_vars):
"""Properly parses a For loop element"""
if isinstance(element.iter, jinja2.nodes.Filter):
if element.iter.name == 'default' \
and element.iter.node.name not in default_vars:
default_vars.append(element.iter.node.name)
default_vars = default_vars + grok_vars(element)
return default_vars | python | def grok_for_node(element, default_vars):
"""Properly parses a For loop element"""
if isinstance(element.iter, jinja2.nodes.Filter):
if element.iter.name == 'default' \
and element.iter.node.name not in default_vars:
default_vars.append(element.iter.node.name)
default_vars = default_vars + grok_vars(element)
return default_vars | [
"def",
"grok_for_node",
"(",
"element",
",",
"default_vars",
")",
":",
"if",
"isinstance",
"(",
"element",
".",
"iter",
",",
"jinja2",
".",
"nodes",
".",
"Filter",
")",
":",
"if",
"element",
".",
"iter",
".",
"name",
"==",
"'default'",
"and",
"element",
... | Properly parses a For loop element | [
"Properly",
"parses",
"a",
"For",
"loop",
"element"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L34-L43 | train | 44,530 |
Autodesk/aomi | aomi/template.py | grok_if_node | def grok_if_node(element, default_vars):
"""Properly parses a If element"""
if isinstance(element.test, jinja2.nodes.Filter) and \
element.test.name == 'default':
default_vars.append(element.test.node.name)
return default_vars + grok_vars(element) | python | def grok_if_node(element, default_vars):
"""Properly parses a If element"""
if isinstance(element.test, jinja2.nodes.Filter) and \
element.test.name == 'default':
default_vars.append(element.test.node.name)
return default_vars + grok_vars(element) | [
"def",
"grok_if_node",
"(",
"element",
",",
"default_vars",
")",
":",
"if",
"isinstance",
"(",
"element",
".",
"test",
",",
"jinja2",
".",
"nodes",
".",
"Filter",
")",
"and",
"element",
".",
"test",
".",
"name",
"==",
"'default'",
":",
"default_vars",
".... | Properly parses a If element | [
"Properly",
"parses",
"a",
"If",
"element"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L46-L52 | train | 44,531 |
Autodesk/aomi | aomi/template.py | grok_vars | def grok_vars(elements):
"""Returns a list of vars for which the value is being appropriately set
This currently includes the default filter, for-based iterators,
and the explicit use of set"""
default_vars = []
iterbody = None
if hasattr(elements, 'body'):
iterbody = elements.body
elif hasattr(elements, 'nodes'):
iterbody = elements.nodes
for element in iterbody:
if isinstance(element, jinja2.nodes.Output):
default_vars = default_vars + grok_vars(element)
elif isinstance(element, jinja2.nodes.Filter):
e_name = grok_filter_name(element)
if e_name not in default_vars:
default_vars.append(e_name)
elif isinstance(element, jinja2.nodes.For):
default_vars = grok_for_node(element, default_vars)
elif isinstance(element, jinja2.nodes.If):
default_vars = grok_if_node(element, default_vars)
elif isinstance(element, jinja2.nodes.Assign):
default_vars.append(element.target.name)
elif isinstance(element, jinja2.nodes.FromImport):
for from_var in element.names:
default_vars.append(from_var)
return default_vars | python | def grok_vars(elements):
"""Returns a list of vars for which the value is being appropriately set
This currently includes the default filter, for-based iterators,
and the explicit use of set"""
default_vars = []
iterbody = None
if hasattr(elements, 'body'):
iterbody = elements.body
elif hasattr(elements, 'nodes'):
iterbody = elements.nodes
for element in iterbody:
if isinstance(element, jinja2.nodes.Output):
default_vars = default_vars + grok_vars(element)
elif isinstance(element, jinja2.nodes.Filter):
e_name = grok_filter_name(element)
if e_name not in default_vars:
default_vars.append(e_name)
elif isinstance(element, jinja2.nodes.For):
default_vars = grok_for_node(element, default_vars)
elif isinstance(element, jinja2.nodes.If):
default_vars = grok_if_node(element, default_vars)
elif isinstance(element, jinja2.nodes.Assign):
default_vars.append(element.target.name)
elif isinstance(element, jinja2.nodes.FromImport):
for from_var in element.names:
default_vars.append(from_var)
return default_vars | [
"def",
"grok_vars",
"(",
"elements",
")",
":",
"default_vars",
"=",
"[",
"]",
"iterbody",
"=",
"None",
"if",
"hasattr",
"(",
"elements",
",",
"'body'",
")",
":",
"iterbody",
"=",
"elements",
".",
"body",
"elif",
"hasattr",
"(",
"elements",
",",
"'nodes'"... | Returns a list of vars for which the value is being appropriately set
This currently includes the default filter, for-based iterators,
and the explicit use of set | [
"Returns",
"a",
"list",
"of",
"vars",
"for",
"which",
"the",
"value",
"is",
"being",
"appropriately",
"set",
"This",
"currently",
"includes",
"the",
"default",
"filter",
"for",
"-",
"based",
"iterators",
"and",
"the",
"explicit",
"use",
"of",
"set"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L55-L83 | train | 44,532 |
Autodesk/aomi | aomi/template.py | jinja_env | def jinja_env(template_path):
"""Sets up our Jinja environment, loading the few filters we have"""
fs_loader = FileSystemLoader(os.path.dirname(template_path))
env = Environment(loader=fs_loader,
autoescape=True,
trim_blocks=True,
lstrip_blocks=True)
env.filters['b64encode'] = portable_b64encode
env.filters['b64decode'] = f_b64decode
return env | python | def jinja_env(template_path):
"""Sets up our Jinja environment, loading the few filters we have"""
fs_loader = FileSystemLoader(os.path.dirname(template_path))
env = Environment(loader=fs_loader,
autoescape=True,
trim_blocks=True,
lstrip_blocks=True)
env.filters['b64encode'] = portable_b64encode
env.filters['b64decode'] = f_b64decode
return env | [
"def",
"jinja_env",
"(",
"template_path",
")",
":",
"fs_loader",
"=",
"FileSystemLoader",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"template_path",
")",
")",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"fs_loader",
",",
"autoescape",
"=",
"True",
",... | Sets up our Jinja environment, loading the few filters we have | [
"Sets",
"up",
"our",
"Jinja",
"environment",
"loading",
"the",
"few",
"filters",
"we",
"have"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L86-L95 | train | 44,533 |
Autodesk/aomi | aomi/template.py | missing_vars | def missing_vars(template_vars, parsed_content, obj):
"""If we find missing variables when rendering a template
we want to give the user a friendly error"""
missing = []
default_vars = grok_vars(parsed_content)
for var in template_vars:
if var not in default_vars and var not in obj:
missing.append(var)
if missing:
e_msg = "Missing required variables %s" % \
','.join(missing)
raise aomi_excep.AomiData(e_msg) | python | def missing_vars(template_vars, parsed_content, obj):
"""If we find missing variables when rendering a template
we want to give the user a friendly error"""
missing = []
default_vars = grok_vars(parsed_content)
for var in template_vars:
if var not in default_vars and var not in obj:
missing.append(var)
if missing:
e_msg = "Missing required variables %s" % \
','.join(missing)
raise aomi_excep.AomiData(e_msg) | [
"def",
"missing_vars",
"(",
"template_vars",
",",
"parsed_content",
",",
"obj",
")",
":",
"missing",
"=",
"[",
"]",
"default_vars",
"=",
"grok_vars",
"(",
"parsed_content",
")",
"for",
"var",
"in",
"template_vars",
":",
"if",
"var",
"not",
"in",
"default_var... | If we find missing variables when rendering a template
we want to give the user a friendly error | [
"If",
"we",
"find",
"missing",
"variables",
"when",
"rendering",
"a",
"template",
"we",
"want",
"to",
"give",
"the",
"user",
"a",
"friendly",
"error"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L104-L116 | train | 44,534 |
Autodesk/aomi | aomi/template.py | render | def render(filename, obj):
"""Render a template, maybe mixing in extra variables"""
template_path = abspath(filename)
env = jinja_env(template_path)
template_base = os.path.basename(template_path)
try:
parsed_content = env.parse(env
.loader
.get_source(env, template_base))
template_vars = meta.find_undeclared_variables(parsed_content)
if template_vars:
missing_vars(template_vars, parsed_content, obj)
LOG.debug("rendering %s with %s vars",
template_path, len(template_vars))
return env \
.get_template(template_base) \
.render(**obj)
except jinja2.exceptions.TemplateSyntaxError as exception:
template_trace = traceback.format_tb(sys.exc_info()[2])
# Different error context depending on whether it is the
# pre-render variable scan or not
if exception.filename:
template_line = template_trace[len(template_trace) - 1]
raise aomi_excep.Validation("Bad template %s %s" %
(template_line,
str(exception)))
template_str = ''
if isinstance(exception.source, tuple):
# PyLint seems confused about whether or not this is a tuple
# pylint: disable=locally-disabled, unsubscriptable-object
template_str = "Embedded Template\n%s" % exception.source[0]
raise aomi_excep.Validation("Bad template %s" % str(exception),
source=template_str)
except jinja2.exceptions.UndefinedError as exception:
template_traces = [x.strip()
for x in traceback.format_tb(sys.exc_info()[2])
if 'template code' in x]
raise aomi_excep.Validation("Missing template variable %s" %
' '.join(template_traces)) | python | def render(filename, obj):
"""Render a template, maybe mixing in extra variables"""
template_path = abspath(filename)
env = jinja_env(template_path)
template_base = os.path.basename(template_path)
try:
parsed_content = env.parse(env
.loader
.get_source(env, template_base))
template_vars = meta.find_undeclared_variables(parsed_content)
if template_vars:
missing_vars(template_vars, parsed_content, obj)
LOG.debug("rendering %s with %s vars",
template_path, len(template_vars))
return env \
.get_template(template_base) \
.render(**obj)
except jinja2.exceptions.TemplateSyntaxError as exception:
template_trace = traceback.format_tb(sys.exc_info()[2])
# Different error context depending on whether it is the
# pre-render variable scan or not
if exception.filename:
template_line = template_trace[len(template_trace) - 1]
raise aomi_excep.Validation("Bad template %s %s" %
(template_line,
str(exception)))
template_str = ''
if isinstance(exception.source, tuple):
# PyLint seems confused about whether or not this is a tuple
# pylint: disable=locally-disabled, unsubscriptable-object
template_str = "Embedded Template\n%s" % exception.source[0]
raise aomi_excep.Validation("Bad template %s" % str(exception),
source=template_str)
except jinja2.exceptions.UndefinedError as exception:
template_traces = [x.strip()
for x in traceback.format_tb(sys.exc_info()[2])
if 'template code' in x]
raise aomi_excep.Validation("Missing template variable %s" %
' '.join(template_traces)) | [
"def",
"render",
"(",
"filename",
",",
"obj",
")",
":",
"template_path",
"=",
"abspath",
"(",
"filename",
")",
"env",
"=",
"jinja_env",
"(",
"template_path",
")",
"template_base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"template_path",
")",
"try",
... | Render a template, maybe mixing in extra variables | [
"Render",
"a",
"template",
"maybe",
"mixing",
"in",
"extra",
"variables"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L119-L161 | train | 44,535 |
Autodesk/aomi | aomi/template.py | load_var_files | def load_var_files(opt, p_obj=None):
"""Load variable files, merge, return contents"""
obj = {}
if p_obj:
obj = p_obj
for var_file in opt.extra_vars_file:
LOG.debug("loading vars from %s", var_file)
obj = merge_dicts(obj.copy(), load_var_file(var_file, obj))
return obj | python | def load_var_files(opt, p_obj=None):
"""Load variable files, merge, return contents"""
obj = {}
if p_obj:
obj = p_obj
for var_file in opt.extra_vars_file:
LOG.debug("loading vars from %s", var_file)
obj = merge_dicts(obj.copy(), load_var_file(var_file, obj))
return obj | [
"def",
"load_var_files",
"(",
"opt",
",",
"p_obj",
"=",
"None",
")",
":",
"obj",
"=",
"{",
"}",
"if",
"p_obj",
":",
"obj",
"=",
"p_obj",
"for",
"var_file",
"in",
"opt",
".",
"extra_vars_file",
":",
"LOG",
".",
"debug",
"(",
"\"loading vars from %s\"",
... | Load variable files, merge, return contents | [
"Load",
"variable",
"files",
"merge",
"return",
"contents"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L176-L186 | train | 44,536 |
Autodesk/aomi | aomi/template.py | load_var_file | def load_var_file(filename, obj):
"""Loads a varible file, processing it as a template"""
rendered = render(filename, obj)
ext = os.path.splitext(filename)[1][1:]
v_obj = dict()
if ext == 'json':
v_obj = json.loads(rendered)
elif ext == 'yaml' or ext == 'yml':
v_obj = yaml.safe_load(rendered)
else:
LOG.warning("assuming yaml for unrecognized extension %s",
ext)
v_obj = yaml.safe_load(rendered)
return v_obj | python | def load_var_file(filename, obj):
"""Loads a varible file, processing it as a template"""
rendered = render(filename, obj)
ext = os.path.splitext(filename)[1][1:]
v_obj = dict()
if ext == 'json':
v_obj = json.loads(rendered)
elif ext == 'yaml' or ext == 'yml':
v_obj = yaml.safe_load(rendered)
else:
LOG.warning("assuming yaml for unrecognized extension %s",
ext)
v_obj = yaml.safe_load(rendered)
return v_obj | [
"def",
"load_var_file",
"(",
"filename",
",",
"obj",
")",
":",
"rendered",
"=",
"render",
"(",
"filename",
",",
"obj",
")",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"v_obj",
"=",
"di... | Loads a varible file, processing it as a template | [
"Loads",
"a",
"varible",
"file",
"processing",
"it",
"as",
"a",
"template"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L189-L203 | train | 44,537 |
Autodesk/aomi | aomi/template.py | load_template_help | def load_template_help(builtin):
"""Loads the help for a given template"""
help_file = "templates/%s-help.yml" % builtin
help_file = resource_filename(__name__, help_file)
help_obj = {}
if os.path.exists(help_file):
help_data = yaml.safe_load(open(help_file))
if 'name' in help_data:
help_obj['name'] = help_data['name']
if 'help' in help_data:
help_obj['help'] = help_data['help']
if 'args' in help_data:
help_obj['args'] = help_data['args']
return help_obj | python | def load_template_help(builtin):
"""Loads the help for a given template"""
help_file = "templates/%s-help.yml" % builtin
help_file = resource_filename(__name__, help_file)
help_obj = {}
if os.path.exists(help_file):
help_data = yaml.safe_load(open(help_file))
if 'name' in help_data:
help_obj['name'] = help_data['name']
if 'help' in help_data:
help_obj['help'] = help_data['help']
if 'args' in help_data:
help_obj['args'] = help_data['args']
return help_obj | [
"def",
"load_template_help",
"(",
"builtin",
")",
":",
"help_file",
"=",
"\"templates/%s-help.yml\"",
"%",
"builtin",
"help_file",
"=",
"resource_filename",
"(",
"__name__",
",",
"help_file",
")",
"help_obj",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exist... | Loads the help for a given template | [
"Loads",
"the",
"help",
"for",
"a",
"given",
"template"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L206-L223 | train | 44,538 |
Autodesk/aomi | aomi/template.py | builtin_list | def builtin_list():
"""Show a listing of all our builtin templates"""
for template in resource_listdir(__name__, "templates"):
builtin, ext = os.path.splitext(os.path.basename(abspath(template)))
if ext == '.yml':
continue
help_obj = load_template_help(builtin)
if 'name' in help_obj:
print("%-*s %s" % (20, builtin, help_obj['name']))
else:
print("%s" % builtin) | python | def builtin_list():
"""Show a listing of all our builtin templates"""
for template in resource_listdir(__name__, "templates"):
builtin, ext = os.path.splitext(os.path.basename(abspath(template)))
if ext == '.yml':
continue
help_obj = load_template_help(builtin)
if 'name' in help_obj:
print("%-*s %s" % (20, builtin, help_obj['name']))
else:
print("%s" % builtin) | [
"def",
"builtin_list",
"(",
")",
":",
"for",
"template",
"in",
"resource_listdir",
"(",
"__name__",
",",
"\"templates\"",
")",
":",
"builtin",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"abspath",
... | Show a listing of all our builtin templates | [
"Show",
"a",
"listing",
"of",
"all",
"our",
"builtin",
"templates"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L226-L237 | train | 44,539 |
Autodesk/aomi | aomi/template.py | builtin_info | def builtin_info(builtin):
"""Show information on a particular builtin template"""
help_obj = load_template_help(builtin)
if help_obj.get('name') and help_obj.get('help'):
print("The %s template" % (help_obj['name']))
print(help_obj['help'])
else:
print("No help for %s" % builtin)
if help_obj.get('args'):
for arg, arg_help in iteritems(help_obj['args']):
print(" %-*s %s" % (20, arg, arg_help)) | python | def builtin_info(builtin):
"""Show information on a particular builtin template"""
help_obj = load_template_help(builtin)
if help_obj.get('name') and help_obj.get('help'):
print("The %s template" % (help_obj['name']))
print(help_obj['help'])
else:
print("No help for %s" % builtin)
if help_obj.get('args'):
for arg, arg_help in iteritems(help_obj['args']):
print(" %-*s %s" % (20, arg, arg_help)) | [
"def",
"builtin_info",
"(",
"builtin",
")",
":",
"help_obj",
"=",
"load_template_help",
"(",
"builtin",
")",
"if",
"help_obj",
".",
"get",
"(",
"'name'",
")",
"and",
"help_obj",
".",
"get",
"(",
"'help'",
")",
":",
"print",
"(",
"\"The %s template\"",
"%",... | Show information on a particular builtin template | [
"Show",
"information",
"on",
"a",
"particular",
"builtin",
"template"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L240-L251 | train | 44,540 |
Autodesk/aomi | aomi/template.py | render_secretfile | def render_secretfile(opt):
"""Renders and returns the Secretfile construct"""
LOG.debug("Using Secretfile %s", opt.secretfile)
secretfile_path = abspath(opt.secretfile)
obj = load_vars(opt)
return render(secretfile_path, obj) | python | def render_secretfile(opt):
"""Renders and returns the Secretfile construct"""
LOG.debug("Using Secretfile %s", opt.secretfile)
secretfile_path = abspath(opt.secretfile)
obj = load_vars(opt)
return render(secretfile_path, obj) | [
"def",
"render_secretfile",
"(",
"opt",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Using Secretfile %s\"",
",",
"opt",
".",
"secretfile",
")",
"secretfile_path",
"=",
"abspath",
"(",
"opt",
".",
"secretfile",
")",
"obj",
"=",
"load_vars",
"(",
"opt",
")",
"ret... | Renders and returns the Secretfile construct | [
"Renders",
"and",
"returns",
"the",
"Secretfile",
"construct"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/template.py#L259-L264 | train | 44,541 |
Autodesk/aomi | aomi/util.py | update_user_password | def update_user_password(client, userpass):
"""Will update the password for a userpass user"""
vault_path = ''
user = ''
user_path_bits = userpass.split('/')
if len(user_path_bits) == 1:
user = user_path_bits[0]
vault_path = "auth/userpass/users/%s/password" % user
LOG.debug("Updating password for user %s at the default path", user)
elif len(user_path_bits) == 2:
mount = user_path_bits[0]
user = user_path_bits[1]
vault_path = "auth/%s/users/%s/password" % (mount, user)
LOG.debug("Updating password for user %s at path %s", user, mount)
else:
client.revoke_self_token()
raise aomi.exceptions.AomiCommand("invalid user path")
new_password = get_password()
obj = {
'user': user,
'password': new_password
}
client.write(vault_path, **obj) | python | def update_user_password(client, userpass):
"""Will update the password for a userpass user"""
vault_path = ''
user = ''
user_path_bits = userpass.split('/')
if len(user_path_bits) == 1:
user = user_path_bits[0]
vault_path = "auth/userpass/users/%s/password" % user
LOG.debug("Updating password for user %s at the default path", user)
elif len(user_path_bits) == 2:
mount = user_path_bits[0]
user = user_path_bits[1]
vault_path = "auth/%s/users/%s/password" % (mount, user)
LOG.debug("Updating password for user %s at path %s", user, mount)
else:
client.revoke_self_token()
raise aomi.exceptions.AomiCommand("invalid user path")
new_password = get_password()
obj = {
'user': user,
'password': new_password
}
client.write(vault_path, **obj) | [
"def",
"update_user_password",
"(",
"client",
",",
"userpass",
")",
":",
"vault_path",
"=",
"''",
"user",
"=",
"''",
"user_path_bits",
"=",
"userpass",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"user_path_bits",
")",
"==",
"1",
":",
"user",
"=",
... | Will update the password for a userpass user | [
"Will",
"update",
"the",
"password",
"for",
"a",
"userpass",
"user"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/util.py#L12-L35 | train | 44,542 |
Autodesk/aomi | aomi/util.py | update_generic_password | def update_generic_password(client, path):
"""Will update a single key in a generic secret backend as
thought it were a password"""
vault_path, key = path_pieces(path)
mount = mount_for_path(vault_path, client)
if not mount:
client.revoke_self_token()
raise aomi.exceptions.VaultConstraint('invalid path')
if backend_type(mount, client) != 'generic':
client.revoke_self_token()
raise aomi.exceptions.AomiData("Unsupported backend type")
LOG.debug("Updating generic password at %s", path)
existing = client.read(vault_path)
if not existing or 'data' not in existing:
LOG.debug("Nothing exists yet at %s!", vault_path)
existing = {}
else:
LOG.debug("Updating %s at %s", key, vault_path)
existing = existing['data']
new_password = get_password()
if key in existing and existing[key] == new_password:
client.revoke_self_token()
raise aomi.exceptions.AomiData("Password is same as existing")
existing[key] = new_password
client.write(vault_path, **existing) | python | def update_generic_password(client, path):
"""Will update a single key in a generic secret backend as
thought it were a password"""
vault_path, key = path_pieces(path)
mount = mount_for_path(vault_path, client)
if not mount:
client.revoke_self_token()
raise aomi.exceptions.VaultConstraint('invalid path')
if backend_type(mount, client) != 'generic':
client.revoke_self_token()
raise aomi.exceptions.AomiData("Unsupported backend type")
LOG.debug("Updating generic password at %s", path)
existing = client.read(vault_path)
if not existing or 'data' not in existing:
LOG.debug("Nothing exists yet at %s!", vault_path)
existing = {}
else:
LOG.debug("Updating %s at %s", key, vault_path)
existing = existing['data']
new_password = get_password()
if key in existing and existing[key] == new_password:
client.revoke_self_token()
raise aomi.exceptions.AomiData("Password is same as existing")
existing[key] = new_password
client.write(vault_path, **existing) | [
"def",
"update_generic_password",
"(",
"client",
",",
"path",
")",
":",
"vault_path",
",",
"key",
"=",
"path_pieces",
"(",
"path",
")",
"mount",
"=",
"mount_for_path",
"(",
"vault_path",
",",
"client",
")",
"if",
"not",
"mount",
":",
"client",
".",
"revoke... | Will update a single key in a generic secret backend as
thought it were a password | [
"Will",
"update",
"a",
"single",
"key",
"in",
"a",
"generic",
"secret",
"backend",
"as",
"thought",
"it",
"were",
"a",
"password"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/util.py#L38-L66 | train | 44,543 |
Autodesk/aomi | aomi/util.py | password | def password(client, path):
"""Will attempt to contextually update a password in Vault"""
if path.startswith('user:'):
update_user_password(client, path[5:])
else:
update_generic_password(client, path) | python | def password(client, path):
"""Will attempt to contextually update a password in Vault"""
if path.startswith('user:'):
update_user_password(client, path[5:])
else:
update_generic_password(client, path) | [
"def",
"password",
"(",
"client",
",",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'user:'",
")",
":",
"update_user_password",
"(",
"client",
",",
"path",
"[",
"5",
":",
"]",
")",
"else",
":",
"update_generic_password",
"(",
"client",
",",
... | Will attempt to contextually update a password in Vault | [
"Will",
"attempt",
"to",
"contextually",
"update",
"a",
"password",
"in",
"Vault"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/util.py#L69-L74 | train | 44,544 |
Autodesk/aomi | aomi/util.py | vault_file | def vault_file(env, default):
"""The path to a misc Vault file
This function will check for the env override on a file
path, compute a fully qualified OS appropriate path to
the desired file and return it if it exists. Otherwise
returns None
"""
home = os.environ['HOME'] if 'HOME' in os.environ else \
os.environ['USERPROFILE']
filename = os.environ.get(env, os.path.join(home, default))
filename = abspath(filename)
if os.path.exists(filename):
return filename
return None | python | def vault_file(env, default):
"""The path to a misc Vault file
This function will check for the env override on a file
path, compute a fully qualified OS appropriate path to
the desired file and return it if it exists. Otherwise
returns None
"""
home = os.environ['HOME'] if 'HOME' in os.environ else \
os.environ['USERPROFILE']
filename = os.environ.get(env, os.path.join(home, default))
filename = abspath(filename)
if os.path.exists(filename):
return filename
return None | [
"def",
"vault_file",
"(",
"env",
",",
"default",
")",
":",
"home",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
"else",
"os",
".",
"environ",
"[",
"'USERPROFILE'",
"]",
"filename",
"=",
"os",
".",
"enviro... | The path to a misc Vault file
This function will check for the env override on a file
path, compute a fully qualified OS appropriate path to
the desired file and return it if it exists. Otherwise
returns None | [
"The",
"path",
"to",
"a",
"misc",
"Vault",
"file",
"This",
"function",
"will",
"check",
"for",
"the",
"env",
"override",
"on",
"a",
"file",
"path",
"compute",
"a",
"fully",
"qualified",
"OS",
"appropriate",
"path",
"to",
"the",
"desired",
"file",
"and",
... | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/util.py#L77-L91 | train | 44,545 |
Autodesk/aomi | aomi/util.py | vault_time_to_s | def vault_time_to_s(time_string):
"""Will convert a time string, as recognized by other Vault
tooling, into an integer representation of seconds"""
if not time_string or len(time_string) < 2:
raise aomi.exceptions \
.AomiData("Invalid timestring %s" % time_string)
last_char = time_string[len(time_string) - 1]
if last_char == 's':
return int(time_string[0:len(time_string) - 1])
elif last_char == 'm':
cur = int(time_string[0:len(time_string) - 1])
return cur * 60
elif last_char == 'h':
cur = int(time_string[0:len(time_string) - 1])
return cur * 3600
elif last_char == 'd':
cur = int(time_string[0:len(time_string) - 1])
return cur * 86400
else:
raise aomi.exceptions \
.AomiData("Invalid time scale %s" % last_char) | python | def vault_time_to_s(time_string):
"""Will convert a time string, as recognized by other Vault
tooling, into an integer representation of seconds"""
if not time_string or len(time_string) < 2:
raise aomi.exceptions \
.AomiData("Invalid timestring %s" % time_string)
last_char = time_string[len(time_string) - 1]
if last_char == 's':
return int(time_string[0:len(time_string) - 1])
elif last_char == 'm':
cur = int(time_string[0:len(time_string) - 1])
return cur * 60
elif last_char == 'h':
cur = int(time_string[0:len(time_string) - 1])
return cur * 3600
elif last_char == 'd':
cur = int(time_string[0:len(time_string) - 1])
return cur * 86400
else:
raise aomi.exceptions \
.AomiData("Invalid time scale %s" % last_char) | [
"def",
"vault_time_to_s",
"(",
"time_string",
")",
":",
"if",
"not",
"time_string",
"or",
"len",
"(",
"time_string",
")",
"<",
"2",
":",
"raise",
"aomi",
".",
"exceptions",
".",
"AomiData",
"(",
"\"Invalid timestring %s\"",
"%",
"time_string",
")",
"last_char"... | Will convert a time string, as recognized by other Vault
tooling, into an integer representation of seconds | [
"Will",
"convert",
"a",
"time",
"string",
"as",
"recognized",
"by",
"other",
"Vault",
"tooling",
"into",
"an",
"integer",
"representation",
"of",
"seconds"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/util.py#L109-L130 | train | 44,546 |
sernst/cauldron | cauldron/runner/python_file.py | set_executing | def set_executing(on: bool):
"""
Toggle whether or not the current thread is executing a step file. This
will only apply when the current thread is a CauldronThread. This function
has no effect when run on a Main thread.
:param on:
Whether or not the thread should be annotated as executing a step file.
"""
my_thread = threading.current_thread()
if isinstance(my_thread, threads.CauldronThread):
my_thread.is_executing = on | python | def set_executing(on: bool):
"""
Toggle whether or not the current thread is executing a step file. This
will only apply when the current thread is a CauldronThread. This function
has no effect when run on a Main thread.
:param on:
Whether or not the thread should be annotated as executing a step file.
"""
my_thread = threading.current_thread()
if isinstance(my_thread, threads.CauldronThread):
my_thread.is_executing = on | [
"def",
"set_executing",
"(",
"on",
":",
"bool",
")",
":",
"my_thread",
"=",
"threading",
".",
"current_thread",
"(",
")",
"if",
"isinstance",
"(",
"my_thread",
",",
"threads",
".",
"CauldronThread",
")",
":",
"my_thread",
".",
"is_executing",
"=",
"on"
] | Toggle whether or not the current thread is executing a step file. This
will only apply when the current thread is a CauldronThread. This function
has no effect when run on a Main thread.
:param on:
Whether or not the thread should be annotated as executing a step file. | [
"Toggle",
"whether",
"or",
"not",
"the",
"current",
"thread",
"is",
"executing",
"a",
"step",
"file",
".",
"This",
"will",
"only",
"apply",
"when",
"the",
"current",
"thread",
"is",
"a",
"CauldronThread",
".",
"This",
"function",
"has",
"no",
"effect",
"wh... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/python_file.py#L29-L42 | train | 44,547 |
sernst/cauldron | cauldron/runner/python_file.py | get_file_contents | def get_file_contents(source_path: str) -> str:
"""
Loads the contents of the source into a string for execution using multiple
loading methods to handle cross-platform encoding edge cases. If none of
the load methods work, a string is returned that contains an error function
response that will be displayed when the step is run alert the user to the
error.
:param source_path:
Path of the step file to load.
"""
open_funcs = [
functools.partial(codecs.open, source_path, encoding='utf-8'),
functools.partial(open, source_path, 'r')
]
for open_func in open_funcs:
try:
with open_func() as f:
return f.read()
except Exception:
pass
return (
'raise IOError("Unable to load step file at: {}")'
.format(source_path)
) | python | def get_file_contents(source_path: str) -> str:
"""
Loads the contents of the source into a string for execution using multiple
loading methods to handle cross-platform encoding edge cases. If none of
the load methods work, a string is returned that contains an error function
response that will be displayed when the step is run alert the user to the
error.
:param source_path:
Path of the step file to load.
"""
open_funcs = [
functools.partial(codecs.open, source_path, encoding='utf-8'),
functools.partial(open, source_path, 'r')
]
for open_func in open_funcs:
try:
with open_func() as f:
return f.read()
except Exception:
pass
return (
'raise IOError("Unable to load step file at: {}")'
.format(source_path)
) | [
"def",
"get_file_contents",
"(",
"source_path",
":",
"str",
")",
"->",
"str",
":",
"open_funcs",
"=",
"[",
"functools",
".",
"partial",
"(",
"codecs",
".",
"open",
",",
"source_path",
",",
"encoding",
"=",
"'utf-8'",
")",
",",
"functools",
".",
"partial",
... | Loads the contents of the source into a string for execution using multiple
loading methods to handle cross-platform encoding edge cases. If none of
the load methods work, a string is returned that contains an error function
response that will be displayed when the step is run alert the user to the
error.
:param source_path:
Path of the step file to load. | [
"Loads",
"the",
"contents",
"of",
"the",
"source",
"into",
"a",
"string",
"for",
"execution",
"using",
"multiple",
"loading",
"methods",
"to",
"handle",
"cross",
"-",
"platform",
"encoding",
"edge",
"cases",
".",
"If",
"none",
"of",
"the",
"load",
"methods",... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/python_file.py#L45-L72 | train | 44,548 |
sernst/cauldron | cauldron/runner/python_file.py | load_step_file | def load_step_file(source_path: str) -> str:
"""
Loads the source for a step file at the given path location and then
renders it in a template to add additional footer data.
The footer is used to force the display to flush the print buffer and
breathe the step to open things up for resolution. This shouldn't be
necessary, but it seems there's an async race condition with print
buffers that is hard to reproduce and so this is in place to fix the
problem.
"""
return templating.render_template(
template_name='embedded-step.py.txt',
source_contents=get_file_contents(source_path)
) | python | def load_step_file(source_path: str) -> str:
"""
Loads the source for a step file at the given path location and then
renders it in a template to add additional footer data.
The footer is used to force the display to flush the print buffer and
breathe the step to open things up for resolution. This shouldn't be
necessary, but it seems there's an async race condition with print
buffers that is hard to reproduce and so this is in place to fix the
problem.
"""
return templating.render_template(
template_name='embedded-step.py.txt',
source_contents=get_file_contents(source_path)
) | [
"def",
"load_step_file",
"(",
"source_path",
":",
"str",
")",
"->",
"str",
":",
"return",
"templating",
".",
"render_template",
"(",
"template_name",
"=",
"'embedded-step.py.txt'",
",",
"source_contents",
"=",
"get_file_contents",
"(",
"source_path",
")",
")"
] | Loads the source for a step file at the given path location and then
renders it in a template to add additional footer data.
The footer is used to force the display to flush the print buffer and
breathe the step to open things up for resolution. This shouldn't be
necessary, but it seems there's an async race condition with print
buffers that is hard to reproduce and so this is in place to fix the
problem. | [
"Loads",
"the",
"source",
"for",
"a",
"step",
"file",
"at",
"the",
"given",
"path",
"location",
"and",
"then",
"renders",
"it",
"in",
"a",
"template",
"to",
"add",
"additional",
"footer",
"data",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/python_file.py#L75-L90 | train | 44,549 |
sernst/cauldron | cauldron/runner/python_file.py | run | def run(
project: 'projects.Project',
step: 'projects.ProjectStep',
) -> dict:
"""
Carries out the execution of the step python source file by loading it into
an artificially created module and then executing that module and returning
the result.
:param project:
The currently open project.
:param step:
The project step for which the run execution will take place.
:return:
A dictionary containing the results of the run execution, which
indicate whether or not the run was successful. If the run failed for
any reason, the dictionary will contain error information for display.
"""
target_module = create_module(project, step)
source_code = load_step_file(step.source_path)
try:
code = InspectLoader.source_to_code(source_code, step.source_path)
except SyntaxError as error:
return render_syntax_error(project, error)
def exec_test():
step.test_locals = dict()
step.test_locals.update(target_module.__dict__)
exec(code, step.test_locals)
try:
set_executing(True)
threads.abort_thread()
if environ.modes.has(environ.modes.TESTING):
exec_test()
else:
exec(code, target_module.__dict__)
out = {
'success': True,
'stop_condition': projects.StopCondition(False, False)
}
except threads.ThreadAbortError:
# Raised when a user explicitly aborts the running of the step through
# a user-interface action.
out = {
'success': False,
'stop_condition': projects.StopCondition(True, True)
}
except UserAbortError as error:
# Raised when a user explicitly aborts the running of the step using
# a cd.step.stop(). This behavior should be considered a successful
# outcome as it was intentional on the part of the user that the step
# abort running early.
out = {
'success': True,
'stop_condition': projects.StopCondition(True, error.halt)
}
except Exception as error:
out = render_error(project, error)
set_executing(False)
return out | python | def run(
project: 'projects.Project',
step: 'projects.ProjectStep',
) -> dict:
"""
Carries out the execution of the step python source file by loading it into
an artificially created module and then executing that module and returning
the result.
:param project:
The currently open project.
:param step:
The project step for which the run execution will take place.
:return:
A dictionary containing the results of the run execution, which
indicate whether or not the run was successful. If the run failed for
any reason, the dictionary will contain error information for display.
"""
target_module = create_module(project, step)
source_code = load_step_file(step.source_path)
try:
code = InspectLoader.source_to_code(source_code, step.source_path)
except SyntaxError as error:
return render_syntax_error(project, error)
def exec_test():
step.test_locals = dict()
step.test_locals.update(target_module.__dict__)
exec(code, step.test_locals)
try:
set_executing(True)
threads.abort_thread()
if environ.modes.has(environ.modes.TESTING):
exec_test()
else:
exec(code, target_module.__dict__)
out = {
'success': True,
'stop_condition': projects.StopCondition(False, False)
}
except threads.ThreadAbortError:
# Raised when a user explicitly aborts the running of the step through
# a user-interface action.
out = {
'success': False,
'stop_condition': projects.StopCondition(True, True)
}
except UserAbortError as error:
# Raised when a user explicitly aborts the running of the step using
# a cd.step.stop(). This behavior should be considered a successful
# outcome as it was intentional on the part of the user that the step
# abort running early.
out = {
'success': True,
'stop_condition': projects.StopCondition(True, error.halt)
}
except Exception as error:
out = render_error(project, error)
set_executing(False)
return out | [
"def",
"run",
"(",
"project",
":",
"'projects.Project'",
",",
"step",
":",
"'projects.ProjectStep'",
",",
")",
"->",
"dict",
":",
"target_module",
"=",
"create_module",
"(",
"project",
",",
"step",
")",
"source_code",
"=",
"load_step_file",
"(",
"step",
".",
... | Carries out the execution of the step python source file by loading it into
an artificially created module and then executing that module and returning
the result.
:param project:
The currently open project.
:param step:
The project step for which the run execution will take place.
:return:
A dictionary containing the results of the run execution, which
indicate whether or not the run was successful. If the run failed for
any reason, the dictionary will contain error information for display. | [
"Carries",
"out",
"the",
"execution",
"of",
"the",
"step",
"python",
"source",
"file",
"by",
"loading",
"it",
"into",
"an",
"artificially",
"created",
"module",
"and",
"then",
"executing",
"that",
"module",
"and",
"returning",
"the",
"result",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/python_file.py#L128-L192 | train | 44,550 |
sernst/cauldron | cauldron/runner/python_file.py | render_syntax_error | def render_syntax_error(
project: 'projects.Project',
error: SyntaxError
) -> dict:
"""
Renders a SyntaxError, which has a shallow, custom stack trace derived
from the data included in the error, instead of the standard stack trace
pulled from the exception frames.
:param project:
Currently open project.
:param error:
The SyntaxError to be rendered to html and text for display.
:return:
A dictionary containing the error response with rendered display
messages for both text and html output.
"""
return render_error(
project=project,
error=error,
stack=[dict(
filename=getattr(error, 'filename'),
location=None,
line_number=error.lineno,
line=error.text.rstrip()
)]
) | python | def render_syntax_error(
project: 'projects.Project',
error: SyntaxError
) -> dict:
"""
Renders a SyntaxError, which has a shallow, custom stack trace derived
from the data included in the error, instead of the standard stack trace
pulled from the exception frames.
:param project:
Currently open project.
:param error:
The SyntaxError to be rendered to html and text for display.
:return:
A dictionary containing the error response with rendered display
messages for both text and html output.
"""
return render_error(
project=project,
error=error,
stack=[dict(
filename=getattr(error, 'filename'),
location=None,
line_number=error.lineno,
line=error.text.rstrip()
)]
) | [
"def",
"render_syntax_error",
"(",
"project",
":",
"'projects.Project'",
",",
"error",
":",
"SyntaxError",
")",
"->",
"dict",
":",
"return",
"render_error",
"(",
"project",
"=",
"project",
",",
"error",
"=",
"error",
",",
"stack",
"=",
"[",
"dict",
"(",
"f... | Renders a SyntaxError, which has a shallow, custom stack trace derived
from the data included in the error, instead of the standard stack trace
pulled from the exception frames.
:param project:
Currently open project.
:param error:
The SyntaxError to be rendered to html and text for display.
:return:
A dictionary containing the error response with rendered display
messages for both text and html output. | [
"Renders",
"a",
"SyntaxError",
"which",
"has",
"a",
"shallow",
"custom",
"stack",
"trace",
"derived",
"from",
"the",
"data",
"included",
"in",
"the",
"error",
"instead",
"of",
"the",
"standard",
"stack",
"trace",
"pulled",
"from",
"the",
"exception",
"frames",... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/python_file.py#L195-L222 | train | 44,551 |
sernst/cauldron | cauldron/runner/python_file.py | render_error | def render_error(
project: 'projects.Project',
error: Exception,
stack: typing.List[dict] = None
) -> dict:
"""
Renders an Exception to an error response that includes rendered text and
html error messages for display.
:param project:
Currently open project.
:param error:
The SyntaxError to be rendered to html and text for display.
:param stack:
Optionally specify a parsed stack. If this value is None the standard
Cauldron stack frames will be rendered.
:return:
A dictionary containing the error response with rendered display
messages for both text and html output.
"""
data = dict(
type=error.__class__.__name__,
message='{}'.format(error),
stack=(
stack
if stack is not None else
render_stack.get_formatted_stack_frame(project)
)
)
return dict(
success=False,
error=error,
message=templating.render_template('user-code-error.txt', **data),
html_message=templating.render_template('user-code-error.html', **data)
) | python | def render_error(
project: 'projects.Project',
error: Exception,
stack: typing.List[dict] = None
) -> dict:
"""
Renders an Exception to an error response that includes rendered text and
html error messages for display.
:param project:
Currently open project.
:param error:
The SyntaxError to be rendered to html and text for display.
:param stack:
Optionally specify a parsed stack. If this value is None the standard
Cauldron stack frames will be rendered.
:return:
A dictionary containing the error response with rendered display
messages for both text and html output.
"""
data = dict(
type=error.__class__.__name__,
message='{}'.format(error),
stack=(
stack
if stack is not None else
render_stack.get_formatted_stack_frame(project)
)
)
return dict(
success=False,
error=error,
message=templating.render_template('user-code-error.txt', **data),
html_message=templating.render_template('user-code-error.html', **data)
) | [
"def",
"render_error",
"(",
"project",
":",
"'projects.Project'",
",",
"error",
":",
"Exception",
",",
"stack",
":",
"typing",
".",
"List",
"[",
"dict",
"]",
"=",
"None",
")",
"->",
"dict",
":",
"data",
"=",
"dict",
"(",
"type",
"=",
"error",
".",
"_... | Renders an Exception to an error response that includes rendered text and
html error messages for display.
:param project:
Currently open project.
:param error:
The SyntaxError to be rendered to html and text for display.
:param stack:
Optionally specify a parsed stack. If this value is None the standard
Cauldron stack frames will be rendered.
:return:
A dictionary containing the error response with rendered display
messages for both text and html output. | [
"Renders",
"an",
"Exception",
"to",
"an",
"error",
"response",
"that",
"includes",
"rendered",
"text",
"and",
"html",
"error",
"messages",
"for",
"display",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/python_file.py#L225-L261 | train | 44,552 |
sernst/cauldron | cauldron/environ/configuration.py | Configuration.save | def save(self) -> 'Configuration':
"""
Saves the configuration settings object to the current user's home
directory
:return:
"""
data = self.load().persistent
if data is None:
return self
directory = os.path.dirname(self._source_path)
if not os.path.exists(directory):
os.makedirs(directory)
path = self._source_path
with open(path, 'w+') as f:
json.dump(data, f)
return self | python | def save(self) -> 'Configuration':
"""
Saves the configuration settings object to the current user's home
directory
:return:
"""
data = self.load().persistent
if data is None:
return self
directory = os.path.dirname(self._source_path)
if not os.path.exists(directory):
os.makedirs(directory)
path = self._source_path
with open(path, 'w+') as f:
json.dump(data, f)
return self | [
"def",
"save",
"(",
"self",
")",
"->",
"'Configuration'",
":",
"data",
"=",
"self",
".",
"load",
"(",
")",
".",
"persistent",
"if",
"data",
"is",
"None",
":",
"return",
"self",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
... | Saves the configuration settings object to the current user's home
directory
:return: | [
"Saves",
"the",
"configuration",
"settings",
"object",
"to",
"the",
"current",
"user",
"s",
"home",
"directory"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/configuration.py#L143-L163 | train | 44,553 |
WimpyAnalytics/django-andablog | demo/democomments/models.py | DemoComment._get_userinfo | def _get_userinfo(self):
"""
Get a dictionary that pulls together information about the poster
safely for both authenticated and non-authenticated comments.
This dict will have ``name``, ``email``, and ``url`` fields.
"""
if not hasattr(self, "_userinfo"):
userinfo = {
"name": self.user_name,
"email": self.user_email,
"url": self.user_url
}
if self.user_id:
u = self.user
if u.email:
userinfo["email"] = u.email
# If the user has a full name, use that for the user name.
# However, a given user_name overrides the raw user.username,
# so only use that if this comment has no associated name.
if u.get_full_name():
userinfo["name"] = self.user.get_full_name()
elif not self.user_name:
userinfo["name"] = u.get_username()
self._userinfo = userinfo
return self._userinfo | python | def _get_userinfo(self):
"""
Get a dictionary that pulls together information about the poster
safely for both authenticated and non-authenticated comments.
This dict will have ``name``, ``email``, and ``url`` fields.
"""
if not hasattr(self, "_userinfo"):
userinfo = {
"name": self.user_name,
"email": self.user_email,
"url": self.user_url
}
if self.user_id:
u = self.user
if u.email:
userinfo["email"] = u.email
# If the user has a full name, use that for the user name.
# However, a given user_name overrides the raw user.username,
# so only use that if this comment has no associated name.
if u.get_full_name():
userinfo["name"] = self.user.get_full_name()
elif not self.user_name:
userinfo["name"] = u.get_username()
self._userinfo = userinfo
return self._userinfo | [
"def",
"_get_userinfo",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_userinfo\"",
")",
":",
"userinfo",
"=",
"{",
"\"name\"",
":",
"self",
".",
"user_name",
",",
"\"email\"",
":",
"self",
".",
"user_email",
",",
"\"url\"",
":",
... | Get a dictionary that pulls together information about the poster
safely for both authenticated and non-authenticated comments.
This dict will have ``name``, ``email``, and ``url`` fields. | [
"Get",
"a",
"dictionary",
"that",
"pulls",
"together",
"information",
"about",
"the",
"poster",
"safely",
"for",
"both",
"authenticated",
"and",
"non",
"-",
"authenticated",
"comments",
"."
] | 9175144140d220e4ce8212d0da6abc8c9ba9816a | https://github.com/WimpyAnalytics/django-andablog/blob/9175144140d220e4ce8212d0da6abc8c9ba9816a/demo/democomments/models.py#L65-L91 | train | 44,554 |
sernst/cauldron | cauldron/session/writing/file_io.py | deploy | def deploy(files_list: typing.List[tuple]):
"""
Iterates through the specified files_list and copies or writes each entry
depending on whether its a file copy entry or a file write entry.
:param files_list:
A list of file write entries and file copy entries
"""
def deploy_entry(entry):
if not entry:
return
if hasattr(entry, 'source') and hasattr(entry, 'destination'):
return copy(entry)
if hasattr(entry, 'path') and hasattr(entry, 'contents'):
return write(entry)
raise ValueError('Unrecognized deployment entry {}'.format(entry))
return [deploy_entry(f) for f in files_list] | python | def deploy(files_list: typing.List[tuple]):
"""
Iterates through the specified files_list and copies or writes each entry
depending on whether its a file copy entry or a file write entry.
:param files_list:
A list of file write entries and file copy entries
"""
def deploy_entry(entry):
if not entry:
return
if hasattr(entry, 'source') and hasattr(entry, 'destination'):
return copy(entry)
if hasattr(entry, 'path') and hasattr(entry, 'contents'):
return write(entry)
raise ValueError('Unrecognized deployment entry {}'.format(entry))
return [deploy_entry(f) for f in files_list] | [
"def",
"deploy",
"(",
"files_list",
":",
"typing",
".",
"List",
"[",
"tuple",
"]",
")",
":",
"def",
"deploy_entry",
"(",
"entry",
")",
":",
"if",
"not",
"entry",
":",
"return",
"if",
"hasattr",
"(",
"entry",
",",
"'source'",
")",
"and",
"hasattr",
"(... | Iterates through the specified files_list and copies or writes each entry
depending on whether its a file copy entry or a file write entry.
:param files_list:
A list of file write entries and file copy entries | [
"Iterates",
"through",
"the",
"specified",
"files_list",
"and",
"copies",
"or",
"writes",
"each",
"entry",
"depending",
"on",
"whether",
"its",
"a",
"file",
"copy",
"entry",
"or",
"a",
"file",
"write",
"entry",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/file_io.py#L28-L48 | train | 44,555 |
sernst/cauldron | cauldron/session/writing/file_io.py | copy | def copy(copy_entry: FILE_COPY_ENTRY):
"""
Copies the specified file from its source location to its destination
location.
"""
source_path = environ.paths.clean(copy_entry.source)
output_path = environ.paths.clean(copy_entry.destination)
copier = shutil.copy2 if os.path.isfile(source_path) else shutil.copytree
make_output_directory(output_path)
for i in range(3):
try:
copier(source_path, output_path)
return
except Exception:
time.sleep(0.5)
raise IOError('Unable to copy "{source}" to "{destination}"'.format(
source=source_path,
destination=output_path
)) | python | def copy(copy_entry: FILE_COPY_ENTRY):
"""
Copies the specified file from its source location to its destination
location.
"""
source_path = environ.paths.clean(copy_entry.source)
output_path = environ.paths.clean(copy_entry.destination)
copier = shutil.copy2 if os.path.isfile(source_path) else shutil.copytree
make_output_directory(output_path)
for i in range(3):
try:
copier(source_path, output_path)
return
except Exception:
time.sleep(0.5)
raise IOError('Unable to copy "{source}" to "{destination}"'.format(
source=source_path,
destination=output_path
)) | [
"def",
"copy",
"(",
"copy_entry",
":",
"FILE_COPY_ENTRY",
")",
":",
"source_path",
"=",
"environ",
".",
"paths",
".",
"clean",
"(",
"copy_entry",
".",
"source",
")",
"output_path",
"=",
"environ",
".",
"paths",
".",
"clean",
"(",
"copy_entry",
".",
"destin... | Copies the specified file from its source location to its destination
location. | [
"Copies",
"the",
"specified",
"file",
"from",
"its",
"source",
"location",
"to",
"its",
"destination",
"location",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/file_io.py#L72-L92 | train | 44,556 |
sernst/cauldron | cauldron/session/writing/file_io.py | write | def write(write_entry: FILE_WRITE_ENTRY):
"""
Writes the contents of the specified file entry to its destination path.
"""
output_path = environ.paths.clean(write_entry.path)
make_output_directory(output_path)
writer.write_file(output_path, write_entry.contents) | python | def write(write_entry: FILE_WRITE_ENTRY):
"""
Writes the contents of the specified file entry to its destination path.
"""
output_path = environ.paths.clean(write_entry.path)
make_output_directory(output_path)
writer.write_file(output_path, write_entry.contents) | [
"def",
"write",
"(",
"write_entry",
":",
"FILE_WRITE_ENTRY",
")",
":",
"output_path",
"=",
"environ",
".",
"paths",
".",
"clean",
"(",
"write_entry",
".",
"path",
")",
"make_output_directory",
"(",
"output_path",
")",
"writer",
".",
"write_file",
"(",
"output_... | Writes the contents of the specified file entry to its destination path. | [
"Writes",
"the",
"contents",
"of",
"the",
"specified",
"file",
"entry",
"to",
"its",
"destination",
"path",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/file_io.py#L95-L101 | train | 44,557 |
sernst/cauldron | cauldron/runner/redirection.py | enable | def enable(step: 'projects.ProjectStep'):
"""
Create a print equivalent function that also writes the output to the
project page. The write_through is enabled so that the TextIOWrapper
immediately writes all of its input data directly to the underlying
BytesIO buffer. This is needed so that we can safely access the buffer
data in a multi-threaded environment to display updates while the buffer
is being written to.
:param step:
"""
# Prevent anything unusual from causing buffer issues
restore_default_configuration()
stdout_interceptor = RedirectBuffer(sys.stdout)
sys.stdout = stdout_interceptor
step.report.stdout_interceptor = stdout_interceptor
stderr_interceptor = RedirectBuffer(sys.stderr)
sys.stderr = stderr_interceptor
step.report.stderr_interceptor = stderr_interceptor
stdout_interceptor.active = True
stderr_interceptor.active = True | python | def enable(step: 'projects.ProjectStep'):
"""
Create a print equivalent function that also writes the output to the
project page. The write_through is enabled so that the TextIOWrapper
immediately writes all of its input data directly to the underlying
BytesIO buffer. This is needed so that we can safely access the buffer
data in a multi-threaded environment to display updates while the buffer
is being written to.
:param step:
"""
# Prevent anything unusual from causing buffer issues
restore_default_configuration()
stdout_interceptor = RedirectBuffer(sys.stdout)
sys.stdout = stdout_interceptor
step.report.stdout_interceptor = stdout_interceptor
stderr_interceptor = RedirectBuffer(sys.stderr)
sys.stderr = stderr_interceptor
step.report.stderr_interceptor = stderr_interceptor
stdout_interceptor.active = True
stderr_interceptor.active = True | [
"def",
"enable",
"(",
"step",
":",
"'projects.ProjectStep'",
")",
":",
"# Prevent anything unusual from causing buffer issues",
"restore_default_configuration",
"(",
")",
"stdout_interceptor",
"=",
"RedirectBuffer",
"(",
"sys",
".",
"stdout",
")",
"sys",
".",
"stdout",
... | Create a print equivalent function that also writes the output to the
project page. The write_through is enabled so that the TextIOWrapper
immediately writes all of its input data directly to the underlying
BytesIO buffer. This is needed so that we can safely access the buffer
data in a multi-threaded environment to display updates while the buffer
is being written to.
:param step: | [
"Create",
"a",
"print",
"equivalent",
"function",
"that",
"also",
"writes",
"the",
"output",
"to",
"the",
"project",
"page",
".",
"The",
"write_through",
"is",
"enabled",
"so",
"that",
"the",
"TextIOWrapper",
"immediately",
"writes",
"all",
"of",
"its",
"input... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/redirection.py#L6-L30 | train | 44,558 |
sernst/cauldron | cauldron/runner/redirection.py | restore_default_configuration | def restore_default_configuration():
"""
Restores the sys.stdout and the sys.stderr buffer streams to their default
values without regard to what step has currently overridden their values.
This is useful during cleanup outside of the running execution block
"""
def restore(target, default_value):
if target == default_value:
return default_value
if not isinstance(target, RedirectBuffer):
return target
try:
target.active = False
target.close()
except Exception:
pass
return default_value
sys.stdout = restore(sys.stdout, sys.__stdout__)
sys.stderr = restore(sys.stderr, sys.__stderr__) | python | def restore_default_configuration():
"""
Restores the sys.stdout and the sys.stderr buffer streams to their default
values without regard to what step has currently overridden their values.
This is useful during cleanup outside of the running execution block
"""
def restore(target, default_value):
if target == default_value:
return default_value
if not isinstance(target, RedirectBuffer):
return target
try:
target.active = False
target.close()
except Exception:
pass
return default_value
sys.stdout = restore(sys.stdout, sys.__stdout__)
sys.stderr = restore(sys.stderr, sys.__stderr__) | [
"def",
"restore_default_configuration",
"(",
")",
":",
"def",
"restore",
"(",
"target",
",",
"default_value",
")",
":",
"if",
"target",
"==",
"default_value",
":",
"return",
"default_value",
"if",
"not",
"isinstance",
"(",
"target",
",",
"RedirectBuffer",
")",
... | Restores the sys.stdout and the sys.stderr buffer streams to their default
values without regard to what step has currently overridden their values.
This is useful during cleanup outside of the running execution block | [
"Restores",
"the",
"sys",
".",
"stdout",
"and",
"the",
"sys",
".",
"stderr",
"buffer",
"streams",
"to",
"their",
"default",
"values",
"without",
"regard",
"to",
"what",
"step",
"has",
"currently",
"overridden",
"their",
"values",
".",
"This",
"is",
"useful",... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/redirection.py#L33-L56 | train | 44,559 |
sernst/cauldron | cauldron/session/writing/html.py | create | def create(
project: 'projects.Project',
destination_directory,
destination_filename: str = None
) -> file_io.FILE_WRITE_ENTRY:
"""
Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given
project that will be saved in the destination directory with the given
filename.
:param project:
The project for which the rendered HTML file will be created
:param destination_directory:
The absolute path to the folder where the HTML file will be saved
:param destination_filename:
The name of the HTML file to be written in the destination directory.
Defaults to the project uuid.
:return:
A FILE_WRITE_ENTRY for the project's HTML file output
"""
template_path = environ.paths.resources('web', 'project.html')
with open(template_path, 'r') as f:
dom = f.read()
dom = dom.replace(
'<!-- CAULDRON:EXPORT -->',
templating.render_template(
'notebook-script-header.html',
uuid=project.uuid,
version=environ.version
)
)
filename = (
destination_filename
if destination_filename else
'{}.html'.format(project.uuid)
)
html_out_path = os.path.join(destination_directory, filename)
return file_io.FILE_WRITE_ENTRY(
path=html_out_path,
contents=dom
) | python | def create(
project: 'projects.Project',
destination_directory,
destination_filename: str = None
) -> file_io.FILE_WRITE_ENTRY:
"""
Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given
project that will be saved in the destination directory with the given
filename.
:param project:
The project for which the rendered HTML file will be created
:param destination_directory:
The absolute path to the folder where the HTML file will be saved
:param destination_filename:
The name of the HTML file to be written in the destination directory.
Defaults to the project uuid.
:return:
A FILE_WRITE_ENTRY for the project's HTML file output
"""
template_path = environ.paths.resources('web', 'project.html')
with open(template_path, 'r') as f:
dom = f.read()
dom = dom.replace(
'<!-- CAULDRON:EXPORT -->',
templating.render_template(
'notebook-script-header.html',
uuid=project.uuid,
version=environ.version
)
)
filename = (
destination_filename
if destination_filename else
'{}.html'.format(project.uuid)
)
html_out_path = os.path.join(destination_directory, filename)
return file_io.FILE_WRITE_ENTRY(
path=html_out_path,
contents=dom
) | [
"def",
"create",
"(",
"project",
":",
"'projects.Project'",
",",
"destination_directory",
",",
"destination_filename",
":",
"str",
"=",
"None",
")",
"->",
"file_io",
".",
"FILE_WRITE_ENTRY",
":",
"template_path",
"=",
"environ",
".",
"paths",
".",
"resources",
"... | Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given
project that will be saved in the destination directory with the given
filename.
:param project:
The project for which the rendered HTML file will be created
:param destination_directory:
The absolute path to the folder where the HTML file will be saved
:param destination_filename:
The name of the HTML file to be written in the destination directory.
Defaults to the project uuid.
:return:
A FILE_WRITE_ENTRY for the project's HTML file output | [
"Creates",
"a",
"FILE_WRITE_ENTRY",
"for",
"the",
"rendered",
"HTML",
"file",
"for",
"the",
"given",
"project",
"that",
"will",
"be",
"saved",
"in",
"the",
"destination",
"directory",
"with",
"the",
"given",
"filename",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/html.py#L9-L54 | train | 44,560 |
sernst/cauldron | launcher.py | run_container | def run_container():
"""Runs an interactive container"""
os.chdir(my_directory)
cmd = [
'docker', 'run',
'-it', '--rm',
'-v', '{}:/cauldron'.format(my_directory),
'-p', '5010:5010',
'cauldron_app',
'/bin/bash'
]
return os.system(' '.join(cmd)) | python | def run_container():
"""Runs an interactive container"""
os.chdir(my_directory)
cmd = [
'docker', 'run',
'-it', '--rm',
'-v', '{}:/cauldron'.format(my_directory),
'-p', '5010:5010',
'cauldron_app',
'/bin/bash'
]
return os.system(' '.join(cmd)) | [
"def",
"run_container",
"(",
")",
":",
"os",
".",
"chdir",
"(",
"my_directory",
")",
"cmd",
"=",
"[",
"'docker'",
",",
"'run'",
",",
"'-it'",
",",
"'--rm'",
",",
"'-v'",
",",
"'{}:/cauldron'",
".",
"format",
"(",
"my_directory",
")",
",",
"'-p'",
",",
... | Runs an interactive container | [
"Runs",
"an",
"interactive",
"container"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/launcher.py#L24-L38 | train | 44,561 |
sernst/cauldron | launcher.py | run | def run():
"""Execute the Cauldron container command"""
command = sys.argv[1].strip().lower()
print('[COMMAND]:', command)
if command == 'test':
return run_test()
elif command == 'build':
return run_build()
elif command == 'up':
return run_container()
elif command == 'serve':
import cauldron
cauldron.run_server(port=5010, public=True) | python | def run():
"""Execute the Cauldron container command"""
command = sys.argv[1].strip().lower()
print('[COMMAND]:', command)
if command == 'test':
return run_test()
elif command == 'build':
return run_build()
elif command == 'up':
return run_container()
elif command == 'serve':
import cauldron
cauldron.run_server(port=5010, public=True) | [
"def",
"run",
"(",
")",
":",
"command",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"print",
"(",
"'[COMMAND]:'",
",",
"command",
")",
"if",
"command",
"==",
"'test'",
":",
"return",
"run_test",
"(",
")... | Execute the Cauldron container command | [
"Execute",
"the",
"Cauldron",
"container",
"command"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/launcher.py#L56-L70 | train | 44,562 |
sernst/cauldron | cauldron/cli/server/authorization.py | gatekeeper | def gatekeeper(func):
"""
This function is used to handle authorization code authentication of
protected endpoints. This form of authentication is not recommended
because it's not very secure, but can be used in places where SSH
tunneling or similar strong connection security is not possible.
The function looks for a special "Cauldron-Authentication-Code" header
in the request and confirms that the specified value matches the code
that was provided by arguments to the Cauldron kernel server. This function
acts as a pass-through if no code is specified when the server starts.
"""
@wraps(func)
def check_identity(*args, **kwargs):
code = server_runner.authorization['code']
comparison = request.headers.get('Cauldron-Authentication-Code')
return (
abort(401)
if code and code != comparison else
func(*args, **kwargs)
)
return check_identity | python | def gatekeeper(func):
"""
This function is used to handle authorization code authentication of
protected endpoints. This form of authentication is not recommended
because it's not very secure, but can be used in places where SSH
tunneling or similar strong connection security is not possible.
The function looks for a special "Cauldron-Authentication-Code" header
in the request and confirms that the specified value matches the code
that was provided by arguments to the Cauldron kernel server. This function
acts as a pass-through if no code is specified when the server starts.
"""
@wraps(func)
def check_identity(*args, **kwargs):
code = server_runner.authorization['code']
comparison = request.headers.get('Cauldron-Authentication-Code')
return (
abort(401)
if code and code != comparison else
func(*args, **kwargs)
)
return check_identity | [
"def",
"gatekeeper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"check_identity",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"code",
"=",
"server_runner",
".",
"authorization",
"[",
"'code'",
"]",
"comparison",
"=",
"reques... | This function is used to handle authorization code authentication of
protected endpoints. This form of authentication is not recommended
because it's not very secure, but can be used in places where SSH
tunneling or similar strong connection security is not possible.
The function looks for a special "Cauldron-Authentication-Code" header
in the request and confirms that the specified value matches the code
that was provided by arguments to the Cauldron kernel server. This function
acts as a pass-through if no code is specified when the server starts. | [
"This",
"function",
"is",
"used",
"to",
"handle",
"authorization",
"code",
"authentication",
"of",
"protected",
"endpoints",
".",
"This",
"form",
"of",
"authentication",
"is",
"not",
"recommended",
"because",
"it",
"s",
"not",
"very",
"secure",
"but",
"can",
"... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/authorization.py#L14-L38 | train | 44,563 |
sernst/cauldron | cauldron/session/display/__init__.py | inspect | def inspect(source: dict):
"""
Inspects the data and structure of the source dictionary object and
adds the results to the display for viewing.
:param source:
A dictionary object to be inspected.
:return:
"""
r = _get_report()
r.append_body(render.inspect(source)) | python | def inspect(source: dict):
"""
Inspects the data and structure of the source dictionary object and
adds the results to the display for viewing.
:param source:
A dictionary object to be inspected.
:return:
"""
r = _get_report()
r.append_body(render.inspect(source)) | [
"def",
"inspect",
"(",
"source",
":",
"dict",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"inspect",
"(",
"source",
")",
")"
] | Inspects the data and structure of the source dictionary object and
adds the results to the display for viewing.
:param source:
A dictionary object to be inspected.
:return: | [
"Inspects",
"the",
"data",
"and",
"structure",
"of",
"the",
"source",
"dictionary",
"object",
"and",
"adds",
"the",
"results",
"to",
"the",
"display",
"for",
"viewing",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L20-L30 | train | 44,564 |
sernst/cauldron | cauldron/session/display/__init__.py | header | def header(header_text: str, level: int = 1, expand_full: bool = False):
"""
Adds a text header to the display with the specified level.
:param header_text:
The text to display in the header.
:param level:
The level of the header, which corresponds to the html header
levels, such as <h1>, <h2>, ...
:param expand_full:
Whether or not the header will expand to fill the width of the entire
notebook page, or be constrained by automatic maximum page width. The
default value of False lines the header up with text displays.
"""
r = _get_report()
r.append_body(render.header(
header_text,
level=level,
expand_full=expand_full
)) | python | def header(header_text: str, level: int = 1, expand_full: bool = False):
"""
Adds a text header to the display with the specified level.
:param header_text:
The text to display in the header.
:param level:
The level of the header, which corresponds to the html header
levels, such as <h1>, <h2>, ...
:param expand_full:
Whether or not the header will expand to fill the width of the entire
notebook page, or be constrained by automatic maximum page width. The
default value of False lines the header up with text displays.
"""
r = _get_report()
r.append_body(render.header(
header_text,
level=level,
expand_full=expand_full
)) | [
"def",
"header",
"(",
"header_text",
":",
"str",
",",
"level",
":",
"int",
"=",
"1",
",",
"expand_full",
":",
"bool",
"=",
"False",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"header",
"(",
"header_text"... | Adds a text header to the display with the specified level.
:param header_text:
The text to display in the header.
:param level:
The level of the header, which corresponds to the html header
levels, such as <h1>, <h2>, ...
:param expand_full:
Whether or not the header will expand to fill the width of the entire
notebook page, or be constrained by automatic maximum page width. The
default value of False lines the header up with text displays. | [
"Adds",
"a",
"text",
"header",
"to",
"the",
"display",
"with",
"the",
"specified",
"level",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L33-L52 | train | 44,565 |
sernst/cauldron | cauldron/session/display/__init__.py | text | def text(value: str, preformatted: bool = False):
"""
Adds text to the display. If the text is not preformatted, it will be
displayed in paragraph format. Preformatted text will be displayed
inside a pre tag with a monospace font.
:param value:
The text to display.
:param preformatted:
Whether or not to preserve the whitespace display of the text.
"""
if preformatted:
result = render_texts.preformatted_text(value)
else:
result = render_texts.text(value)
r = _get_report()
r.append_body(result)
r.stdout_interceptor.write_source(
'{}\n'.format(textwrap.dedent(value))
) | python | def text(value: str, preformatted: bool = False):
"""
Adds text to the display. If the text is not preformatted, it will be
displayed in paragraph format. Preformatted text will be displayed
inside a pre tag with a monospace font.
:param value:
The text to display.
:param preformatted:
Whether or not to preserve the whitespace display of the text.
"""
if preformatted:
result = render_texts.preformatted_text(value)
else:
result = render_texts.text(value)
r = _get_report()
r.append_body(result)
r.stdout_interceptor.write_source(
'{}\n'.format(textwrap.dedent(value))
) | [
"def",
"text",
"(",
"value",
":",
"str",
",",
"preformatted",
":",
"bool",
"=",
"False",
")",
":",
"if",
"preformatted",
":",
"result",
"=",
"render_texts",
".",
"preformatted_text",
"(",
"value",
")",
"else",
":",
"result",
"=",
"render_texts",
".",
"te... | Adds text to the display. If the text is not preformatted, it will be
displayed in paragraph format. Preformatted text will be displayed
inside a pre tag with a monospace font.
:param value:
The text to display.
:param preformatted:
Whether or not to preserve the whitespace display of the text. | [
"Adds",
"text",
"to",
"the",
"display",
".",
"If",
"the",
"text",
"is",
"not",
"preformatted",
"it",
"will",
"be",
"displayed",
"in",
"paragraph",
"format",
".",
"Preformatted",
"text",
"will",
"be",
"displayed",
"inside",
"a",
"pre",
"tag",
"with",
"a",
... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L55-L74 | train | 44,566 |
sernst/cauldron | cauldron/session/display/__init__.py | markdown | def markdown(
source: str = None,
source_path: str = None,
preserve_lines: bool = False,
font_size: float = None,
**kwargs
):
"""
Renders the specified source string or source file using markdown and
adds the resulting HTML to the notebook display.
:param source:
A markdown formatted string.
:param source_path:
A file containing markdown text.
:param preserve_lines:
If True, all line breaks will be treated as hard breaks. Use this
for pre-formatted markdown text where newlines should be retained
during rendering.
:param font_size:
Specifies a relative font size adjustment. The default value is 1.0,
which preserves the inherited font size values. Set it to a value
below 1.0 for smaller font-size rendering and greater than 1.0 for
larger font size rendering.
:param kwargs:
Any variable replacements to make within the string using Jinja2
templating syntax.
"""
r = _get_report()
result = render_texts.markdown(
source=source,
source_path=source_path,
preserve_lines=preserve_lines,
font_size=font_size,
**kwargs
)
r.library_includes += result['library_includes']
r.append_body(result['body'])
r.stdout_interceptor.write_source(
'{}\n'.format(textwrap.dedent(result['rendered']))
) | python | def markdown(
source: str = None,
source_path: str = None,
preserve_lines: bool = False,
font_size: float = None,
**kwargs
):
"""
Renders the specified source string or source file using markdown and
adds the resulting HTML to the notebook display.
:param source:
A markdown formatted string.
:param source_path:
A file containing markdown text.
:param preserve_lines:
If True, all line breaks will be treated as hard breaks. Use this
for pre-formatted markdown text where newlines should be retained
during rendering.
:param font_size:
Specifies a relative font size adjustment. The default value is 1.0,
which preserves the inherited font size values. Set it to a value
below 1.0 for smaller font-size rendering and greater than 1.0 for
larger font size rendering.
:param kwargs:
Any variable replacements to make within the string using Jinja2
templating syntax.
"""
r = _get_report()
result = render_texts.markdown(
source=source,
source_path=source_path,
preserve_lines=preserve_lines,
font_size=font_size,
**kwargs
)
r.library_includes += result['library_includes']
r.append_body(result['body'])
r.stdout_interceptor.write_source(
'{}\n'.format(textwrap.dedent(result['rendered']))
) | [
"def",
"markdown",
"(",
"source",
":",
"str",
"=",
"None",
",",
"source_path",
":",
"str",
"=",
"None",
",",
"preserve_lines",
":",
"bool",
"=",
"False",
",",
"font_size",
":",
"float",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"_ge... | Renders the specified source string or source file using markdown and
adds the resulting HTML to the notebook display.
:param source:
A markdown formatted string.
:param source_path:
A file containing markdown text.
:param preserve_lines:
If True, all line breaks will be treated as hard breaks. Use this
for pre-formatted markdown text where newlines should be retained
during rendering.
:param font_size:
Specifies a relative font size adjustment. The default value is 1.0,
which preserves the inherited font size values. Set it to a value
below 1.0 for smaller font-size rendering and greater than 1.0 for
larger font size rendering.
:param kwargs:
Any variable replacements to make within the string using Jinja2
templating syntax. | [
"Renders",
"the",
"specified",
"source",
"string",
"or",
"source",
"file",
"using",
"markdown",
"and",
"adds",
"the",
"resulting",
"HTML",
"to",
"the",
"notebook",
"display",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L77-L119 | train | 44,567 |
sernst/cauldron | cauldron/session/display/__init__.py | json | def json(**kwargs):
"""
Adds the specified data to the the output display window with the
specified key. This allows the user to make available arbitrary
JSON-compatible data to the display for runtime use.
:param kwargs:
Each keyword argument is added to the CD.data object with the
specified key and value.
"""
r = _get_report()
r.append_body(render.json(**kwargs))
r.stdout_interceptor.write_source(
'{}\n'.format(_json_io.dumps(kwargs, indent=2))
) | python | def json(**kwargs):
"""
Adds the specified data to the the output display window with the
specified key. This allows the user to make available arbitrary
JSON-compatible data to the display for runtime use.
:param kwargs:
Each keyword argument is added to the CD.data object with the
specified key and value.
"""
r = _get_report()
r.append_body(render.json(**kwargs))
r.stdout_interceptor.write_source(
'{}\n'.format(_json_io.dumps(kwargs, indent=2))
) | [
"def",
"json",
"(",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"json",
"(",
"*",
"*",
"kwargs",
")",
")",
"r",
".",
"stdout_interceptor",
".",
"write_source",
"(",
"'{}\\n'",
".",
"... | Adds the specified data to the the output display window with the
specified key. This allows the user to make available arbitrary
JSON-compatible data to the display for runtime use.
:param kwargs:
Each keyword argument is added to the CD.data object with the
specified key and value. | [
"Adds",
"the",
"specified",
"data",
"to",
"the",
"the",
"output",
"display",
"window",
"with",
"the",
"specified",
"key",
".",
"This",
"allows",
"the",
"user",
"to",
"make",
"available",
"arbitrary",
"JSON",
"-",
"compatible",
"data",
"to",
"the",
"display",... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L122-L136 | train | 44,568 |
sernst/cauldron | cauldron/session/display/__init__.py | plotly | def plotly(
data: typing.Union[dict, list] = None,
layout: dict = None,
scale: float = 0.5,
figure: dict = None,
static: bool = False
):
"""
Creates a Plotly plot in the display with the specified data and
layout.
:param data:
The Plotly trace data to be plotted.
:param layout:
The layout data used for the plot.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param figure:
In cases where you need to create a figure instead of separate data
and layout information, you can pass the figure here and leave the
data and layout values as None.
:param static:
If true, the plot will be created without interactivity.
This is useful if you have a lot of plots in your notebook.
"""
r = _get_report()
if not figure and not isinstance(data, (list, tuple)):
data = [data]
if 'plotly' not in r.library_includes:
r.library_includes.append('plotly')
r.append_body(render.plotly(
data=data,
layout=layout,
scale=scale,
figure=figure,
static=static
))
r.stdout_interceptor.write_source('[ADDED] Plotly plot\n') | python | def plotly(
data: typing.Union[dict, list] = None,
layout: dict = None,
scale: float = 0.5,
figure: dict = None,
static: bool = False
):
"""
Creates a Plotly plot in the display with the specified data and
layout.
:param data:
The Plotly trace data to be plotted.
:param layout:
The layout data used for the plot.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param figure:
In cases where you need to create a figure instead of separate data
and layout information, you can pass the figure here and leave the
data and layout values as None.
:param static:
If true, the plot will be created without interactivity.
This is useful if you have a lot of plots in your notebook.
"""
r = _get_report()
if not figure and not isinstance(data, (list, tuple)):
data = [data]
if 'plotly' not in r.library_includes:
r.library_includes.append('plotly')
r.append_body(render.plotly(
data=data,
layout=layout,
scale=scale,
figure=figure,
static=static
))
r.stdout_interceptor.write_source('[ADDED] Plotly plot\n') | [
"def",
"plotly",
"(",
"data",
":",
"typing",
".",
"Union",
"[",
"dict",
",",
"list",
"]",
"=",
"None",
",",
"layout",
":",
"dict",
"=",
"None",
",",
"scale",
":",
"float",
"=",
"0.5",
",",
"figure",
":",
"dict",
"=",
"None",
",",
"static",
":",
... | Creates a Plotly plot in the display with the specified data and
layout.
:param data:
The Plotly trace data to be plotted.
:param layout:
The layout data used for the plot.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param figure:
In cases where you need to create a figure instead of separate data
and layout information, you can pass the figure here and leave the
data and layout values as None.
:param static:
If true, the plot will be created without interactivity.
This is useful if you have a lot of plots in your notebook. | [
"Creates",
"a",
"Plotly",
"plot",
"in",
"the",
"display",
"with",
"the",
"specified",
"data",
"and",
"layout",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L139-L182 | train | 44,569 |
sernst/cauldron | cauldron/session/display/__init__.py | table | def table(
data_frame,
scale: float = 0.7,
include_index: bool = False,
max_rows: int = 500
):
"""
Adds the specified data frame to the display in a nicely formatted
scrolling table.
:param data_frame:
The pandas data frame to be rendered to a table.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param include_index:
Whether or not the index column should be included in the displayed
output. The index column is not included by default because it is
often unnecessary extra information in the display of the data.
:param max_rows:
This argument exists to prevent accidentally writing very large data
frames to a table, which can cause the notebook display to become
sluggish or unresponsive. If you want to display large tables, you need
only increase the value of this argument.
"""
r = _get_report()
r.append_body(render.table(
data_frame=data_frame,
scale=scale,
include_index=include_index,
max_rows=max_rows
))
r.stdout_interceptor.write_source('[ADDED] Table\n') | python | def table(
data_frame,
scale: float = 0.7,
include_index: bool = False,
max_rows: int = 500
):
"""
Adds the specified data frame to the display in a nicely formatted
scrolling table.
:param data_frame:
The pandas data frame to be rendered to a table.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param include_index:
Whether or not the index column should be included in the displayed
output. The index column is not included by default because it is
often unnecessary extra information in the display of the data.
:param max_rows:
This argument exists to prevent accidentally writing very large data
frames to a table, which can cause the notebook display to become
sluggish or unresponsive. If you want to display large tables, you need
only increase the value of this argument.
"""
r = _get_report()
r.append_body(render.table(
data_frame=data_frame,
scale=scale,
include_index=include_index,
max_rows=max_rows
))
r.stdout_interceptor.write_source('[ADDED] Table\n') | [
"def",
"table",
"(",
"data_frame",
",",
"scale",
":",
"float",
"=",
"0.7",
",",
"include_index",
":",
"bool",
"=",
"False",
",",
"max_rows",
":",
"int",
"=",
"500",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
... | Adds the specified data frame to the display in a nicely formatted
scrolling table.
:param data_frame:
The pandas data frame to be rendered to a table.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param include_index:
Whether or not the index column should be included in the displayed
output. The index column is not included by default because it is
often unnecessary extra information in the display of the data.
:param max_rows:
This argument exists to prevent accidentally writing very large data
frames to a table, which can cause the notebook display to become
sluggish or unresponsive. If you want to display large tables, you need
only increase the value of this argument. | [
"Adds",
"the",
"specified",
"data",
"frame",
"to",
"the",
"display",
"in",
"a",
"nicely",
"formatted",
"scrolling",
"table",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L185-L219 | train | 44,570 |
sernst/cauldron | cauldron/session/display/__init__.py | svg | def svg(svg_dom: str, filename: str = None):
"""
Adds the specified SVG string to the display. If a filename is
included, the SVG data will also be saved to that filename within the
project results folder.
:param svg_dom:
The SVG string data to add to the display.
:param filename:
An optional filename where the SVG data should be saved within
the project results folder.
"""
r = _get_report()
r.append_body(render.svg(svg_dom))
r.stdout_interceptor.write_source('[ADDED] SVG\n')
if not filename:
return
if not filename.endswith('.svg'):
filename += '.svg'
r.files[filename] = svg_dom | python | def svg(svg_dom: str, filename: str = None):
"""
Adds the specified SVG string to the display. If a filename is
included, the SVG data will also be saved to that filename within the
project results folder.
:param svg_dom:
The SVG string data to add to the display.
:param filename:
An optional filename where the SVG data should be saved within
the project results folder.
"""
r = _get_report()
r.append_body(render.svg(svg_dom))
r.stdout_interceptor.write_source('[ADDED] SVG\n')
if not filename:
return
if not filename.endswith('.svg'):
filename += '.svg'
r.files[filename] = svg_dom | [
"def",
"svg",
"(",
"svg_dom",
":",
"str",
",",
"filename",
":",
"str",
"=",
"None",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"svg",
"(",
"svg_dom",
")",
")",
"r",
".",
"stdout_interceptor",
".",
"wri... | Adds the specified SVG string to the display. If a filename is
included, the SVG data will also be saved to that filename within the
project results folder.
:param svg_dom:
The SVG string data to add to the display.
:param filename:
An optional filename where the SVG data should be saved within
the project results folder. | [
"Adds",
"the",
"specified",
"SVG",
"string",
"to",
"the",
"display",
".",
"If",
"a",
"filename",
"is",
"included",
"the",
"SVG",
"data",
"will",
"also",
"be",
"saved",
"to",
"that",
"filename",
"within",
"the",
"project",
"results",
"folder",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L222-L244 | train | 44,571 |
sernst/cauldron | cauldron/session/display/__init__.py | jinja | def jinja(path: str, **kwargs):
"""
Renders the specified Jinja2 template to HTML and adds the output to the
display.
:param path:
The fully-qualified path to the template to be rendered.
:param kwargs:
Any keyword arguments that will be use as variable replacements within
the template.
"""
r = _get_report()
r.append_body(render.jinja(path, **kwargs))
r.stdout_interceptor.write_source('[ADDED] Jinja2 rendered HTML\n') | python | def jinja(path: str, **kwargs):
"""
Renders the specified Jinja2 template to HTML and adds the output to the
display.
:param path:
The fully-qualified path to the template to be rendered.
:param kwargs:
Any keyword arguments that will be use as variable replacements within
the template.
"""
r = _get_report()
r.append_body(render.jinja(path, **kwargs))
r.stdout_interceptor.write_source('[ADDED] Jinja2 rendered HTML\n') | [
"def",
"jinja",
"(",
"path",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"jinja",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
")",
"r",
".",
"stdout_interceptor",
"... | Renders the specified Jinja2 template to HTML and adds the output to the
display.
:param path:
The fully-qualified path to the template to be rendered.
:param kwargs:
Any keyword arguments that will be use as variable replacements within
the template. | [
"Renders",
"the",
"specified",
"Jinja2",
"template",
"to",
"HTML",
"and",
"adds",
"the",
"output",
"to",
"the",
"display",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L247-L260 | train | 44,572 |
sernst/cauldron | cauldron/session/display/__init__.py | whitespace | def whitespace(lines: float = 1.0):
"""
Adds the specified number of lines of whitespace.
:param lines:
The number of lines of whitespace to show.
"""
r = _get_report()
r.append_body(render.whitespace(lines))
r.stdout_interceptor.write_source('\n') | python | def whitespace(lines: float = 1.0):
"""
Adds the specified number of lines of whitespace.
:param lines:
The number of lines of whitespace to show.
"""
r = _get_report()
r.append_body(render.whitespace(lines))
r.stdout_interceptor.write_source('\n') | [
"def",
"whitespace",
"(",
"lines",
":",
"float",
"=",
"1.0",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"whitespace",
"(",
"lines",
")",
")",
"r",
".",
"stdout_interceptor",
".",
"write_source",
"(",
"'\\n... | Adds the specified number of lines of whitespace.
:param lines:
The number of lines of whitespace to show. | [
"Adds",
"the",
"specified",
"number",
"of",
"lines",
"of",
"whitespace",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L263-L272 | train | 44,573 |
sernst/cauldron | cauldron/session/display/__init__.py | image | def image(
filename: str,
width: int = None,
height: int = None,
justify: str = 'left'
):
"""
Adds an image to the display. The image must be located within the
assets directory of the Cauldron notebook's folder.
:param filename:
Name of the file within the assets directory,
:param width:
Optional width in pixels for the image.
:param height:
Optional height in pixels for the image.
:param justify:
One of 'left', 'center' or 'right', which specifies how the image
is horizontally justified within the notebook display.
"""
r = _get_report()
path = '/'.join(['reports', r.project.uuid, 'latest', 'assets', filename])
r.append_body(render.image(path, width, height, justify))
r.stdout_interceptor.write_source('[ADDED] Image\n') | python | def image(
filename: str,
width: int = None,
height: int = None,
justify: str = 'left'
):
"""
Adds an image to the display. The image must be located within the
assets directory of the Cauldron notebook's folder.
:param filename:
Name of the file within the assets directory,
:param width:
Optional width in pixels for the image.
:param height:
Optional height in pixels for the image.
:param justify:
One of 'left', 'center' or 'right', which specifies how the image
is horizontally justified within the notebook display.
"""
r = _get_report()
path = '/'.join(['reports', r.project.uuid, 'latest', 'assets', filename])
r.append_body(render.image(path, width, height, justify))
r.stdout_interceptor.write_source('[ADDED] Image\n') | [
"def",
"image",
"(",
"filename",
":",
"str",
",",
"width",
":",
"int",
"=",
"None",
",",
"height",
":",
"int",
"=",
"None",
",",
"justify",
":",
"str",
"=",
"'left'",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"path",
"=",
"'/'",
".",
"join",
... | Adds an image to the display. The image must be located within the
assets directory of the Cauldron notebook's folder.
:param filename:
Name of the file within the assets directory,
:param width:
Optional width in pixels for the image.
:param height:
Optional height in pixels for the image.
:param justify:
One of 'left', 'center' or 'right', which specifies how the image
is horizontally justified within the notebook display. | [
"Adds",
"an",
"image",
"to",
"the",
"display",
".",
"The",
"image",
"must",
"be",
"located",
"within",
"the",
"assets",
"directory",
"of",
"the",
"Cauldron",
"notebook",
"s",
"folder",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L275-L298 | train | 44,574 |
sernst/cauldron | cauldron/session/display/__init__.py | html | def html(dom: str):
"""
A string containing a valid HTML snippet.
:param dom:
The HTML string to add to the display.
"""
r = _get_report()
r.append_body(render.html(dom))
r.stdout_interceptor.write_source('[ADDED] HTML\n') | python | def html(dom: str):
"""
A string containing a valid HTML snippet.
:param dom:
The HTML string to add to the display.
"""
r = _get_report()
r.append_body(render.html(dom))
r.stdout_interceptor.write_source('[ADDED] HTML\n') | [
"def",
"html",
"(",
"dom",
":",
"str",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"html",
"(",
"dom",
")",
")",
"r",
".",
"stdout_interceptor",
".",
"write_source",
"(",
"'[ADDED] HTML\\n'",
")"
] | A string containing a valid HTML snippet.
:param dom:
The HTML string to add to the display. | [
"A",
"string",
"containing",
"a",
"valid",
"HTML",
"snippet",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L301-L310 | train | 44,575 |
sernst/cauldron | cauldron/session/display/__init__.py | workspace | def workspace(show_values: bool = True, show_types: bool = True):
"""
Adds a list of the shared variables currently stored in the project
workspace.
:param show_values:
When true the values for each variable will be shown in addition to
their name.
:param show_types:
When true the data types for each shared variable will be shown in
addition to their name.
"""
r = _get_report()
data = {}
for key, value in r.project.shared.fetch(None).items():
if key.startswith('__cauldron_'):
continue
data[key] = value
r.append_body(render.status(data, values=show_values, types=show_types)) | python | def workspace(show_values: bool = True, show_types: bool = True):
"""
Adds a list of the shared variables currently stored in the project
workspace.
:param show_values:
When true the values for each variable will be shown in addition to
their name.
:param show_types:
When true the data types for each shared variable will be shown in
addition to their name.
"""
r = _get_report()
data = {}
for key, value in r.project.shared.fetch(None).items():
if key.startswith('__cauldron_'):
continue
data[key] = value
r.append_body(render.status(data, values=show_values, types=show_types)) | [
"def",
"workspace",
"(",
"show_values",
":",
"bool",
"=",
"True",
",",
"show_types",
":",
"bool",
"=",
"True",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"r",
".",
"project",
".",
"shared",... | Adds a list of the shared variables currently stored in the project
workspace.
:param show_values:
When true the values for each variable will be shown in addition to
their name.
:param show_types:
When true the data types for each shared variable will be shown in
addition to their name. | [
"Adds",
"a",
"list",
"of",
"the",
"shared",
"variables",
"currently",
"stored",
"in",
"the",
"project",
"workspace",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L313-L333 | train | 44,576 |
sernst/cauldron | cauldron/session/display/__init__.py | pyplot | def pyplot(
figure=None,
scale: float = 0.8,
clear: bool = True,
aspect_ratio: typing.Union[list, tuple] = None
):
"""
Creates a matplotlib plot in the display for the specified figure. The size
of the plot is determined automatically to best fit the notebook.
:param figure:
The matplotlib figure to plot. If omitted, the currently active
figure will be used.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param clear:
Clears the figure after it has been rendered. This is useful to
prevent persisting old plot data between repeated runs of the
project files. This can be disabled if the plot is going to be
used later in the project files.
:param aspect_ratio:
The aspect ratio for the displayed plot as a two-element list or
tuple. The first element is the width and the second element the
height. The units are "inches," which is an important consideration
for the display of text within the figure. If no aspect ratio is
specified, the currently assigned values to the plot will be used
instead.
"""
r = _get_report()
r.append_body(render_plots.pyplot(
figure,
scale=scale,
clear=clear,
aspect_ratio=aspect_ratio
))
r.stdout_interceptor.write_source('[ADDED] PyPlot plot\n') | python | def pyplot(
figure=None,
scale: float = 0.8,
clear: bool = True,
aspect_ratio: typing.Union[list, tuple] = None
):
"""
Creates a matplotlib plot in the display for the specified figure. The size
of the plot is determined automatically to best fit the notebook.
:param figure:
The matplotlib figure to plot. If omitted, the currently active
figure will be used.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param clear:
Clears the figure after it has been rendered. This is useful to
prevent persisting old plot data between repeated runs of the
project files. This can be disabled if the plot is going to be
used later in the project files.
:param aspect_ratio:
The aspect ratio for the displayed plot as a two-element list or
tuple. The first element is the width and the second element the
height. The units are "inches," which is an important consideration
for the display of text within the figure. If no aspect ratio is
specified, the currently assigned values to the plot will be used
instead.
"""
r = _get_report()
r.append_body(render_plots.pyplot(
figure,
scale=scale,
clear=clear,
aspect_ratio=aspect_ratio
))
r.stdout_interceptor.write_source('[ADDED] PyPlot plot\n') | [
"def",
"pyplot",
"(",
"figure",
"=",
"None",
",",
"scale",
":",
"float",
"=",
"0.8",
",",
"clear",
":",
"bool",
"=",
"True",
",",
"aspect_ratio",
":",
"typing",
".",
"Union",
"[",
"list",
",",
"tuple",
"]",
"=",
"None",
")",
":",
"r",
"=",
"_get_... | Creates a matplotlib plot in the display for the specified figure. The size
of the plot is determined automatically to best fit the notebook.
:param figure:
The matplotlib figure to plot. If omitted, the currently active
figure will be used.
:param scale:
The display scale with units of fractional screen height. A value
of 0.5 constrains the output to a maximum height equal to half the
height of browser window when viewed. Values below 1.0 are usually
recommended so the entire output can be viewed without scrolling.
:param clear:
Clears the figure after it has been rendered. This is useful to
prevent persisting old plot data between repeated runs of the
project files. This can be disabled if the plot is going to be
used later in the project files.
:param aspect_ratio:
The aspect ratio for the displayed plot as a two-element list or
tuple. The first element is the width and the second element the
height. The units are "inches," which is an important consideration
for the display of text within the figure. If no aspect ratio is
specified, the currently assigned values to the plot will be used
instead. | [
"Creates",
"a",
"matplotlib",
"plot",
"in",
"the",
"display",
"for",
"the",
"specified",
"figure",
".",
"The",
"size",
"of",
"the",
"plot",
"is",
"determined",
"automatically",
"to",
"best",
"fit",
"the",
"notebook",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L336-L374 | train | 44,577 |
sernst/cauldron | cauldron/session/display/__init__.py | bokeh | def bokeh(model, scale: float = 0.7, responsive: bool = True):
"""
Adds a Bokeh plot object to the notebook display.
:param model:
The plot object to be added to the notebook display.
:param scale:
How tall the plot should be in the notebook as a fraction of screen
height. A number between 0.1 and 1.0. The default value is 0.7.
:param responsive:
Whether or not the plot should responsively scale to fill the width
of the notebook. The default is True.
"""
r = _get_report()
if 'bokeh' not in r.library_includes:
r.library_includes.append('bokeh')
r.append_body(render_plots.bokeh_plot(
model=model,
scale=scale,
responsive=responsive
))
r.stdout_interceptor.write_source('[ADDED] Bokeh plot\n') | python | def bokeh(model, scale: float = 0.7, responsive: bool = True):
"""
Adds a Bokeh plot object to the notebook display.
:param model:
The plot object to be added to the notebook display.
:param scale:
How tall the plot should be in the notebook as a fraction of screen
height. A number between 0.1 and 1.0. The default value is 0.7.
:param responsive:
Whether or not the plot should responsively scale to fill the width
of the notebook. The default is True.
"""
r = _get_report()
if 'bokeh' not in r.library_includes:
r.library_includes.append('bokeh')
r.append_body(render_plots.bokeh_plot(
model=model,
scale=scale,
responsive=responsive
))
r.stdout_interceptor.write_source('[ADDED] Bokeh plot\n') | [
"def",
"bokeh",
"(",
"model",
",",
"scale",
":",
"float",
"=",
"0.7",
",",
"responsive",
":",
"bool",
"=",
"True",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"if",
"'bokeh'",
"not",
"in",
"r",
".",
"library_includes",
":",
"r",
".",
"library_includ... | Adds a Bokeh plot object to the notebook display.
:param model:
The plot object to be added to the notebook display.
:param scale:
How tall the plot should be in the notebook as a fraction of screen
height. A number between 0.1 and 1.0. The default value is 0.7.
:param responsive:
Whether or not the plot should responsively scale to fill the width
of the notebook. The default is True. | [
"Adds",
"a",
"Bokeh",
"plot",
"object",
"to",
"the",
"notebook",
"display",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L377-L400 | train | 44,578 |
sernst/cauldron | cauldron/session/display/__init__.py | head | def head(source, count: int = 5):
"""
Displays a specified number of elements in a source object of many
different possible types.
:param source:
DataFrames will show *count* rows of that DataFrame. A list, tuple or
other iterable, will show the first *count* rows. Dictionaries will
show *count* keys from the dictionary, which will be randomly selected
unless you are using an OrderedDict. Strings will show the first
*count* characters.
:param count:
The number of elements to show from the source.
"""
r = _get_report()
r.append_body(render_texts.head(source, count=count))
r.stdout_interceptor.write_source('[ADDED] Head\n') | python | def head(source, count: int = 5):
"""
Displays a specified number of elements in a source object of many
different possible types.
:param source:
DataFrames will show *count* rows of that DataFrame. A list, tuple or
other iterable, will show the first *count* rows. Dictionaries will
show *count* keys from the dictionary, which will be randomly selected
unless you are using an OrderedDict. Strings will show the first
*count* characters.
:param count:
The number of elements to show from the source.
"""
r = _get_report()
r.append_body(render_texts.head(source, count=count))
r.stdout_interceptor.write_source('[ADDED] Head\n') | [
"def",
"head",
"(",
"source",
",",
"count",
":",
"int",
"=",
"5",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render_texts",
".",
"head",
"(",
"source",
",",
"count",
"=",
"count",
")",
")",
"r",
".",
"stdout_interce... | Displays a specified number of elements in a source object of many
different possible types.
:param source:
DataFrames will show *count* rows of that DataFrame. A list, tuple or
other iterable, will show the first *count* rows. Dictionaries will
show *count* keys from the dictionary, which will be randomly selected
unless you are using an OrderedDict. Strings will show the first
*count* characters.
:param count:
The number of elements to show from the source. | [
"Displays",
"a",
"specified",
"number",
"of",
"elements",
"in",
"a",
"source",
"object",
"of",
"many",
"different",
"possible",
"types",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L486-L502 | train | 44,579 |
sernst/cauldron | cauldron/session/display/__init__.py | status | def status(
message: str = None,
progress: float = None,
section_message: str = None,
section_progress: float = None,
):
"""
Updates the status display, which is only visible while a step is running.
This is useful for providing feedback and information during long-running
steps.
A section progress is also available for cases where long running tasks
consist of multiple tasks and you want to display sub-progress messages
within the context of the larger status.
Note: this is only supported when running in the Cauldron desktop
application.
:param message:
The status message you want to display. If left blank the previously
set status message will be retained. Should you desire to remove an
existing message, specify a blank string for this argument.
:param progress:
A number between zero and one that indicates the overall progress for
the current status. If no value is specified, the previously assigned
progress will be retained.
:param section_message:
The status message you want to display for a particular task within a
long-running step. If left blank the previously set section message
will be retained. Should you desire to remove an existing message,
specify a blank string for this argument.
:param section_progress:
A number between zero and one that indicates the progress for the
current section status. If no value is specified, the previously
assigned section progress value will be retained.
"""
environ.abort_thread()
step = _cd.project.get_internal_project().current_step
if message is not None:
step.progress_message = message
if progress is not None:
step.progress = max(0.0, min(1.0, progress))
if section_message is not None:
step.sub_progress_message = section_message
if section_progress is not None:
step.sub_progress = section_progress | python | def status(
message: str = None,
progress: float = None,
section_message: str = None,
section_progress: float = None,
):
"""
Updates the status display, which is only visible while a step is running.
This is useful for providing feedback and information during long-running
steps.
A section progress is also available for cases where long running tasks
consist of multiple tasks and you want to display sub-progress messages
within the context of the larger status.
Note: this is only supported when running in the Cauldron desktop
application.
:param message:
The status message you want to display. If left blank the previously
set status message will be retained. Should you desire to remove an
existing message, specify a blank string for this argument.
:param progress:
A number between zero and one that indicates the overall progress for
the current status. If no value is specified, the previously assigned
progress will be retained.
:param section_message:
The status message you want to display for a particular task within a
long-running step. If left blank the previously set section message
will be retained. Should you desire to remove an existing message,
specify a blank string for this argument.
:param section_progress:
A number between zero and one that indicates the progress for the
current section status. If no value is specified, the previously
assigned section progress value will be retained.
"""
environ.abort_thread()
step = _cd.project.get_internal_project().current_step
if message is not None:
step.progress_message = message
if progress is not None:
step.progress = max(0.0, min(1.0, progress))
if section_message is not None:
step.sub_progress_message = section_message
if section_progress is not None:
step.sub_progress = section_progress | [
"def",
"status",
"(",
"message",
":",
"str",
"=",
"None",
",",
"progress",
":",
"float",
"=",
"None",
",",
"section_message",
":",
"str",
"=",
"None",
",",
"section_progress",
":",
"float",
"=",
"None",
",",
")",
":",
"environ",
".",
"abort_thread",
"(... | Updates the status display, which is only visible while a step is running.
This is useful for providing feedback and information during long-running
steps.
A section progress is also available for cases where long running tasks
consist of multiple tasks and you want to display sub-progress messages
within the context of the larger status.
Note: this is only supported when running in the Cauldron desktop
application.
:param message:
The status message you want to display. If left blank the previously
set status message will be retained. Should you desire to remove an
existing message, specify a blank string for this argument.
:param progress:
A number between zero and one that indicates the overall progress for
the current status. If no value is specified, the previously assigned
progress will be retained.
:param section_message:
The status message you want to display for a particular task within a
long-running step. If left blank the previously set section message
will be retained. Should you desire to remove an existing message,
specify a blank string for this argument.
:param section_progress:
A number between zero and one that indicates the progress for the
current section status. If no value is specified, the previously
assigned section progress value will be retained. | [
"Updates",
"the",
"status",
"display",
"which",
"is",
"only",
"visible",
"while",
"a",
"step",
"is",
"running",
".",
"This",
"is",
"useful",
"for",
"providing",
"feedback",
"and",
"information",
"during",
"long",
"-",
"running",
"steps",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L524-L570 | train | 44,580 |
sernst/cauldron | cauldron/session/display/__init__.py | code_block | def code_block(
code: str = None,
path: str = None,
language_id: str = None,
title: str = None,
caption: str = None
):
"""
Adds a block of syntax highlighted code to the display from either
the supplied code argument, or from the code file specified
by the path argument.
:param code:
A string containing the code to be added to the display
:param path:
A path to a file containing code to be added to the display
:param language_id:
The language identifier that indicates what language should
be used by the syntax highlighter. Valid values are any of the
languages supported by the Pygments highlighter.
:param title:
If specified, the code block will include a title bar with the
value of this argument
:param caption:
If specified, the code block will include a caption box below the code
that contains the value of this argument
"""
environ.abort_thread()
r = _get_report()
r.append_body(render.code_block(
block=code,
path=path,
language=language_id,
title=title,
caption=caption
))
r.stdout_interceptor.write_source('{}\n'.format(code)) | python | def code_block(
code: str = None,
path: str = None,
language_id: str = None,
title: str = None,
caption: str = None
):
"""
Adds a block of syntax highlighted code to the display from either
the supplied code argument, or from the code file specified
by the path argument.
:param code:
A string containing the code to be added to the display
:param path:
A path to a file containing code to be added to the display
:param language_id:
The language identifier that indicates what language should
be used by the syntax highlighter. Valid values are any of the
languages supported by the Pygments highlighter.
:param title:
If specified, the code block will include a title bar with the
value of this argument
:param caption:
If specified, the code block will include a caption box below the code
that contains the value of this argument
"""
environ.abort_thread()
r = _get_report()
r.append_body(render.code_block(
block=code,
path=path,
language=language_id,
title=title,
caption=caption
))
r.stdout_interceptor.write_source('{}\n'.format(code)) | [
"def",
"code_block",
"(",
"code",
":",
"str",
"=",
"None",
",",
"path",
":",
"str",
"=",
"None",
",",
"language_id",
":",
"str",
"=",
"None",
",",
"title",
":",
"str",
"=",
"None",
",",
"caption",
":",
"str",
"=",
"None",
")",
":",
"environ",
"."... | Adds a block of syntax highlighted code to the display from either
the supplied code argument, or from the code file specified
by the path argument.
:param code:
A string containing the code to be added to the display
:param path:
A path to a file containing code to be added to the display
:param language_id:
The language identifier that indicates what language should
be used by the syntax highlighter. Valid values are any of the
languages supported by the Pygments highlighter.
:param title:
If specified, the code block will include a title bar with the
value of this argument
:param caption:
If specified, the code block will include a caption box below the code
that contains the value of this argument | [
"Adds",
"a",
"block",
"of",
"syntax",
"highlighted",
"code",
"to",
"the",
"display",
"from",
"either",
"the",
"supplied",
"code",
"argument",
"or",
"from",
"the",
"code",
"file",
"specified",
"by",
"the",
"path",
"argument",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L573-L609 | train | 44,581 |
sernst/cauldron | cauldron/session/display/__init__.py | elapsed | def elapsed():
"""
Displays the elapsed time since the step started running.
"""
environ.abort_thread()
step = _cd.project.get_internal_project().current_step
r = _get_report()
r.append_body(render.elapsed_time(step.elapsed_time))
result = '[ELAPSED]: {}\n'.format(timedelta(seconds=step.elapsed_time))
r.stdout_interceptor.write_source(result) | python | def elapsed():
"""
Displays the elapsed time since the step started running.
"""
environ.abort_thread()
step = _cd.project.get_internal_project().current_step
r = _get_report()
r.append_body(render.elapsed_time(step.elapsed_time))
result = '[ELAPSED]: {}\n'.format(timedelta(seconds=step.elapsed_time))
r.stdout_interceptor.write_source(result) | [
"def",
"elapsed",
"(",
")",
":",
"environ",
".",
"abort_thread",
"(",
")",
"step",
"=",
"_cd",
".",
"project",
".",
"get_internal_project",
"(",
")",
".",
"current_step",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"... | Displays the elapsed time since the step started running. | [
"Displays",
"the",
"elapsed",
"time",
"since",
"the",
"step",
"started",
"running",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L612-L622 | train | 44,582 |
sernst/cauldron | cauldron/session/reloading.py | get_module | def get_module(name: str) -> typing.Union[types.ModuleType, None]:
"""
Retrieves the loaded module for the given module name or returns None if
no such module has been loaded.
:param name:
The name of the module to be retrieved
:return:
Either the loaded module with the specified name, or None if no such
module has been imported.
"""
return sys.modules.get(name) | python | def get_module(name: str) -> typing.Union[types.ModuleType, None]:
"""
Retrieves the loaded module for the given module name or returns None if
no such module has been loaded.
:param name:
The name of the module to be retrieved
:return:
Either the loaded module with the specified name, or None if no such
module has been imported.
"""
return sys.modules.get(name) | [
"def",
"get_module",
"(",
"name",
":",
"str",
")",
"->",
"typing",
".",
"Union",
"[",
"types",
".",
"ModuleType",
",",
"None",
"]",
":",
"return",
"sys",
".",
"modules",
".",
"get",
"(",
"name",
")"
] | Retrieves the loaded module for the given module name or returns None if
no such module has been loaded.
:param name:
The name of the module to be retrieved
:return:
Either the loaded module with the specified name, or None if no such
module has been imported. | [
"Retrieves",
"the",
"loaded",
"module",
"for",
"the",
"given",
"module",
"name",
"or",
"returns",
"None",
"if",
"no",
"such",
"module",
"has",
"been",
"loaded",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L10-L21 | train | 44,583 |
sernst/cauldron | cauldron/session/reloading.py | get_module_name | def get_module_name(module: types.ModuleType) -> str:
"""
Returns the name of the specified module by looking up its name in
multiple ways to prevent incompatibility issues.
:param module:
A module object for which to retrieve the name.
"""
try:
return module.__spec__.name
except AttributeError:
return module.__name__ | python | def get_module_name(module: types.ModuleType) -> str:
"""
Returns the name of the specified module by looking up its name in
multiple ways to prevent incompatibility issues.
:param module:
A module object for which to retrieve the name.
"""
try:
return module.__spec__.name
except AttributeError:
return module.__name__ | [
"def",
"get_module_name",
"(",
"module",
":",
"types",
".",
"ModuleType",
")",
"->",
"str",
":",
"try",
":",
"return",
"module",
".",
"__spec__",
".",
"name",
"except",
"AttributeError",
":",
"return",
"module",
".",
"__name__"
] | Returns the name of the specified module by looking up its name in
multiple ways to prevent incompatibility issues.
:param module:
A module object for which to retrieve the name. | [
"Returns",
"the",
"name",
"of",
"the",
"specified",
"module",
"by",
"looking",
"up",
"its",
"name",
"in",
"multiple",
"ways",
"to",
"prevent",
"incompatibility",
"issues",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L24-L35 | train | 44,584 |
sernst/cauldron | cauldron/session/reloading.py | do_reload | def do_reload(module: types.ModuleType, newer_than: int) -> bool:
"""
Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in seconds since epoch that should be used to determine if
the module needs to be reloaded. If the module source was modified
more recently than this time, the module will be refreshed.
:return:
Whether or not the module was reloaded
"""
path = getattr(module, '__file__')
directory = getattr(module, '__path__', [None])[0]
if path is None and directory:
path = os.path.join(directory, '__init__.py')
last_modified = os.path.getmtime(path)
if last_modified < newer_than:
return False
try:
importlib.reload(module)
return True
except ImportError:
return False | python | def do_reload(module: types.ModuleType, newer_than: int) -> bool:
"""
Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in seconds since epoch that should be used to determine if
the module needs to be reloaded. If the module source was modified
more recently than this time, the module will be refreshed.
:return:
Whether or not the module was reloaded
"""
path = getattr(module, '__file__')
directory = getattr(module, '__path__', [None])[0]
if path is None and directory:
path = os.path.join(directory, '__init__.py')
last_modified = os.path.getmtime(path)
if last_modified < newer_than:
return False
try:
importlib.reload(module)
return True
except ImportError:
return False | [
"def",
"do_reload",
"(",
"module",
":",
"types",
".",
"ModuleType",
",",
"newer_than",
":",
"int",
")",
"->",
"bool",
":",
"path",
"=",
"getattr",
"(",
"module",
",",
"'__file__'",
")",
"directory",
"=",
"getattr",
"(",
"module",
",",
"'__path__'",
",",
... | Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in seconds since epoch that should be used to determine if
the module needs to be reloaded. If the module source was modified
more recently than this time, the module will be refreshed.
:return:
Whether or not the module was reloaded | [
"Executes",
"the",
"reload",
"of",
"the",
"specified",
"module",
"if",
"the",
"source",
"file",
"that",
"it",
"was",
"loaded",
"from",
"was",
"updated",
"more",
"recently",
"than",
"the",
"specified",
"time"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L38-L67 | train | 44,585 |
sernst/cauldron | cauldron/session/reloading.py | reload_children | def reload_children(parent_module: types.ModuleType, newer_than: int) -> bool:
"""
Reloads all imported children of the specified parent module object
:param parent_module:
A module object whose children should be refreshed if their
currently loaded versions are out of date.
:param newer_than:
An integer time in seconds for comparison. Any children modules that
were modified more recently than this time will be reloaded.
:return:
Whether or not any children were reloaded
"""
if not hasattr(parent_module, '__path__'):
return False
parent_name = get_module_name(parent_module)
children = filter(
lambda item: item[0].startswith(parent_name),
sys.modules.items()
)
return any([do_reload(item[1], newer_than) for item in children]) | python | def reload_children(parent_module: types.ModuleType, newer_than: int) -> bool:
"""
Reloads all imported children of the specified parent module object
:param parent_module:
A module object whose children should be refreshed if their
currently loaded versions are out of date.
:param newer_than:
An integer time in seconds for comparison. Any children modules that
were modified more recently than this time will be reloaded.
:return:
Whether or not any children were reloaded
"""
if not hasattr(parent_module, '__path__'):
return False
parent_name = get_module_name(parent_module)
children = filter(
lambda item: item[0].startswith(parent_name),
sys.modules.items()
)
return any([do_reload(item[1], newer_than) for item in children]) | [
"def",
"reload_children",
"(",
"parent_module",
":",
"types",
".",
"ModuleType",
",",
"newer_than",
":",
"int",
")",
"->",
"bool",
":",
"if",
"not",
"hasattr",
"(",
"parent_module",
",",
"'__path__'",
")",
":",
"return",
"False",
"parent_name",
"=",
"get_mod... | Reloads all imported children of the specified parent module object
:param parent_module:
A module object whose children should be refreshed if their
currently loaded versions are out of date.
:param newer_than:
An integer time in seconds for comparison. Any children modules that
were modified more recently than this time will be reloaded.
:return:
Whether or not any children were reloaded | [
"Reloads",
"all",
"imported",
"children",
"of",
"the",
"specified",
"parent",
"module",
"object"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L70-L93 | train | 44,586 |
sernst/cauldron | cauldron/session/reloading.py | reload_module | def reload_module(
module: typing.Union[str, types.ModuleType],
recursive: bool,
force: bool
) -> bool:
"""
Reloads the specified module, which can either be a module object or
a string name of a module. Will not reload a module that has not been
imported
:param module:
A module object or string module name that should be refreshed if its
currently loaded version is out of date or the action is forced.
:param recursive:
When true, any imported sub-modules of this module will also be
refreshed if they have been updated.
:param force:
When true, all modules will be refreshed even if it doesn't appear
that they have been updated.
:return:
"""
if isinstance(module, str):
module = get_module(module)
if module is None or not isinstance(module, types.ModuleType):
return False
try:
step = session.project.get_internal_project().current_step
modified = step.last_modified if step else None
except AttributeError:
modified = 0
if modified is None:
# If the step has no modified time it hasn't been run yet and
# a reload won't be needed
return False
newer_than = modified if not force and modified else 0
if recursive:
children_reloaded = reload_children(module, newer_than)
else:
children_reloaded = False
reloaded = do_reload(module, newer_than)
return reloaded or children_reloaded | python | def reload_module(
module: typing.Union[str, types.ModuleType],
recursive: bool,
force: bool
) -> bool:
"""
Reloads the specified module, which can either be a module object or
a string name of a module. Will not reload a module that has not been
imported
:param module:
A module object or string module name that should be refreshed if its
currently loaded version is out of date or the action is forced.
:param recursive:
When true, any imported sub-modules of this module will also be
refreshed if they have been updated.
:param force:
When true, all modules will be refreshed even if it doesn't appear
that they have been updated.
:return:
"""
if isinstance(module, str):
module = get_module(module)
if module is None or not isinstance(module, types.ModuleType):
return False
try:
step = session.project.get_internal_project().current_step
modified = step.last_modified if step else None
except AttributeError:
modified = 0
if modified is None:
# If the step has no modified time it hasn't been run yet and
# a reload won't be needed
return False
newer_than = modified if not force and modified else 0
if recursive:
children_reloaded = reload_children(module, newer_than)
else:
children_reloaded = False
reloaded = do_reload(module, newer_than)
return reloaded or children_reloaded | [
"def",
"reload_module",
"(",
"module",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"types",
".",
"ModuleType",
"]",
",",
"recursive",
":",
"bool",
",",
"force",
":",
"bool",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"module",
",",
"str",
")"... | Reloads the specified module, which can either be a module object or
a string name of a module. Will not reload a module that has not been
imported
:param module:
A module object or string module name that should be refreshed if its
currently loaded version is out of date or the action is forced.
:param recursive:
When true, any imported sub-modules of this module will also be
refreshed if they have been updated.
:param force:
When true, all modules will be refreshed even if it doesn't appear
that they have been updated.
:return: | [
"Reloads",
"the",
"specified",
"module",
"which",
"can",
"either",
"be",
"a",
"module",
"object",
"or",
"a",
"string",
"name",
"of",
"a",
"module",
".",
"Will",
"not",
"reload",
"a",
"module",
"that",
"has",
"not",
"been",
"imported"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L96-L143 | train | 44,587 |
sernst/cauldron | cauldron/session/reloading.py | refresh | def refresh(
*modules: typing.Union[str, types.ModuleType],
recursive: bool = False,
force: bool = False
) -> bool:
"""
Checks the specified module or modules for changes and reloads them if
they have been changed since the module was first imported or last
refreshed.
:param modules:
One or more module objects that should be refreshed if they the
currently loaded versions are out of date. The package name for
modules can also be used.
:param recursive:
When true, any imported sub-modules of this module will also be
refreshed if they have been updated.
:param force:
When true, all modules will be refreshed even if it doesn't appear
that they have been updated.
:return:
True or False depending on whether any modules were refreshed by this
call.
"""
out = []
for module in modules:
out.append(reload_module(module, recursive, force))
return any(out) | python | def refresh(
*modules: typing.Union[str, types.ModuleType],
recursive: bool = False,
force: bool = False
) -> bool:
"""
Checks the specified module or modules for changes and reloads them if
they have been changed since the module was first imported or last
refreshed.
:param modules:
One or more module objects that should be refreshed if they the
currently loaded versions are out of date. The package name for
modules can also be used.
:param recursive:
When true, any imported sub-modules of this module will also be
refreshed if they have been updated.
:param force:
When true, all modules will be refreshed even if it doesn't appear
that they have been updated.
:return:
True or False depending on whether any modules were refreshed by this
call.
"""
out = []
for module in modules:
out.append(reload_module(module, recursive, force))
return any(out) | [
"def",
"refresh",
"(",
"*",
"modules",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"types",
".",
"ModuleType",
"]",
",",
"recursive",
":",
"bool",
"=",
"False",
",",
"force",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"out",
"=",
"[",
"... | Checks the specified module or modules for changes and reloads them if
they have been changed since the module was first imported or last
refreshed.
:param modules:
One or more module objects that should be refreshed if they the
currently loaded versions are out of date. The package name for
modules can also be used.
:param recursive:
When true, any imported sub-modules of this module will also be
refreshed if they have been updated.
:param force:
When true, all modules will be refreshed even if it doesn't appear
that they have been updated.
:return:
True or False depending on whether any modules were refreshed by this
call. | [
"Checks",
"the",
"specified",
"module",
"or",
"modules",
"for",
"changes",
"and",
"reloads",
"them",
"if",
"they",
"have",
"been",
"changed",
"since",
"the",
"module",
"was",
"first",
"imported",
"or",
"last",
"refreshed",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L146-L175 | train | 44,588 |
sernst/cauldron | cauldron/docgen/params.py | get_arg_names | def get_arg_names(target) -> typing.List[str]:
"""
Gets the list of named arguments for the target function
:param target:
Function for which the argument names will be retrieved
"""
code = getattr(target, '__code__')
if code is None:
return []
arg_count = code.co_argcount
kwarg_count = code.co_kwonlyargcount
args_index = get_args_index(target)
kwargs_index = get_kwargs_index(target)
arg_names = list(code.co_varnames[:arg_count])
if args_index != -1:
arg_names.append(code.co_varnames[args_index])
arg_names += list(code.co_varnames[arg_count:(arg_count + kwarg_count)])
if kwargs_index != -1:
arg_names.append(code.co_varnames[kwargs_index])
if len(arg_names) > 0 and arg_names[0] in ['self', 'cls']:
arg_count -= 1
arg_names.pop(0)
return arg_names | python | def get_arg_names(target) -> typing.List[str]:
"""
Gets the list of named arguments for the target function
:param target:
Function for which the argument names will be retrieved
"""
code = getattr(target, '__code__')
if code is None:
return []
arg_count = code.co_argcount
kwarg_count = code.co_kwonlyargcount
args_index = get_args_index(target)
kwargs_index = get_kwargs_index(target)
arg_names = list(code.co_varnames[:arg_count])
if args_index != -1:
arg_names.append(code.co_varnames[args_index])
arg_names += list(code.co_varnames[arg_count:(arg_count + kwarg_count)])
if kwargs_index != -1:
arg_names.append(code.co_varnames[kwargs_index])
if len(arg_names) > 0 and arg_names[0] in ['self', 'cls']:
arg_count -= 1
arg_names.pop(0)
return arg_names | [
"def",
"get_arg_names",
"(",
"target",
")",
"->",
"typing",
".",
"List",
"[",
"str",
"]",
":",
"code",
"=",
"getattr",
"(",
"target",
",",
"'__code__'",
")",
"if",
"code",
"is",
"None",
":",
"return",
"[",
"]",
"arg_count",
"=",
"code",
".",
"co_argc... | Gets the list of named arguments for the target function
:param target:
Function for which the argument names will be retrieved | [
"Gets",
"the",
"list",
"of",
"named",
"arguments",
"for",
"the",
"target",
"function"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/docgen/params.py#L48-L76 | train | 44,589 |
sernst/cauldron | cauldron/docgen/params.py | create_argument | def create_argument(target, name, description: str = '') -> dict:
"""
Creates a dictionary representation of the parameter
:param target:
The function object in which the parameter resides
:param name:
The name of the parameter
:param description:
The documentation description for the parameter
"""
arg_names = get_arg_names(target)
annotations = getattr(target, '__annotations__', {})
out = dict(
name=name,
index=arg_names.index(name),
description=description,
type=conversions.arg_type_to_string(annotations.get(name, 'Any'))
)
out.update(get_optional_data(target, name, arg_names))
return out | python | def create_argument(target, name, description: str = '') -> dict:
"""
Creates a dictionary representation of the parameter
:param target:
The function object in which the parameter resides
:param name:
The name of the parameter
:param description:
The documentation description for the parameter
"""
arg_names = get_arg_names(target)
annotations = getattr(target, '__annotations__', {})
out = dict(
name=name,
index=arg_names.index(name),
description=description,
type=conversions.arg_type_to_string(annotations.get(name, 'Any'))
)
out.update(get_optional_data(target, name, arg_names))
return out | [
"def",
"create_argument",
"(",
"target",
",",
"name",
",",
"description",
":",
"str",
"=",
"''",
")",
"->",
"dict",
":",
"arg_names",
"=",
"get_arg_names",
"(",
"target",
")",
"annotations",
"=",
"getattr",
"(",
"target",
",",
"'__annotations__'",
",",
"{"... | Creates a dictionary representation of the parameter
:param target:
The function object in which the parameter resides
:param name:
The name of the parameter
:param description:
The documentation description for the parameter | [
"Creates",
"a",
"dictionary",
"representation",
"of",
"the",
"parameter"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/docgen/params.py#L79-L101 | train | 44,590 |
sernst/cauldron | cauldron/docgen/params.py | explode_line | def explode_line(argument_line: str) -> typing.Tuple[str, str]:
"""
Returns a tuple containing the parameter name and the description parsed
from the given argument line
"""
parts = tuple(argument_line.split(' ', 1)[-1].split(':', 1))
return parts if len(parts) > 1 else (parts[0], '') | python | def explode_line(argument_line: str) -> typing.Tuple[str, str]:
"""
Returns a tuple containing the parameter name and the description parsed
from the given argument line
"""
parts = tuple(argument_line.split(' ', 1)[-1].split(':', 1))
return parts if len(parts) > 1 else (parts[0], '') | [
"def",
"explode_line",
"(",
"argument_line",
":",
"str",
")",
"->",
"typing",
".",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"parts",
"=",
"tuple",
"(",
"argument_line",
".",
"split",
"(",
"' '",
",",
"1",
")",
"[",
"-",
"1",
"]",
".",
"split",
... | Returns a tuple containing the parameter name and the description parsed
from the given argument line | [
"Returns",
"a",
"tuple",
"containing",
"the",
"parameter",
"name",
"and",
"the",
"description",
"parsed",
"from",
"the",
"given",
"argument",
"line"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/docgen/params.py#L104-L111 | train | 44,591 |
sernst/cauldron | docker-builder.py | update_base_image | def update_base_image(path: str):
"""Pulls the latest version of the base image"""
with open(path, 'r') as file_handle:
contents = file_handle.read()
regex = re.compile('from\s+(?P<source>[^\s]+)', re.IGNORECASE)
matches = regex.findall(contents)
if not matches:
return None
match = matches[0]
os.system('docker pull {}'.format(match))
return match | python | def update_base_image(path: str):
"""Pulls the latest version of the base image"""
with open(path, 'r') as file_handle:
contents = file_handle.read()
regex = re.compile('from\s+(?P<source>[^\s]+)', re.IGNORECASE)
matches = regex.findall(contents)
if not matches:
return None
match = matches[0]
os.system('docker pull {}'.format(match))
return match | [
"def",
"update_base_image",
"(",
"path",
":",
"str",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"file_handle",
":",
"contents",
"=",
"file_handle",
".",
"read",
"(",
")",
"regex",
"=",
"re",
".",
"compile",
"(",
"'from\\s+(?P<source>[^... | Pulls the latest version of the base image | [
"Pulls",
"the",
"latest",
"version",
"of",
"the",
"base",
"image"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/docker-builder.py#L19-L32 | train | 44,592 |
sernst/cauldron | docker-builder.py | build | def build(path: str) -> dict:
"""Builds the container from the specified docker file path"""
update_base_image(path)
match = file_pattern.search(os.path.basename(path))
build_id = match.group('id')
tags = [
'{}:{}-{}'.format(HUB_PREFIX, version, build_id),
'{}:latest-{}'.format(HUB_PREFIX, build_id),
'{}:current-{}'.format(HUB_PREFIX, build_id)
]
if build_id == 'standard':
tags.append('{}:latest'.format(HUB_PREFIX))
command = 'docker build --file "{}" {} .'.format(
path,
' '.join(['-t {}'.format(t) for t in tags])
)
print('[BUILDING]:', build_id)
os.system(command)
return dict(
id=build_id,
path=path,
command=command,
tags=tags
) | python | def build(path: str) -> dict:
"""Builds the container from the specified docker file path"""
update_base_image(path)
match = file_pattern.search(os.path.basename(path))
build_id = match.group('id')
tags = [
'{}:{}-{}'.format(HUB_PREFIX, version, build_id),
'{}:latest-{}'.format(HUB_PREFIX, build_id),
'{}:current-{}'.format(HUB_PREFIX, build_id)
]
if build_id == 'standard':
tags.append('{}:latest'.format(HUB_PREFIX))
command = 'docker build --file "{}" {} .'.format(
path,
' '.join(['-t {}'.format(t) for t in tags])
)
print('[BUILDING]:', build_id)
os.system(command)
return dict(
id=build_id,
path=path,
command=command,
tags=tags
) | [
"def",
"build",
"(",
"path",
":",
"str",
")",
"->",
"dict",
":",
"update_base_image",
"(",
"path",
")",
"match",
"=",
"file_pattern",
".",
"search",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"build_id",
"=",
"match",
".",
"group... | Builds the container from the specified docker file path | [
"Builds",
"the",
"container",
"from",
"the",
"specified",
"docker",
"file",
"path"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/docker-builder.py#L35-L61 | train | 44,593 |
sernst/cauldron | docker-builder.py | publish | def publish(build_entry: dict):
"""Publishes the specified build entry to docker hub"""
for tag in build_entry['tags']:
print('[PUSHING]:', tag)
os.system('docker push {}'.format(tag)) | python | def publish(build_entry: dict):
"""Publishes the specified build entry to docker hub"""
for tag in build_entry['tags']:
print('[PUSHING]:', tag)
os.system('docker push {}'.format(tag)) | [
"def",
"publish",
"(",
"build_entry",
":",
"dict",
")",
":",
"for",
"tag",
"in",
"build_entry",
"[",
"'tags'",
"]",
":",
"print",
"(",
"'[PUSHING]:'",
",",
"tag",
")",
"os",
".",
"system",
"(",
"'docker push {}'",
".",
"format",
"(",
"tag",
")",
")"
] | Publishes the specified build entry to docker hub | [
"Publishes",
"the",
"specified",
"build",
"entry",
"to",
"docker",
"hub"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/docker-builder.py#L64-L68 | train | 44,594 |
sernst/cauldron | docker-builder.py | run | def run():
"""Execute the build process"""
args = parse()
build_results = [build(p) for p in glob.iglob(glob_path)]
if not args['publish']:
return
for entry in build_results:
publish(entry) | python | def run():
"""Execute the build process"""
args = parse()
build_results = [build(p) for p in glob.iglob(glob_path)]
if not args['publish']:
return
for entry in build_results:
publish(entry) | [
"def",
"run",
"(",
")",
":",
"args",
"=",
"parse",
"(",
")",
"build_results",
"=",
"[",
"build",
"(",
"p",
")",
"for",
"p",
"in",
"glob",
".",
"iglob",
"(",
"glob_path",
")",
"]",
"if",
"not",
"args",
"[",
"'publish'",
"]",
":",
"return",
"for",
... | Execute the build process | [
"Execute",
"the",
"build",
"process"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/docker-builder.py#L78-L87 | train | 44,595 |
sernst/cauldron | cauldron/render/__init__.py | elapsed_time | def elapsed_time(seconds: float) -> str:
"""Displays the elapsed time since the current step started running."""
environ.abort_thread()
parts = (
'{}'.format(timedelta(seconds=seconds))
.rsplit('.', 1)
)
hours, minutes, seconds = parts[0].split(':')
return templating.render_template(
'elapsed_time.html',
hours=hours.zfill(2),
minutes=minutes.zfill(2),
seconds=seconds.zfill(2),
microseconds=parts[-1] if len(parts) > 1 else ''
) | python | def elapsed_time(seconds: float) -> str:
"""Displays the elapsed time since the current step started running."""
environ.abort_thread()
parts = (
'{}'.format(timedelta(seconds=seconds))
.rsplit('.', 1)
)
hours, minutes, seconds = parts[0].split(':')
return templating.render_template(
'elapsed_time.html',
hours=hours.zfill(2),
minutes=minutes.zfill(2),
seconds=seconds.zfill(2),
microseconds=parts[-1] if len(parts) > 1 else ''
) | [
"def",
"elapsed_time",
"(",
"seconds",
":",
"float",
")",
"->",
"str",
":",
"environ",
".",
"abort_thread",
"(",
")",
"parts",
"=",
"(",
"'{}'",
".",
"format",
"(",
"timedelta",
"(",
"seconds",
"=",
"seconds",
")",
")",
".",
"rsplit",
"(",
"'.'",
","... | Displays the elapsed time since the current step started running. | [
"Displays",
"the",
"elapsed",
"time",
"since",
"the",
"current",
"step",
"started",
"running",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/render/__init__.py#L18-L32 | train | 44,596 |
sernst/cauldron | cauldron/render/__init__.py | image | def image(
rendered_path: str,
width: int = None,
height: int = None,
justify: str = None
) -> str:
"""Renders an image block"""
environ.abort_thread()
return templating.render_template(
'image.html',
path=rendered_path,
width=width,
height=height,
justification=(justify or 'left').lower()
) | python | def image(
rendered_path: str,
width: int = None,
height: int = None,
justify: str = None
) -> str:
"""Renders an image block"""
environ.abort_thread()
return templating.render_template(
'image.html',
path=rendered_path,
width=width,
height=height,
justification=(justify or 'left').lower()
) | [
"def",
"image",
"(",
"rendered_path",
":",
"str",
",",
"width",
":",
"int",
"=",
"None",
",",
"height",
":",
"int",
"=",
"None",
",",
"justify",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"environ",
".",
"abort_thread",
"(",
")",
"return",
"te... | Renders an image block | [
"Renders",
"an",
"image",
"block"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/render/__init__.py#L229-L243 | train | 44,597 |
sernst/cauldron | cauldron/__init__.py | get_environment_info | def get_environment_info() -> dict:
"""
Information about Cauldron and its Python interpreter.
:return:
A dictionary containing information about the Cauldron and its
Python environment. This information is useful when providing feedback
and bug reports.
"""
data = _environ.systems.get_system_data()
data['cauldron'] = _environ.package_settings.copy()
return data | python | def get_environment_info() -> dict:
"""
Information about Cauldron and its Python interpreter.
:return:
A dictionary containing information about the Cauldron and its
Python environment. This information is useful when providing feedback
and bug reports.
"""
data = _environ.systems.get_system_data()
data['cauldron'] = _environ.package_settings.copy()
return data | [
"def",
"get_environment_info",
"(",
")",
"->",
"dict",
":",
"data",
"=",
"_environ",
".",
"systems",
".",
"get_system_data",
"(",
")",
"data",
"[",
"'cauldron'",
"]",
"=",
"_environ",
".",
"package_settings",
".",
"copy",
"(",
")",
"return",
"data"
] | Information about Cauldron and its Python interpreter.
:return:
A dictionary containing information about the Cauldron and its
Python environment. This information is useful when providing feedback
and bug reports. | [
"Information",
"about",
"Cauldron",
"and",
"its",
"Python",
"interpreter",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/__init__.py#L24-L35 | train | 44,598 |
sernst/cauldron | cauldron/__init__.py | run_server | def run_server(port=5010, debug=False, **kwargs):
"""
Run the cauldron http server used to interact with cauldron from a remote
host.
:param port:
The port on which to bind the cauldron server.
:param debug:
Whether or not the server should be run in debug mode. If true, the
server will echo debugging information during operation.
:param kwargs:
Custom properties to alter the way the server runs.
"""
from cauldron.cli.server import run
run.execute(port=port, debug=debug, **kwargs) | python | def run_server(port=5010, debug=False, **kwargs):
"""
Run the cauldron http server used to interact with cauldron from a remote
host.
:param port:
The port on which to bind the cauldron server.
:param debug:
Whether or not the server should be run in debug mode. If true, the
server will echo debugging information during operation.
:param kwargs:
Custom properties to alter the way the server runs.
"""
from cauldron.cli.server import run
run.execute(port=port, debug=debug, **kwargs) | [
"def",
"run_server",
"(",
"port",
"=",
"5010",
",",
"debug",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"cauldron",
".",
"cli",
".",
"server",
"import",
"run",
"run",
".",
"execute",
"(",
"port",
"=",
"port",
",",
"debug",
"=",
"debug... | Run the cauldron http server used to interact with cauldron from a remote
host.
:param port:
The port on which to bind the cauldron server.
:param debug:
Whether or not the server should be run in debug mode. If true, the
server will echo debugging information during operation.
:param kwargs:
Custom properties to alter the way the server runs. | [
"Run",
"the",
"cauldron",
"http",
"server",
"used",
"to",
"interact",
"with",
"cauldron",
"from",
"a",
"remote",
"host",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/__init__.py#L44-L58 | train | 44,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.