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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
sernst/cauldron | cauldron/session/exposed.py | ExposedStep.render_to_console | def render_to_console(self, message: str, **kwargs):
"""
Renders the specified message to the console using Jinja2 template
rendering with the kwargs as render variables. The message will also
be dedented prior to rendering in the same fashion as other Cauldron
template rendering actions.
:param message:
Template string to be rendered.
:param kwargs:
Variables to be used in rendering the template.
"""
rendered = templating.render(message, **kwargs)
return self.write_to_console(rendered) | python | def render_to_console(self, message: str, **kwargs):
"""
Renders the specified message to the console using Jinja2 template
rendering with the kwargs as render variables. The message will also
be dedented prior to rendering in the same fashion as other Cauldron
template rendering actions.
:param message:
Template string to be rendered.
:param kwargs:
Variables to be used in rendering the template.
"""
rendered = templating.render(message, **kwargs)
return self.write_to_console(rendered) | [
"def",
"render_to_console",
"(",
"self",
",",
"message",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
":",
"rendered",
"=",
"templating",
".",
"render",
"(",
"message",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"write_to_console",
"(",
"rendered"... | Renders the specified message to the console using Jinja2 template
rendering with the kwargs as render variables. The message will also
be dedented prior to rendering in the same fashion as other Cauldron
template rendering actions.
:param message:
Template string to be rendered.
:param kwargs:
Variables to be used in rendering the template. | [
"Renders",
"the",
"specified",
"message",
"to",
"the",
"console",
"using",
"Jinja2",
"template",
"rendering",
"with",
"the",
"kwargs",
"as",
"render",
"variables",
".",
"The",
"message",
"will",
"also",
"be",
"dedented",
"prior",
"to",
"rendering",
"in",
"the"... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L267-L280 | train | 44,700 |
sernst/cauldron | cauldron/session/report.py | Report.last_update_time | def last_update_time(self) -> float:
"""The last time at which the report was modified."""
stdout = self.stdout_interceptor
stderr = self.stderr_interceptor
return max([
self._last_update_time,
stdout.last_write_time if stdout else 0,
stderr.last_write_time if stderr else 0,
]) | python | def last_update_time(self) -> float:
"""The last time at which the report was modified."""
stdout = self.stdout_interceptor
stderr = self.stderr_interceptor
return max([
self._last_update_time,
stdout.last_write_time if stdout else 0,
stderr.last_write_time if stderr else 0,
]) | [
"def",
"last_update_time",
"(",
"self",
")",
"->",
"float",
":",
"stdout",
"=",
"self",
".",
"stdout_interceptor",
"stderr",
"=",
"self",
".",
"stderr_interceptor",
"return",
"max",
"(",
"[",
"self",
".",
"_last_update_time",
",",
"stdout",
".",
"last_write_ti... | The last time at which the report was modified. | [
"The",
"last",
"time",
"at",
"which",
"the",
"report",
"was",
"modified",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/report.py#L38-L47 | train | 44,701 |
sernst/cauldron | cauldron/session/report.py | Report.results_cache_path | def results_cache_path(self) -> str:
"""
Location where step report is cached between sessions to
prevent loss of display data between runs.
"""
if not self.project:
return ''
return os.path.join(
self.project.results_path,
'.cache',
'steps',
'{}.json'.format(self.id)
) | python | def results_cache_path(self) -> str:
"""
Location where step report is cached between sessions to
prevent loss of display data between runs.
"""
if not self.project:
return ''
return os.path.join(
self.project.results_path,
'.cache',
'steps',
'{}.json'.format(self.id)
) | [
"def",
"results_cache_path",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"project",
":",
"return",
"''",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project",
".",
"results_path",
",",
"'.cache'",
",",
"'steps'",
",",... | Location where step report is cached between sessions to
prevent loss of display data between runs. | [
"Location",
"where",
"step",
"report",
"is",
"cached",
"between",
"sessions",
"to",
"prevent",
"loss",
"of",
"display",
"data",
"between",
"runs",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/report.py#L58-L70 | train | 44,702 |
sernst/cauldron | cauldron/session/report.py | Report.clear | def clear(self) -> 'Report':
"""
Clear all user-data stored in this instance and reset it to its
originally loaded state
:return:
The instance that was called for method chaining
"""
self.body = []
self.data = SharedCache()
self.files = SharedCache()
self._last_update_time = time.time()
return self | python | def clear(self) -> 'Report':
"""
Clear all user-data stored in this instance and reset it to its
originally loaded state
:return:
The instance that was called for method chaining
"""
self.body = []
self.data = SharedCache()
self.files = SharedCache()
self._last_update_time = time.time()
return self | [
"def",
"clear",
"(",
"self",
")",
"->",
"'Report'",
":",
"self",
".",
"body",
"=",
"[",
"]",
"self",
".",
"data",
"=",
"SharedCache",
"(",
")",
"self",
".",
"files",
"=",
"SharedCache",
"(",
")",
"self",
".",
"_last_update_time",
"=",
"time",
".",
... | Clear all user-data stored in this instance and reset it to its
originally loaded state
:return:
The instance that was called for method chaining | [
"Clear",
"all",
"user",
"-",
"data",
"stored",
"in",
"this",
"instance",
"and",
"reset",
"it",
"to",
"its",
"originally",
"loaded",
"state"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/report.py#L82-L94 | train | 44,703 |
sernst/cauldron | cauldron/session/report.py | Report.append_body | def append_body(self, dom: str):
"""
Appends the specified HTML-formatted DOM string to the
currently stored report body for the step.
"""
self.flush_stdout()
self.body.append(dom)
self._last_update_time = time.time() | python | def append_body(self, dom: str):
"""
Appends the specified HTML-formatted DOM string to the
currently stored report body for the step.
"""
self.flush_stdout()
self.body.append(dom)
self._last_update_time = time.time() | [
"def",
"append_body",
"(",
"self",
",",
"dom",
":",
"str",
")",
":",
"self",
".",
"flush_stdout",
"(",
")",
"self",
".",
"body",
".",
"append",
"(",
"dom",
")",
"self",
".",
"_last_update_time",
"=",
"time",
".",
"time",
"(",
")"
] | Appends the specified HTML-formatted DOM string to the
currently stored report body for the step. | [
"Appends",
"the",
"specified",
"HTML",
"-",
"formatted",
"DOM",
"string",
"to",
"the",
"currently",
"stored",
"report",
"body",
"for",
"the",
"step",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/report.py#L96-L103 | train | 44,704 |
sernst/cauldron | cauldron/session/report.py | Report.flush_stdout | def flush_stdout(self):
"""
Empties the standard out redirect buffer and renders the
contents to the body as a preformatted text box.
"""
try:
contents = self.stdout_interceptor.flush_all()
except Exception:
return
if len(contents) > 0:
self.body.append(render_texts.preformatted_text(contents))
self._last_update_time = time.time()
return contents | python | def flush_stdout(self):
"""
Empties the standard out redirect buffer and renders the
contents to the body as a preformatted text box.
"""
try:
contents = self.stdout_interceptor.flush_all()
except Exception:
return
if len(contents) > 0:
self.body.append(render_texts.preformatted_text(contents))
self._last_update_time = time.time()
return contents | [
"def",
"flush_stdout",
"(",
"self",
")",
":",
"try",
":",
"contents",
"=",
"self",
".",
"stdout_interceptor",
".",
"flush_all",
"(",
")",
"except",
"Exception",
":",
"return",
"if",
"len",
"(",
"contents",
")",
">",
"0",
":",
"self",
".",
"body",
".",
... | Empties the standard out redirect buffer and renders the
contents to the body as a preformatted text box. | [
"Empties",
"the",
"standard",
"out",
"redirect",
"buffer",
"and",
"renders",
"the",
"contents",
"to",
"the",
"body",
"as",
"a",
"preformatted",
"text",
"box",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/report.py#L122-L136 | train | 44,705 |
seomoz/qless-py | qless/util.py | import_class | def import_class(klass):
'''Import the named class and return that class'''
mod = __import__(klass.rpartition('.')[0])
for segment in klass.split('.')[1:-1]:
mod = getattr(mod, segment)
return getattr(mod, klass.rpartition('.')[2]) | python | def import_class(klass):
'''Import the named class and return that class'''
mod = __import__(klass.rpartition('.')[0])
for segment in klass.split('.')[1:-1]:
mod = getattr(mod, segment)
return getattr(mod, klass.rpartition('.')[2]) | [
"def",
"import_class",
"(",
"klass",
")",
":",
"mod",
"=",
"__import__",
"(",
"klass",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"for",
"segment",
"in",
"klass",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"-",
"1",
"]",
":",
"m... | Import the named class and return that class | [
"Import",
"the",
"named",
"class",
"and",
"return",
"that",
"class"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/util.py#L4-L9 | train | 44,706 |
sernst/cauldron | cauldron/session/writing/components/project_component.py | create | def create(
project: 'projects.Project',
include_path: str
) -> COMPONENT:
"""
Creates a COMPONENT instance for the project component specified by the
include path
:param project:
The project in which the component resides
:param include_path:
The relative path within the project where the component resides
:return:
The created COMPONENT instance
"""
source_path = environ.paths.clean(
os.path.join(project.source_directory, include_path)
)
if not os.path.exists(source_path):
return COMPONENT([], [])
if os.path.isdir(source_path):
glob_path = os.path.join(source_path, '**', '*')
include_paths = glob.iglob(glob_path, recursive=True)
else:
include_paths = [source_path]
destination_path = os.path.join(project.output_directory, include_path)
return COMPONENT(
includes=filter(
lambda web_include: web_include is not None,
map(functools.partial(to_web_include, project), include_paths)
),
files=[file_io.FILE_COPY_ENTRY(
source=source_path,
destination=destination_path
)]
) | python | def create(
project: 'projects.Project',
include_path: str
) -> COMPONENT:
"""
Creates a COMPONENT instance for the project component specified by the
include path
:param project:
The project in which the component resides
:param include_path:
The relative path within the project where the component resides
:return:
The created COMPONENT instance
"""
source_path = environ.paths.clean(
os.path.join(project.source_directory, include_path)
)
if not os.path.exists(source_path):
return COMPONENT([], [])
if os.path.isdir(source_path):
glob_path = os.path.join(source_path, '**', '*')
include_paths = glob.iglob(glob_path, recursive=True)
else:
include_paths = [source_path]
destination_path = os.path.join(project.output_directory, include_path)
return COMPONENT(
includes=filter(
lambda web_include: web_include is not None,
map(functools.partial(to_web_include, project), include_paths)
),
files=[file_io.FILE_COPY_ENTRY(
source=source_path,
destination=destination_path
)]
) | [
"def",
"create",
"(",
"project",
":",
"'projects.Project'",
",",
"include_path",
":",
"str",
")",
"->",
"COMPONENT",
":",
"source_path",
"=",
"environ",
".",
"paths",
".",
"clean",
"(",
"os",
".",
"path",
".",
"join",
"(",
"project",
".",
"source_directory... | Creates a COMPONENT instance for the project component specified by the
include path
:param project:
The project in which the component resides
:param include_path:
The relative path within the project where the component resides
:return:
The created COMPONENT instance | [
"Creates",
"a",
"COMPONENT",
"instance",
"for",
"the",
"project",
"component",
"specified",
"by",
"the",
"include",
"path"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/project_component.py#L14-L53 | train | 44,707 |
sernst/cauldron | cauldron/session/writing/components/project_component.py | create_many | def create_many(
project: 'projects.Project',
include_paths: typing.List[str]
) -> COMPONENT:
"""
Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of relative paths within the project directory to files or
directories that should be included in the project
:return:
The combined COMPONENT instance for all of the included paths
"""
return definitions.merge_components(*map(
functools.partial(create, project),
include_paths
)) | python | def create_many(
project: 'projects.Project',
include_paths: typing.List[str]
) -> COMPONENT:
"""
Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of relative paths within the project directory to files or
directories that should be included in the project
:return:
The combined COMPONENT instance for all of the included paths
"""
return definitions.merge_components(*map(
functools.partial(create, project),
include_paths
)) | [
"def",
"create_many",
"(",
"project",
":",
"'projects.Project'",
",",
"include_paths",
":",
"typing",
".",
"List",
"[",
"str",
"]",
")",
"->",
"COMPONENT",
":",
"return",
"definitions",
".",
"merge_components",
"(",
"*",
"map",
"(",
"functools",
".",
"partia... | Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of relative paths within the project directory to files or
directories that should be included in the project
:return:
The combined COMPONENT instance for all of the included paths | [
"Creates",
"a",
"single",
"COMPONENT",
"instance",
"for",
"all",
"of",
"the",
"specified",
"project",
"include",
"paths"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/project_component.py#L56-L76 | train | 44,708 |
sernst/cauldron | cauldron/session/writing/components/project_component.py | to_web_include | def to_web_include(
project: 'projects.Project',
file_path: str
) -> WEB_INCLUDE:
"""
Converts the given file_path into a WEB_INCLUDE instance that represents
the deployed version of this file to be loaded into the results project
page
:param project:
Project in which the file_path resides
:param file_path:
Absolute path to the source file for which the WEB_INCLUDE instance
will be created
:return:
The WEB_INCLUDE instance that represents the given source file
"""
if not file_path.endswith('.css') and not file_path.endswith('.js'):
return None
slug = file_path[len(project.source_directory):]
url = '/{}' \
.format(slug) \
.replace('\\', '/') \
.replace('//', '/')
return WEB_INCLUDE(name=':project:{}'.format(url), src=url) | python | def to_web_include(
project: 'projects.Project',
file_path: str
) -> WEB_INCLUDE:
"""
Converts the given file_path into a WEB_INCLUDE instance that represents
the deployed version of this file to be loaded into the results project
page
:param project:
Project in which the file_path resides
:param file_path:
Absolute path to the source file for which the WEB_INCLUDE instance
will be created
:return:
The WEB_INCLUDE instance that represents the given source file
"""
if not file_path.endswith('.css') and not file_path.endswith('.js'):
return None
slug = file_path[len(project.source_directory):]
url = '/{}' \
.format(slug) \
.replace('\\', '/') \
.replace('//', '/')
return WEB_INCLUDE(name=':project:{}'.format(url), src=url) | [
"def",
"to_web_include",
"(",
"project",
":",
"'projects.Project'",
",",
"file_path",
":",
"str",
")",
"->",
"WEB_INCLUDE",
":",
"if",
"not",
"file_path",
".",
"endswith",
"(",
"'.css'",
")",
"and",
"not",
"file_path",
".",
"endswith",
"(",
"'.js'",
")",
"... | Converts the given file_path into a WEB_INCLUDE instance that represents
the deployed version of this file to be loaded into the results project
page
:param project:
Project in which the file_path resides
:param file_path:
Absolute path to the source file for which the WEB_INCLUDE instance
will be created
:return:
The WEB_INCLUDE instance that represents the given source file | [
"Converts",
"the",
"given",
"file_path",
"into",
"a",
"WEB_INCLUDE",
"instance",
"that",
"represents",
"the",
"deployed",
"version",
"of",
"this",
"file",
"to",
"be",
"loaded",
"into",
"the",
"results",
"project",
"page"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/project_component.py#L79-L106 | train | 44,709 |
sernst/cauldron | cauldron/cli/__init__.py | reformat | def reformat(source: str) -> str:
"""
Formats the source string to strip newlines on both ends and dedents the
the entire string
:param source:
The string to reformat
"""
value = source if source else ''
return dedent(value.strip('\n')).strip() | python | def reformat(source: str) -> str:
"""
Formats the source string to strip newlines on both ends and dedents the
the entire string
:param source:
The string to reformat
"""
value = source if source else ''
return dedent(value.strip('\n')).strip() | [
"def",
"reformat",
"(",
"source",
":",
"str",
")",
"->",
"str",
":",
"value",
"=",
"source",
"if",
"source",
"else",
"''",
"return",
"dedent",
"(",
"value",
".",
"strip",
"(",
"'\\n'",
")",
")",
".",
"strip",
"(",
")"
] | Formats the source string to strip newlines on both ends and dedents the
the entire string
:param source:
The string to reformat | [
"Formats",
"the",
"source",
"string",
"to",
"strip",
"newlines",
"on",
"both",
"ends",
"and",
"dedents",
"the",
"the",
"entire",
"string"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/__init__.py#L53-L63 | train | 44,710 |
sernst/cauldron | cauldron/templating.py | get_environment | def get_environment() -> Environment:
"""
Returns the jinja2 templating environment updated with the most recent
cauldron environment configurations
:return:
"""
env = JINJA_ENVIRONMENT
loader = env.loader
resource_path = environ.configs.make_path(
'resources', 'templates',
override_key='template_path'
)
if not loader:
env.filters['id'] = get_id
env.filters['latex'] = get_latex
if not loader or resource_path not in loader.searchpath:
env.loader = FileSystemLoader(resource_path)
return env | python | def get_environment() -> Environment:
"""
Returns the jinja2 templating environment updated with the most recent
cauldron environment configurations
:return:
"""
env = JINJA_ENVIRONMENT
loader = env.loader
resource_path = environ.configs.make_path(
'resources', 'templates',
override_key='template_path'
)
if not loader:
env.filters['id'] = get_id
env.filters['latex'] = get_latex
if not loader or resource_path not in loader.searchpath:
env.loader = FileSystemLoader(resource_path)
return env | [
"def",
"get_environment",
"(",
")",
"->",
"Environment",
":",
"env",
"=",
"JINJA_ENVIRONMENT",
"loader",
"=",
"env",
".",
"loader",
"resource_path",
"=",
"environ",
".",
"configs",
".",
"make_path",
"(",
"'resources'",
",",
"'templates'",
",",
"override_key",
... | Returns the jinja2 templating environment updated with the most recent
cauldron environment configurations
:return: | [
"Returns",
"the",
"jinja2",
"templating",
"environment",
"updated",
"with",
"the",
"most",
"recent",
"cauldron",
"environment",
"configurations"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/templating.py#L77-L100 | train | 44,711 |
sernst/cauldron | cauldron/templating.py | render | def render(template: typing.Union[str, Template], **kwargs):
"""
Renders a template string using Jinja2 and the Cauldron templating
environment.
:param template:
The string containing the template to be rendered
:param kwargs:
Any named arguments to pass to Jinja2 for use in rendering
:return:
The rendered template string
"""
if not hasattr(template, 'render'):
template = get_environment().from_string(textwrap.dedent(template))
return template.render(
cauldron_template_uid=make_template_uid(),
**kwargs
) | python | def render(template: typing.Union[str, Template], **kwargs):
"""
Renders a template string using Jinja2 and the Cauldron templating
environment.
:param template:
The string containing the template to be rendered
:param kwargs:
Any named arguments to pass to Jinja2 for use in rendering
:return:
The rendered template string
"""
if not hasattr(template, 'render'):
template = get_environment().from_string(textwrap.dedent(template))
return template.render(
cauldron_template_uid=make_template_uid(),
**kwargs
) | [
"def",
"render",
"(",
"template",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"Template",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"template",
",",
"'render'",
")",
":",
"template",
"=",
"get_environment",
"(",
")",
".",... | Renders a template string using Jinja2 and the Cauldron templating
environment.
:param template:
The string containing the template to be rendered
:param kwargs:
Any named arguments to pass to Jinja2 for use in rendering
:return:
The rendered template string | [
"Renders",
"a",
"template",
"string",
"using",
"Jinja2",
"and",
"the",
"Cauldron",
"templating",
"environment",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/templating.py#L103-L122 | train | 44,712 |
sernst/cauldron | cauldron/templating.py | render_file | def render_file(path: str, **kwargs):
"""
Renders a file at the specified absolute path. The file can reside
anywhere on the local disk as Cauldron's template environment path
searching is ignored.
:param path:
Absolute path to a template file to render
:param kwargs:
Named arguments that should be passed to Jinja2 for rendering
:return:
The rendered template string
"""
with open(path, 'r') as f:
contents = f.read()
return get_environment().from_string(contents).render(
cauldron_template_uid=make_template_uid(),
**kwargs
) | python | def render_file(path: str, **kwargs):
"""
Renders a file at the specified absolute path. The file can reside
anywhere on the local disk as Cauldron's template environment path
searching is ignored.
:param path:
Absolute path to a template file to render
:param kwargs:
Named arguments that should be passed to Jinja2 for rendering
:return:
The rendered template string
"""
with open(path, 'r') as f:
contents = f.read()
return get_environment().from_string(contents).render(
cauldron_template_uid=make_template_uid(),
**kwargs
) | [
"def",
"render_file",
"(",
"path",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"return",
"get_environment",
"(",
")",
".",
"from_string",
... | Renders a file at the specified absolute path. The file can reside
anywhere on the local disk as Cauldron's template environment path
searching is ignored.
:param path:
Absolute path to a template file to render
:param kwargs:
Named arguments that should be passed to Jinja2 for rendering
:return:
The rendered template string | [
"Renders",
"a",
"file",
"at",
"the",
"specified",
"absolute",
"path",
".",
"The",
"file",
"can",
"reside",
"anywhere",
"on",
"the",
"local",
"disk",
"as",
"Cauldron",
"s",
"template",
"environment",
"path",
"searching",
"is",
"ignored",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/templating.py#L125-L145 | train | 44,713 |
sernst/cauldron | cauldron/templating.py | render_template | def render_template(template_name: str, **kwargs):
"""
Renders the template file with the given filename from within Cauldron's
template environment folder.
:param template_name:
The filename of the template to render. Any path elements should be
relative to Cauldron's root template folder.
:param kwargs:
Any elements passed to Jinja2 for rendering the template
:return:
The rendered string
"""
return get_environment().get_template(template_name).render(
cauldron_template_uid=make_template_uid(),
**kwargs
) | python | def render_template(template_name: str, **kwargs):
"""
Renders the template file with the given filename from within Cauldron's
template environment folder.
:param template_name:
The filename of the template to render. Any path elements should be
relative to Cauldron's root template folder.
:param kwargs:
Any elements passed to Jinja2 for rendering the template
:return:
The rendered string
"""
return get_environment().get_template(template_name).render(
cauldron_template_uid=make_template_uid(),
**kwargs
) | [
"def",
"render_template",
"(",
"template_name",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"get_environment",
"(",
")",
".",
"get_template",
"(",
"template_name",
")",
".",
"render",
"(",
"cauldron_template_uid",
"=",
"make_template_uid",
"(",
")... | Renders the template file with the given filename from within Cauldron's
template environment folder.
:param template_name:
The filename of the template to render. Any path elements should be
relative to Cauldron's root template folder.
:param kwargs:
Any elements passed to Jinja2 for rendering the template
:return:
The rendered string | [
"Renders",
"the",
"template",
"file",
"with",
"the",
"given",
"filename",
"from",
"within",
"Cauldron",
"s",
"template",
"environment",
"folder",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/templating.py#L148-L165 | train | 44,714 |
sernst/cauldron | cauldron/environ/paths.py | clean | def clean(path: str) -> str:
"""
Cleans the specified path by expanding shorthand elements, redirecting to
the real path for symbolic links, and removing any relative components to
return a complete, absolute path to the specified location.
:param path:
The source path to be cleaned
"""
if not path or path == '.':
path = os.curdir
if path.startswith('~'):
path = os.path.expanduser(path)
return os.path.realpath(os.path.abspath(path)) | python | def clean(path: str) -> str:
"""
Cleans the specified path by expanding shorthand elements, redirecting to
the real path for symbolic links, and removing any relative components to
return a complete, absolute path to the specified location.
:param path:
The source path to be cleaned
"""
if not path or path == '.':
path = os.curdir
if path.startswith('~'):
path = os.path.expanduser(path)
return os.path.realpath(os.path.abspath(path)) | [
"def",
"clean",
"(",
"path",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"path",
"or",
"path",
"==",
"'.'",
":",
"path",
"=",
"os",
".",
"curdir",
"if",
"path",
".",
"startswith",
"(",
"'~'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
... | Cleans the specified path by expanding shorthand elements, redirecting to
the real path for symbolic links, and removing any relative components to
return a complete, absolute path to the specified location.
:param path:
The source path to be cleaned | [
"Cleans",
"the",
"specified",
"path",
"by",
"expanding",
"shorthand",
"elements",
"redirecting",
"to",
"the",
"real",
"path",
"for",
"symbolic",
"links",
"and",
"removing",
"any",
"relative",
"components",
"to",
"return",
"a",
"complete",
"absolute",
"path",
"to... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/paths.py#L10-L26 | train | 44,715 |
sernst/cauldron | cauldron/environ/paths.py | package | def package(*args: str) -> str:
"""
Creates an absolute path to a file or folder within the cauldron package
using the relative path elements specified by the args.
:param args:
Zero or more relative path elements that describe a file or folder
within the reporting
"""
return clean(os.path.join(os.path.dirname(__file__), '..', *args)) | python | def package(*args: str) -> str:
"""
Creates an absolute path to a file or folder within the cauldron package
using the relative path elements specified by the args.
:param args:
Zero or more relative path elements that describe a file or folder
within the reporting
"""
return clean(os.path.join(os.path.dirname(__file__), '..', *args)) | [
"def",
"package",
"(",
"*",
"args",
":",
"str",
")",
"->",
"str",
":",
"return",
"clean",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'..'",
",",
"*",
"args",
")",
")"
] | Creates an absolute path to a file or folder within the cauldron package
using the relative path elements specified by the args.
:param args:
Zero or more relative path elements that describe a file or folder
within the reporting | [
"Creates",
"an",
"absolute",
"path",
"to",
"a",
"file",
"or",
"folder",
"within",
"the",
"cauldron",
"package",
"using",
"the",
"relative",
"path",
"elements",
"specified",
"by",
"the",
"args",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/paths.py#L29-L39 | train | 44,716 |
sernst/cauldron | cauldron/cli/interaction/query.py | confirm | def confirm(question: str, default: bool = True) -> bool:
"""
Requests confirmation of the specified question and returns that result
:param question:
The question to print to the console for the confirmation
:param default:
The default value if the user hits enter without entering a value
"""
result = input('{question} [{yes}/{no}]:'.format(
question=question,
yes='(Y)' if default else 'Y',
no='N' if default else '(N)'
))
if not result:
return default
if result[0].lower() in ['y', 't', '1']:
return True
return False | python | def confirm(question: str, default: bool = True) -> bool:
"""
Requests confirmation of the specified question and returns that result
:param question:
The question to print to the console for the confirmation
:param default:
The default value if the user hits enter without entering a value
"""
result = input('{question} [{yes}/{no}]:'.format(
question=question,
yes='(Y)' if default else 'Y',
no='N' if default else '(N)'
))
if not result:
return default
if result[0].lower() in ['y', 't', '1']:
return True
return False | [
"def",
"confirm",
"(",
"question",
":",
"str",
",",
"default",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"result",
"=",
"input",
"(",
"'{question} [{yes}/{no}]:'",
".",
"format",
"(",
"question",
"=",
"question",
",",
"yes",
"=",
"'(Y)'",
"if",
... | Requests confirmation of the specified question and returns that result
:param question:
The question to print to the console for the confirmation
:param default:
The default value if the user hits enter without entering a value | [
"Requests",
"confirmation",
"of",
"the",
"specified",
"question",
"and",
"returns",
"that",
"result"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/interaction/query.py#L7-L28 | train | 44,717 |
sernst/cauldron | cauldron/cli/commands/open/actions.py | fetch_last | def fetch_last(response: Response) -> typing.Union[str, None]:
""" Returns the last opened project path if such a path exists """
recent_paths = environ.configs.fetch('recent_paths', [])
if len(recent_paths) < 1:
response.fail(
code='NO_RECENT_PROJECTS',
message='No projects have been opened recently'
).console()
return None
return recent_paths[0] | python | def fetch_last(response: Response) -> typing.Union[str, None]:
""" Returns the last opened project path if such a path exists """
recent_paths = environ.configs.fetch('recent_paths', [])
if len(recent_paths) < 1:
response.fail(
code='NO_RECENT_PROJECTS',
message='No projects have been opened recently'
).console()
return None
return recent_paths[0] | [
"def",
"fetch_last",
"(",
"response",
":",
"Response",
")",
"->",
"typing",
".",
"Union",
"[",
"str",
",",
"None",
"]",
":",
"recent_paths",
"=",
"environ",
".",
"configs",
".",
"fetch",
"(",
"'recent_paths'",
",",
"[",
"]",
")",
"if",
"len",
"(",
"r... | Returns the last opened project path if such a path exists | [
"Returns",
"the",
"last",
"opened",
"project",
"path",
"if",
"such",
"a",
"path",
"exists"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commands/open/actions.py#L129-L141 | train | 44,718 |
sernst/cauldron | cauldron/cli/server/routes/synchronize/status.py | of_project | def of_project(project: 'projects.Project') -> dict:
"""
Returns the file status information for every file within the project
source directory and its shared library folders.
:param project:
The project for which the status information should be generated
:return:
A dictionary containing:
- project: the status information for all files within
the projects source directory
- libraries: a list of status information dictionaries for all
files within each of the project's library directories. If a
library resides within the project source directory, the entry
will be an empty dictionary to prevent duplication.
"""
source_directory = project.source_directory
libraries_status = [
{} if d.startswith(source_directory) else of_directory(d)
for d in project.library_directories
]
return dict(
project=of_directory(source_directory),
libraries=libraries_status
) | python | def of_project(project: 'projects.Project') -> dict:
"""
Returns the file status information for every file within the project
source directory and its shared library folders.
:param project:
The project for which the status information should be generated
:return:
A dictionary containing:
- project: the status information for all files within
the projects source directory
- libraries: a list of status information dictionaries for all
files within each of the project's library directories. If a
library resides within the project source directory, the entry
will be an empty dictionary to prevent duplication.
"""
source_directory = project.source_directory
libraries_status = [
{} if d.startswith(source_directory) else of_directory(d)
for d in project.library_directories
]
return dict(
project=of_directory(source_directory),
libraries=libraries_status
) | [
"def",
"of_project",
"(",
"project",
":",
"'projects.Project'",
")",
"->",
"dict",
":",
"source_directory",
"=",
"project",
".",
"source_directory",
"libraries_status",
"=",
"[",
"{",
"}",
"if",
"d",
".",
"startswith",
"(",
"source_directory",
")",
"else",
"of... | Returns the file status information for every file within the project
source directory and its shared library folders.
:param project:
The project for which the status information should be generated
:return:
A dictionary containing:
- project: the status information for all files within
the projects source directory
- libraries: a list of status information dictionaries for all
files within each of the project's library directories. If a
library resides within the project source directory, the entry
will be an empty dictionary to prevent duplication. | [
"Returns",
"the",
"file",
"status",
"information",
"for",
"every",
"file",
"within",
"the",
"project",
"source",
"directory",
"and",
"its",
"shared",
"library",
"folders",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/synchronize/status.py#L7-L33 | train | 44,719 |
sernst/cauldron | cauldron/cli/server/routes/synchronize/status.py | of_file | def of_file(path: str, root_directory: str = None) -> dict:
"""
Returns a dictionary containing status information for the specified file
including when its name relative to the root directory, when it was last
modified and its size.
:param path:
The absolute path to the file for which the status information should
be generated
:param root_directory:
The directory to use for creating relative path names for the returned
status. If this argument is None the path in the status will be the
absolute path argument.
:return:
A dictionary containing the status information for the file at the
specified path. If no such file exists, then the dictionary will
contain -1 values for both the file size and the last modified time.
"""
slug = (
path
if root_directory is None
else path[len(root_directory):].lstrip(os.sep)
)
if not os.path.exists(path) or os.path.isdir(path):
return dict(
size=-1,
modified=-1,
path=slug
)
size = os.path.getsize(path)
modified = max(os.path.getmtime(path), os.path.getctime(path))
return dict(
modified=modified,
path=slug,
size=size
) | python | def of_file(path: str, root_directory: str = None) -> dict:
"""
Returns a dictionary containing status information for the specified file
including when its name relative to the root directory, when it was last
modified and its size.
:param path:
The absolute path to the file for which the status information should
be generated
:param root_directory:
The directory to use for creating relative path names for the returned
status. If this argument is None the path in the status will be the
absolute path argument.
:return:
A dictionary containing the status information for the file at the
specified path. If no such file exists, then the dictionary will
contain -1 values for both the file size and the last modified time.
"""
slug = (
path
if root_directory is None
else path[len(root_directory):].lstrip(os.sep)
)
if not os.path.exists(path) or os.path.isdir(path):
return dict(
size=-1,
modified=-1,
path=slug
)
size = os.path.getsize(path)
modified = max(os.path.getmtime(path), os.path.getctime(path))
return dict(
modified=modified,
path=slug,
size=size
) | [
"def",
"of_file",
"(",
"path",
":",
"str",
",",
"root_directory",
":",
"str",
"=",
"None",
")",
"->",
"dict",
":",
"slug",
"=",
"(",
"path",
"if",
"root_directory",
"is",
"None",
"else",
"path",
"[",
"len",
"(",
"root_directory",
")",
":",
"]",
".",
... | Returns a dictionary containing status information for the specified file
including when its name relative to the root directory, when it was last
modified and its size.
:param path:
The absolute path to the file for which the status information should
be generated
:param root_directory:
The directory to use for creating relative path names for the returned
status. If this argument is None the path in the status will be the
absolute path argument.
:return:
A dictionary containing the status information for the file at the
specified path. If no such file exists, then the dictionary will
contain -1 values for both the file size and the last modified time. | [
"Returns",
"a",
"dictionary",
"containing",
"status",
"information",
"for",
"the",
"specified",
"file",
"including",
"when",
"its",
"name",
"relative",
"to",
"the",
"root",
"directory",
"when",
"it",
"was",
"last",
"modified",
"and",
"its",
"size",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/synchronize/status.py#L36-L75 | train | 44,720 |
sernst/cauldron | cauldron/cli/server/routes/synchronize/status.py | of_directory | def of_directory(directory: str, root_directory: str = None) -> dict:
"""
Returns a dictionary containing status entries recursively for all files
within the specified directory and its descendant directories.
:param directory:
The directory in which to retrieve status information
:param root_directory:
Directory relative to which all file status paths are related. If this
argument is None then the directory argument itself will be used.
:return:
A dictionary containing status information for each file within the
specified directory and its descendants. The keys of the dictionary
are the relative path names for each of the files.
"""
glob_path = os.path.join(directory, '**/*')
root = root_directory if root_directory else directory
results = filter(
lambda result: (result['modified'] != -1),
[of_file(path, root) for path in glob.iglob(glob_path, recursive=True)]
)
return dict([(result['path'], result) for result in results]) | python | def of_directory(directory: str, root_directory: str = None) -> dict:
"""
Returns a dictionary containing status entries recursively for all files
within the specified directory and its descendant directories.
:param directory:
The directory in which to retrieve status information
:param root_directory:
Directory relative to which all file status paths are related. If this
argument is None then the directory argument itself will be used.
:return:
A dictionary containing status information for each file within the
specified directory and its descendants. The keys of the dictionary
are the relative path names for each of the files.
"""
glob_path = os.path.join(directory, '**/*')
root = root_directory if root_directory else directory
results = filter(
lambda result: (result['modified'] != -1),
[of_file(path, root) for path in glob.iglob(glob_path, recursive=True)]
)
return dict([(result['path'], result) for result in results]) | [
"def",
"of_directory",
"(",
"directory",
":",
"str",
",",
"root_directory",
":",
"str",
"=",
"None",
")",
"->",
"dict",
":",
"glob_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'**/*'",
")",
"root",
"=",
"root_directory",
"if",
"r... | Returns a dictionary containing status entries recursively for all files
within the specified directory and its descendant directories.
:param directory:
The directory in which to retrieve status information
:param root_directory:
Directory relative to which all file status paths are related. If this
argument is None then the directory argument itself will be used.
:return:
A dictionary containing status information for each file within the
specified directory and its descendants. The keys of the dictionary
are the relative path names for each of the files. | [
"Returns",
"a",
"dictionary",
"containing",
"status",
"entries",
"recursively",
"for",
"all",
"files",
"within",
"the",
"specified",
"directory",
"and",
"its",
"descendant",
"directories",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/synchronize/status.py#L78-L100 | train | 44,721 |
sernst/cauldron | cauldron/cli/commands/run/__init__.py | run_local | def run_local(
context: cli.CommandContext,
project: projects.Project,
project_steps: typing.List[projects.ProjectStep],
force: bool,
continue_after: bool,
single_step: bool,
limit: int,
print_status: bool,
skip_library_reload: bool = False
) -> environ.Response:
"""
Execute the run command locally within this cauldron environment
:param context:
:param project:
:param project_steps:
:param force:
:param continue_after:
:param single_step:
:param limit:
:param print_status:
:param skip_library_reload:
Whether or not to skip reloading all project libraries prior to
execution of the project. By default this is False in which case
the project libraries are reloaded prior to execution.
:return:
"""
skip_reload = (
skip_library_reload
or environ.modes.has(environ.modes.TESTING)
)
if not skip_reload:
runner.reload_libraries()
environ.log_header('RUNNING', 5)
steps_run = []
if single_step:
# If the user specifies the single step flag, only run one step. Force
# the step to be run if they specified it explicitly
ps = project_steps[0] if len(project_steps) > 0 else None
force = force or (single_step and bool(ps is not None))
steps_run = runner.section(
response=context.response,
project=project,
starting=ps,
limit=1,
force=force
)
elif continue_after or len(project_steps) == 0:
# If the continue after flag is set, start with the specified step
# and run the rest of the project after that. Or, if no steps were
# specified, run the entire project with the specified flags.
ps = project_steps[0] if len(project_steps) > 0 else None
steps_run = runner.complete(
context.response,
project,
ps,
force=force,
limit=limit
)
else:
for ps in project_steps:
steps_run += runner.section(
response=context.response,
project=project,
starting=ps,
limit=max(1, limit),
force=force or (limit < 1 and len(project_steps) < 2),
skips=steps_run + []
)
project.write()
environ.log_blanks()
step_changes = []
for ps in steps_run:
step_changes.append(dict(
name=ps.definition.name,
action='updated',
step=writing.step_writer.serialize(ps)._asdict()
))
context.response.update(step_changes=step_changes)
if print_status or context.response.failed:
context.response.update(project=project.kernel_serialize())
return context.response | python | def run_local(
context: cli.CommandContext,
project: projects.Project,
project_steps: typing.List[projects.ProjectStep],
force: bool,
continue_after: bool,
single_step: bool,
limit: int,
print_status: bool,
skip_library_reload: bool = False
) -> environ.Response:
"""
Execute the run command locally within this cauldron environment
:param context:
:param project:
:param project_steps:
:param force:
:param continue_after:
:param single_step:
:param limit:
:param print_status:
:param skip_library_reload:
Whether or not to skip reloading all project libraries prior to
execution of the project. By default this is False in which case
the project libraries are reloaded prior to execution.
:return:
"""
skip_reload = (
skip_library_reload
or environ.modes.has(environ.modes.TESTING)
)
if not skip_reload:
runner.reload_libraries()
environ.log_header('RUNNING', 5)
steps_run = []
if single_step:
# If the user specifies the single step flag, only run one step. Force
# the step to be run if they specified it explicitly
ps = project_steps[0] if len(project_steps) > 0 else None
force = force or (single_step and bool(ps is not None))
steps_run = runner.section(
response=context.response,
project=project,
starting=ps,
limit=1,
force=force
)
elif continue_after or len(project_steps) == 0:
# If the continue after flag is set, start with the specified step
# and run the rest of the project after that. Or, if no steps were
# specified, run the entire project with the specified flags.
ps = project_steps[0] if len(project_steps) > 0 else None
steps_run = runner.complete(
context.response,
project,
ps,
force=force,
limit=limit
)
else:
for ps in project_steps:
steps_run += runner.section(
response=context.response,
project=project,
starting=ps,
limit=max(1, limit),
force=force or (limit < 1 and len(project_steps) < 2),
skips=steps_run + []
)
project.write()
environ.log_blanks()
step_changes = []
for ps in steps_run:
step_changes.append(dict(
name=ps.definition.name,
action='updated',
step=writing.step_writer.serialize(ps)._asdict()
))
context.response.update(step_changes=step_changes)
if print_status or context.response.failed:
context.response.update(project=project.kernel_serialize())
return context.response | [
"def",
"run_local",
"(",
"context",
":",
"cli",
".",
"CommandContext",
",",
"project",
":",
"projects",
".",
"Project",
",",
"project_steps",
":",
"typing",
".",
"List",
"[",
"projects",
".",
"ProjectStep",
"]",
",",
"force",
":",
"bool",
",",
"continue_af... | Execute the run command locally within this cauldron environment
:param context:
:param project:
:param project_steps:
:param force:
:param continue_after:
:param single_step:
:param limit:
:param print_status:
:param skip_library_reload:
Whether or not to skip reloading all project libraries prior to
execution of the project. By default this is False in which case
the project libraries are reloaded prior to execution.
:return: | [
"Execute",
"the",
"run",
"command",
"locally",
"within",
"this",
"cauldron",
"environment"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commands/run/__init__.py#L229-L322 | train | 44,722 |
WimpyAnalytics/django-andablog | build.py | loadalldatas | def loadalldatas():
"""Loads all demo fixtures."""
dependency_order = ['common', 'profiles', 'blog', 'democomments']
for app in dependency_order:
project.recursive_load(os.path.join(paths.project_paths.manage_root, app)) | python | def loadalldatas():
"""Loads all demo fixtures."""
dependency_order = ['common', 'profiles', 'blog', 'democomments']
for app in dependency_order:
project.recursive_load(os.path.join(paths.project_paths.manage_root, app)) | [
"def",
"loadalldatas",
"(",
")",
":",
"dependency_order",
"=",
"[",
"'common'",
",",
"'profiles'",
",",
"'blog'",
",",
"'democomments'",
"]",
"for",
"app",
"in",
"dependency_order",
":",
"project",
".",
"recursive_load",
"(",
"os",
".",
"path",
".",
"join",
... | Loads all demo fixtures. | [
"Loads",
"all",
"demo",
"fixtures",
"."
] | 9175144140d220e4ce8212d0da6abc8c9ba9816a | https://github.com/WimpyAnalytics/django-andablog/blob/9175144140d220e4ce8212d0da6abc8c9ba9816a/build.py#L23-L27 | train | 44,723 |
WimpyAnalytics/django-andablog | andablog/models.py | Entry._insert_timestamp | def _insert_timestamp(self, slug, max_length=255):
"""Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length.
"""
timestamp = str(int(time.time()))
ts_len = len(timestamp) + 1
while len(slug) + ts_len > max_length:
slug = '-'.join(slug.split('-')[:-1])
slug = '-'.join([slug, timestamp])
return slug | python | def _insert_timestamp(self, slug, max_length=255):
"""Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length.
"""
timestamp = str(int(time.time()))
ts_len = len(timestamp) + 1
while len(slug) + ts_len > max_length:
slug = '-'.join(slug.split('-')[:-1])
slug = '-'.join([slug, timestamp])
return slug | [
"def",
"_insert_timestamp",
"(",
"self",
",",
"slug",
",",
"max_length",
"=",
"255",
")",
":",
"timestamp",
"=",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"ts_len",
"=",
"len",
"(",
"timestamp",
")",
"+",
"1",
"while",
"len",... | Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length. | [
"Appends",
"a",
"timestamp",
"integer",
"to",
"the",
"given",
"slug",
"yet",
"ensuring",
"the",
"result",
"is",
"less",
"than",
"the",
"specified",
"max_length",
"."
] | 9175144140d220e4ce8212d0da6abc8c9ba9816a | https://github.com/WimpyAnalytics/django-andablog/blob/9175144140d220e4ce8212d0da6abc8c9ba9816a/andablog/models.py#L40-L49 | train | 44,724 |
WimpyAnalytics/django-andablog | andablog/models.py | Entry._slugify_title | def _slugify_title(self):
"""Slugify the Entry title, but ensure it's less than the maximum
number of characters. This method also ensures that a slug is unique by
appending a timestamp to any duplicate slugs.
"""
# Restrict slugs to their maximum number of chars, but don't split mid-word
self.slug = slugify(self.title)
while len(self.slug) > 255:
self.slug = '-'.join(self.slug.split('-')[:-1])
# Is the same slug as another entry?
if Entry.objects.filter(slug=self.slug).exclude(id=self.id).exists():
# Append time to differentiate.
self.slug = self._insert_timestamp(self.slug) | python | def _slugify_title(self):
"""Slugify the Entry title, but ensure it's less than the maximum
number of characters. This method also ensures that a slug is unique by
appending a timestamp to any duplicate slugs.
"""
# Restrict slugs to their maximum number of chars, but don't split mid-word
self.slug = slugify(self.title)
while len(self.slug) > 255:
self.slug = '-'.join(self.slug.split('-')[:-1])
# Is the same slug as another entry?
if Entry.objects.filter(slug=self.slug).exclude(id=self.id).exists():
# Append time to differentiate.
self.slug = self._insert_timestamp(self.slug) | [
"def",
"_slugify_title",
"(",
"self",
")",
":",
"# Restrict slugs to their maximum number of chars, but don't split mid-word",
"self",
".",
"slug",
"=",
"slugify",
"(",
"self",
".",
"title",
")",
"while",
"len",
"(",
"self",
".",
"slug",
")",
">",
"255",
":",
"s... | Slugify the Entry title, but ensure it's less than the maximum
number of characters. This method also ensures that a slug is unique by
appending a timestamp to any duplicate slugs. | [
"Slugify",
"the",
"Entry",
"title",
"but",
"ensure",
"it",
"s",
"less",
"than",
"the",
"maximum",
"number",
"of",
"characters",
".",
"This",
"method",
"also",
"ensures",
"that",
"a",
"slug",
"is",
"unique",
"by",
"appending",
"a",
"timestamp",
"to",
"any",... | 9175144140d220e4ce8212d0da6abc8c9ba9816a | https://github.com/WimpyAnalytics/django-andablog/blob/9175144140d220e4ce8212d0da6abc8c9ba9816a/andablog/models.py#L51-L64 | train | 44,725 |
seomoz/qless-py | qless/workers/serial.py | SerialWorker.run | def run(self):
'''Run jobs, popping one after another'''
# Register our signal handlers
self.signals()
with self.listener():
for job in self.jobs():
# If there was no job to be had, we should sleep a little bit
if not job:
self.jid = None
self.title('Sleeping for %fs' % self.interval)
time.sleep(self.interval)
else:
self.jid = job.jid
self.title('Working on %s (%s)' % (job.jid, job.klass_name))
with Worker.sandbox(self.sandbox):
job.sandbox = self.sandbox
job.process()
if self.shutdown:
break | python | def run(self):
'''Run jobs, popping one after another'''
# Register our signal handlers
self.signals()
with self.listener():
for job in self.jobs():
# If there was no job to be had, we should sleep a little bit
if not job:
self.jid = None
self.title('Sleeping for %fs' % self.interval)
time.sleep(self.interval)
else:
self.jid = job.jid
self.title('Working on %s (%s)' % (job.jid, job.klass_name))
with Worker.sandbox(self.sandbox):
job.sandbox = self.sandbox
job.process()
if self.shutdown:
break | [
"def",
"run",
"(",
"self",
")",
":",
"# Register our signal handlers",
"self",
".",
"signals",
"(",
")",
"with",
"self",
".",
"listener",
"(",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
"(",
")",
":",
"# If there was no job to be had, we should sleep a... | Run jobs, popping one after another | [
"Run",
"jobs",
"popping",
"one",
"after",
"another"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/serial.py#L24-L43 | train | 44,726 |
sernst/cauldron | cauldron/invoke/__init__.py | initialize | def initialize():
"""
Initializes the cauldron library by confirming that it can be imported
by the importlib library. If the attempt to import it fails, the system
path will be modified and the attempt retried. If both attempts fail, an
import error will be raised.
"""
cauldron_module = get_cauldron_module()
if cauldron_module is not None:
return cauldron_module
sys.path.append(ROOT_DIRECTORY)
cauldron_module = get_cauldron_module()
if cauldron_module is not None:
return cauldron_module
raise ImportError(' '.join((
'Unable to import cauldron.'
'The package was not installed in a known location.'
))) | python | def initialize():
"""
Initializes the cauldron library by confirming that it can be imported
by the importlib library. If the attempt to import it fails, the system
path will be modified and the attempt retried. If both attempts fail, an
import error will be raised.
"""
cauldron_module = get_cauldron_module()
if cauldron_module is not None:
return cauldron_module
sys.path.append(ROOT_DIRECTORY)
cauldron_module = get_cauldron_module()
if cauldron_module is not None:
return cauldron_module
raise ImportError(' '.join((
'Unable to import cauldron.'
'The package was not installed in a known location.'
))) | [
"def",
"initialize",
"(",
")",
":",
"cauldron_module",
"=",
"get_cauldron_module",
"(",
")",
"if",
"cauldron_module",
"is",
"not",
"None",
":",
"return",
"cauldron_module",
"sys",
".",
"path",
".",
"append",
"(",
"ROOT_DIRECTORY",
")",
"cauldron_module",
"=",
... | Initializes the cauldron library by confirming that it can be imported
by the importlib library. If the attempt to import it fails, the system
path will be modified and the attempt retried. If both attempts fail, an
import error will be raised. | [
"Initializes",
"the",
"cauldron",
"library",
"by",
"confirming",
"that",
"it",
"can",
"be",
"imported",
"by",
"the",
"importlib",
"library",
".",
"If",
"the",
"attempt",
"to",
"import",
"it",
"fails",
"the",
"system",
"path",
"will",
"be",
"modified",
"and",... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/__init__.py#L22-L43 | train | 44,727 |
sernst/cauldron | cauldron/invoke/__init__.py | run | def run(arguments: typing.List[str] = None):
"""Executes the cauldron command"""
initialize()
from cauldron.invoke import parser
from cauldron.invoke import invoker
args = parser.parse(arguments)
exit_code = invoker.run(args.get('command'), args)
sys.exit(exit_code) | python | def run(arguments: typing.List[str] = None):
"""Executes the cauldron command"""
initialize()
from cauldron.invoke import parser
from cauldron.invoke import invoker
args = parser.parse(arguments)
exit_code = invoker.run(args.get('command'), args)
sys.exit(exit_code) | [
"def",
"run",
"(",
"arguments",
":",
"typing",
".",
"List",
"[",
"str",
"]",
"=",
"None",
")",
":",
"initialize",
"(",
")",
"from",
"cauldron",
".",
"invoke",
"import",
"parser",
"from",
"cauldron",
".",
"invoke",
"import",
"invoker",
"args",
"=",
"par... | Executes the cauldron command | [
"Executes",
"the",
"cauldron",
"command"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/__init__.py#L46-L55 | train | 44,728 |
WimpyAnalytics/django-andablog | andablog/templatetags/andablog_tags.py | author_display | def author_display(author, *args):
"""Returns either the linked or not-linked profile name."""
# Call get_absolute_url or a function returning none if not defined
url = getattr(author, 'get_absolute_url', lambda: None)()
# get_short_name or unicode representation
short_name = getattr(author, 'get_short_name', lambda: six.text_type(author))()
if url:
return mark_safe('<a href="{}">{}</a>'.format(url, short_name))
else:
return short_name | python | def author_display(author, *args):
"""Returns either the linked or not-linked profile name."""
# Call get_absolute_url or a function returning none if not defined
url = getattr(author, 'get_absolute_url', lambda: None)()
# get_short_name or unicode representation
short_name = getattr(author, 'get_short_name', lambda: six.text_type(author))()
if url:
return mark_safe('<a href="{}">{}</a>'.format(url, short_name))
else:
return short_name | [
"def",
"author_display",
"(",
"author",
",",
"*",
"args",
")",
":",
"# Call get_absolute_url or a function returning none if not defined",
"url",
"=",
"getattr",
"(",
"author",
",",
"'get_absolute_url'",
",",
"lambda",
":",
"None",
")",
"(",
")",
"# get_short_name or ... | Returns either the linked or not-linked profile name. | [
"Returns",
"either",
"the",
"linked",
"or",
"not",
"-",
"linked",
"profile",
"name",
"."
] | 9175144140d220e4ce8212d0da6abc8c9ba9816a | https://github.com/WimpyAnalytics/django-andablog/blob/9175144140d220e4ce8212d0da6abc8c9ba9816a/andablog/templatetags/andablog_tags.py#L9-L19 | train | 44,729 |
sernst/cauldron | cauldron/invoke/invoker.py | in_project_directory | def in_project_directory() -> bool:
"""
Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file.
"""
current_directory = os.path.realpath(os.curdir)
project_path = os.path.join(current_directory, 'cauldron.json')
return os.path.exists(project_path) and os.path.isfile(project_path) | python | def in_project_directory() -> bool:
"""
Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file.
"""
current_directory = os.path.realpath(os.curdir)
project_path = os.path.join(current_directory, 'cauldron.json')
return os.path.exists(project_path) and os.path.isfile(project_path) | [
"def",
"in_project_directory",
"(",
")",
"->",
"bool",
":",
"current_directory",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"curdir",
")",
"project_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_directory",
",",
"'cauldron.json'",
... | Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file. | [
"Returns",
"whether",
"or",
"not",
"the",
"current",
"working",
"directory",
"is",
"a",
"Cauldron",
"project",
"directory",
"which",
"contains",
"a",
"cauldron",
".",
"json",
"file",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/invoker.py#L12-L19 | train | 44,730 |
sernst/cauldron | cauldron/invoke/invoker.py | load_shared_data | def load_shared_data(path: typing.Union[str, None]) -> dict:
"""Load shared data from a JSON file stored on disk"""
if path is None:
return dict()
if not os.path.exists(path):
raise FileNotFoundError('No such shared data file "{}"'.format(path))
try:
with open(path, 'r') as fp:
data = json.load(fp)
except Exception:
raise IOError('Unable to read shared data file "{}"'.format(path))
if not isinstance(data, dict):
raise ValueError('Shared data must load into a dictionary object')
return data | python | def load_shared_data(path: typing.Union[str, None]) -> dict:
"""Load shared data from a JSON file stored on disk"""
if path is None:
return dict()
if not os.path.exists(path):
raise FileNotFoundError('No such shared data file "{}"'.format(path))
try:
with open(path, 'r') as fp:
data = json.load(fp)
except Exception:
raise IOError('Unable to read shared data file "{}"'.format(path))
if not isinstance(data, dict):
raise ValueError('Shared data must load into a dictionary object')
return data | [
"def",
"load_shared_data",
"(",
"path",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"None",
"]",
")",
"->",
"dict",
":",
"if",
"path",
"is",
"None",
":",
"return",
"dict",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")... | Load shared data from a JSON file stored on disk | [
"Load",
"shared",
"data",
"from",
"a",
"JSON",
"file",
"stored",
"on",
"disk"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/invoker.py#L22-L40 | train | 44,731 |
sernst/cauldron | cauldron/invoke/invoker.py | run_version | def run_version(args: dict) -> int:
"""Displays the current version"""
version = environ.package_settings.get('version', 'unknown')
print('VERSION: {}'.format(version))
return 0 | python | def run_version(args: dict) -> int:
"""Displays the current version"""
version = environ.package_settings.get('version', 'unknown')
print('VERSION: {}'.format(version))
return 0 | [
"def",
"run_version",
"(",
"args",
":",
"dict",
")",
"->",
"int",
":",
"version",
"=",
"environ",
".",
"package_settings",
".",
"get",
"(",
"'version'",
",",
"'unknown'",
")",
"print",
"(",
"'VERSION: {}'",
".",
"format",
"(",
"version",
")",
")",
"retur... | Displays the current version | [
"Displays",
"the",
"current",
"version"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/invoker.py#L43-L47 | train | 44,732 |
sernst/cauldron | cauldron/invoke/invoker.py | run_batch | def run_batch(args: dict) -> int:
"""Runs a batch operation for the given arguments"""
batcher.run_project(
project_directory=args.get('project_directory'),
log_path=args.get('logging_path'),
output_directory=args.get('output_directory'),
shared_data=load_shared_data(args.get('shared_data_path'))
)
return 0 | python | def run_batch(args: dict) -> int:
"""Runs a batch operation for the given arguments"""
batcher.run_project(
project_directory=args.get('project_directory'),
log_path=args.get('logging_path'),
output_directory=args.get('output_directory'),
shared_data=load_shared_data(args.get('shared_data_path'))
)
return 0 | [
"def",
"run_batch",
"(",
"args",
":",
"dict",
")",
"->",
"int",
":",
"batcher",
".",
"run_project",
"(",
"project_directory",
"=",
"args",
".",
"get",
"(",
"'project_directory'",
")",
",",
"log_path",
"=",
"args",
".",
"get",
"(",
"'logging_path'",
")",
... | Runs a batch operation for the given arguments | [
"Runs",
"a",
"batch",
"operation",
"for",
"the",
"given",
"arguments"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/invoker.py#L50-L59 | train | 44,733 |
sernst/cauldron | cauldron/invoke/invoker.py | run_shell | def run_shell(args: dict) -> int:
"""Run the shell sub command"""
if args.get('project_directory'):
return run_batch(args)
shell = CauldronShell()
if in_project_directory():
shell.cmdqueue.append('open "{}"'.format(os.path.realpath(os.curdir)))
shell.cmdloop()
return 0 | python | def run_shell(args: dict) -> int:
"""Run the shell sub command"""
if args.get('project_directory'):
return run_batch(args)
shell = CauldronShell()
if in_project_directory():
shell.cmdqueue.append('open "{}"'.format(os.path.realpath(os.curdir)))
shell.cmdloop()
return 0 | [
"def",
"run_shell",
"(",
"args",
":",
"dict",
")",
"->",
"int",
":",
"if",
"args",
".",
"get",
"(",
"'project_directory'",
")",
":",
"return",
"run_batch",
"(",
"args",
")",
"shell",
"=",
"CauldronShell",
"(",
")",
"if",
"in_project_directory",
"(",
")",... | Run the shell sub command | [
"Run",
"the",
"shell",
"sub",
"command"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/invoker.py#L62-L74 | train | 44,734 |
sernst/cauldron | cauldron/cli/server/run.py | parse | def parse(
args: typing.List[str] = None,
arg_parser: ArgumentParser = None
) -> dict:
"""Parses the arguments for the cauldron server"""
parser = arg_parser or create_parser()
return vars(parser.parse_args(args)) | python | def parse(
args: typing.List[str] = None,
arg_parser: ArgumentParser = None
) -> dict:
"""Parses the arguments for the cauldron server"""
parser = arg_parser or create_parser()
return vars(parser.parse_args(args)) | [
"def",
"parse",
"(",
"args",
":",
"typing",
".",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"arg_parser",
":",
"ArgumentParser",
"=",
"None",
")",
"->",
"dict",
":",
"parser",
"=",
"arg_parser",
"or",
"create_parser",
"(",
")",
"return",
"vars",
"(",
... | Parses the arguments for the cauldron server | [
"Parses",
"the",
"arguments",
"for",
"the",
"cauldron",
"server"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/run.py#L78-L85 | train | 44,735 |
sernst/cauldron | cauldron/cli/server/run.py | create_parser | def create_parser(arg_parser: ArgumentParser = None) -> ArgumentParser:
"""
Creates an argument parser populated with the arg formats for the server
command.
"""
parser = arg_parser or ArgumentParser()
parser.description = 'Cauldron kernel server'
parser.add_argument(
'-p', '--port',
dest='port',
type=int,
default=5010
)
parser.add_argument(
'-d', '--debug',
dest='debug',
default=False,
action='store_true'
)
parser.add_argument(
'-v', '--version',
dest='version',
default=False,
action='store_true'
)
parser.add_argument(
'-c', '--code',
dest='authentication_code',
type=str,
default=''
)
parser.add_argument(
'-n', '--name',
dest='host',
type=str,
default=None
)
return parser | python | def create_parser(arg_parser: ArgumentParser = None) -> ArgumentParser:
"""
Creates an argument parser populated with the arg formats for the server
command.
"""
parser = arg_parser or ArgumentParser()
parser.description = 'Cauldron kernel server'
parser.add_argument(
'-p', '--port',
dest='port',
type=int,
default=5010
)
parser.add_argument(
'-d', '--debug',
dest='debug',
default=False,
action='store_true'
)
parser.add_argument(
'-v', '--version',
dest='version',
default=False,
action='store_true'
)
parser.add_argument(
'-c', '--code',
dest='authentication_code',
type=str,
default=''
)
parser.add_argument(
'-n', '--name',
dest='host',
type=str,
default=None
)
return parser | [
"def",
"create_parser",
"(",
"arg_parser",
":",
"ArgumentParser",
"=",
"None",
")",
"->",
"ArgumentParser",
":",
"parser",
"=",
"arg_parser",
"or",
"ArgumentParser",
"(",
")",
"parser",
".",
"description",
"=",
"'Cauldron kernel server'",
"parser",
".",
"add_argum... | Creates an argument parser populated with the arg formats for the server
command. | [
"Creates",
"an",
"argument",
"parser",
"populated",
"with",
"the",
"arg",
"formats",
"for",
"the",
"server",
"command",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/run.py#L88-L132 | train | 44,736 |
ayoungprogrammer/Lango | lango/matcher.py | match_rules | def match_rules(tree, rules, fun=None, multi=False):
"""Matches a Tree structure with the given query rules.
Query rules are represented as a dictionary of template to action.
Action is either a function, or a dictionary of subtemplate parameter to rules::
rules = { 'template' : { 'key': rules } }
| { 'template' : {} }
Args:
tree (Tree): Parsed tree structure
rules (dict): A dictionary of query rules
fun (function): Function to call with context (set to None if you want to return context)
multi (Bool): If True, returns all matched contexts, else returns first matched context
Returns:
Contexts from matched rules
"""
if multi:
context = match_rules_context_multi(tree, rules)
else:
context = match_rules_context(tree, rules)
if not context:
return None
if fun:
args = fun.__code__.co_varnames
if multi:
res = []
for c in context:
action_context = {}
for arg in args:
if arg in c:
action_context[arg] = c[arg]
res.append(fun(**action_context))
return res
else:
action_context = {}
for arg in args:
if arg in context:
action_context[arg] = context[arg]
return fun(**action_context)
else:
return context | python | def match_rules(tree, rules, fun=None, multi=False):
"""Matches a Tree structure with the given query rules.
Query rules are represented as a dictionary of template to action.
Action is either a function, or a dictionary of subtemplate parameter to rules::
rules = { 'template' : { 'key': rules } }
| { 'template' : {} }
Args:
tree (Tree): Parsed tree structure
rules (dict): A dictionary of query rules
fun (function): Function to call with context (set to None if you want to return context)
multi (Bool): If True, returns all matched contexts, else returns first matched context
Returns:
Contexts from matched rules
"""
if multi:
context = match_rules_context_multi(tree, rules)
else:
context = match_rules_context(tree, rules)
if not context:
return None
if fun:
args = fun.__code__.co_varnames
if multi:
res = []
for c in context:
action_context = {}
for arg in args:
if arg in c:
action_context[arg] = c[arg]
res.append(fun(**action_context))
return res
else:
action_context = {}
for arg in args:
if arg in context:
action_context[arg] = context[arg]
return fun(**action_context)
else:
return context | [
"def",
"match_rules",
"(",
"tree",
",",
"rules",
",",
"fun",
"=",
"None",
",",
"multi",
"=",
"False",
")",
":",
"if",
"multi",
":",
"context",
"=",
"match_rules_context_multi",
"(",
"tree",
",",
"rules",
")",
"else",
":",
"context",
"=",
"match_rules_con... | Matches a Tree structure with the given query rules.
Query rules are represented as a dictionary of template to action.
Action is either a function, or a dictionary of subtemplate parameter to rules::
rules = { 'template' : { 'key': rules } }
| { 'template' : {} }
Args:
tree (Tree): Parsed tree structure
rules (dict): A dictionary of query rules
fun (function): Function to call with context (set to None if you want to return context)
multi (Bool): If True, returns all matched contexts, else returns first matched context
Returns:
Contexts from matched rules | [
"Matches",
"a",
"Tree",
"structure",
"with",
"the",
"given",
"query",
"rules",
"."
] | 0c4284c153abc2d8de4b03a86731bd84385e6afa | https://github.com/ayoungprogrammer/Lango/blob/0c4284c153abc2d8de4b03a86731bd84385e6afa/lango/matcher.py#L6-L48 | train | 44,737 |
sernst/cauldron | cauldron/session/spark/__init__.py | initialize | def initialize(spark_home_path: str = None):
"""
Registers and initializes the PySpark library dependencies so that the
pyspark package can be imported and used within the notebook.
If you specify the path to the spark home folder, the PySpark libraries
from that location will be loaded. If a value is omitted, the $SPARK_HOME
environmental variable will be used to determine from where to load the
libraries.
:param spark_home_path:
The path to the spark folder on your system. Leave this blank if you
want to use the $SPARK_HOME environmental variable default instead.
:return:
"""
if not spark_home_path:
spark_home_path = os.environ.get('SPARK_HOME')
spark_home_path = environ.paths.clean(spark_home_path)
if not os.path.exists(spark_home_path):
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
spark_home_path
)
spark_python_path = os.path.join(spark_home_path, 'python')
if not os.path.exists(spark_python_path):
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
spark_python_path
)
spark_pylib_path = os.path.join(spark_python_path, 'lib')
if not os.path.exists(spark_pylib_path):
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
spark_python_path
)
lib_glob = os.path.join(spark_pylib_path, '*.zip')
lib_sources = [path for path in glob.iglob(lib_glob)]
unload()
for p in lib_sources:
if p not in sys.path:
sys.path.append(p)
spark_environment.update(dict(
spark_home_path=spark_home_path,
spark_python_path=spark_python_path,
spark_pylib_path=spark_pylib_path,
libs=lib_sources
)) | python | def initialize(spark_home_path: str = None):
"""
Registers and initializes the PySpark library dependencies so that the
pyspark package can be imported and used within the notebook.
If you specify the path to the spark home folder, the PySpark libraries
from that location will be loaded. If a value is omitted, the $SPARK_HOME
environmental variable will be used to determine from where to load the
libraries.
:param spark_home_path:
The path to the spark folder on your system. Leave this blank if you
want to use the $SPARK_HOME environmental variable default instead.
:return:
"""
if not spark_home_path:
spark_home_path = os.environ.get('SPARK_HOME')
spark_home_path = environ.paths.clean(spark_home_path)
if not os.path.exists(spark_home_path):
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
spark_home_path
)
spark_python_path = os.path.join(spark_home_path, 'python')
if not os.path.exists(spark_python_path):
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
spark_python_path
)
spark_pylib_path = os.path.join(spark_python_path, 'lib')
if not os.path.exists(spark_pylib_path):
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
spark_python_path
)
lib_glob = os.path.join(spark_pylib_path, '*.zip')
lib_sources = [path for path in glob.iglob(lib_glob)]
unload()
for p in lib_sources:
if p not in sys.path:
sys.path.append(p)
spark_environment.update(dict(
spark_home_path=spark_home_path,
spark_python_path=spark_python_path,
spark_pylib_path=spark_pylib_path,
libs=lib_sources
)) | [
"def",
"initialize",
"(",
"spark_home_path",
":",
"str",
"=",
"None",
")",
":",
"if",
"not",
"spark_home_path",
":",
"spark_home_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SPARK_HOME'",
")",
"spark_home_path",
"=",
"environ",
".",
"paths",
".",
"... | Registers and initializes the PySpark library dependencies so that the
pyspark package can be imported and used within the notebook.
If you specify the path to the spark home folder, the PySpark libraries
from that location will be loaded. If a value is omitted, the $SPARK_HOME
environmental variable will be used to determine from where to load the
libraries.
:param spark_home_path:
The path to the spark folder on your system. Leave this blank if you
want to use the $SPARK_HOME environmental variable default instead.
:return: | [
"Registers",
"and",
"initializes",
"the",
"PySpark",
"library",
"dependencies",
"so",
"that",
"the",
"pyspark",
"package",
"can",
"be",
"imported",
"and",
"used",
"within",
"the",
"notebook",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/spark/__init__.py#L26-L86 | train | 44,738 |
sernst/cauldron | cauldron/session/projects/project.py | Project.is_remote_project | def is_remote_project(self) -> bool:
"""Whether or not this project is remote"""
project_path = environ.paths.clean(self.source_directory)
return project_path.find('cd-remote-project') != -1 | python | def is_remote_project(self) -> bool:
"""Whether or not this project is remote"""
project_path = environ.paths.clean(self.source_directory)
return project_path.find('cd-remote-project') != -1 | [
"def",
"is_remote_project",
"(",
"self",
")",
"->",
"bool",
":",
"project_path",
"=",
"environ",
".",
"paths",
".",
"clean",
"(",
"self",
".",
"source_directory",
")",
"return",
"project_path",
".",
"find",
"(",
"'cd-remote-project'",
")",
"!=",
"-",
"1"
] | Whether or not this project is remote | [
"Whether",
"or",
"not",
"this",
"project",
"is",
"remote"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/project.py#L75-L78 | train | 44,739 |
sernst/cauldron | cauldron/session/projects/project.py | Project.library_directories | def library_directories(self) -> typing.List[str]:
"""
The list of directories to all of the library locations
"""
def listify(value):
return [value] if isinstance(value, str) else list(value)
# If this is a project running remotely remove external library
# folders as the remote shared libraries folder will contain all
# of the necessary dependencies
is_local_project = not self.is_remote_project
folders = [
f
for f in listify(self.settings.fetch('library_folders', ['libs']))
if is_local_project or not f.startswith('..')
]
# Include the remote shared library folder as well
folders.append('../__cauldron_shared_libs')
# Include the project directory as well
folders.append(self.source_directory)
return [
environ.paths.clean(os.path.join(self.source_directory, folder))
for folder in folders
] | python | def library_directories(self) -> typing.List[str]:
"""
The list of directories to all of the library locations
"""
def listify(value):
return [value] if isinstance(value, str) else list(value)
# If this is a project running remotely remove external library
# folders as the remote shared libraries folder will contain all
# of the necessary dependencies
is_local_project = not self.is_remote_project
folders = [
f
for f in listify(self.settings.fetch('library_folders', ['libs']))
if is_local_project or not f.startswith('..')
]
# Include the remote shared library folder as well
folders.append('../__cauldron_shared_libs')
# Include the project directory as well
folders.append(self.source_directory)
return [
environ.paths.clean(os.path.join(self.source_directory, folder))
for folder in folders
] | [
"def",
"library_directories",
"(",
"self",
")",
"->",
"typing",
".",
"List",
"[",
"str",
"]",
":",
"def",
"listify",
"(",
"value",
")",
":",
"return",
"[",
"value",
"]",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
"else",
"list",
"(",
"value",... | The list of directories to all of the library locations | [
"The",
"list",
"of",
"directories",
"to",
"all",
"of",
"the",
"library",
"locations"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/project.py#L81-L107 | train | 44,740 |
sernst/cauldron | cauldron/session/projects/project.py | Project.results_path | def results_path(self) -> str:
"""The path where the project results will be written"""
def possible_paths():
yield self._results_path
yield self.settings.fetch('path_results')
yield environ.configs.fetch('results_directory')
yield environ.paths.results(self.uuid)
return next(p for p in possible_paths() if p is not None) | python | def results_path(self) -> str:
"""The path where the project results will be written"""
def possible_paths():
yield self._results_path
yield self.settings.fetch('path_results')
yield environ.configs.fetch('results_directory')
yield environ.paths.results(self.uuid)
return next(p for p in possible_paths() if p is not None) | [
"def",
"results_path",
"(",
"self",
")",
"->",
"str",
":",
"def",
"possible_paths",
"(",
")",
":",
"yield",
"self",
".",
"_results_path",
"yield",
"self",
".",
"settings",
".",
"fetch",
"(",
"'path_results'",
")",
"yield",
"environ",
".",
"configs",
".",
... | The path where the project results will be written | [
"The",
"path",
"where",
"the",
"project",
"results",
"will",
"be",
"written"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/project.py#L175-L184 | train | 44,741 |
sernst/cauldron | cauldron/session/projects/project.py | Project.output_directory | def output_directory(self) -> str:
"""
Returns the directory where the project results files will be written
"""
return os.path.join(self.results_path, 'reports', self.uuid, 'latest') | python | def output_directory(self) -> str:
"""
Returns the directory where the project results files will be written
"""
return os.path.join(self.results_path, 'reports', self.uuid, 'latest') | [
"def",
"output_directory",
"(",
"self",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"results_path",
",",
"'reports'",
",",
"self",
".",
"uuid",
",",
"'latest'",
")"
] | Returns the directory where the project results files will be written | [
"Returns",
"the",
"directory",
"where",
"the",
"project",
"results",
"files",
"will",
"be",
"written"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/project.py#L217-L222 | train | 44,742 |
sernst/cauldron | cauldron/session/projects/project.py | Project.refresh | def refresh(self, force: bool = False) -> bool:
"""
Loads the cauldron.json definition file for the project and populates
the project with the loaded data. Any existing data will be overwritten,
if the new definition file differs from the previous one.
If the project has already loaded with the most recent version of the
cauldron.json file, this method will return without making any changes
to the project.
:param force:
If true the project will be refreshed even if the project file
modified timestamp doesn't indicate that it needs to be refreshed.
:return:
Whether or not a refresh was needed and carried out
"""
lm = self.last_modified
is_newer = lm is not None and lm >= os.path.getmtime(self.source_path)
if not force and is_newer:
return False
old_definition = self.settings.fetch(None)
new_definition = definitions.load_project_definition(
self.source_directory
)
if not force and old_definition == new_definition:
return False
self.settings.clear().put(**new_definition)
old_step_definitions = old_definition.get('steps', [])
new_step_definitions = new_definition.get('steps', [])
if not force and old_step_definitions == new_step_definitions:
return True
old_steps = self.steps
self.steps = []
for step_data in new_step_definitions:
matches = [s for s in old_step_definitions if s == step_data]
if len(matches) > 0:
index = old_step_definitions.index(matches[0])
self.steps.append(old_steps[index])
else:
self.add_step(step_data)
self.last_modified = time.time()
return True | python | def refresh(self, force: bool = False) -> bool:
"""
Loads the cauldron.json definition file for the project and populates
the project with the loaded data. Any existing data will be overwritten,
if the new definition file differs from the previous one.
If the project has already loaded with the most recent version of the
cauldron.json file, this method will return without making any changes
to the project.
:param force:
If true the project will be refreshed even if the project file
modified timestamp doesn't indicate that it needs to be refreshed.
:return:
Whether or not a refresh was needed and carried out
"""
lm = self.last_modified
is_newer = lm is not None and lm >= os.path.getmtime(self.source_path)
if not force and is_newer:
return False
old_definition = self.settings.fetch(None)
new_definition = definitions.load_project_definition(
self.source_directory
)
if not force and old_definition == new_definition:
return False
self.settings.clear().put(**new_definition)
old_step_definitions = old_definition.get('steps', [])
new_step_definitions = new_definition.get('steps', [])
if not force and old_step_definitions == new_step_definitions:
return True
old_steps = self.steps
self.steps = []
for step_data in new_step_definitions:
matches = [s for s in old_step_definitions if s == step_data]
if len(matches) > 0:
index = old_step_definitions.index(matches[0])
self.steps.append(old_steps[index])
else:
self.add_step(step_data)
self.last_modified = time.time()
return True | [
"def",
"refresh",
"(",
"self",
",",
"force",
":",
"bool",
"=",
"False",
")",
"->",
"bool",
":",
"lm",
"=",
"self",
".",
"last_modified",
"is_newer",
"=",
"lm",
"is",
"not",
"None",
"and",
"lm",
">=",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",... | Loads the cauldron.json definition file for the project and populates
the project with the loaded data. Any existing data will be overwritten,
if the new definition file differs from the previous one.
If the project has already loaded with the most recent version of the
cauldron.json file, this method will return without making any changes
to the project.
:param force:
If true the project will be refreshed even if the project file
modified timestamp doesn't indicate that it needs to be refreshed.
:return:
Whether or not a refresh was needed and carried out | [
"Loads",
"the",
"cauldron",
".",
"json",
"definition",
"file",
"for",
"the",
"project",
"and",
"populates",
"the",
"project",
"with",
"the",
"loaded",
"data",
".",
"Any",
"existing",
"data",
"will",
"be",
"overwritten",
"if",
"the",
"new",
"definition",
"fil... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/project.py#L267-L317 | train | 44,743 |
sernst/cauldron | cauldron/render/texts.py | preformatted_text | def preformatted_text(source: str) -> str:
"""Renders preformatted text box"""
environ.abort_thread()
if not source:
return ''
source = render_utils.html_escape(source)
return '<pre class="preformatted-textbox">{text}</pre>'.format(
text=str(textwrap.dedent(source))
) | python | def preformatted_text(source: str) -> str:
"""Renders preformatted text box"""
environ.abort_thread()
if not source:
return ''
source = render_utils.html_escape(source)
return '<pre class="preformatted-textbox">{text}</pre>'.format(
text=str(textwrap.dedent(source))
) | [
"def",
"preformatted_text",
"(",
"source",
":",
"str",
")",
"->",
"str",
":",
"environ",
".",
"abort_thread",
"(",
")",
"if",
"not",
"source",
":",
"return",
"''",
"source",
"=",
"render_utils",
".",
"html_escape",
"(",
"source",
")",
"return",
"'<pre clas... | Renders preformatted text box | [
"Renders",
"preformatted",
"text",
"box"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/render/texts.py#L142-L153 | train | 44,744 |
sernst/cauldron | cauldron/render/texts.py | markdown | def markdown(
source: str = None,
source_path: str = None,
preserve_lines: bool = False,
font_size: float = None,
**kwargs
) -> dict:
"""
Renders a markdown file with support for Jinja2 templating. Any keyword
arguments will be passed to Jinja2 for templating prior to rendering the
markdown to HTML for display within the notebook.
:param source:
A string of markdown text that should be rendered to HTML for
notebook display.
:param source_path:
The path to a markdown file that should be rendered to HTML for
notebook display.
: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.
:return:
The HTML results of rendering the specified markdown string or file.
"""
environ.abort_thread()
library_includes = []
rendered = textwrap.dedent(
templating.render_file(source_path, **kwargs)
if source_path else
templating.render(source or '', **kwargs)
)
if md is None:
raise ImportError('Unable to import the markdown package')
offset = 0
while offset < len(rendered):
bound_chars = '$$'
start_index = rendered.find(bound_chars, offset)
if start_index < 0:
break
inline = rendered[start_index + 2] != '$'
bound_chars = '$$' if inline else '$$$'
end_index = rendered.find(
bound_chars,
start_index + len(bound_chars)
)
if end_index < 0:
break
end_index += len(bound_chars)
chunk = rendered[start_index: end_index] \
.strip('$') \
.strip() \
.replace('@', '\\')
if inline:
chunk = chunk.replace('\\', '\\\\')
chunk = latex(chunk, inline)
rendered = '{pre}{gap}{latex}{gap}{post}'.format(
pre=rendered[:start_index],
latex=chunk,
post=rendered[end_index:],
gap='' if inline else '\n\n'
)
if 'katex' not in library_includes:
library_includes.append('katex')
offset = end_index
extensions = [
'markdown.extensions.extra',
'markdown.extensions.admonition',
'markdown.extensions.sane_lists',
'markdown.extensions.nl2br' if preserve_lines else None
]
body = templating.render_template(
'markdown-block.html',
text=md.markdown(rendered, extensions=[
e for e in extensions if e is not None
]),
font_size=font_size
)
pattern = re.compile('src="(?P<url>[^"]+)"')
body = pattern.sub(r'data-src="\g<url>"', body)
return dict(
body=body,
library_includes=library_includes,
rendered=rendered
) | python | def markdown(
source: str = None,
source_path: str = None,
preserve_lines: bool = False,
font_size: float = None,
**kwargs
) -> dict:
"""
Renders a markdown file with support for Jinja2 templating. Any keyword
arguments will be passed to Jinja2 for templating prior to rendering the
markdown to HTML for display within the notebook.
:param source:
A string of markdown text that should be rendered to HTML for
notebook display.
:param source_path:
The path to a markdown file that should be rendered to HTML for
notebook display.
: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.
:return:
The HTML results of rendering the specified markdown string or file.
"""
environ.abort_thread()
library_includes = []
rendered = textwrap.dedent(
templating.render_file(source_path, **kwargs)
if source_path else
templating.render(source or '', **kwargs)
)
if md is None:
raise ImportError('Unable to import the markdown package')
offset = 0
while offset < len(rendered):
bound_chars = '$$'
start_index = rendered.find(bound_chars, offset)
if start_index < 0:
break
inline = rendered[start_index + 2] != '$'
bound_chars = '$$' if inline else '$$$'
end_index = rendered.find(
bound_chars,
start_index + len(bound_chars)
)
if end_index < 0:
break
end_index += len(bound_chars)
chunk = rendered[start_index: end_index] \
.strip('$') \
.strip() \
.replace('@', '\\')
if inline:
chunk = chunk.replace('\\', '\\\\')
chunk = latex(chunk, inline)
rendered = '{pre}{gap}{latex}{gap}{post}'.format(
pre=rendered[:start_index],
latex=chunk,
post=rendered[end_index:],
gap='' if inline else '\n\n'
)
if 'katex' not in library_includes:
library_includes.append('katex')
offset = end_index
extensions = [
'markdown.extensions.extra',
'markdown.extensions.admonition',
'markdown.extensions.sane_lists',
'markdown.extensions.nl2br' if preserve_lines else None
]
body = templating.render_template(
'markdown-block.html',
text=md.markdown(rendered, extensions=[
e for e in extensions if e is not None
]),
font_size=font_size
)
pattern = re.compile('src="(?P<url>[^"]+)"')
body = pattern.sub(r'data-src="\g<url>"', body)
return dict(
body=body,
library_includes=library_includes,
rendered=rendered
) | [
"def",
"markdown",
"(",
"source",
":",
"str",
"=",
"None",
",",
"source_path",
":",
"str",
"=",
"None",
",",
"preserve_lines",
":",
"bool",
"=",
"False",
",",
"font_size",
":",
"float",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
... | Renders a markdown file with support for Jinja2 templating. Any keyword
arguments will be passed to Jinja2 for templating prior to rendering the
markdown to HTML for display within the notebook.
:param source:
A string of markdown text that should be rendered to HTML for
notebook display.
:param source_path:
The path to a markdown file that should be rendered to HTML for
notebook display.
: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.
:return:
The HTML results of rendering the specified markdown string or file. | [
"Renders",
"a",
"markdown",
"file",
"with",
"support",
"for",
"Jinja2",
"templating",
".",
"Any",
"keyword",
"arguments",
"will",
"be",
"passed",
"to",
"Jinja2",
"for",
"templating",
"prior",
"to",
"rendering",
"the",
"markdown",
"to",
"HTML",
"for",
"display"... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/render/texts.py#L156-L261 | train | 44,745 |
sernst/cauldron | setup.py | populate_extra_files | def populate_extra_files():
"""
Creates a list of non-python data files to include in package distribution
"""
out = ['cauldron/settings.json']
for entry in glob.iglob('cauldron/resources/examples/**/*', recursive=True):
out.append(entry)
for entry in glob.iglob('cauldron/resources/templates/**/*', recursive=True):
out.append(entry)
for entry in glob.iglob('cauldron/resources/web/**/*', recursive=True):
out.append(entry)
return out | python | def populate_extra_files():
"""
Creates a list of non-python data files to include in package distribution
"""
out = ['cauldron/settings.json']
for entry in glob.iglob('cauldron/resources/examples/**/*', recursive=True):
out.append(entry)
for entry in glob.iglob('cauldron/resources/templates/**/*', recursive=True):
out.append(entry)
for entry in glob.iglob('cauldron/resources/web/**/*', recursive=True):
out.append(entry)
return out | [
"def",
"populate_extra_files",
"(",
")",
":",
"out",
"=",
"[",
"'cauldron/settings.json'",
"]",
"for",
"entry",
"in",
"glob",
".",
"iglob",
"(",
"'cauldron/resources/examples/**/*'",
",",
"recursive",
"=",
"True",
")",
":",
"out",
".",
"append",
"(",
"entry",
... | Creates a list of non-python data files to include in package distribution | [
"Creates",
"a",
"list",
"of",
"non",
"-",
"python",
"data",
"files",
"to",
"include",
"in",
"package",
"distribution"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/setup.py#L39-L55 | train | 44,746 |
sernst/cauldron | cauldron/cli/commands/steps/renaming.py | create_rename_entry | def create_rename_entry(
step: 'projects.ProjectStep',
insertion_index: int = None,
stash_path: str = None
) -> typing.Union[None, STEP_RENAME]:
"""
Creates a STEP_RENAME for the given ProjectStep instance
:param step:
The ProjectStep instance for which the STEP_RENAME will be created
:param insertion_index:
An optional index where a step will be inserted as part of this
renaming process. Allows files to be renamed prior to the insertion
of the step to prevent conflicts.
:param stash_path:
:return:
"""
project = step.project
name = step.definition.name
name_parts = naming.explode_filename(name, project.naming_scheme)
index = project.index_of_step(name)
name_index = index
if insertion_index is not None and insertion_index <= index:
# Adjusts indexing when renaming is for the purpose of
# inserting a new step
name_index += 1
name_parts['index'] = name_index
new_name = naming.assemble_filename(
scheme=project.naming_scheme,
**name_parts
)
if name == new_name:
return None
if not stash_path:
fd, stash_path = tempfile.mkstemp(
prefix='{}-{}--{}--'.format(step.reference_id, name, new_name)
)
os.close(fd)
return STEP_RENAME(
id=step.reference_id,
index=index,
old_name=name,
new_name=new_name,
old_path=step.source_path,
stash_path=stash_path,
new_path=os.path.join(step.project.source_directory, new_name)
) | python | def create_rename_entry(
step: 'projects.ProjectStep',
insertion_index: int = None,
stash_path: str = None
) -> typing.Union[None, STEP_RENAME]:
"""
Creates a STEP_RENAME for the given ProjectStep instance
:param step:
The ProjectStep instance for which the STEP_RENAME will be created
:param insertion_index:
An optional index where a step will be inserted as part of this
renaming process. Allows files to be renamed prior to the insertion
of the step to prevent conflicts.
:param stash_path:
:return:
"""
project = step.project
name = step.definition.name
name_parts = naming.explode_filename(name, project.naming_scheme)
index = project.index_of_step(name)
name_index = index
if insertion_index is not None and insertion_index <= index:
# Adjusts indexing when renaming is for the purpose of
# inserting a new step
name_index += 1
name_parts['index'] = name_index
new_name = naming.assemble_filename(
scheme=project.naming_scheme,
**name_parts
)
if name == new_name:
return None
if not stash_path:
fd, stash_path = tempfile.mkstemp(
prefix='{}-{}--{}--'.format(step.reference_id, name, new_name)
)
os.close(fd)
return STEP_RENAME(
id=step.reference_id,
index=index,
old_name=name,
new_name=new_name,
old_path=step.source_path,
stash_path=stash_path,
new_path=os.path.join(step.project.source_directory, new_name)
) | [
"def",
"create_rename_entry",
"(",
"step",
":",
"'projects.ProjectStep'",
",",
"insertion_index",
":",
"int",
"=",
"None",
",",
"stash_path",
":",
"str",
"=",
"None",
")",
"->",
"typing",
".",
"Union",
"[",
"None",
",",
"STEP_RENAME",
"]",
":",
"project",
... | Creates a STEP_RENAME for the given ProjectStep instance
:param step:
The ProjectStep instance for which the STEP_RENAME will be created
:param insertion_index:
An optional index where a step will be inserted as part of this
renaming process. Allows files to be renamed prior to the insertion
of the step to prevent conflicts.
:param stash_path:
:return: | [
"Creates",
"a",
"STEP_RENAME",
"for",
"the",
"given",
"ProjectStep",
"instance"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/commands/steps/renaming.py#L24-L76 | train | 44,747 |
sernst/cauldron | cauldron/cli/sync/comm.py | assemble_url | def assemble_url(
endpoint: str,
remote_connection: 'environ.RemoteConnection' = None
) -> str:
"""
Assembles a fully-resolved remote connection URL from the given endpoint
and remote_connection structure. If the remote_connection is omitted, the
global remote_connection object stored in the environ module will be
used in its place.
:param endpoint:
The endpoint for the API call
:param remote_connection:
The remote connection definition data structure
:return:
The fully-resolved URL for the given endpoint
"""
url_root = (
remote_connection.url
if remote_connection else
environ.remote_connection.url
)
url_root = url_root if url_root else 'localhost:5010'
parts = [
'http://' if not url_root.startswith('http') else '',
url_root.rstrip('/'),
'/',
endpoint.lstrip('/')
]
return ''.join(parts) | python | def assemble_url(
endpoint: str,
remote_connection: 'environ.RemoteConnection' = None
) -> str:
"""
Assembles a fully-resolved remote connection URL from the given endpoint
and remote_connection structure. If the remote_connection is omitted, the
global remote_connection object stored in the environ module will be
used in its place.
:param endpoint:
The endpoint for the API call
:param remote_connection:
The remote connection definition data structure
:return:
The fully-resolved URL for the given endpoint
"""
url_root = (
remote_connection.url
if remote_connection else
environ.remote_connection.url
)
url_root = url_root if url_root else 'localhost:5010'
parts = [
'http://' if not url_root.startswith('http') else '',
url_root.rstrip('/'),
'/',
endpoint.lstrip('/')
]
return ''.join(parts) | [
"def",
"assemble_url",
"(",
"endpoint",
":",
"str",
",",
"remote_connection",
":",
"'environ.RemoteConnection'",
"=",
"None",
")",
"->",
"str",
":",
"url_root",
"=",
"(",
"remote_connection",
".",
"url",
"if",
"remote_connection",
"else",
"environ",
".",
"remote... | Assembles a fully-resolved remote connection URL from the given endpoint
and remote_connection structure. If the remote_connection is omitted, the
global remote_connection object stored in the environ module will be
used in its place.
:param endpoint:
The endpoint for the API call
:param remote_connection:
The remote connection definition data structure
:return:
The fully-resolved URL for the given endpoint | [
"Assembles",
"a",
"fully",
"-",
"resolved",
"remote",
"connection",
"URL",
"from",
"the",
"given",
"endpoint",
"and",
"remote_connection",
"structure",
".",
"If",
"the",
"remote_connection",
"is",
"omitted",
"the",
"global",
"remote_connection",
"object",
"stored",
... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/comm.py#L6-L37 | train | 44,748 |
sernst/cauldron | cauldron/cli/sync/comm.py | parse_http_response | def parse_http_response(http_response: HttpResponse) -> 'environ.Response':
"""
Returns a Cauldron response object parsed from the serialized JSON data
specified in the http_response argument. If the response doesn't contain
valid Cauldron response data, an error Cauldron response object is
returned instead.
:param http_response:
The response object from an http request that contains a JSON
serialized Cauldron response object as its body
:return:
The Cauldron response object for the given http response
"""
try:
response = environ.Response.deserialize(http_response.json())
except Exception as error:
response = environ.Response().fail(
code='INVALID_REMOTE_RESPONSE',
error=error,
message='Invalid HTTP response from remote connection'
).console(
whitespace=1
).response
response.http_response = http_response
return response | python | def parse_http_response(http_response: HttpResponse) -> 'environ.Response':
"""
Returns a Cauldron response object parsed from the serialized JSON data
specified in the http_response argument. If the response doesn't contain
valid Cauldron response data, an error Cauldron response object is
returned instead.
:param http_response:
The response object from an http request that contains a JSON
serialized Cauldron response object as its body
:return:
The Cauldron response object for the given http response
"""
try:
response = environ.Response.deserialize(http_response.json())
except Exception as error:
response = environ.Response().fail(
code='INVALID_REMOTE_RESPONSE',
error=error,
message='Invalid HTTP response from remote connection'
).console(
whitespace=1
).response
response.http_response = http_response
return response | [
"def",
"parse_http_response",
"(",
"http_response",
":",
"HttpResponse",
")",
"->",
"'environ.Response'",
":",
"try",
":",
"response",
"=",
"environ",
".",
"Response",
".",
"deserialize",
"(",
"http_response",
".",
"json",
"(",
")",
")",
"except",
"Exception",
... | Returns a Cauldron response object parsed from the serialized JSON data
specified in the http_response argument. If the response doesn't contain
valid Cauldron response data, an error Cauldron response object is
returned instead.
:param http_response:
The response object from an http request that contains a JSON
serialized Cauldron response object as its body
:return:
The Cauldron response object for the given http response | [
"Returns",
"a",
"Cauldron",
"response",
"object",
"parsed",
"from",
"the",
"serialized",
"JSON",
"data",
"specified",
"in",
"the",
"http_response",
"argument",
".",
"If",
"the",
"response",
"doesn",
"t",
"contain",
"valid",
"Cauldron",
"response",
"data",
"an",
... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/comm.py#L40-L65 | train | 44,749 |
sernst/cauldron | cauldron/cli/sync/comm.py | send_request | def send_request(
endpoint: str,
data: dict = None,
remote_connection: 'environ.RemoteConnection' = None,
method: str = None,
timeout: int = 10,
max_retries: int = 10,
**kwargs
) -> 'environ.Response':
"""
Sends a request to the remote kernel specified by the RemoteConnection
object and processes the result. If the request fails or times out it
will be retried until the max retries is reached. After that a failed
response will be returned instead.
:param endpoint:
Remote endpoint where the request will be directed.
:param data:
An optional JSON-serializable dictionary containing the request
body data.
:param remote_connection:
Defines the connection to the remote server where the request will
be sent.
:param method:
The HTTP method type for the request, e.g. GET, POST.
:param timeout:
Number of seconds before the request aborts when trying to either
connect to the target endpoint or receive data from the server.
:param max_retries:
Number of retry attempts to make before giving up if a non-HTTP
error is encountered during communication.
"""
if max_retries < 0:
return environ.Response().fail(
code='COMMUNICATION_ERROR',
error=None,
message='Unable to communicate with the remote kernel.'
).console(whitespace=1).response
url = assemble_url(endpoint, remote_connection)
retriable_errors = (
requests.ConnectionError,
requests.HTTPError,
requests.Timeout
)
default_method = 'POST' if data is not None else 'GET'
try:
http_response = requests.request(
method=method or default_method,
url=url,
json=data,
timeout=10,
**kwargs
)
except retriable_errors:
return send_request(
endpoint=endpoint,
data=data,
remote_connection=remote_connection,
method=method,
timeout=timeout,
max_retries=max_retries - 1,
**kwargs
)
return parse_http_response(http_response) | python | def send_request(
endpoint: str,
data: dict = None,
remote_connection: 'environ.RemoteConnection' = None,
method: str = None,
timeout: int = 10,
max_retries: int = 10,
**kwargs
) -> 'environ.Response':
"""
Sends a request to the remote kernel specified by the RemoteConnection
object and processes the result. If the request fails or times out it
will be retried until the max retries is reached. After that a failed
response will be returned instead.
:param endpoint:
Remote endpoint where the request will be directed.
:param data:
An optional JSON-serializable dictionary containing the request
body data.
:param remote_connection:
Defines the connection to the remote server where the request will
be sent.
:param method:
The HTTP method type for the request, e.g. GET, POST.
:param timeout:
Number of seconds before the request aborts when trying to either
connect to the target endpoint or receive data from the server.
:param max_retries:
Number of retry attempts to make before giving up if a non-HTTP
error is encountered during communication.
"""
if max_retries < 0:
return environ.Response().fail(
code='COMMUNICATION_ERROR',
error=None,
message='Unable to communicate with the remote kernel.'
).console(whitespace=1).response
url = assemble_url(endpoint, remote_connection)
retriable_errors = (
requests.ConnectionError,
requests.HTTPError,
requests.Timeout
)
default_method = 'POST' if data is not None else 'GET'
try:
http_response = requests.request(
method=method or default_method,
url=url,
json=data,
timeout=10,
**kwargs
)
except retriable_errors:
return send_request(
endpoint=endpoint,
data=data,
remote_connection=remote_connection,
method=method,
timeout=timeout,
max_retries=max_retries - 1,
**kwargs
)
return parse_http_response(http_response) | [
"def",
"send_request",
"(",
"endpoint",
":",
"str",
",",
"data",
":",
"dict",
"=",
"None",
",",
"remote_connection",
":",
"'environ.RemoteConnection'",
"=",
"None",
",",
"method",
":",
"str",
"=",
"None",
",",
"timeout",
":",
"int",
"=",
"10",
",",
"max_... | Sends a request to the remote kernel specified by the RemoteConnection
object and processes the result. If the request fails or times out it
will be retried until the max retries is reached. After that a failed
response will be returned instead.
:param endpoint:
Remote endpoint where the request will be directed.
:param data:
An optional JSON-serializable dictionary containing the request
body data.
:param remote_connection:
Defines the connection to the remote server where the request will
be sent.
:param method:
The HTTP method type for the request, e.g. GET, POST.
:param timeout:
Number of seconds before the request aborts when trying to either
connect to the target endpoint or receive data from the server.
:param max_retries:
Number of retry attempts to make before giving up if a non-HTTP
error is encountered during communication. | [
"Sends",
"a",
"request",
"to",
"the",
"remote",
"kernel",
"specified",
"by",
"the",
"RemoteConnection",
"object",
"and",
"processes",
"the",
"result",
".",
"If",
"the",
"request",
"fails",
"or",
"times",
"out",
"it",
"will",
"be",
"retried",
"until",
"the",
... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/sync/comm.py#L68-L134 | train | 44,750 |
sernst/cauldron | cauldron/cli/server/routes/display.py | view | def view(route: str):
"""
Retrieves the contents of the file specified by the view route if it
exists.
"""
project = cauldron.project.get_internal_project()
results_path = project.results_path if project else None
if not project or not results_path:
return '', 204
path = os.path.join(results_path, route)
if not os.path.exists(path):
return '', 204
return flask.send_file(
path,
mimetype=mimetypes.guess_type(path)[0],
cache_timeout=-1
) | python | def view(route: str):
"""
Retrieves the contents of the file specified by the view route if it
exists.
"""
project = cauldron.project.get_internal_project()
results_path = project.results_path if project else None
if not project or not results_path:
return '', 204
path = os.path.join(results_path, route)
if not os.path.exists(path):
return '', 204
return flask.send_file(
path,
mimetype=mimetypes.guess_type(path)[0],
cache_timeout=-1
) | [
"def",
"view",
"(",
"route",
":",
"str",
")",
":",
"project",
"=",
"cauldron",
".",
"project",
".",
"get_internal_project",
"(",
")",
"results_path",
"=",
"project",
".",
"results_path",
"if",
"project",
"else",
"None",
"if",
"not",
"project",
"or",
"not",... | Retrieves the contents of the file specified by the view route if it
exists. | [
"Retrieves",
"the",
"contents",
"of",
"the",
"file",
"specified",
"by",
"the",
"view",
"route",
"if",
"it",
"exists",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/cli/server/routes/display.py#L10-L28 | train | 44,751 |
sernst/cauldron | cauldron/session/writing/__init__.py | save | def save(
project: 'projects.Project',
write_list: typing.List[tuple] = None
) -> typing.List[tuple]:
"""
Computes the file write list for the current state of the project if no
write_list was specified in the arguments, and then writes each entry in
that list to disk.
:param project:
The project to be saved
:param write_list:
The file writes list for the project if one already exists, or None
if a new writes list should be computed
:return:
The file write list that was used to save the project to disk
"""
try:
writes = (
to_write_list(project)
if write_list is None
else write_list.copy()
)
except Exception as err:
raise
environ.systems.remove(project.output_directory)
os.makedirs(project.output_directory)
file_io.deploy(writes)
return writes | python | def save(
project: 'projects.Project',
write_list: typing.List[tuple] = None
) -> typing.List[tuple]:
"""
Computes the file write list for the current state of the project if no
write_list was specified in the arguments, and then writes each entry in
that list to disk.
:param project:
The project to be saved
:param write_list:
The file writes list for the project if one already exists, or None
if a new writes list should be computed
:return:
The file write list that was used to save the project to disk
"""
try:
writes = (
to_write_list(project)
if write_list is None
else write_list.copy()
)
except Exception as err:
raise
environ.systems.remove(project.output_directory)
os.makedirs(project.output_directory)
file_io.deploy(writes)
return writes | [
"def",
"save",
"(",
"project",
":",
"'projects.Project'",
",",
"write_list",
":",
"typing",
".",
"List",
"[",
"tuple",
"]",
"=",
"None",
")",
"->",
"typing",
".",
"List",
"[",
"tuple",
"]",
":",
"try",
":",
"writes",
"=",
"(",
"to_write_list",
"(",
"... | Computes the file write list for the current state of the project if no
write_list was specified in the arguments, and then writes each entry in
that list to disk.
:param project:
The project to be saved
:param write_list:
The file writes list for the project if one already exists, or None
if a new writes list should be computed
:return:
The file write list that was used to save the project to disk | [
"Computes",
"the",
"file",
"write",
"list",
"for",
"the",
"current",
"state",
"of",
"the",
"project",
"if",
"no",
"write_list",
"was",
"specified",
"in",
"the",
"arguments",
"and",
"then",
"writes",
"each",
"entry",
"in",
"that",
"list",
"to",
"disk",
"."
... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/__init__.py#L14-L45 | train | 44,752 |
sernst/cauldron | cauldron/runner/__init__.py | add_library_path | def add_library_path(path: str) -> bool:
"""
Adds the path to the Python system path if not already added and the path
exists.
:param path:
The path to add to the system paths
:return:
Whether or not the path was added. Only returns False if the path was
not added because it doesn't exist
"""
if not os.path.exists(path):
return False
if path not in sys.path:
sys.path.append(path)
return True | python | def add_library_path(path: str) -> bool:
"""
Adds the path to the Python system path if not already added and the path
exists.
:param path:
The path to add to the system paths
:return:
Whether or not the path was added. Only returns False if the path was
not added because it doesn't exist
"""
if not os.path.exists(path):
return False
if path not in sys.path:
sys.path.append(path)
return True | [
"def",
"add_library_path",
"(",
"path",
":",
"str",
")",
"->",
"bool",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"False",
"if",
"path",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"app... | Adds the path to the Python system path if not already added and the path
exists.
:param path:
The path to add to the system paths
:return:
Whether or not the path was added. Only returns False if the path was
not added because it doesn't exist | [
"Adds",
"the",
"path",
"to",
"the",
"Python",
"system",
"path",
"if",
"not",
"already",
"added",
"and",
"the",
"path",
"exists",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L15-L33 | train | 44,753 |
sernst/cauldron | cauldron/runner/__init__.py | remove_library_path | def remove_library_path(path: str) -> bool:
"""
Removes the path from the Python system path if it is found in the system
paths.
:param path:
The path to remove from the system paths
:return:
Whether or not the path was removed.
"""
if path in sys.path:
sys.path.remove(path)
return True
return False | python | def remove_library_path(path: str) -> bool:
"""
Removes the path from the Python system path if it is found in the system
paths.
:param path:
The path to remove from the system paths
:return:
Whether or not the path was removed.
"""
if path in sys.path:
sys.path.remove(path)
return True
return False | [
"def",
"remove_library_path",
"(",
"path",
":",
"str",
")",
"->",
"bool",
":",
"if",
"path",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"remove",
"(",
"path",
")",
"return",
"True",
"return",
"False"
] | Removes the path from the Python system path if it is found in the system
paths.
:param path:
The path to remove from the system paths
:return:
Whether or not the path was removed. | [
"Removes",
"the",
"path",
"from",
"the",
"Python",
"system",
"path",
"if",
"it",
"is",
"found",
"in",
"the",
"system",
"paths",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L36-L51 | train | 44,754 |
sernst/cauldron | cauldron/runner/__init__.py | reload_libraries | def reload_libraries(library_directories: list = None):
"""
Reload the libraries stored in the project's local and shared library
directories
"""
directories = library_directories or []
project = cauldron.project.get_internal_project()
if project:
directories += project.library_directories
if not directories:
return
def reload_module(path: str, library_directory: str):
path = os.path.dirname(path) if path.endswith('__init__.py') else path
start_index = len(library_directory) + 1
end_index = -3 if path.endswith('.py') else None
package_path = path[start_index:end_index]
module = sys.modules.get(package_path.replace(os.sep, '.'))
return importlib.reload(module) if module is not None else None
def reload_library(directory: str) -> list:
if not add_library_path(directory):
# If the library wasn't added because it doesn't exist, remove it
# in case the directory has recently been deleted and then return
# an empty result
remove_library_path(directory)
return []
glob_path = os.path.join(directory, '**', '*.py')
return [
reload_module(path, directory)
for path in glob.glob(glob_path, recursive=True)
]
return [
reloaded_module
for directory in directories
for reloaded_module in reload_library(directory)
if reload_module is not None
] | python | def reload_libraries(library_directories: list = None):
"""
Reload the libraries stored in the project's local and shared library
directories
"""
directories = library_directories or []
project = cauldron.project.get_internal_project()
if project:
directories += project.library_directories
if not directories:
return
def reload_module(path: str, library_directory: str):
path = os.path.dirname(path) if path.endswith('__init__.py') else path
start_index = len(library_directory) + 1
end_index = -3 if path.endswith('.py') else None
package_path = path[start_index:end_index]
module = sys.modules.get(package_path.replace(os.sep, '.'))
return importlib.reload(module) if module is not None else None
def reload_library(directory: str) -> list:
if not add_library_path(directory):
# If the library wasn't added because it doesn't exist, remove it
# in case the directory has recently been deleted and then return
# an empty result
remove_library_path(directory)
return []
glob_path = os.path.join(directory, '**', '*.py')
return [
reload_module(path, directory)
for path in glob.glob(glob_path, recursive=True)
]
return [
reloaded_module
for directory in directories
for reloaded_module in reload_library(directory)
if reload_module is not None
] | [
"def",
"reload_libraries",
"(",
"library_directories",
":",
"list",
"=",
"None",
")",
":",
"directories",
"=",
"library_directories",
"or",
"[",
"]",
"project",
"=",
"cauldron",
".",
"project",
".",
"get_internal_project",
"(",
")",
"if",
"project",
":",
"dire... | Reload the libraries stored in the project's local and shared library
directories | [
"Reload",
"the",
"libraries",
"stored",
"in",
"the",
"project",
"s",
"local",
"and",
"shared",
"library",
"directories"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L82-L123 | train | 44,755 |
sernst/cauldron | cauldron/runner/__init__.py | complete | def complete(
response: Response,
project: typing.Union[Project, None],
starting: ProjectStep = None,
force: bool = False,
limit: int = -1
) -> list:
"""
Runs the entire project, writes the results files, and returns the URL to
the report file
:param response:
:param project:
:param starting:
:param force:
:param limit:
:return:
Local URL to the report path
"""
if project is None:
project = cauldron.project.get_internal_project()
starting_index = 0
if starting:
starting_index = project.steps.index(starting)
count = 0
steps_run = []
for ps in project.steps:
if 0 < limit <= count:
break
if ps.index < starting_index:
continue
if not force and not ps.is_dirty():
if limit < 1:
environ.log(
'[{}]: Nothing to update'.format(ps.definition.name)
)
continue
count += 1
steps_run.append(ps)
success = source.run_step(response, project, ps, force=True)
if not success or project.stop_condition.halt:
return steps_run
return steps_run | python | def complete(
response: Response,
project: typing.Union[Project, None],
starting: ProjectStep = None,
force: bool = False,
limit: int = -1
) -> list:
"""
Runs the entire project, writes the results files, and returns the URL to
the report file
:param response:
:param project:
:param starting:
:param force:
:param limit:
:return:
Local URL to the report path
"""
if project is None:
project = cauldron.project.get_internal_project()
starting_index = 0
if starting:
starting_index = project.steps.index(starting)
count = 0
steps_run = []
for ps in project.steps:
if 0 < limit <= count:
break
if ps.index < starting_index:
continue
if not force and not ps.is_dirty():
if limit < 1:
environ.log(
'[{}]: Nothing to update'.format(ps.definition.name)
)
continue
count += 1
steps_run.append(ps)
success = source.run_step(response, project, ps, force=True)
if not success or project.stop_condition.halt:
return steps_run
return steps_run | [
"def",
"complete",
"(",
"response",
":",
"Response",
",",
"project",
":",
"typing",
".",
"Union",
"[",
"Project",
",",
"None",
"]",
",",
"starting",
":",
"ProjectStep",
"=",
"None",
",",
"force",
":",
"bool",
"=",
"False",
",",
"limit",
":",
"int",
"... | Runs the entire project, writes the results files, and returns the URL to
the report file
:param response:
:param project:
:param starting:
:param force:
:param limit:
:return:
Local URL to the report path | [
"Runs",
"the",
"entire",
"project",
"writes",
"the",
"results",
"files",
"and",
"returns",
"the",
"URL",
"to",
"the",
"report",
"file"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/runner/__init__.py#L180-L231 | train | 44,756 |
sernst/cauldron | cauldron/session/projects/steps.py | ProjectStep.elapsed_time | def elapsed_time(self) -> float:
"""
The number of seconds that has elapsed since the step started running
if the step is still running. Or, if the step has already finished
running, the amount of time that elapsed during the last execution of
the step.
"""
current_time = datetime.utcnow()
start = self.start_time or current_time
end = self.end_time or current_time
return (end - start).total_seconds() | python | def elapsed_time(self) -> float:
"""
The number of seconds that has elapsed since the step started running
if the step is still running. Or, if the step has already finished
running, the amount of time that elapsed during the last execution of
the step.
"""
current_time = datetime.utcnow()
start = self.start_time or current_time
end = self.end_time or current_time
return (end - start).total_seconds() | [
"def",
"elapsed_time",
"(",
"self",
")",
"->",
"float",
":",
"current_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"start",
"=",
"self",
".",
"start_time",
"or",
"current_time",
"end",
"=",
"self",
".",
"end_time",
"or",
"current_time",
"return",
"(",
... | The number of seconds that has elapsed since the step started running
if the step is still running. Or, if the step has already finished
running, the amount of time that elapsed during the last execution of
the step. | [
"The",
"number",
"of",
"seconds",
"that",
"has",
"elapsed",
"since",
"the",
"step",
"started",
"running",
"if",
"the",
"step",
"is",
"still",
"running",
".",
"Or",
"if",
"the",
"step",
"has",
"already",
"finished",
"running",
"the",
"amount",
"of",
"time",... | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L97-L107 | train | 44,757 |
sernst/cauldron | cauldron/session/projects/steps.py | ProjectStep.get_elapsed_timestamp | def get_elapsed_timestamp(self) -> str:
"""
A human-readable version of the elapsed time for the last execution
of the step. The value is derived from the `ProjectStep.elapsed_time`
property.
"""
t = self.elapsed_time
minutes = int(t / 60)
seconds = int(t - (60 * minutes))
millis = int(100 * (t - int(t)))
return '{:>02d}:{:>02d}.{:<02d}'.format(minutes, seconds, millis) | python | def get_elapsed_timestamp(self) -> str:
"""
A human-readable version of the elapsed time for the last execution
of the step. The value is derived from the `ProjectStep.elapsed_time`
property.
"""
t = self.elapsed_time
minutes = int(t / 60)
seconds = int(t - (60 * minutes))
millis = int(100 * (t - int(t)))
return '{:>02d}:{:>02d}.{:<02d}'.format(minutes, seconds, millis) | [
"def",
"get_elapsed_timestamp",
"(",
"self",
")",
"->",
"str",
":",
"t",
"=",
"self",
".",
"elapsed_time",
"minutes",
"=",
"int",
"(",
"t",
"/",
"60",
")",
"seconds",
"=",
"int",
"(",
"t",
"-",
"(",
"60",
"*",
"minutes",
")",
")",
"millis",
"=",
... | A human-readable version of the elapsed time for the last execution
of the step. The value is derived from the `ProjectStep.elapsed_time`
property. | [
"A",
"human",
"-",
"readable",
"version",
"of",
"the",
"elapsed",
"time",
"for",
"the",
"last",
"execution",
"of",
"the",
"step",
".",
"The",
"value",
"is",
"derived",
"from",
"the",
"ProjectStep",
".",
"elapsed_time",
"property",
"."
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L109-L119 | train | 44,758 |
sernst/cauldron | cauldron/session/projects/steps.py | ProjectStep.get_dom | def get_dom(self) -> str:
""" Retrieves the current value of the DOM for the step """
if self.is_running:
return self.dumps()
if self.dom is not None:
return self.dom
dom = self.dumps()
self.dom = dom
return dom | python | def get_dom(self) -> str:
""" Retrieves the current value of the DOM for the step """
if self.is_running:
return self.dumps()
if self.dom is not None:
return self.dom
dom = self.dumps()
self.dom = dom
return dom | [
"def",
"get_dom",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"is_running",
":",
"return",
"self",
".",
"dumps",
"(",
")",
"if",
"self",
".",
"dom",
"is",
"not",
"None",
":",
"return",
"self",
".",
"dom",
"dom",
"=",
"self",
".",
"dump... | Retrieves the current value of the DOM for the step | [
"Retrieves",
"the",
"current",
"value",
"of",
"the",
"DOM",
"for",
"the",
"step"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L179-L190 | train | 44,759 |
sernst/cauldron | cauldron/session/projects/steps.py | ProjectStep.dumps | def dumps(self) -> str:
"""Writes the step information to an HTML-formatted string"""
code_file_path = os.path.join(
self.project.source_directory,
self.filename
)
code = dict(
filename=self.filename,
path=code_file_path,
code=render.code_file(code_file_path)
)
if not self.is_running:
# If no longer running, make sure to flush the stdout buffer so
# any print statements at the end of the step get included in
# the body
self.report.flush_stdout()
# Create a copy of the body for dumping
body = self.report.body[:]
if self.is_running:
# If still running add a temporary copy of anything not flushed
# from the stdout buffer to the copy of the body for display. Do
# not flush the buffer though until the step is done running or
# it gets flushed by another display call.
body.append(self.report.read_stdout())
body = ''.join(body)
has_body = len(body) > 0 and (
body.find('<div') != -1 or
body.find('<span') != -1 or
body.find('<p') != -1 or
body.find('<pre') != -1 or
body.find('<h') != -1 or
body.find('<ol') != -1 or
body.find('<ul') != -1 or
body.find('<li') != -1
)
std_err = (
self.report.read_stderr()
if self.is_running else
self.report.flush_stderr()
).strip('\n').rstrip()
# The step will be visible in the display if any of the following
# conditions are true.
is_visible = self.is_visible or self.is_running or self.error
dom = templating.render_template(
'step-body.html',
last_display_update=self.report.last_update_time,
elapsed_time=self.get_elapsed_timestamp(),
code=code,
body=body,
has_body=has_body,
id=self.definition.name,
title=self.report.title,
subtitle=self.report.subtitle,
summary=self.report.summary,
error=self.error,
index=self.index,
is_running=self.is_running,
is_visible=is_visible,
progress_message=self.progress_message,
progress=int(round(max(0, min(100, 100 * self.progress)))),
sub_progress_message=self.sub_progress_message,
sub_progress=int(round(max(0, min(100, 100 * self.sub_progress)))),
std_err=std_err
)
if not self.is_running:
self.dom = dom
return dom | python | def dumps(self) -> str:
"""Writes the step information to an HTML-formatted string"""
code_file_path = os.path.join(
self.project.source_directory,
self.filename
)
code = dict(
filename=self.filename,
path=code_file_path,
code=render.code_file(code_file_path)
)
if not self.is_running:
# If no longer running, make sure to flush the stdout buffer so
# any print statements at the end of the step get included in
# the body
self.report.flush_stdout()
# Create a copy of the body for dumping
body = self.report.body[:]
if self.is_running:
# If still running add a temporary copy of anything not flushed
# from the stdout buffer to the copy of the body for display. Do
# not flush the buffer though until the step is done running or
# it gets flushed by another display call.
body.append(self.report.read_stdout())
body = ''.join(body)
has_body = len(body) > 0 and (
body.find('<div') != -1 or
body.find('<span') != -1 or
body.find('<p') != -1 or
body.find('<pre') != -1 or
body.find('<h') != -1 or
body.find('<ol') != -1 or
body.find('<ul') != -1 or
body.find('<li') != -1
)
std_err = (
self.report.read_stderr()
if self.is_running else
self.report.flush_stderr()
).strip('\n').rstrip()
# The step will be visible in the display if any of the following
# conditions are true.
is_visible = self.is_visible or self.is_running or self.error
dom = templating.render_template(
'step-body.html',
last_display_update=self.report.last_update_time,
elapsed_time=self.get_elapsed_timestamp(),
code=code,
body=body,
has_body=has_body,
id=self.definition.name,
title=self.report.title,
subtitle=self.report.subtitle,
summary=self.report.summary,
error=self.error,
index=self.index,
is_running=self.is_running,
is_visible=is_visible,
progress_message=self.progress_message,
progress=int(round(max(0, min(100, 100 * self.progress)))),
sub_progress_message=self.sub_progress_message,
sub_progress=int(round(max(0, min(100, 100 * self.sub_progress)))),
std_err=std_err
)
if not self.is_running:
self.dom = dom
return dom | [
"def",
"dumps",
"(",
"self",
")",
"->",
"str",
":",
"code_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project",
".",
"source_directory",
",",
"self",
".",
"filename",
")",
"code",
"=",
"dict",
"(",
"filename",
"=",
"self",
"."... | Writes the step information to an HTML-formatted string | [
"Writes",
"the",
"step",
"information",
"to",
"an",
"HTML",
"-",
"formatted",
"string"
] | 4086aec9c038c402ea212c79fe8bd0d27104f9cf | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L192-L267 | train | 44,760 |
seomoz/qless-py | qless/__init__.py | retry | def retry(*excepts):
'''A decorator to specify a bunch of exceptions that should be caught
and the job retried. It turns out this comes up with relative frequency'''
@decorator.decorator
def new_func(func, job):
'''No docstring'''
try:
func(job)
except tuple(excepts):
job.retry()
return new_func | python | def retry(*excepts):
'''A decorator to specify a bunch of exceptions that should be caught
and the job retried. It turns out this comes up with relative frequency'''
@decorator.decorator
def new_func(func, job):
'''No docstring'''
try:
func(job)
except tuple(excepts):
job.retry()
return new_func | [
"def",
"retry",
"(",
"*",
"excepts",
")",
":",
"@",
"decorator",
".",
"decorator",
"def",
"new_func",
"(",
"func",
",",
"job",
")",
":",
"'''No docstring'''",
"try",
":",
"func",
"(",
"job",
")",
"except",
"tuple",
"(",
"excepts",
")",
":",
"job",
".... | A decorator to specify a bunch of exceptions that should be caught
and the job retried. It turns out this comes up with relative frequency | [
"A",
"decorator",
"to",
"specify",
"a",
"bunch",
"of",
"exceptions",
"that",
"should",
"be",
"caught",
"and",
"the",
"job",
"retried",
".",
"It",
"turns",
"out",
"this",
"comes",
"up",
"with",
"relative",
"frequency"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L28-L38 | train | 44,761 |
seomoz/qless-py | qless/__init__.py | Jobs.tracked | def tracked(self):
'''Return an array of job objects that are being tracked'''
results = json.loads(self.client('track'))
results['jobs'] = [Job(self, **job) for job in results['jobs']]
return results | python | def tracked(self):
'''Return an array of job objects that are being tracked'''
results = json.loads(self.client('track'))
results['jobs'] = [Job(self, **job) for job in results['jobs']]
return results | [
"def",
"tracked",
"(",
"self",
")",
":",
"results",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"client",
"(",
"'track'",
")",
")",
"results",
"[",
"'jobs'",
"]",
"=",
"[",
"Job",
"(",
"self",
",",
"*",
"*",
"job",
")",
"for",
"job",
"in",
"re... | Return an array of job objects that are being tracked | [
"Return",
"an",
"array",
"of",
"job",
"objects",
"that",
"are",
"being",
"tracked"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L50-L54 | train | 44,762 |
seomoz/qless-py | qless/__init__.py | Jobs.tagged | def tagged(self, tag, offset=0, count=25):
'''Return the paginated jids of jobs tagged with a tag'''
return json.loads(self.client('tag', 'get', tag, offset, count)) | python | def tagged(self, tag, offset=0, count=25):
'''Return the paginated jids of jobs tagged with a tag'''
return json.loads(self.client('tag', 'get', tag, offset, count)) | [
"def",
"tagged",
"(",
"self",
",",
"tag",
",",
"offset",
"=",
"0",
",",
"count",
"=",
"25",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"client",
"(",
"'tag'",
",",
"'get'",
",",
"tag",
",",
"offset",
",",
"count",
")",
")"
] | Return the paginated jids of jobs tagged with a tag | [
"Return",
"the",
"paginated",
"jids",
"of",
"jobs",
"tagged",
"with",
"a",
"tag"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L56-L58 | train | 44,763 |
seomoz/qless-py | qless/__init__.py | Jobs.failed | def failed(self, group=None, start=0, limit=25):
'''If no group is provided, this returns a JSON blob of the counts of
the various types of failures known. If a type is provided, returns
paginated job objects affected by that kind of failure.'''
if not group:
return json.loads(self.client('failed'))
else:
results = json.loads(
self.client('failed', group, start, limit))
results['jobs'] = self.get(*results['jobs'])
return results | python | def failed(self, group=None, start=0, limit=25):
'''If no group is provided, this returns a JSON blob of the counts of
the various types of failures known. If a type is provided, returns
paginated job objects affected by that kind of failure.'''
if not group:
return json.loads(self.client('failed'))
else:
results = json.loads(
self.client('failed', group, start, limit))
results['jobs'] = self.get(*results['jobs'])
return results | [
"def",
"failed",
"(",
"self",
",",
"group",
"=",
"None",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"25",
")",
":",
"if",
"not",
"group",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"client",
"(",
"'failed'",
")",
")",
"else",
":",
"... | If no group is provided, this returns a JSON blob of the counts of
the various types of failures known. If a type is provided, returns
paginated job objects affected by that kind of failure. | [
"If",
"no",
"group",
"is",
"provided",
"this",
"returns",
"a",
"JSON",
"blob",
"of",
"the",
"counts",
"of",
"the",
"various",
"types",
"of",
"failures",
"known",
".",
"If",
"a",
"type",
"is",
"provided",
"returns",
"paginated",
"job",
"objects",
"affected"... | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L60-L70 | train | 44,764 |
seomoz/qless-py | qless/__init__.py | Jobs.get | def get(self, *jids):
'''Return jobs objects for all the jids'''
if jids:
return [
Job(self.client, **j) for j in
json.loads(self.client('multiget', *jids))]
return [] | python | def get(self, *jids):
'''Return jobs objects for all the jids'''
if jids:
return [
Job(self.client, **j) for j in
json.loads(self.client('multiget', *jids))]
return [] | [
"def",
"get",
"(",
"self",
",",
"*",
"jids",
")",
":",
"if",
"jids",
":",
"return",
"[",
"Job",
"(",
"self",
".",
"client",
",",
"*",
"*",
"j",
")",
"for",
"j",
"in",
"json",
".",
"loads",
"(",
"self",
".",
"client",
"(",
"'multiget'",
",",
"... | Return jobs objects for all the jids | [
"Return",
"jobs",
"objects",
"for",
"all",
"the",
"jids"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/__init__.py#L72-L78 | train | 44,765 |
seomoz/qless-py | qless/workers/__init__.py | Worker.title | def title(cls, message=None):
'''Set the title of the process'''
if message == None:
return getproctitle()
else:
setproctitle('qless-py-worker %s' % message)
logger.info(message) | python | def title(cls, message=None):
'''Set the title of the process'''
if message == None:
return getproctitle()
else:
setproctitle('qless-py-worker %s' % message)
logger.info(message) | [
"def",
"title",
"(",
"cls",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"==",
"None",
":",
"return",
"getproctitle",
"(",
")",
"else",
":",
"setproctitle",
"(",
"'qless-py-worker %s'",
"%",
"message",
")",
"logger",
".",
"info",
"(",
"message... | Set the title of the process | [
"Set",
"the",
"title",
"of",
"the",
"process"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L43-L49 | train | 44,766 |
seomoz/qless-py | qless/workers/__init__.py | Worker.divide | def divide(cls, jobs, count):
'''Divide up the provided jobs into count evenly-sized groups'''
jobs = list(zip(*zip_longest(*[iter(jobs)] * count)))
# If we had no jobs to resume, then we get an empty list
jobs = jobs or [()] * count
for index in range(count):
# Filter out the items in jobs that are Nones
jobs[index] = [j for j in jobs[index] if j != None]
return jobs | python | def divide(cls, jobs, count):
'''Divide up the provided jobs into count evenly-sized groups'''
jobs = list(zip(*zip_longest(*[iter(jobs)] * count)))
# If we had no jobs to resume, then we get an empty list
jobs = jobs or [()] * count
for index in range(count):
# Filter out the items in jobs that are Nones
jobs[index] = [j for j in jobs[index] if j != None]
return jobs | [
"def",
"divide",
"(",
"cls",
",",
"jobs",
",",
"count",
")",
":",
"jobs",
"=",
"list",
"(",
"zip",
"(",
"*",
"zip_longest",
"(",
"*",
"[",
"iter",
"(",
"jobs",
")",
"]",
"*",
"count",
")",
")",
")",
"# If we had no jobs to resume, then we get an empty li... | Divide up the provided jobs into count evenly-sized groups | [
"Divide",
"up",
"the",
"provided",
"jobs",
"into",
"count",
"evenly",
"-",
"sized",
"groups"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L52-L60 | train | 44,767 |
seomoz/qless-py | qless/workers/__init__.py | Worker.clean | def clean(cls, path):
'''Clean up all the files in a provided path'''
for pth in os.listdir(path):
pth = os.path.abspath(os.path.join(path, pth))
if os.path.isdir(pth):
logger.debug('Removing directory %s' % pth)
shutil.rmtree(pth)
else:
logger.debug('Removing file %s' % pth)
os.remove(pth) | python | def clean(cls, path):
'''Clean up all the files in a provided path'''
for pth in os.listdir(path):
pth = os.path.abspath(os.path.join(path, pth))
if os.path.isdir(pth):
logger.debug('Removing directory %s' % pth)
shutil.rmtree(pth)
else:
logger.debug('Removing file %s' % pth)
os.remove(pth) | [
"def",
"clean",
"(",
"cls",
",",
"path",
")",
":",
"for",
"pth",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"pth",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"pth",
")",
")",
"if",
... | Clean up all the files in a provided path | [
"Clean",
"up",
"all",
"the",
"files",
"in",
"a",
"provided",
"path"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L63-L72 | train | 44,768 |
seomoz/qless-py | qless/workers/__init__.py | Worker.sandbox | def sandbox(cls, path):
'''Ensures path exists before yielding, cleans up after'''
# Ensure the path exists and is clean
try:
os.makedirs(path)
logger.debug('Making %s' % path)
except OSError:
if not os.path.isdir(path):
raise
finally:
cls.clean(path)
# Then yield, but make sure to clean up the directory afterwards
try:
yield
finally:
cls.clean(path) | python | def sandbox(cls, path):
'''Ensures path exists before yielding, cleans up after'''
# Ensure the path exists and is clean
try:
os.makedirs(path)
logger.debug('Making %s' % path)
except OSError:
if not os.path.isdir(path):
raise
finally:
cls.clean(path)
# Then yield, but make sure to clean up the directory afterwards
try:
yield
finally:
cls.clean(path) | [
"def",
"sandbox",
"(",
"cls",
",",
"path",
")",
":",
"# Ensure the path exists and is clean",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"'Making %s'",
"%",
"path",
")",
"except",
"OSError",
":",
"if",
"not",
"os",
... | Ensures path exists before yielding, cleans up after | [
"Ensures",
"path",
"exists",
"before",
"yielding",
"cleans",
"up",
"after"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L76-L91 | train | 44,769 |
seomoz/qless-py | qless/workers/__init__.py | Worker.resumable | def resumable(self):
'''Find all the jobs that we'd previously been working on'''
# First, find the jids of all the jobs registered to this client.
# Then, get the corresponding job objects
jids = self.client.workers[self.client.worker_name]['jobs']
jobs = self.client.jobs.get(*jids)
# We'll filter out all the jobs that aren't in any of the queues
# we're working on.
queue_names = set([queue.name for queue in self.queues])
return [job for job in jobs if job.queue_name in queue_names] | python | def resumable(self):
'''Find all the jobs that we'd previously been working on'''
# First, find the jids of all the jobs registered to this client.
# Then, get the corresponding job objects
jids = self.client.workers[self.client.worker_name]['jobs']
jobs = self.client.jobs.get(*jids)
# We'll filter out all the jobs that aren't in any of the queues
# we're working on.
queue_names = set([queue.name for queue in self.queues])
return [job for job in jobs if job.queue_name in queue_names] | [
"def",
"resumable",
"(",
"self",
")",
":",
"# First, find the jids of all the jobs registered to this client.",
"# Then, get the corresponding job objects",
"jids",
"=",
"self",
".",
"client",
".",
"workers",
"[",
"self",
".",
"client",
".",
"worker_name",
"]",
"[",
"'j... | Find all the jobs that we'd previously been working on | [
"Find",
"all",
"the",
"jobs",
"that",
"we",
"d",
"previously",
"been",
"working",
"on"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L116-L126 | train | 44,770 |
seomoz/qless-py | qless/workers/__init__.py | Worker.jobs | def jobs(self):
'''Generator for all the jobs'''
# If we should resume work, then we should hand those out first,
# assuming we can still heartbeat them
for job in self.resume:
try:
if job.heartbeat():
yield job
except exceptions.LostLockException:
logger.exception('Cannot resume %s' % job.jid)
while True:
seen = False
for queue in self.queues:
job = queue.pop()
if job:
seen = True
yield job
if not seen:
yield None | python | def jobs(self):
'''Generator for all the jobs'''
# If we should resume work, then we should hand those out first,
# assuming we can still heartbeat them
for job in self.resume:
try:
if job.heartbeat():
yield job
except exceptions.LostLockException:
logger.exception('Cannot resume %s' % job.jid)
while True:
seen = False
for queue in self.queues:
job = queue.pop()
if job:
seen = True
yield job
if not seen:
yield None | [
"def",
"jobs",
"(",
"self",
")",
":",
"# If we should resume work, then we should hand those out first,",
"# assuming we can still heartbeat them",
"for",
"job",
"in",
"self",
".",
"resume",
":",
"try",
":",
"if",
"job",
".",
"heartbeat",
"(",
")",
":",
"yield",
"jo... | Generator for all the jobs | [
"Generator",
"for",
"all",
"the",
"jobs"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L128-L146 | train | 44,771 |
seomoz/qless-py | qless/workers/__init__.py | Worker.listener | def listener(self):
'''Listen for pubsub messages relevant to this worker in a thread'''
channels = ['ql:w:' + self.client.worker_name]
listener = Listener(self.client.redis, channels)
thread = threading.Thread(target=self.listen, args=(listener,))
thread.start()
try:
yield
finally:
listener.unlisten()
thread.join() | python | def listener(self):
'''Listen for pubsub messages relevant to this worker in a thread'''
channels = ['ql:w:' + self.client.worker_name]
listener = Listener(self.client.redis, channels)
thread = threading.Thread(target=self.listen, args=(listener,))
thread.start()
try:
yield
finally:
listener.unlisten()
thread.join() | [
"def",
"listener",
"(",
"self",
")",
":",
"channels",
"=",
"[",
"'ql:w:'",
"+",
"self",
".",
"client",
".",
"worker_name",
"]",
"listener",
"=",
"Listener",
"(",
"self",
".",
"client",
".",
"redis",
",",
"channels",
")",
"thread",
"=",
"threading",
"."... | Listen for pubsub messages relevant to this worker in a thread | [
"Listen",
"for",
"pubsub",
"messages",
"relevant",
"to",
"this",
"worker",
"in",
"a",
"thread"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L149-L159 | train | 44,772 |
seomoz/qless-py | qless/workers/__init__.py | Worker.listen | def listen(self, listener):
'''Listen for events that affect our ownership of a job'''
for message in listener.listen():
try:
data = json.loads(message['data'])
if data['event'] in ('canceled', 'lock_lost', 'put'):
self.kill(data['jid'])
except:
logger.exception('Pubsub error') | python | def listen(self, listener):
'''Listen for events that affect our ownership of a job'''
for message in listener.listen():
try:
data = json.loads(message['data'])
if data['event'] in ('canceled', 'lock_lost', 'put'):
self.kill(data['jid'])
except:
logger.exception('Pubsub error') | [
"def",
"listen",
"(",
"self",
",",
"listener",
")",
":",
"for",
"message",
"in",
"listener",
".",
"listen",
"(",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"message",
"[",
"'data'",
"]",
")",
"if",
"data",
"[",
"'event'",
"]",
... | Listen for events that affect our ownership of a job | [
"Listen",
"for",
"events",
"that",
"affect",
"our",
"ownership",
"of",
"a",
"job"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L161-L169 | train | 44,773 |
seomoz/qless-py | qless/workers/__init__.py | Worker.signals | def signals(self, signals=('QUIT', 'USR1', 'USR2')):
'''Register our signal handler'''
for sig in signals:
signal.signal(getattr(signal, 'SIG' + sig), self.handler) | python | def signals(self, signals=('QUIT', 'USR1', 'USR2')):
'''Register our signal handler'''
for sig in signals:
signal.signal(getattr(signal, 'SIG' + sig), self.handler) | [
"def",
"signals",
"(",
"self",
",",
"signals",
"=",
"(",
"'QUIT'",
",",
"'USR1'",
",",
"'USR2'",
")",
")",
":",
"for",
"sig",
"in",
"signals",
":",
"signal",
".",
"signal",
"(",
"getattr",
"(",
"signal",
",",
"'SIG'",
"+",
"sig",
")",
",",
"self",
... | Register our signal handler | [
"Register",
"our",
"signal",
"handler"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L175-L178 | train | 44,774 |
WimpyAnalytics/django-andablog | andablog/migrations/0004_shorten_entry_title.py | truncate_entry_titles | def truncate_entry_titles(apps, schema_editor):
"""This function will truncate the values of Entry.title so they are
255 characters or less.
"""
Entry = apps.get_model("andablog", "Entry")
for entry in Entry.objects.all():
# Truncate to 255 characters (or less) but keep whole words intact.
while len(entry.title) > TITLE_LENGTH:
entry.title = ' '.join(entry.title.split()[:-1])
entry.save() | python | def truncate_entry_titles(apps, schema_editor):
"""This function will truncate the values of Entry.title so they are
255 characters or less.
"""
Entry = apps.get_model("andablog", "Entry")
for entry in Entry.objects.all():
# Truncate to 255 characters (or less) but keep whole words intact.
while len(entry.title) > TITLE_LENGTH:
entry.title = ' '.join(entry.title.split()[:-1])
entry.save() | [
"def",
"truncate_entry_titles",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Entry",
"=",
"apps",
".",
"get_model",
"(",
"\"andablog\"",
",",
"\"Entry\"",
")",
"for",
"entry",
"in",
"Entry",
".",
"objects",
".",
"all",
"(",
")",
":",
"# Truncate to 255 char... | This function will truncate the values of Entry.title so they are
255 characters or less. | [
"This",
"function",
"will",
"truncate",
"the",
"values",
"of",
"Entry",
".",
"title",
"so",
"they",
"are",
"255",
"characters",
"or",
"less",
"."
] | 9175144140d220e4ce8212d0da6abc8c9ba9816a | https://github.com/WimpyAnalytics/django-andablog/blob/9175144140d220e4ce8212d0da6abc8c9ba9816a/andablog/migrations/0004_shorten_entry_title.py#L12-L22 | train | 44,775 |
seomoz/qless-py | qless/workers/greenlet.py | GeventWorker.process | def process(self, job):
'''Process a job'''
sandbox = self.sandboxes.pop(0)
try:
with Worker.sandbox(sandbox):
job.sandbox = sandbox
job.process()
finally:
# Delete its entry from our greenlets mapping
self.greenlets.pop(job.jid, None)
self.sandboxes.append(sandbox) | python | def process(self, job):
'''Process a job'''
sandbox = self.sandboxes.pop(0)
try:
with Worker.sandbox(sandbox):
job.sandbox = sandbox
job.process()
finally:
# Delete its entry from our greenlets mapping
self.greenlets.pop(job.jid, None)
self.sandboxes.append(sandbox) | [
"def",
"process",
"(",
"self",
",",
"job",
")",
":",
"sandbox",
"=",
"self",
".",
"sandboxes",
".",
"pop",
"(",
"0",
")",
"try",
":",
"with",
"Worker",
".",
"sandbox",
"(",
"sandbox",
")",
":",
"job",
".",
"sandbox",
"=",
"sandbox",
"job",
".",
"... | Process a job | [
"Process",
"a",
"job"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/greenlet.py#L28-L38 | train | 44,776 |
seomoz/qless-py | qless/workers/greenlet.py | GeventWorker.kill | def kill(self, jid):
'''Stop the greenlet processing the provided jid'''
greenlet = self.greenlets.get(jid)
if greenlet is not None:
logger.warn('Lost ownership of %s' % jid)
greenlet.kill() | python | def kill(self, jid):
'''Stop the greenlet processing the provided jid'''
greenlet = self.greenlets.get(jid)
if greenlet is not None:
logger.warn('Lost ownership of %s' % jid)
greenlet.kill() | [
"def",
"kill",
"(",
"self",
",",
"jid",
")",
":",
"greenlet",
"=",
"self",
".",
"greenlets",
".",
"get",
"(",
"jid",
")",
"if",
"greenlet",
"is",
"not",
"None",
":",
"logger",
".",
"warn",
"(",
"'Lost ownership of %s'",
"%",
"jid",
")",
"greenlet",
"... | Stop the greenlet processing the provided jid | [
"Stop",
"the",
"greenlet",
"processing",
"the",
"provided",
"jid"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/greenlet.py#L40-L45 | train | 44,777 |
seomoz/qless-py | qless/workers/greenlet.py | GeventWorker.run | def run(self):
'''Work on jobs'''
# Register signal handlers
self.signals()
# Start listening
with self.listener():
try:
generator = self.jobs()
while not self.shutdown:
self.pool.wait_available()
job = next(generator)
if job:
# For whatever reason, doing imports within a greenlet
# (there's one implicitly invoked in job.process), was
# throwing exceptions. The hacky way to get around this
# is to force the import to happen before the greenlet
# is spawned.
job.klass
greenlet = gevent.Greenlet(self.process, job)
self.greenlets[job.jid] = greenlet
self.pool.start(greenlet)
else:
logger.debug('Sleeping for %fs' % self.interval)
gevent.sleep(self.interval)
except StopIteration:
logger.info('Exhausted jobs')
finally:
logger.info('Waiting for greenlets to finish')
self.pool.join() | python | def run(self):
'''Work on jobs'''
# Register signal handlers
self.signals()
# Start listening
with self.listener():
try:
generator = self.jobs()
while not self.shutdown:
self.pool.wait_available()
job = next(generator)
if job:
# For whatever reason, doing imports within a greenlet
# (there's one implicitly invoked in job.process), was
# throwing exceptions. The hacky way to get around this
# is to force the import to happen before the greenlet
# is spawned.
job.klass
greenlet = gevent.Greenlet(self.process, job)
self.greenlets[job.jid] = greenlet
self.pool.start(greenlet)
else:
logger.debug('Sleeping for %fs' % self.interval)
gevent.sleep(self.interval)
except StopIteration:
logger.info('Exhausted jobs')
finally:
logger.info('Waiting for greenlets to finish')
self.pool.join() | [
"def",
"run",
"(",
"self",
")",
":",
"# Register signal handlers",
"self",
".",
"signals",
"(",
")",
"# Start listening",
"with",
"self",
".",
"listener",
"(",
")",
":",
"try",
":",
"generator",
"=",
"self",
".",
"jobs",
"(",
")",
"while",
"not",
"self",... | Work on jobs | [
"Work",
"on",
"jobs"
] | 3eda4ffcd4c0016c9a7e44f780d6155e1a354dda | https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/greenlet.py#L47-L76 | train | 44,778 |
Riffstation/flask-philo | flask_philo/db/postgresql/connection.py | init_db_conn | def init_db_conn(connection_name, connection_string, scopefunc=None):
"""
Initialize a postgresql connection by each connection string
defined in the configuration file
"""
engine = create_engine(connection_string)
session = scoped_session(sessionmaker(), scopefunc=scopefunc)
session.configure(bind=engine)
pool.connections[connection_name] = Connection(engine, session) | python | def init_db_conn(connection_name, connection_string, scopefunc=None):
"""
Initialize a postgresql connection by each connection string
defined in the configuration file
"""
engine = create_engine(connection_string)
session = scoped_session(sessionmaker(), scopefunc=scopefunc)
session.configure(bind=engine)
pool.connections[connection_name] = Connection(engine, session) | [
"def",
"init_db_conn",
"(",
"connection_name",
",",
"connection_string",
",",
"scopefunc",
"=",
"None",
")",
":",
"engine",
"=",
"create_engine",
"(",
"connection_string",
")",
"session",
"=",
"scoped_session",
"(",
"sessionmaker",
"(",
")",
",",
"scopefunc",
"=... | Initialize a postgresql connection by each connection string
defined in the configuration file | [
"Initialize",
"a",
"postgresql",
"connection",
"by",
"each",
"connection",
"string",
"defined",
"in",
"the",
"configuration",
"file"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/connection.py#L47-L55 | train | 44,779 |
Riffstation/flask-philo | flask_philo/db/postgresql/connection.py | initialize | def initialize(g, app):
"""
If postgresql url is defined in configuration params a
scoped session will be created
"""
if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']:
# Database connection established for console commands
for k, v in app.config['DATABASES']['POSTGRESQL'].items():
init_db_conn(k, v)
if 'test' not in sys.argv:
# Establish a new connection every request
@app.before_request
def before_request():
"""
Assign postgresql connection pool to the global
flask object at the beginning of every request
"""
# inject stack context if not testing
from flask import _app_ctx_stack
for k, v in app.config['DATABASES']['POSTGRESQL'].items():
init_db_conn(k, v, scopefunc=_app_ctx_stack)
g.postgresql_pool = pool
# avoid to close connections if testing
@app.teardown_request
def teardown_request(exception):
"""
Releasing connection after finish request, not required in unit
testing
"""
pool = getattr(g, 'postgresql_pool', None)
if pool is not None:
for k, v in pool.connections.items():
v.session.remove()
else:
@app.before_request
def before_request():
"""
Assign postgresql connection pool to the global
flask object at the beginning of every request
"""
for k, v in app.config['DATABASES']['POSTGRESQL'].items():
init_db_conn(k, v)
g.postgresql_pool = pool | python | def initialize(g, app):
"""
If postgresql url is defined in configuration params a
scoped session will be created
"""
if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']:
# Database connection established for console commands
for k, v in app.config['DATABASES']['POSTGRESQL'].items():
init_db_conn(k, v)
if 'test' not in sys.argv:
# Establish a new connection every request
@app.before_request
def before_request():
"""
Assign postgresql connection pool to the global
flask object at the beginning of every request
"""
# inject stack context if not testing
from flask import _app_ctx_stack
for k, v in app.config['DATABASES']['POSTGRESQL'].items():
init_db_conn(k, v, scopefunc=_app_ctx_stack)
g.postgresql_pool = pool
# avoid to close connections if testing
@app.teardown_request
def teardown_request(exception):
"""
Releasing connection after finish request, not required in unit
testing
"""
pool = getattr(g, 'postgresql_pool', None)
if pool is not None:
for k, v in pool.connections.items():
v.session.remove()
else:
@app.before_request
def before_request():
"""
Assign postgresql connection pool to the global
flask object at the beginning of every request
"""
for k, v in app.config['DATABASES']['POSTGRESQL'].items():
init_db_conn(k, v)
g.postgresql_pool = pool | [
"def",
"initialize",
"(",
"g",
",",
"app",
")",
":",
"if",
"'DATABASES'",
"in",
"app",
".",
"config",
"and",
"'POSTGRESQL'",
"in",
"app",
".",
"config",
"[",
"'DATABASES'",
"]",
":",
"# Database connection established for console commands",
"for",
"k",
",",
"v... | If postgresql url is defined in configuration params a
scoped session will be created | [
"If",
"postgresql",
"url",
"is",
"defined",
"in",
"configuration",
"params",
"a",
"scoped",
"session",
"will",
"be",
"created"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/connection.py#L58-L102 | train | 44,780 |
Riffstation/flask-philo | flask_philo/jinja2/__init__.py | TemplatesManager.set_request | def set_request(self, r):
"""
Appends request object to the globals dict
"""
for k in self.environments.keys():
self.environments[k].globals['REQUEST'] = r | python | def set_request(self, r):
"""
Appends request object to the globals dict
"""
for k in self.environments.keys():
self.environments[k].globals['REQUEST'] = r | [
"def",
"set_request",
"(",
"self",
",",
"r",
")",
":",
"for",
"k",
"in",
"self",
".",
"environments",
".",
"keys",
"(",
")",
":",
"self",
".",
"environments",
"[",
"k",
"]",
".",
"globals",
"[",
"'REQUEST'",
"]",
"=",
"r"
] | Appends request object to the globals dict | [
"Appends",
"request",
"object",
"to",
"the",
"globals",
"dict"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/jinja2/__init__.py#L18-L23 | train | 44,781 |
Riffstation/flask-philo | flask_philo/views.py | BaseView.json_response | def json_response(self, status=200, data={}, headers={}):
'''
To set flask to inject specific headers on response request,
such as CORS_ORIGIN headers
'''
mimetype = 'application/json'
header_dict = {}
for k, v in headers.items():
header_dict[k] = v
return Response(
json.dumps(data),
status=status,
mimetype=mimetype,
headers=header_dict) | python | def json_response(self, status=200, data={}, headers={}):
'''
To set flask to inject specific headers on response request,
such as CORS_ORIGIN headers
'''
mimetype = 'application/json'
header_dict = {}
for k, v in headers.items():
header_dict[k] = v
return Response(
json.dumps(data),
status=status,
mimetype=mimetype,
headers=header_dict) | [
"def",
"json_response",
"(",
"self",
",",
"status",
"=",
"200",
",",
"data",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
")",
":",
"mimetype",
"=",
"'application/json'",
"header_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"headers",
".",
"i... | To set flask to inject specific headers on response request,
such as CORS_ORIGIN headers | [
"To",
"set",
"flask",
"to",
"inject",
"specific",
"headers",
"on",
"response",
"request",
"such",
"as",
"CORS_ORIGIN",
"headers"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/views.py#L25-L40 | train | 44,782 |
Riffstation/flask-philo | flask_philo/views.py | BaseView.template_response | def template_response(self, template_name, headers={}, **values):
"""
Constructs a response, allowing custom template name and content_type
"""
response = make_response(
self.render_template(template_name, **values))
for field, value in headers.items():
response.headers.set(field, value)
return response | python | def template_response(self, template_name, headers={}, **values):
"""
Constructs a response, allowing custom template name and content_type
"""
response = make_response(
self.render_template(template_name, **values))
for field, value in headers.items():
response.headers.set(field, value)
return response | [
"def",
"template_response",
"(",
"self",
",",
"template_name",
",",
"headers",
"=",
"{",
"}",
",",
"*",
"*",
"values",
")",
":",
"response",
"=",
"make_response",
"(",
"self",
".",
"render_template",
"(",
"template_name",
",",
"*",
"*",
"values",
")",
")... | Constructs a response, allowing custom template name and content_type | [
"Constructs",
"a",
"response",
"allowing",
"custom",
"template",
"name",
"and",
"content_type"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/views.py#L49-L59 | train | 44,783 |
Riffstation/flask-philo | flask_philo/cloud/aws/key_pair.py | describe_key_pairs | def describe_key_pairs():
"""
Returns all key pairs for region
"""
region_keys = {}
for r in boto3.client('ec2', 'us-west-2').describe_regions()['Regions']:
region = r['RegionName']
client = boto3.client('ec2', region_name=region)
try:
pairs = client.describe_key_pairs()
if pairs:
region_keys[region] = pairs
except Exception as e:
app.logger.info(e)
return region_keys | python | def describe_key_pairs():
"""
Returns all key pairs for region
"""
region_keys = {}
for r in boto3.client('ec2', 'us-west-2').describe_regions()['Regions']:
region = r['RegionName']
client = boto3.client('ec2', region_name=region)
try:
pairs = client.describe_key_pairs()
if pairs:
region_keys[region] = pairs
except Exception as e:
app.logger.info(e)
return region_keys | [
"def",
"describe_key_pairs",
"(",
")",
":",
"region_keys",
"=",
"{",
"}",
"for",
"r",
"in",
"boto3",
".",
"client",
"(",
"'ec2'",
",",
"'us-west-2'",
")",
".",
"describe_regions",
"(",
")",
"[",
"'Regions'",
"]",
":",
"region",
"=",
"r",
"[",
"'RegionN... | Returns all key pairs for region | [
"Returns",
"all",
"key",
"pairs",
"for",
"region"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/cloud/aws/key_pair.py#L29-L43 | train | 44,784 |
Riffstation/flask-philo | flask_philo/__init__.py | init_app | def init_app(module, BASE_DIR, **kwargs):
"""
Initalize an app, call this method once from start_app
"""
global app
def init_config():
"""
Load settings module and attach values to the application
config dictionary
"""
if 'FLASK_PHILO_SETTINGS_MODULE' not in os.environ:
raise ConfigurationError('No settings has been defined')
app.config['BASE_DIR'] = BASE_DIR
# default settings
for v in dir(default_settings):
if not v.startswith('_'):
app.config[v] = getattr(default_settings, v)
app.debug = app.config['DEBUG']
# app settings
settings = importlib.import_module(
os.environ['FLASK_PHILO_SETTINGS_MODULE'])
for v in dir(settings):
if not v.startswith('_'):
app.config[v] = getattr(settings, v)
def init_urls():
# Reads urls definition from URLs file and bind routes and views
urls_module = importlib.import_module(app.config['URLS'])
for route in urls_module.URLS:
app.add_url_rule(
route[0], view_func=route[1].as_view(route[2]))
def init_logging():
"""
initialize logger for the app
"""
hndlr = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
hndlr.setFormatter(formatter)
app.logger.addHandler(hndlr)
log_level = app.config['LOG_LEVEL']
app.logger.setLevel(getattr(logging, log_level))
def init_flask_oauthlib():
"""
http://flask-oauthlib.readthedocs.io/en/latest/oauth2.html
"""
oauth.init_app(app)
def init_cors(app):
"""
Initializes cors protection if config
"""
if 'CORS' in app.config:
CORS(
app,
resources=app.config['CORS'],
supports_credentials=app.config.get(
"CORS_SUPPORT_CREDENTIALS",
False
),
allow_headers=app.config.get(
"CORS_ALLOW_HEADERS",
"Content-Type,Authorization,accept-language,accept"
)
)
init_db(g, app)
init_logging()
init_urls()
init_flask_oauthlib()
init_jinja2(g, app)
init_cors(app)
app = Flask(module)
init_config()
return app | python | def init_app(module, BASE_DIR, **kwargs):
"""
Initalize an app, call this method once from start_app
"""
global app
def init_config():
"""
Load settings module and attach values to the application
config dictionary
"""
if 'FLASK_PHILO_SETTINGS_MODULE' not in os.environ:
raise ConfigurationError('No settings has been defined')
app.config['BASE_DIR'] = BASE_DIR
# default settings
for v in dir(default_settings):
if not v.startswith('_'):
app.config[v] = getattr(default_settings, v)
app.debug = app.config['DEBUG']
# app settings
settings = importlib.import_module(
os.environ['FLASK_PHILO_SETTINGS_MODULE'])
for v in dir(settings):
if not v.startswith('_'):
app.config[v] = getattr(settings, v)
def init_urls():
# Reads urls definition from URLs file and bind routes and views
urls_module = importlib.import_module(app.config['URLS'])
for route in urls_module.URLS:
app.add_url_rule(
route[0], view_func=route[1].as_view(route[2]))
def init_logging():
"""
initialize logger for the app
"""
hndlr = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
hndlr.setFormatter(formatter)
app.logger.addHandler(hndlr)
log_level = app.config['LOG_LEVEL']
app.logger.setLevel(getattr(logging, log_level))
def init_flask_oauthlib():
"""
http://flask-oauthlib.readthedocs.io/en/latest/oauth2.html
"""
oauth.init_app(app)
def init_cors(app):
"""
Initializes cors protection if config
"""
if 'CORS' in app.config:
CORS(
app,
resources=app.config['CORS'],
supports_credentials=app.config.get(
"CORS_SUPPORT_CREDENTIALS",
False
),
allow_headers=app.config.get(
"CORS_ALLOW_HEADERS",
"Content-Type,Authorization,accept-language,accept"
)
)
init_db(g, app)
init_logging()
init_urls()
init_flask_oauthlib()
init_jinja2(g, app)
init_cors(app)
app = Flask(module)
init_config()
return app | [
"def",
"init_app",
"(",
"module",
",",
"BASE_DIR",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"app",
"def",
"init_config",
"(",
")",
":",
"\"\"\"\n Load settings module and attach values to the application\n config dictionary\n \"\"\"",
"if",
"'FLASK_... | Initalize an app, call this method once from start_app | [
"Initalize",
"an",
"app",
"call",
"this",
"method",
"once",
"from",
"start_app"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/__init__.py#L27-L110 | train | 44,785 |
Riffstation/flask-philo | flask_philo/__init__.py | execute_command | def execute_command(cmd, **kwargs):
"""
execute a console command
"""
cmd_dict = {
c: 'flask_philo.commands_flask_philo.' + c for c
in dir(commands_flask_philo) if not c.startswith('_') and c != 'os' # noqa
}
# loading specific app commands
try:
import console_commands
for cm in console_commands.__all__:
if not cm.startswith('_'):
cmd_dict[cm] = 'console_commands.' + cm
except Exception:
pass
if cmd not in cmd_dict:
raise ConfigurationError('command {} does not exists'.format(cmd))
cmd_module = importlib.import_module(cmd_dict[cmd])
kwargs['app'] = app
cmd_module.run(**kwargs) | python | def execute_command(cmd, **kwargs):
"""
execute a console command
"""
cmd_dict = {
c: 'flask_philo.commands_flask_philo.' + c for c
in dir(commands_flask_philo) if not c.startswith('_') and c != 'os' # noqa
}
# loading specific app commands
try:
import console_commands
for cm in console_commands.__all__:
if not cm.startswith('_'):
cmd_dict[cm] = 'console_commands.' + cm
except Exception:
pass
if cmd not in cmd_dict:
raise ConfigurationError('command {} does not exists'.format(cmd))
cmd_module = importlib.import_module(cmd_dict[cmd])
kwargs['app'] = app
cmd_module.run(**kwargs) | [
"def",
"execute_command",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd_dict",
"=",
"{",
"c",
":",
"'flask_philo.commands_flask_philo.'",
"+",
"c",
"for",
"c",
"in",
"dir",
"(",
"commands_flask_philo",
")",
"if",
"not",
"c",
".",
"startswith",
"(",
... | execute a console command | [
"execute",
"a",
"console",
"command"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/__init__.py#L113-L135 | train | 44,786 |
Riffstation/flask-philo | flask_philo/db/postgresql/types.py | Password._convert | def _convert(self, value):
"""Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError.
"""
if isinstance(value, PasswordHash):
return value
elif isinstance(value, str):
value = value.encode('utf-8')
return PasswordHash.new(value, self.rounds)
elif value is not None:
raise TypeError(
'Cannot convert {} to a PasswordHash'.format(type(value))) | python | def _convert(self, value):
"""Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError.
"""
if isinstance(value, PasswordHash):
return value
elif isinstance(value, str):
value = value.encode('utf-8')
return PasswordHash.new(value, self.rounds)
elif value is not None:
raise TypeError(
'Cannot convert {} to a PasswordHash'.format(type(value))) | [
"def",
"_convert",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"PasswordHash",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
... | Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError. | [
"Returns",
"a",
"PasswordHash",
"from",
"the",
"given",
"string",
"."
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/postgresql/types.py#L76-L90 | train | 44,787 |
Riffstation/flask-philo | flask_philo/db/redis/connection.py | initialize | def initialize(g, app):
"""
If redis connection parameters are defined in configuration params a
session will be created
"""
if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:
# Initialize connections for console commands
for k, v in app.config['DATABASES']['REDIS'].items():
init_db_conn(k, **v)
@app.before_request
def before_request():
"""
Assign redis connection pool to the global
flask object at the beginning of every request
"""
for k, v in app.config['DATABASES']['REDIS'].items():
init_db_conn(k, **v)
g.redis_pool = redis_pool
if 'test' not in sys.argv:
@app.teardown_request
def teardown_request(exception):
pool = getattr(g, 'redis_pool', None)
if pool is not None:
pool.close() | python | def initialize(g, app):
"""
If redis connection parameters are defined in configuration params a
session will be created
"""
if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:
# Initialize connections for console commands
for k, v in app.config['DATABASES']['REDIS'].items():
init_db_conn(k, **v)
@app.before_request
def before_request():
"""
Assign redis connection pool to the global
flask object at the beginning of every request
"""
for k, v in app.config['DATABASES']['REDIS'].items():
init_db_conn(k, **v)
g.redis_pool = redis_pool
if 'test' not in sys.argv:
@app.teardown_request
def teardown_request(exception):
pool = getattr(g, 'redis_pool', None)
if pool is not None:
pool.close() | [
"def",
"initialize",
"(",
"g",
",",
"app",
")",
":",
"if",
"'DATABASES'",
"in",
"app",
".",
"config",
"and",
"'REDIS'",
"in",
"app",
".",
"config",
"[",
"'DATABASES'",
"]",
":",
"# Initialize connections for console commands",
"for",
"k",
",",
"v",
"in",
"... | If redis connection parameters are defined in configuration params a
session will be created | [
"If",
"redis",
"connection",
"parameters",
"are",
"defined",
"in",
"configuration",
"params",
"a",
"session",
"will",
"be",
"created"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/db/redis/connection.py#L74-L101 | train | 44,788 |
Riffstation/flask-philo | flask_philo/serializers.py | BaseSerializer._initialize_from_dict | def _initialize_from_dict(self, data):
"""
Loads serializer from a request object
"""
self._json = data
self._validate()
for name, value in self._json.items():
if name in self._properties:
if '$ref' in self._properties[name]:
if 'decimal' in self._properties[name]['$ref']:
value = Decimal(value)
# applying proper formatting when required
if 'format' in self._properties[name]:
format = self._properties[name]['format']
if 'date-time' == format:
value = utils.string_to_datetime(value)
elif 'date' == format:
value = utils.string_to_date(value)
setattr(self, name, value) | python | def _initialize_from_dict(self, data):
"""
Loads serializer from a request object
"""
self._json = data
self._validate()
for name, value in self._json.items():
if name in self._properties:
if '$ref' in self._properties[name]:
if 'decimal' in self._properties[name]['$ref']:
value = Decimal(value)
# applying proper formatting when required
if 'format' in self._properties[name]:
format = self._properties[name]['format']
if 'date-time' == format:
value = utils.string_to_datetime(value)
elif 'date' == format:
value = utils.string_to_date(value)
setattr(self, name, value) | [
"def",
"_initialize_from_dict",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_json",
"=",
"data",
"self",
".",
"_validate",
"(",
")",
"for",
"name",
",",
"value",
"in",
"self",
".",
"_json",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"se... | Loads serializer from a request object | [
"Loads",
"serializer",
"from",
"a",
"request",
"object"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L60-L81 | train | 44,789 |
Riffstation/flask-philo | flask_philo/serializers.py | BaseSerializer._initialize_from_model | def _initialize_from_model(self, model):
"""
Loads a model from
"""
for name, value in model.__dict__.items():
if name in self._properties:
setattr(self, name, value) | python | def _initialize_from_model(self, model):
"""
Loads a model from
"""
for name, value in model.__dict__.items():
if name in self._properties:
setattr(self, name, value) | [
"def",
"_initialize_from_model",
"(",
"self",
",",
"model",
")",
":",
"for",
"name",
",",
"value",
"in",
"model",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"self",
".",
"_properties",
":",
"setattr",
"(",
"self",
",",
"name",
... | Loads a model from | [
"Loads",
"a",
"model",
"from"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L83-L89 | train | 44,790 |
Riffstation/flask-philo | flask_philo/serializers.py | BaseSerializer.update | def update(self):
"""
Finds record and update it based in serializer values
"""
obj = self.__model__.objects.get_for_update(id=self.id)
for name, value in self.__dict__.items():
if name in self._properties:
setattr(obj, name, value)
obj.update()
return obj | python | def update(self):
"""
Finds record and update it based in serializer values
"""
obj = self.__model__.objects.get_for_update(id=self.id)
for name, value in self.__dict__.items():
if name in self._properties:
setattr(obj, name, value)
obj.update()
return obj | [
"def",
"update",
"(",
"self",
")",
":",
"obj",
"=",
"self",
".",
"__model__",
".",
"objects",
".",
"get_for_update",
"(",
"id",
"=",
"self",
".",
"id",
")",
"for",
"name",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
... | Finds record and update it based in serializer values | [
"Finds",
"record",
"and",
"update",
"it",
"based",
"in",
"serializer",
"values"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L91-L100 | train | 44,791 |
Riffstation/flask-philo | flask_philo/serializers.py | BaseSerializer.to_json | def to_json(self):
"""
Returns a json representation
"""
data = {}
for k, v in self.__dict__.items():
if not k.startswith('_'):
# values not serializable, should be converted to strings
if isinstance(v, datetime):
v = utils.datetime_to_string(v)
elif isinstance(v, date):
v = utils.date_to_string(v)
elif isinstance(v, uuid.UUID):
v = str(v)
elif isinstance(v, Decimal):
v = str(v)
data[k] = v
return data | python | def to_json(self):
"""
Returns a json representation
"""
data = {}
for k, v in self.__dict__.items():
if not k.startswith('_'):
# values not serializable, should be converted to strings
if isinstance(v, datetime):
v = utils.datetime_to_string(v)
elif isinstance(v, date):
v = utils.date_to_string(v)
elif isinstance(v, uuid.UUID):
v = str(v)
elif isinstance(v, Decimal):
v = str(v)
data[k] = v
return data | [
"def",
"to_json",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"not",
"k",
".",
"startswith",
"(",
"'_'",
")",
":",
"# values not serializable, should be converted... | Returns a json representation | [
"Returns",
"a",
"json",
"representation"
] | 76c9d562edb4a77010c8da6dfdb6489fa29cbc9e | https://github.com/Riffstation/flask-philo/blob/76c9d562edb4a77010c8da6dfdb6489fa29cbc9e/flask_philo/serializers.py#L102-L119 | train | 44,792 |
remram44/usagestats | usagestats.py | OPERATING_SYSTEM | def OPERATING_SYSTEM(stats, info):
"""General information about the operating system.
This is a flag you can pass to `Stats.submit()`.
"""
info.append(('architecture', platform.machine().lower()))
info.append(('distribution',
"%s;%s" % (platform.linux_distribution()[0:2])))
info.append(('system',
"%s;%s" % (platform.system(), platform.release()))) | python | def OPERATING_SYSTEM(stats, info):
"""General information about the operating system.
This is a flag you can pass to `Stats.submit()`.
"""
info.append(('architecture', platform.machine().lower()))
info.append(('distribution',
"%s;%s" % (platform.linux_distribution()[0:2])))
info.append(('system',
"%s;%s" % (platform.system(), platform.release()))) | [
"def",
"OPERATING_SYSTEM",
"(",
"stats",
",",
"info",
")",
":",
"info",
".",
"append",
"(",
"(",
"'architecture'",
",",
"platform",
".",
"machine",
"(",
")",
".",
"lower",
"(",
")",
")",
")",
"info",
".",
"append",
"(",
"(",
"'distribution'",
",",
"\... | General information about the operating system.
This is a flag you can pass to `Stats.submit()`. | [
"General",
"information",
"about",
"the",
"operating",
"system",
"."
] | 6ffd1a51d81d1b4570916c1594aee6a98089fa71 | https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L41-L50 | train | 44,793 |
remram44/usagestats | usagestats.py | SESSION_TIME | def SESSION_TIME(stats, info):
"""Total time of this session.
Reports the time elapsed from the construction of the `Stats` object to
this `submit()` call.
This is a flag you can pass to `Stats.submit()`.
"""
duration = time.time() - stats.started_time
secs = int(duration)
msecs = int((duration - secs) * 1000)
info.append(('session_time', '%d.%d' % (secs, msecs))) | python | def SESSION_TIME(stats, info):
"""Total time of this session.
Reports the time elapsed from the construction of the `Stats` object to
this `submit()` call.
This is a flag you can pass to `Stats.submit()`.
"""
duration = time.time() - stats.started_time
secs = int(duration)
msecs = int((duration - secs) * 1000)
info.append(('session_time', '%d.%d' % (secs, msecs))) | [
"def",
"SESSION_TIME",
"(",
"stats",
",",
"info",
")",
":",
"duration",
"=",
"time",
".",
"time",
"(",
")",
"-",
"stats",
".",
"started_time",
"secs",
"=",
"int",
"(",
"duration",
")",
"msecs",
"=",
"int",
"(",
"(",
"duration",
"-",
"secs",
")",
"*... | Total time of this session.
Reports the time elapsed from the construction of the `Stats` object to
this `submit()` call.
This is a flag you can pass to `Stats.submit()`. | [
"Total",
"time",
"of",
"this",
"session",
"."
] | 6ffd1a51d81d1b4570916c1594aee6a98089fa71 | https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L53-L64 | train | 44,794 |
remram44/usagestats | usagestats.py | PYTHON_VERSION | def PYTHON_VERSION(stats, info):
"""Python interpreter version.
This is a flag you can pass to `Stats.submit()`.
"""
# Some versions of Python have a \n in sys.version!
version = sys.version.replace(' \n', ' ').replace('\n', ' ')
python = ';'.join([str(c) for c in sys.version_info] + [version])
info.append(('python', python)) | python | def PYTHON_VERSION(stats, info):
"""Python interpreter version.
This is a flag you can pass to `Stats.submit()`.
"""
# Some versions of Python have a \n in sys.version!
version = sys.version.replace(' \n', ' ').replace('\n', ' ')
python = ';'.join([str(c) for c in sys.version_info] + [version])
info.append(('python', python)) | [
"def",
"PYTHON_VERSION",
"(",
"stats",
",",
"info",
")",
":",
"# Some versions of Python have a \\n in sys.version!",
"version",
"=",
"sys",
".",
"version",
".",
"replace",
"(",
"' \\n'",
",",
"' '",
")",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")",
"python"... | Python interpreter version.
This is a flag you can pass to `Stats.submit()`. | [
"Python",
"interpreter",
"version",
"."
] | 6ffd1a51d81d1b4570916c1594aee6a98089fa71 | https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L67-L75 | train | 44,795 |
remram44/usagestats | usagestats.py | Stats.read_config | def read_config(self):
"""Reads the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is read
from the reports' directory.
This should set `self.status` to one of the state constants, and make
sure `self.location` points to a writable directory where the reports
will be written.
The possible values for `self.status` are:
- `UNSET`: nothing has been selected and the user should be prompted
- `ENABLED`: collect and upload reports
- `DISABLED`: don't collect or upload anything, stop prompting
- `ERRORED`: something is broken, and we can't do anything in this
session (for example, the configuration directory is not writable)
"""
if self.enabled and not os.path.isdir(self.location):
try:
os.makedirs(self.location, 0o700)
except OSError:
logger.warning("Couldn't create %s, usage statistics won't be "
"collected", self.location)
self.status = Stats.ERRORED
status_file = os.path.join(self.location, 'status')
if self.enabled and os.path.exists(status_file):
with open(status_file, 'r') as fp:
status = fp.read().strip()
if status == 'ENABLED':
self.status = Stats.ENABLED
elif status == 'DISABLED':
self.status = Stats.DISABLED | python | def read_config(self):
"""Reads the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is read
from the reports' directory.
This should set `self.status` to one of the state constants, and make
sure `self.location` points to a writable directory where the reports
will be written.
The possible values for `self.status` are:
- `UNSET`: nothing has been selected and the user should be prompted
- `ENABLED`: collect and upload reports
- `DISABLED`: don't collect or upload anything, stop prompting
- `ERRORED`: something is broken, and we can't do anything in this
session (for example, the configuration directory is not writable)
"""
if self.enabled and not os.path.isdir(self.location):
try:
os.makedirs(self.location, 0o700)
except OSError:
logger.warning("Couldn't create %s, usage statistics won't be "
"collected", self.location)
self.status = Stats.ERRORED
status_file = os.path.join(self.location, 'status')
if self.enabled and os.path.exists(status_file):
with open(status_file, 'r') as fp:
status = fp.read().strip()
if status == 'ENABLED':
self.status = Stats.ENABLED
elif status == 'DISABLED':
self.status = Stats.DISABLED | [
"def",
"read_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"enabled",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"location",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"location",
",",
"0o700",
")",
... | Reads the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is read
from the reports' directory.
This should set `self.status` to one of the state constants, and make
sure `self.location` points to a writable directory where the reports
will be written.
The possible values for `self.status` are:
- `UNSET`: nothing has been selected and the user should be prompted
- `ENABLED`: collect and upload reports
- `DISABLED`: don't collect or upload anything, stop prompting
- `ERRORED`: something is broken, and we can't do anything in this
session (for example, the configuration directory is not writable) | [
"Reads",
"the",
"configuration",
"."
] | 6ffd1a51d81d1b4570916c1594aee6a98089fa71 | https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L180-L214 | train | 44,796 |
remram44/usagestats | usagestats.py | Stats.write_config | def write_config(self, enabled):
"""Writes the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is written
in the reports' directory, containing either ``ENABLED`` or
``DISABLED``; if the file doesn't exist, `UNSET` is assumed.
:param enabled: Either `Stats.UNSET`, `Stats.DISABLED` or
`Stats.ENABLED`.
"""
status_file = os.path.join(self.location, 'status')
with open(status_file, 'w') as fp:
if enabled is Stats.ENABLED:
fp.write('ENABLED')
elif enabled is Stats.DISABLED:
fp.write('DISABLED')
else:
raise ValueError("Unknown reporting state %r" % enabled) | python | def write_config(self, enabled):
"""Writes the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is written
in the reports' directory, containing either ``ENABLED`` or
``DISABLED``; if the file doesn't exist, `UNSET` is assumed.
:param enabled: Either `Stats.UNSET`, `Stats.DISABLED` or
`Stats.ENABLED`.
"""
status_file = os.path.join(self.location, 'status')
with open(status_file, 'w') as fp:
if enabled is Stats.ENABLED:
fp.write('ENABLED')
elif enabled is Stats.DISABLED:
fp.write('DISABLED')
else:
raise ValueError("Unknown reporting state %r" % enabled) | [
"def",
"write_config",
"(",
"self",
",",
"enabled",
")",
":",
"status_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"location",
",",
"'status'",
")",
"with",
"open",
"(",
"status_file",
",",
"'w'",
")",
"as",
"fp",
":",
"if",
"enabled... | Writes the configuration.
This method can be overloaded to integrate with your application's own
configuration mechanism. By default, a single 'status' file is written
in the reports' directory, containing either ``ENABLED`` or
``DISABLED``; if the file doesn't exist, `UNSET` is assumed.
:param enabled: Either `Stats.UNSET`, `Stats.DISABLED` or
`Stats.ENABLED`. | [
"Writes",
"the",
"configuration",
"."
] | 6ffd1a51d81d1b4570916c1594aee6a98089fa71 | https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L216-L234 | train | 44,797 |
remram44/usagestats | usagestats.py | Stats.enable_reporting | def enable_reporting(self):
"""Call this method to explicitly enable reporting.
The current report will be uploaded, plus the previously recorded ones,
and the configuration will be updated so that future runs also upload
automatically.
"""
if self.status == Stats.ENABLED:
return
if not self.enableable:
logger.critical("Can't enable reporting")
return
self.status = Stats.ENABLED
self.write_config(self.status) | python | def enable_reporting(self):
"""Call this method to explicitly enable reporting.
The current report will be uploaded, plus the previously recorded ones,
and the configuration will be updated so that future runs also upload
automatically.
"""
if self.status == Stats.ENABLED:
return
if not self.enableable:
logger.critical("Can't enable reporting")
return
self.status = Stats.ENABLED
self.write_config(self.status) | [
"def",
"enable_reporting",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"==",
"Stats",
".",
"ENABLED",
":",
"return",
"if",
"not",
"self",
".",
"enableable",
":",
"logger",
".",
"critical",
"(",
"\"Can't enable reporting\"",
")",
"return",
"self",
"... | Call this method to explicitly enable reporting.
The current report will be uploaded, plus the previously recorded ones,
and the configuration will be updated so that future runs also upload
automatically. | [
"Call",
"this",
"method",
"to",
"explicitly",
"enable",
"reporting",
"."
] | 6ffd1a51d81d1b4570916c1594aee6a98089fa71 | https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L236-L249 | train | 44,798 |
remram44/usagestats | usagestats.py | Stats.disable_reporting | def disable_reporting(self):
"""Call this method to explicitly disable reporting.
The current report will be discarded, along with the previously
recorded ones that haven't been uploaded. The configuration is updated
so that future runs do not record or upload reports.
"""
if self.status == Stats.DISABLED:
return
if not self.disableable:
logger.critical("Can't disable reporting")
return
self.status = Stats.DISABLED
self.write_config(self.status)
if os.path.exists(self.location):
old_reports = [f for f in os.listdir(self.location)
if f.startswith('report_')]
for old_filename in old_reports:
fullname = os.path.join(self.location, old_filename)
os.remove(fullname)
logger.info("Deleted %d pending reports", len(old_reports)) | python | def disable_reporting(self):
"""Call this method to explicitly disable reporting.
The current report will be discarded, along with the previously
recorded ones that haven't been uploaded. The configuration is updated
so that future runs do not record or upload reports.
"""
if self.status == Stats.DISABLED:
return
if not self.disableable:
logger.critical("Can't disable reporting")
return
self.status = Stats.DISABLED
self.write_config(self.status)
if os.path.exists(self.location):
old_reports = [f for f in os.listdir(self.location)
if f.startswith('report_')]
for old_filename in old_reports:
fullname = os.path.join(self.location, old_filename)
os.remove(fullname)
logger.info("Deleted %d pending reports", len(old_reports)) | [
"def",
"disable_reporting",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"==",
"Stats",
".",
"DISABLED",
":",
"return",
"if",
"not",
"self",
".",
"disableable",
":",
"logger",
".",
"critical",
"(",
"\"Can't disable reporting\"",
")",
"return",
"self",... | Call this method to explicitly disable reporting.
The current report will be discarded, along with the previously
recorded ones that haven't been uploaded. The configuration is updated
so that future runs do not record or upload reports. | [
"Call",
"this",
"method",
"to",
"explicitly",
"disable",
"reporting",
"."
] | 6ffd1a51d81d1b4570916c1594aee6a98089fa71 | https://github.com/remram44/usagestats/blob/6ffd1a51d81d1b4570916c1594aee6a98089fa71/usagestats.py#L251-L271 | train | 44,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.