code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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) | Executes the cauldron command | 5.597569 | 4.538796 | 1.233272 |
# 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="{}... | def author_display(author, *args) | Returns either the linked or not-linked profile name. | 3.519024 | 3.468254 | 1.014638 |
if len(project.steps) < 1:
response.update(
steps=[]
).notify(
kind='SUCCESS',
code='ECHO_STEPS',
message='No steps in project'
).console(
,
whitespace=1
)
return
response.update(
steps... | def echo_steps(response: Response, project: Project) | :param response:
:param project:
:return: | 5.756096 | 5.405522 | 1.064855 |
if not scheme:
return split_filename(name)
replacements = {
'name': '(?P<name>.*)',
'ext': '(?P<extension>.+)$',
'index': '(?P<index>[0-9]{{{length}}})'
}
scheme_pattern = '^'
empty_scheme_pattern = ''
offset = 0
while offset < len(scheme):
ch... | def explode_filename(name: str, scheme: str) -> dict | Removes any path components from the input filename and returns a
dictionary containing the name of the file without extension and the
extension (if an extension exists)
:param name:
:param scheme:
:return: | 2.7797 | 2.847432 | 0.976213 |
source_path = get_source_path()
if not source_path:
return COMPONENT([], [])
output_slug = 'components/plotly/plotly.min.js'
output_path = os.path.join(project.output_directory, output_slug)
return COMPONENT(
includes=[WEB_INCLUDE(
name='plotly',
src='... | def create(project: 'projects.Project') -> COMPONENT | :param project:
:return: | 5.391899 | 5.188978 | 1.039106 |
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 | Returns whether or not the current working directory is a Cauldron project
directory, which contains a cauldron.json file. | 2.841861 | 2.037126 | 1.395034 |
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 "{}... | def load_shared_data(path: typing.Union[str, None]) -> dict | Load shared data from a JSON file stored on disk | 2.326602 | 2.276683 | 1.021926 |
version = environ.package_settings.get('version', 'unknown')
print('VERSION: {}'.format(version))
return 0 | def run_version(args: dict) -> int | Displays the current version | 10.540841 | 8.147028 | 1.293827 |
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 | Runs a batch operation for the given arguments | 4.30811 | 3.914708 | 1.100493 |
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 | Run the shell sub command | 7.313127 | 6.610524 | 1.106285 |
if args.get('show_version_info'):
return run_version(args)
actions = dict(
shell=run_shell,
kernel=run_kernel,
serve=run_kernel,
version=run_version
)
if action not in actions:
print('[ERROR]: Unrecognized sub command "{}"'.format(action))
p... | def run(action: str, args: dict) -> int | Runs the specified command action and returns the return status code
for exit.
:param action:
The action to run
:param args:
The arguments parsed for the specified action | 4.049656 | 4.249779 | 0.95291 |
project = cd.project.get_internal_project()
running_steps = list(filter(
lambda step: step.is_running,
project.steps
))
def get_changes(step):
step_data = writing.step_writer.serialize(step)
if write:
writing.save(project, step_data.file_writes)
... | def get_running_step_changes(write: bool = False) -> list | ... | 5.525381 | 5.105995 | 1.082136 |
parser = arg_parser or create_parser()
return vars(parser.parse_args(args)) | def parse(
args: typing.List[str] = None,
arg_parser: ArgumentParser = None
) -> dict | Parses the arguments for the cauldron server | 4.389901 | 3.655712 | 1.200833 |
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,
... | def create_parser(arg_parser: ArgumentParser = None) -> ArgumentParser | Creates an argument parser populated with the arg formats for the server
command. | 2.101669 | 2.004862 | 1.048286 |
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:
... | 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... | 2.072349 | 2.147787 | 0.964876 |
for template, match_rules in rules.items():
context = parent_context.copy()
if match_template(tree, template, context):
for key, child_rules in match_rules.items():
child_context = match_rules_context(context[key], child_rules, context)
if child_conte... | def match_rules_context(tree, rules, parent_context={}) | Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched dictionary of matched rules or
None if no match | 2.556117 | 2.829627 | 0.90334 |
if not contextss:
return []
product = [{}]
for contexts in contextss:
tmp_product = []
for c in contexts:
for ce in product:
c_copy = c.copy()
c_copy.update(ce)
tmp_product.append(c_copy)
product = tmp_product... | def cross_context(contextss) | Cross product of all contexts
[[a], [b], [c]] -> [[a] x [b] x [c]] | 3.131814 | 2.922707 | 1.071546 |
all_contexts = []
for template, match_rules in rules.items():
context = parent_context.copy()
if match_template(tree, template, context):
child_contextss = []
if not match_rules:
all_contexts += [context]
else:
for key, chi... | def match_rules_context_multi(tree, rules, parent_context={}) | Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched dictionary of matched rules or
None if no match | 3.331077 | 3.858143 | 0.863389 |
tokens = get_tokens(template.split())
cur_args = {}
if match_tokens(tree, tokens, cur_args):
if args is not None:
for k, v in cur_args.items():
args[k] = v
logger.debug('MATCHED: {0}'.format(template))
return True
else:
return False | def match_template(tree, template, args=None) | Check if match string matches Tree structure
Args:
tree (Tree): Parsed Tree structure of a sentence
template (str): String template to match. Example: "( S ( NP ) )"
Returns:
bool: If they match or not | 3.212888 | 3.664634 | 0.876728 |
arg_type_to_func = {
'r': get_raw_lower,
'R': get_raw,
'o': get_object_lower,
'O': get_object,
}
if len(tokens) == 0:
return True
if not isinstance(tree, Tree):
return False
root_token = tokens[0]
# Equality
if root_token.find('=') >= ... | def match_tokens(tree, tokens, args) | Check if stack of tokens matches the Tree structure
Special matching rules that can be specified in the template::
':label': Label a token, the token will be returned as part of the context with key 'label'.
'-@': Additional single letter argument determining return format of labeled token. Va... | 2.603887 | 2.538975 | 1.025566 |
tokens = tokens[1:-1]
ret = []
start = 0
stack = 0
for i in range(len(tokens)):
if tokens[i] == '(':
if stack == 0:
start = i
stack += 1
elif tokens[i] == ')':
stack -= 1
if stack < 0:
raise Exceptio... | def get_tokens(tokens) | Recursively gets tokens from a match list
Args:
tokens : List of tokens ['(', 'S', '(', 'NP', ')', ')']
Returns:
Stack of tokens | 1.902773 | 2.017386 | 0.943187 |
if isinstance(tree, Tree):
if tree.label() == 'DT' or tree.label() == 'POS':
return ''
words = []
for child in tree:
words.append(get_object(child))
return ' '.join([_f for _f in words if _f])
else:
return tree | def get_object(tree) | Get the object in the tree object.
Method should remove unnecessary letters and words::
the
a/an
's
Args:
tree (Tree): Parsed tree structure
Returns:
Resulting string of tree ``(Ex: "red car")`` | 3.102019 | 3.078231 | 1.007728 |
if isinstance(tree, Tree):
words = []
for child in tree:
words.append(get_raw(child))
return ' '.join(words)
else:
return tree | def get_raw(tree) | Get the exact words in lowercase in the tree object.
Args:
tree (Tree): Parsed tree structure
Returns:
Resulting string of tree ``(Ex: "The red car")`` | 2.355673 | 2.548862 | 0.924206 |
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
... | 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 w... | 1.827684 | 1.864117 | 0.980456 |
project_path = environ.paths.clean(self.source_directory)
return project_path.find('cd-remote-project') != -1 | def is_remote_project(self) -> bool | Whether or not this project is remote | 12.796234 | 10.979964 | 1.165417 |
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 = ... | def library_directories(self) -> typing.List[str] | The list of directories to all of the library locations | 6.101507 | 5.956265 | 1.024385 |
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 | The path where the project results will be written | 8.467677 | 7.217326 | 1.173243 |
return 'file://{path}?id={id}'.format(
path=os.path.join(self.results_path, 'project.html'),
id=self.uuid
) | def url(self) -> str | Returns the URL that will open this project results file in the browser
:return: | 8.776283 | 5.356407 | 1.638465 |
return os.path.join(self.results_path, 'reports', self.uuid, 'latest') | def output_directory(self) -> str | Returns the directory where the project results files will be written | 12.958622 | 8.578257 | 1.510636 |
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_d... | 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 fi... | 2.662424 | 2.496113 | 1.066628 |
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 | Renders preformatted text box | 9.148268 | 6.760007 | 1.353293 |
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')
... | 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.
... | 3.113948 | 3.151582 | 0.988059 |
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/**/*', ... | def populate_extra_files() | Creates a list of non-python data files to include in package distribution | 2.783642 | 2.507149 | 1.110282 |
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 purp... | 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 inse... | 3.156659 | 3.26427 | 0.967034 |
response = Response()
response.returned = dict()
if not project.naming_scheme:
return response
create_mapper_func = functools.partial(
create_rename_entry,
insertion_index=insert_index
)
step_renames = list([create_mapper_func(s) for s in project.steps])
step... | def synchronize_step_names(
project: 'projects.Project',
insert_index: int = None
) -> Response | :param project:
:param insert_index: | 3.137905 | 3.102696 | 1.011348 |
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('/'),
'/',
endp... | 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 re... | 3.227565 | 3.238578 | 0.996599 |
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(
... | 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 th... | 5.942756 | 5.802867 | 1.024107 |
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 = (... | 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 reques... | 2.788834 | 2.864913 | 0.973445 |
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(
... | def view(route: str) | Retrieves the contents of the file specified by the view route if it
exists. | 2.564984 | 2.503088 | 1.024728 |
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)
r... | 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 N... | 6.904214 | 6.498062 | 1.062504 |
def make_asset_copy(directory: str) -> file_io.FILE_COPY_ENTRY:
output_directory = os.path.join(
project.output_directory,
directory[len(project.source_directory):].lstrip(os.sep)
)
return file_io.FILE_COPY_ENTRY(
source=directory,
desti... | def list_asset_writes(
project: 'projects.Project'
) -> typing.List[file_io.FILE_COPY_ENTRY] | Returns a list containing the file/directory writes that should be executed
to deploy the project assets to the results folder. If the project has no
assets an empty list is returned.
:param project:
The project for which the assets should be copied
:return:
A list containing the file c... | 2.352571 | 2.482507 | 0.94766 |
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 | 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 | 2.818644 | 2.550805 | 1.105002 |
if path in sys.path:
sys.path.remove(path)
return True
return False | 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. | 4.358709 | 3.352405 | 1.300174 |
os.chdir(os.path.expanduser('~'))
project = cauldron.project.internal_project
if not project:
return False
[remove_library_path(path) for path in project.library_directories]
remove_library_path(project.source_directory)
cauldron.project.unload()
return True | def close() | ... | 5.375312 | 5.456179 | 0.985179 |
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.endswi... | def reload_libraries(library_directories: list = None) | Reload the libraries stored in the project's local and shared library
directories | 2.9392 | 2.886143 | 1.018383 |
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 < ... | 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 | 4.382333 | 4.443121 | 0.986318 |
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 | 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. | 3.161588 | 2.895455 | 1.091914 |
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 | 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. | 2.89725 | 2.713842 | 1.067582 |
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 | Retrieves the current value of the DOM for the step | 5.17145 | 4.668805 | 1.10766 |
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:
... | def dumps(self) -> str | Writes the step information to an HTML-formatted string | 3.368958 | 3.272128 | 1.029592 |
'''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.retr... | 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 | 10.549798 | 3.285368 | 3.211146 |
'''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) | Return an array of job objects that are being tracked | 7.432059 | 4.998134 | 1.486967 |
'''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 the paginated jids of jobs tagged with a tag | 13.174668 | 5.68603 | 2.317024 |
'''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:
... | 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. | 8.480367 | 2.795103 | 3.034009 |
'''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) | Return jobs objects for all the jids | 7.603343 | 5.597007 | 1.358466 |
'''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) | Set the title of the process | 7.781593 | 7.44004 | 1.045907 |
'''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 a... | def divide(cls, jobs, count) | Divide up the provided jobs into count evenly-sized groups | 6.234952 | 5.465354 | 1.140814 |
'''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:
logg... | def clean(cls, path) | Clean up all the files in a provided path | 2.26275 | 2.028605 | 1.115422 |
'''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.... | def sandbox(cls, path) | Ensures path exists before yielding, cleans up after | 4.213904 | 3.33381 | 1.263991 |
'''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... | def resumable(self) | Find all the jobs that we'd previously been working on | 5.828141 | 4.510081 | 1.292248 |
'''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.LostLockExcept... | def jobs(self) | Generator for all the jobs | 8.049431 | 8.027082 | 1.002784 |
'''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
... | def listener(self) | Listen for pubsub messages relevant to this worker in a thread | 6.629122 | 4.364848 | 1.518752 |
'''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:
... | def listen(self, listener) | Listen for events that affect our ownership of a job | 8.953071 | 6.307492 | 1.419434 |
'''Register our signal handler'''
for sig in signals:
signal.signal(getattr(signal, 'SIG' + sig), self.handler) | def signals(self, signals=('QUIT', 'USR1', 'USR2')) | Register our signal handler | 5.173525 | 4.363506 | 1.185635 |
# QUIT - Finish processing, but don't do any more work after that
self.stop()
elif signum == signal.SIGUSR1:
# USR1 - Print the backtrace
message = ''.join(traceback.format_stack(frame))
message = 'Signaled traceback for %s:\n%s' % (os.getpid(), messag... | def handler(self, signum, frame): # pragma: no cover
'''Signal handler for this process'''
if signum == signal.SIGQUIT | Signal handler for this process | 3.813964 | 3.8372 | 0.993945 |
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) | This function will truncate the values of Entry.title so they are
255 characters or less. | 3.900935 | 3.838743 | 1.016201 |
'''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)
... | def process(self, job) | Process a job | 7.30201 | 8.08989 | 0.902609 |
'''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) | Stop the greenlet processing the provided jid | 5.819886 | 4.286355 | 1.35777 |
'''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(ge... | def run(self) | Work on jobs | 5.748693 | 5.582004 | 1.029862 |
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) | Initialize a postgresql connection by each connection string
defined in the configuration file | 3.440835 | 3.836871 | 0.896781 |
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... | def initialize(g, app) | If postgresql url is defined in configuration params a
scoped session will be created | 3.31122 | 3.278766 | 1.009898 |
extensions = []
if 'EXTENSIONS' in config:
for ext in config['EXTENSIONS']:
try:
extensions.append(locate(ext))
except Exception as e:
print(e)
return extensions | def load_extensions_from_config(**config) | Loads extensions | 3.068116 | 3.061196 | 1.002261 |
for k in self.environments.keys():
self.environments[k].globals['REQUEST'] = r | def set_request(self, r) | Appends request object to the globals dict | 9.187578 | 7.221288 | 1.272291 |
el = elasticsearch.Elasticsearch(hosts=HOSTS)
el_pool.connections[connection_name] = ElasticSearchClient(el) | def init_db_conn(connection_name, HOSTS=None) | Initialize a redis connection by each connection string
defined in the configuration file | 11.544982 | 11.559756 | 0.998722 |
tags = {}
for t in targs:
split_tag = t.split(':')
if len(split_tag) > 1:
tags['tag:' + split_tag[0]] = split_tag[1]
else:
tags['tag:' + split_tag[0]] = ''
return tags | def parse_tags(targs) | Tags can be in the forma key:value or simply value | 1.945065 | 1.851747 | 1.050394 |
'''
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),... | def json_response(self, status=200, data={}, headers={}) | To set flask to inject specific headers on response request,
such as CORS_ORIGIN headers | 5.603341 | 2.256656 | 2.483028 |
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) | Constructs a response, allowing custom template name and content_type | 2.952809 | 2.96568 | 0.99566 |
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
... | def describe_key_pairs() | Returns all key pairs for region | 2.39718 | 2.312965 | 1.03641 |
global app
def init_config():
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.starts... | def init_app(module, BASE_DIR, **kwargs) | Initalize an app, call this method once from start_app | 2.612975 | 2.571742 | 1.016033 |
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.sta... | def execute_command(cmd, **kwargs) | execute a console command | 4.329353 | 4.128901 | 1.048548 |
from flask_philo.db.postgresql.schema import Base
from flask_philo.db.postgresql.orm import BaseModel # noqa
from flask_philo.db.postgresql.connection import get_pool
for conn_name, conn in get_pool().connections.items():
Base.metadata.create_all(conn.engine) | def syncdb() | Create tables if they don't exist | 4.365821 | 4.422251 | 0.987239 |
if isinstance(password, str):
password = password.encode('utf8')
value = bcrypt.hashpw(password, bcrypt.gensalt(rounds))
return cls(value) | def new(cls, password, rounds) | Creates a PasswordHash from the given password. | 2.580132 | 2.489906 | 1.036237 |
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 Passwo... | 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. | 3.042515 | 2.527901 | 1.203573 |
rpool = redis.ConnectionPool(
host=HOST, port=PORT, db=DB, password=PASSWORD)
r = redis.Redis(connection_pool=rpool)
redis_pool.connections[connection_name] = RedisClient(r) | def init_db_conn(
connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None) | Initialize a redis connection by each connection string
defined in the configuration file | 3.44589 | 3.287222 | 1.048268 |
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():
for k, ... | def initialize(g, app) | If redis connection parameters are defined in configuration params a
session will be created | 2.804718 | 2.931426 | 0.956776 |
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)
... | def _initialize_from_dict(self, data) | Loads serializer from a request object | 2.999834 | 2.907026 | 1.031925 |
for name, value in model.__dict__.items():
if name in self._properties:
setattr(self, name, value) | def _initialize_from_model(self, model) | Loads a model from | 3.673066 | 4.06061 | 0.90456 |
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) | Finds record and update it based in serializer values | 4.298153 | 3.669773 | 1.171231 |
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):
... | def to_json(self) | Returns a json representation | 2.229241 | 2.240918 | 0.994789 |
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) | General information about the operating system.
This is a flag you can pass to `Stats.submit()`. | 4.14176 | 4.598443 | 0.900687 |
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) | 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()`. | 3.150722 | 3.694688 | 0.852771 |
# 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) | Python interpreter version.
This is a flag you can pass to `Stats.submit()`. | 5.492325 | 6.640282 | 0.827122 |
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)
... | 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.loca... | 2.718343 | 2.333002 | 1.16517 |
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... | 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... | 3.576123 | 2.737018 | 1.306576 |
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) | 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. | 5.67478 | 6.042112 | 0.939205 |
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 =... | 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. | 3.387062 | 3.336568 | 1.015134 |
if self.recording:
if self.notes is None:
raise ValueError("This report has already been submitted")
self.notes.extend(self._to_notes(info)) | def note(self, info) | Record some info to the report.
:param info: Dictionary of info to record. Note that previous info
recorded under the same keys will not be overwritten. | 8.560055 | 8.406955 | 1.018211 |
if not self.recording:
return
env_val = os.environ.get(self.env_var, '').lower()
if env_val not in (None, '', '1', 'on', 'enabled', 'yes', 'true'):
self.status = Stats.DISABLED_ENV
self.notes = None
return
if self.notes is None:
... | def submit(self, info, *flags) | Finish recording and upload or save the report.
This closes the `Stats` object, no further methods should be called.
The report is either saved, uploaded or discarded, depending on
configuration. If uploading is enabled, previous reports might be
uploaded too. If uploading is not explic... | 2.992806 | 2.927408 | 1.02234 |
now = time.time()
secs = int(now)
msecs = int((now - secs) * 1000)
submitted_date = filename = None # avoids warnings
while True:
submitted_date = '%d.%03d' % (secs, msecs)
filename = 'report_%s.txt' % submitted_date
filename = os.path.join(DESTINATION, filename)
... | def store(report, address) | Stores the report on disk. | 3.149154 | 3.111997 | 1.01194 |
def send_response(status, body):
if not isinstance(body, bytes):
body = body.encode('utf-8')
start_response(status, [('Content-Type', 'text/plain'),
('Content-Length', '%d' % len(body))])
return [body]
if environ['REQUEST_METHOD'] != 'P... | def application(environ, start_response) | WSGI interface. | 2.317649 | 2.347524 | 0.987274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.