code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if preformatted: result = render_texts.preformatted_text(value) else: result = render_texts.text(value) r = _get_report() r.append_body(result) r.stdout_interceptor.write_source( '{}\n'.format(textwrap.dedent(value)) )
def text(value: str, preformatted: bool = False)
Adds text to the display. If the text is not preformatted, it will be displayed in paragraph format. Preformatted text will be displayed inside a pre tag with a monospace font. :param value: The text to display. :param preformatted: Whether or not to preserve the whitespace display of t...
6.743949
7.42233
0.908603
r = _get_report() result = render_texts.markdown( source=source, source_path=source_path, preserve_lines=preserve_lines, font_size=font_size, **kwargs ) r.library_includes += result['library_includes'] r.append_body(result['body']) r.stdout_intercep...
def markdown( source: str = None, source_path: str = None, preserve_lines: bool = False, font_size: float = None, **kwargs )
Renders the specified source string or source file using markdown and adds the resulting HTML to the notebook display. :param source: A markdown formatted string. :param source_path: A file containing markdown text. :param preserve_lines: If True, all line breaks will be treate...
5.695539
6.087383
0.93563
r = _get_report() r.append_body(render.json(**kwargs)) r.stdout_interceptor.write_source( '{}\n'.format(_json_io.dumps(kwargs, indent=2)) )
def json(**kwargs)
Adds the specified data to the the output display window with the specified key. This allows the user to make available arbitrary JSON-compatible data to the display for runtime use. :param kwargs: Each keyword argument is added to the CD.data object with the specified key and value.
14.093679
16.025934
0.87943
r = _get_report() if not figure and not isinstance(data, (list, tuple)): data = [data] if 'plotly' not in r.library_includes: r.library_includes.append('plotly') r.append_body(render.plotly( data=data, layout=layout, scale=scale, figure=figure, ...
def plotly( data: typing.Union[dict, list] = None, layout: dict = None, scale: float = 0.5, figure: dict = None, static: bool = False )
Creates a Plotly plot in the display with the specified data and layout. :param data: The Plotly trace data to be plotted. :param layout: The layout data used for the plot. :param scale: The display scale with units of fractional screen height. A value of 0.5 constrains ...
6.005989
7.185363
0.835864
r = _get_report() r.append_body(render.table( data_frame=data_frame, scale=scale, include_index=include_index, max_rows=max_rows )) r.stdout_interceptor.write_source('[ADDED] Table\n')
def table( data_frame, scale: float = 0.7, include_index: bool = False, max_rows: int = 500 )
Adds the specified data frame to the display in a nicely formatted scrolling table. :param data_frame: The pandas data frame to be rendered to a table. :param scale: The display scale with units of fractional screen height. A value of 0.5 constrains the output to a maximum height eq...
7.709549
8.368256
0.921285
r = _get_report() r.append_body(render.svg(svg_dom)) r.stdout_interceptor.write_source('[ADDED] SVG\n') if not filename: return if not filename.endswith('.svg'): filename += '.svg' r.files[filename] = svg_dom
def svg(svg_dom: str, filename: str = None)
Adds the specified SVG string to the display. If a filename is included, the SVG data will also be saved to that filename within the project results folder. :param svg_dom: The SVG string data to add to the display. :param filename: An optional filename where the SVG data should be save...
9.792821
10.208539
0.959277
r = _get_report() r.append_body(render.jinja(path, **kwargs)) r.stdout_interceptor.write_source('[ADDED] Jinja2 rendered HTML\n')
def jinja(path: str, **kwargs)
Renders the specified Jinja2 template to HTML and adds the output to the display. :param path: The fully-qualified path to the template to be rendered. :param kwargs: Any keyword arguments that will be use as variable replacements within the template.
24.776129
23.815174
1.040351
r = _get_report() r.append_body(render.whitespace(lines)) r.stdout_interceptor.write_source('\n')
def whitespace(lines: float = 1.0)
Adds the specified number of lines of whitespace. :param lines: The number of lines of whitespace to show.
28.167259
34.066269
0.826837
r = _get_report() path = '/'.join(['reports', r.project.uuid, 'latest', 'assets', filename]) r.append_body(render.image(path, width, height, justify)) r.stdout_interceptor.write_source('[ADDED] Image\n')
def image( filename: str, width: int = None, height: int = None, justify: str = 'left' )
Adds an image to the display. The image must be located within the assets directory of the Cauldron notebook's folder. :param filename: Name of the file within the assets directory, :param width: Optional width in pixels for the image. :param height: Optional height in pixels fo...
15.185962
16.304077
0.931421
r = _get_report() r.append_body(render.html(dom)) r.stdout_interceptor.write_source('[ADDED] HTML\n')
def html(dom: str)
A string containing a valid HTML snippet. :param dom: The HTML string to add to the display.
30.647034
30.405657
1.007939
r = _get_report() data = {} for key, value in r.project.shared.fetch(None).items(): if key.startswith('__cauldron_'): continue data[key] = value r.append_body(render.status(data, values=show_values, types=show_types))
def workspace(show_values: bool = True, show_types: bool = True)
Adds a list of the shared variables currently stored in the project workspace. :param show_values: When true the values for each variable will be shown in addition to their name. :param show_types: When true the data types for each shared variable will be shown in addition t...
9.479156
9.262793
1.023358
r = _get_report() r.append_body(render_plots.pyplot( figure, scale=scale, clear=clear, aspect_ratio=aspect_ratio )) r.stdout_interceptor.write_source('[ADDED] PyPlot plot\n')
def pyplot( figure=None, scale: float = 0.8, clear: bool = True, aspect_ratio: typing.Union[list, tuple] = None )
Creates a matplotlib plot in the display for the specified figure. The size of the plot is determined automatically to best fit the notebook. :param figure: The matplotlib figure to plot. If omitted, the currently active figure will be used. :param scale: The display scale with unit...
12.999342
13.730032
0.946782
r = _get_report() if 'bokeh' not in r.library_includes: r.library_includes.append('bokeh') r.append_body(render_plots.bokeh_plot( model=model, scale=scale, responsive=responsive )) r.stdout_interceptor.write_source('[ADDED] Bokeh plot\n')
def bokeh(model, scale: float = 0.7, responsive: bool = True)
Adds a Bokeh plot object to the notebook display. :param model: The plot object to be added to the notebook display. :param scale: How tall the plot should be in the notebook as a fraction of screen height. A number between 0.1 and 1.0. The default value is 0.7. :param responsive: ...
8.850465
9.289422
0.952747
r = _get_report() r.append_body(render.listing( source=source, ordered=ordered, expand_full=expand_full )) r.stdout_interceptor.write_source('[ADDED] Listing\n')
def listing( source: list, ordered: bool = False, expand_full: bool = False )
An unordered or ordered list of the specified *source* iterable where each element is converted to a string representation for display. :param source: The iterable to display as a list. :param ordered: Whether or not the list should be ordered. If False, which is the default, an uno...
12.520429
15.110103
0.828613
r = _get_report() r.append_body(render.list_grid( source=source, expand_full=expand_full, column_count=column_count, row_spacing=row_spacing )) r.stdout_interceptor.write_source('[ADDED] List grid\n')
def list_grid( source: list, expand_full: bool = False, column_count: int = 2, row_spacing: float = 1.0 )
An multi-column list of the specified *source* iterable where each element is converted to a string representation for display. :param source: The iterable to display as a list. :param expand_full: Whether or not the list should expand to fill the screen horizontally. When defaulted...
7.391466
8.649312
0.854573
r = _get_report() if 'katex' not in r.library_includes: r.library_includes.append('katex') r.append_body(render_texts.latex(source.replace('@', '\\'))) r.stdout_interceptor.write_source('[ADDED] Latex equation\n')
def latex(source: str)
Add a mathematical equation in latex math-mode syntax to the display. Instead of the traditional backslash escape character, the @ character is used instead to prevent backslash conflicts with Python strings. For example, \\delta would be @delta. :param source: The string representing the latex...
17.04496
14.006779
1.216908
r = _get_report() r.append_body(render_texts.head(source, count=count)) r.stdout_interceptor.write_source('[ADDED] Head\n')
def head(source, count: int = 5)
Displays a specified number of elements in a source object of many different possible types. :param source: DataFrames will show *count* rows of that DataFrame. A list, tuple or other iterable, will show the first *count* rows. Dictionaries will show *count* keys from the dictionary, wh...
28.749184
36.250057
0.79308
environ.abort_thread() step = _cd.project.get_internal_project().current_step if message is not None: step.progress_message = message if progress is not None: step.progress = max(0.0, min(1.0, progress)) if section_message is not None: step.sub_progress_message = sectio...
def status( message: str = None, progress: float = None, section_message: str = None, section_progress: float = None, )
Updates the status display, which is only visible while a step is running. This is useful for providing feedback and information during long-running steps. A section progress is also available for cases where long running tasks consist of multiple tasks and you want to display sub-progress messages ...
3.661789
3.863398
0.947816
environ.abort_thread() r = _get_report() r.append_body(render.code_block( block=code, path=path, language=language_id, title=title, caption=caption )) r.stdout_interceptor.write_source('{}\n'.format(code))
def code_block( code: str = None, path: str = None, language_id: str = None, title: str = None, caption: str = None )
Adds a block of syntax highlighted code to the display from either the supplied code argument, or from the code file specified by the path argument. :param code: A string containing the code to be added to the display :param path: A path to a file containing code to be added to the disp...
8.345458
9.566862
0.87233
environ.abort_thread() step = _cd.project.get_internal_project().current_step r = _get_report() r.append_body(render.elapsed_time(step.elapsed_time)) result = '[ELAPSED]: {}\n'.format(timedelta(seconds=step.elapsed_time)) r.stdout_interceptor.write_source(result)
def elapsed()
Displays the elapsed time since the step started running.
13.780979
13.237241
1.041076
return sys.modules.get(name)
def get_module(name: str) -> typing.Union[types.ModuleType, None]
Retrieves the loaded module for the given module name or returns None if no such module has been loaded. :param name: The name of the module to be retrieved :return: Either the loaded module with the specified name, or None if no such module has been imported.
5.505513
33.082333
0.166419
try: return module.__spec__.name except AttributeError: return module.__name__
def get_module_name(module: types.ModuleType) -> str
Returns the name of the specified module by looking up its name in multiple ways to prevent incompatibility issues. :param module: A module object for which to retrieve the name.
5.490092
6.020329
0.911926
path = getattr(module, '__file__') directory = getattr(module, '__path__', [None])[0] if path is None and directory: path = os.path.join(directory, '__init__.py') last_modified = os.path.getmtime(path) if last_modified < newer_than: return False try: importlib.re...
def do_reload(module: types.ModuleType, newer_than: int) -> bool
Executes the reload of the specified module if the source file that it was loaded from was updated more recently than the specified time :param module: A module object to be reloaded :param newer_than: The time in seconds since epoch that should be used to determine if the module ne...
2.712153
2.881735
0.941153
if not hasattr(parent_module, '__path__'): return False parent_name = get_module_name(parent_module) children = filter( lambda item: item[0].startswith(parent_name), sys.modules.items() ) return any([do_reload(item[1], newer_than) for item in children])
def reload_children(parent_module: types.ModuleType, newer_than: int) -> bool
Reloads all imported children of the specified parent module object :param parent_module: A module object whose children should be refreshed if their currently loaded versions are out of date. :param newer_than: An integer time in seconds for comparison. Any children modules that ...
3.111524
3.140029
0.990922
if isinstance(module, str): module = get_module(module) if module is None or not isinstance(module, types.ModuleType): return False try: step = session.project.get_internal_project().current_step modified = step.last_modified if step else None except AttributeErro...
def reload_module( module: typing.Union[str, types.ModuleType], recursive: bool, force: bool ) -> bool
Reloads the specified module, which can either be a module object or a string name of a module. Will not reload a module that has not been imported :param module: A module object or string module name that should be refreshed if its currently loaded version is out of date or the action is f...
4.303403
4.399692
0.978115
out = [] for module in modules: out.append(reload_module(module, recursive, force)) return any(out)
def refresh( *modules: typing.Union[str, types.ModuleType], recursive: bool = False, force: bool = False ) -> bool
Checks the specified module or modules for changes and reloads them if they have been changed since the module was first imported or last refreshed. :param modules: One or more module objects that should be refreshed if they the currently loaded versions are out of date. The package name fo...
4.794649
5.529289
0.867137
code = target.__code__ if not bool(code.co_flags & inspect.CO_VARARGS): return -1 return code.co_argcount + code.co_kwonlyargcount
def get_args_index(target) -> int
Returns the index of the "*args" parameter if such a parameter exists in the function arguments or -1 otherwise. :param target: The target function for which the args index should be determined :return: The arguments index if it exists or -1 if not
3.818658
3.527716
1.082473
code = target.__code__ if not bool(code.co_flags & inspect.CO_VARKEYWORDS): return -1 return ( code.co_argcount + code.co_kwonlyargcount + (1 if code.co_flags & inspect.CO_VARARGS else 0) )
def get_kwargs_index(target) -> int
Returns the index of the "**kwargs" parameter if such a parameter exists in the function arguments or -1 otherwise. :param target: The target function for which the kwargs index should be determined :return: The keyword arguments index if it exists or -1 if not
3.048603
2.928696
1.040942
code = getattr(target, '__code__') if code is None: return [] arg_count = code.co_argcount kwarg_count = code.co_kwonlyargcount args_index = get_args_index(target) kwargs_index = get_kwargs_index(target) arg_names = list(code.co_varnames[:arg_count]) if args_index != -1:...
def get_arg_names(target) -> typing.List[str]
Gets the list of named arguments for the target function :param target: Function for which the argument names will be retrieved
1.907371
2.006927
0.950394
arg_names = get_arg_names(target) annotations = getattr(target, '__annotations__', {}) out = dict( name=name, index=arg_names.index(name), description=description, type=conversions.arg_type_to_string(annotations.get(name, 'Any')) ) out.update(get_optional_data(...
def create_argument(target, name, description: str = '') -> dict
Creates a dictionary representation of the parameter :param target: The function object in which the parameter resides :param name: The name of the parameter :param description: The documentation description for the parameter
3.761326
3.707623
1.014485
parts = tuple(argument_line.split(' ', 1)[-1].split(':', 1)) return parts if len(parts) > 1 else (parts[0], '')
def explode_line(argument_line: str) -> typing.Tuple[str, str]
Returns a tuple containing the parameter name and the description parsed from the given argument line
3.660432
3.683567
0.993719
with open(path, 'r') as file_handle: contents = file_handle.read() regex = re.compile('from\s+(?P<source>[^\s]+)', re.IGNORECASE) matches = regex.findall(contents) if not matches: return None match = matches[0] os.system('docker pull {}'.format(match)) return match
def update_base_image(path: str)
Pulls the latest version of the base image
3.044986
2.772559
1.098259
update_base_image(path) match = file_pattern.search(os.path.basename(path)) build_id = match.group('id') tags = [ '{}:{}-{}'.format(HUB_PREFIX, version, build_id), '{}:latest-{}'.format(HUB_PREFIX, build_id), '{}:current-{}'.format(HUB_PREFIX, build_id) ] if build_id...
def build(path: str) -> dict
Builds the container from the specified docker file path
3.376603
3.121705
1.081653
for tag in build_entry['tags']: print('[PUSHING]:', tag) os.system('docker push {}'.format(tag))
def publish(build_entry: dict)
Publishes the specified build entry to docker hub
7.637385
5.953603
1.282817
parser = ArgumentParser() parser.add_argument('-p', '--publish', action='store_true', default=False) return vars(parser.parse_args())
def parse() -> dict
Parse command line arguments
3.674128
2.657053
1.382783
args = parse() build_results = [build(p) for p in glob.iglob(glob_path)] if not args['publish']: return for entry in build_results: publish(entry)
def run()
Execute the build process
7.759216
7.240357
1.071662
environ.abort_thread() parts = ( '{}'.format(timedelta(seconds=seconds)) .rsplit('.', 1) ) hours, minutes, seconds = parts[0].split(':') return templating.render_template( 'elapsed_time.html', hours=hours.zfill(2), minutes=minutes.zfill(2), second...
def elapsed_time(seconds: float) -> str
Displays the elapsed time since the current step started running.
3.703083
3.440649
1.076275
environ.abort_thread() return templating.render_template( 'image.html', path=rendered_path, width=width, height=height, justification=(justify or 'left').lower() )
def image( rendered_path: str, width: int = None, height: int = None, justify: str = None ) -> str
Renders an image block
6.391341
5.746937
1.11213
data = _environ.systems.get_system_data() data['cauldron'] = _environ.package_settings.copy() return data
def get_environment_info() -> dict
Information about Cauldron and its Python interpreter. :return: A dictionary containing information about the Cauldron and its Python environment. This information is useful when providing feedback and bug reports.
24.915691
18.198971
1.369071
from cauldron.cli.server import run run.execute(port=port, debug=debug, **kwargs)
def run_server(port=5010, debug=False, **kwargs)
Run the cauldron http server used to interact with cauldron from a remote host. :param port: The port on which to bind the cauldron server. :param debug: Whether or not the server should be run in debug mode. If true, the server will echo debugging information during operation. ...
5.380125
5.537629
0.971557
from cauldron.cli import batcher return batcher.run_project( project_directory=project_directory, output_directory=output_directory, log_path=logging_path, reader_path=reader_path, reload_project_libraries=reload_project_libraries, shared_data=kwargs )
def run_project( project_directory: str, output_directory: str = None, logging_path: str = None, reader_path: str = None, reload_project_libraries: bool = False, **kwargs ) -> ExecutionResult
Runs a project as a single command directly within the current Python interpreter. :param project_directory: The fully-qualified path to the directory where the Cauldron project is located :param output_directory: The fully-qualified path to the directory where the results will be ...
2.710069
2.695514
1.0054
try: self.thread.join(timeout) return True except AttributeError: return False
def join(self, timeout: float = None) -> bool
Joins on the thread associated with the response if it exists, or just returns after a no-op if no thread exists to join. :param timeout: Maximum number of seconds to block on the join before given up and continuing operation. The default `None` value will wait forev...
5.91913
4.790091
1.235703
r = Response(serial_data.get('id')) r.data.update(serial_data.get('data', {})) r.ended = serial_data.get('ended', False) r.failed = not serial_data.get('success', True) def load_messages(message_type: str): messages = [ ResponseMessage(**dat...
def deserialize(serial_data: dict) -> 'Response'
Converts a serialized dictionary response to a Response object
2.670208
2.706563
0.986568
thread = threading.current_thread() if not isinstance(thread, CauldronThread): return if thread.is_executing and thread.abort: raise ThreadAbortError('User Aborted Execution')
def abort_thread()
This function checks to see if the user has indicated that they want the currently running execution to stop prematurely by marking the running thread as aborted. It only applies to operations that are run within CauldronThreads and not the main thread.
8.546891
4.526017
1.888391
return ( self._has_started and self.is_alive() or self.completed_at is None or (datetime.utcnow() - self.completed_at).total_seconds() < 0.5 )
def is_running(self) -> bool
Specifies whether or not the thread is running
5.717684
4.80516
1.189905
async def run_command(): try: self.result = self.command( context=self.context, **self.kwargs ) except Exception as error: self.exception = error print(error) ...
def run(self)
Executes the Cauldron command in a thread to prevent long-running computations from locking the main Cauldron thread, which is needed to serve and print status information.
3.833402
3.579684
1.070877
if not self._loop: return False try: self._loop.stop() return True except Exception: return False finally: self.completed_at = datetime.utcnow()
def abort_running(self) -> bool
Executes a hard abort by shutting down the event loop in this thread in which the running command was operating. This is carried out using the asyncio library to prevent the stopped execution from destabilizing the Python environment.
5.751235
4.230042
1.359616
request = request if request else flask_request try: json_args = request.get_json(silent=True) except Exception: json_args = None try: get_args = request.values except Exception: get_args = None arg_sources = list(filter( lambda arg: arg is not No...
def from_request(request=None) -> dict
Fetches the arguments for the current Flask application request
3.138135
2.800353
1.120621
# type: (Rule, List[Union[str, None]], List[Union[List[str], None]], str, List[int]) -> str pred_label = np.argmax(rule.output) if label == "label": output = str(pred_label) + " ({})".format(rule.output[pred_label]) elif label == "prob": output = "[{}]".format(", ".join(["{:.4f}".fo...
def print_rule(rule, feature_names=None, category_names=None, label="label", support=None)
print the rule in a nice way :param rule: An instance of Rule :param feature_names: a list of n_features feature names, :param category_names: the names of the categories of each feature. :param label: Can take two values, 'label': just print the label as output, or 'prob': print the prob distribution. ...
2.619327
2.744169
0.954506
# type: (str, float) -> Rule if rule_str == "default": return Rule([], prob) raw_rules = rule_str[1:-1].split(",") clauses = [] for raw_rule in raw_rules: idx = raw_rule.find("=") if idx == -1: raise ValueError("No \"=\" find in the rule!") clauses.a...
def rule_str2rule(rule_str, prob)
A helper function that converts the resulting string returned from C function to the Rule object :param rule_str: a string representing the rule :param prob: the output probability :return: a Rule object
3.19163
3.826389
0.83411
satisfied = [] if self.is_default(): return np.ones(x_cat.shape[0], dtype=bool) for idx, cat in self.clauses: satisfied.append(x_cat[:, idx] == cat) return reduce(np.logical_and, satisfied)
def is_satisfied(self, x_cat)
:param x_cat: a 2D array of pure categorical data of shape [n_data, n_features] :return: a bool array of shape [n_data,] representing whether the rule is fired by each input data.
3.717806
3.852737
0.964978
verbose = self.verbose # Create temporary files data_file = tempfile.NamedTemporaryFile("w+b", delete=False) label_file = tempfile.NamedTemporaryFile("w+b", delete=False) start = time.time() raw_rules = categorical2pysbrl_data(x, y, data_file.name, label_file.na...
def fit(self, x, y)
:param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int :param y: 1D np.ndarray (n_instances, ) labels :return:
3.520103
3.528029
0.997753
self._rule_pool = [([], [])] + raw_rules self._rule_list = [] for i, idx in enumerate(rule_ids): rule = Rule([Clause(f, c) for f, c in zip(*self._rule_pool[idx])], outputs[i]) self._rule_list.append(rule) # self._rule_list.append(rule_str2rule(_rule_n...
def from_raw(self, rule_ids, outputs, raw_rules)
A helper function that converts the results returned from C function :param rule_ids: :param outputs: :param raw_rules: :return:
3.871969
3.956695
0.978587
# type: (np.ndarray, np.ndarray) -> np.ndarray caught_matrix = self.caught_matrix(x) if np.sum(caught_matrix.astype(np.int)) != x.shape[0]: raise RuntimeError("The sum of the support should equal to the number of instances!") support_summary = np.zeros((self.n_rules,...
def compute_support(self, x, y)
Calculate the support for the rules. The support of each rule is a list of `n_classes` integers: [l1, l2, ...]. Each integer represents the number of data of label i that is caught by this rule :param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int ...
2.975952
2.944808
1.010576
# type: (np.ndarray) -> np.ndarray un_satisfied = np.ones((x.shape[0],), dtype=np.bool) supports = np.zeros((self.n_rules, x.shape[0]), dtype=np.bool) for i, rule in enumerate(self._rule_list): is_satisfied = rule.is_satisfied(x) satisfied = np.logical_an...
def caught_matrix(self, x)
compute the caught matrix of x Each rule has an array of bools, showing whether each instances is caught by this rule :param x: 2D np.ndarray (n_instances, n_features) should be categorical data, must be of type int :return: a bool np.ndarray of shape (n_rules, n_instances)
3.309866
3.365592
0.983442
# type: (np.ndarray) -> np.ndarray un_satisfied = np.ones([x.shape[0]], dtype=np.bool) paths = np.zeros((self.n_rules, x.shape[0]), dtype=np.bool) for i, rule in enumerate(self._rule_list): paths[i, :] = un_satisfied satisfied = rule.is_satisfied(x) ...
def decision_path(self, x)
compute the decision path of the rule list on x :param x: x should be already transformed :return: return a np.ndarray of shape [n_rules, n_instances] of type bool, representing whether an instance has consulted a rule or not
3.641302
3.399958
1.070984
environ.abort_thread() index = 0 while index < (len(args) - 1): key = args[index] value = args[index + 1] self._shared_cache_data[key] = value index += 2 for key, value in kwargs.items(): if value is None and key in ...
def put(self, *args, **kwargs) -> 'SharedCache'
Adds one or more variables to the cache. :param args: Variables can be specified by two consecutive arguments where the first argument is a key and the second one the corresponding value. For example: ``` put('a', 1, 'b', False) ``` ...
2.551383
2.751714
0.927198
return tuple([self.fetch(k, default_value) for k in keys])
def grab( self, *keys: typing.List[str], default_value=None ) -> typing.Tuple
Returns a tuple containing multiple values from the cache specified by the keys arguments :param keys: One or more variable names stored in the cache that should be returned by the grab function. The order of these arguments are preserved by the returned tuple. ...
8.647735
7.355374
1.175703
environ.abort_thread() if key is None: return self._shared_cache_data return self._shared_cache_data.get(key, default_value)
def fetch(self, key: typing.Union[str, None], default_value=None)
Retrieves the value of the specified variable from the cache :param key: The name of the variable for which the value should be returned :param default_value: The value to return if the variable does not exist in the cache :return: The value of the specified ...
7.432957
7.709667
0.964109
if isinstance(alpha, int): alphas = np.array([alpha], dtype=np.int32) elif isinstance(alpha, list): for a in alpha: assert isinstance(a, int) alphas = np.array(alpha, dtype=np.int32) else: raise ValueError('the argument alpha can only be int or List[int]') ...
def train_sbrl(data_file, label_file, lambda_=20, eta=2, max_iters=300000, n_chains=20, alpha=1, seed=None, verbose=0)
The basic training function of the scalable bayesian rule list. Users are suggested to use SBRL instead of this function. It takes the paths of the pre-processed data and label files as input, and return the parameters of the trained rule list. Check pysbrl.utils:categorical2pysbrl_data to see how to c...
1.88852
1.999542
0.944476
tree = list(self.parser.raw_parse(line))[0] tree = tree[0] return tree
def parse(self, line)
Returns tree objects from a sentence Args: line: Sentence to be parsed into a tree Returns: Tree object representing parsed sentence None if parse fails
6.098557
6.710224
0.908845
if not source_data: return '' chunk_compressed = zlib.compress(source_data) return binascii.b2a_base64(chunk_compressed).decode('utf-8')
def pack_chunk(source_data: bytes) -> str
Packs the specified binary source data by compressing it with the Zlib library and then converting the bytes to a base64 encoded string for non-binary transmission. :param source_data: The data to be converted to a compressed, base64 string
3.229011
3.485164
0.926502
if not chunk_data: return b'' chunk_compressed = binascii.a2b_base64(chunk_data.encode('utf-8')) return zlib.decompress(chunk_compressed)
def unpack_chunk(chunk_data: str) -> bytes
Unpacks a previously packed chunk data back into the original bytes representation :param chunk_data: The compressed, base64 encoded string to convert back to the source bytes object.
3.389968
3.11269
1.08908
if not os.path.exists(file_path): return 0 file_size = os.path.getsize(file_path) return max(1, int(math.ceil(file_size / chunk_size)))
def get_file_chunk_count( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> int
Determines the number of chunks necessary to send the file for the given chunk size :param file_path: The absolute path to the file that will be synchronized in chunks :param chunk_size: The maximum size of each chunk in bytes :return The number of chunks necessary to send the e...
2.257054
2.352319
0.959502
chunk_count = get_file_chunk_count(file_path, chunk_size) if chunk_count < 1: return '' with open(file_path, mode='rb') as fp: for chunk_index in range(chunk_count): source = fp.read(chunk_size) chunk = pack_chunk(source) yield chunk
def read_file_chunks( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> bytes
Reads the specified file in chunks and returns a generator where each returned chunk is a compressed base64 encoded string for sync transmission :param file_path: The path to the file to read in chunks :param chunk_size: The size, in bytes, of each chunk. The final chunk will be less th...
2.963891
3.180427
0.931916
mode = 'ab' if append else 'wb' contents = unpack_chunk(packed_chunk) writer.write_file(file_path, contents, mode=mode, offset=offset)
def write_file_chunk( file_path: str, packed_chunk: str, append: bool = True, offset: int = -1 )
Write or append the specified chunk data to the given file path, unpacking the chunk before writing. If the file does not yet exist, it will be created. Set the append argument to False if you do not want the chunk to be appended to an existing file. :param file_path: The file where the chunk w...
4.831471
5.420581
0.89132
cleaned = paths.clean(path or os.getcwd()) if cleaned not in _logging_paths: _logging_paths.append(cleaned) return cleaned
def add_output_path(path: str = None) -> str
Adds the specified path to the output logging paths if it is not already in the listed paths. :param path: The path to add to the logging output paths. If the path is empty or no path is given, the current working directory will be used instead.
8.060833
7.019655
1.148323
cleaned = paths.clean(path or os.getcwd()) if cleaned in _logging_paths: _logging_paths.remove(path) return cleaned
def remove_output_path(path: str = None) -> str
Removes the specified path from the output logging paths if it is in the listed paths. :param path: The path to remove from the logging output paths. If the path is empty or no path is given, the current working directory will be used instead.
9.47419
9.863657
0.960515
m = add_to_message(message) for key, value in kwargs.items(): m.append('{key}: {value}'.format(key=key, value=value)) pre_whitespace = int(max(whitespace, whitespace_top)) post_whitespace = int(max(whitespace, whitespace_bottom)) if pre_whitespace: m.insert(0, max(0, pre_white...
def log( message: typing.Union[str, typing.List[str]], whitespace: int = 0, whitespace_top: int = 0, whitespace_bottom: int = 0, indent_by: int = 0, trace: bool = True, file_path: str = None, append_to_file: bool = True, **kwargs ) -> str
Logs a message to the console with the formatting support beyond a simple print statement or logger statement. :param message: The primary log message for the entry :param whitespace: The number of lines of whitespace to append to the beginning and end of the log message when printe...
2.542215
2.620535
0.970113
message = [] if isinstance(data, str): message.append(indent( dedent(data.strip('\n')).strip(), indent_level * ' ' )) return message for line in data: offset = 0 if isinstance(line, str) else 1 message += add_to_message(line, indent_lev...
def add_to_message(data, indent_level=0) -> list
Adds data to the message object
3.499687
3.340398
1.047686
if not has(mode_id): _current_modes.append(mode_id) return _current_modes.copy()
def add(mode_id: str) -> list
Adds the specified mode identifier to the list of active modes and returns a copy of the currently active modes list.
6.399855
5.056705
1.265617
had_mode = has(mode_id) if had_mode: _current_modes.remove(mode_id) return had_mode
def remove(mode_id: str) -> bool
Removes the specified mode identifier from the active modes and returns whether or not a remove operation was carried out. If the mode identifier is not in the currently active modes, it does need to be removed.
6.017922
4.771985
1.261094
'''Clone the redis client to be slowlog-compatible''' kwargs = client.redis.connection_pool.connection_kwargs kwargs['parser_class'] = redis.connection.PythonParser pool = redis.connection.ConnectionPool(**kwargs) return redis.Redis(connection_pool=pool)
def clone(client)
Clone the redis client to be slowlog-compatible
6.643707
4.220686
1.574082
'''Print timing stats''' results = [(sum(values), len(values), key) for key, values in timings.items()] print(label) print('=' * 65) print('%20s => %13s | %8s | %13s' % ( 'Command', 'Average', '# Calls', 'Total time')) print('-' * 65) for t...
def pretty(timings, label)
Print timing stats
3.588151
3.564323
1.006685
'''Get ready for a profiling run''' self._configs = self._client.config_get('slow-*') self._client.config_set('slowlog-max-len', 100000) self._client.config_set('slowlog-log-slower-than', 0) self._client.execute_command('slowlog', 'reset')
def start(self)
Get ready for a profiling run
5.780115
4.747495
1.217508
'''Set everything back to normal and collect our data''' for key, value in self._configs.items(): self._client.config_set(key, value) logs = self._client.execute_command('slowlog', 'get', 100000) current = { 'name': None, 'accumulated': defaultdict(list) }...
def stop(self)
Set everything back to normal and collect our data
3.106176
2.845855
1.091474
'''Print the results of this profiling''' self.pretty(self._timings, 'Raw Redis Commands') print() for key, value in self._commands.items(): self.pretty(value, 'Qless "%s" Command' % key) print()
def display(self)
Print the results of this profiling
14.58403
10.753828
1.356171
sub_parser.add_argument( '-p', '--project', dest='project_directory', type=str, default=None ) sub_parser.add_argument( '-l', '--log', dest='logging_path', type=str, default=None ) sub_parser.add_argument( '-o', '--outpu...
def add_shell_action(sub_parser: ArgumentParser) -> ArgumentParser
Populates the sub parser with the shell arguments
1.97619
1.828254
1.080917
parser = ArgumentParser(description='Cauldron command') parser.add_argument( 'command', nargs='?', default='shell', help='The Cauldron command action to execute' ) parser.add_argument( '-v', '--version', dest='show_version_info', default=Fal...
def parse(args: list = None) -> dict
Parses the command line arguments and returns a dictionary containing the results. :param args: The command line arguments to parse. If None, the system command line arguments will be used instead.
2.99206
3.015074
0.992367
'''Return all the currently-running jobs''' return self.client('jobs', 'running', self.name, offset, count)
def running(self, offset=0, count=25)
Return all the currently-running jobs
9.393284
7.125189
1.318321
'''Return all the currently-stalled jobs''' return self.client('jobs', 'stalled', self.name, offset, count)
def stalled(self, offset=0, count=25)
Return all the currently-stalled jobs
8.268286
6.591395
1.254406
'''Return all the currently-scheduled jobs''' return self.client('jobs', 'scheduled', self.name, offset, count)
def scheduled(self, offset=0, count=25)
Return all the currently-scheduled jobs
11.151232
7.691456
1.449821
'''Return all the currently dependent jobs''' return self.client('jobs', 'depends', self.name, offset, count)
def depends(self, offset=0, count=25)
Return all the currently dependent jobs
12.681736
6.749773
1.878839
'''Return all the recurring jobs''' return self.client('jobs', 'recurring', self.name, offset, count)
def recurring(self, offset=0, count=25)
Return all the recurring jobs
10.9217
8.195287
1.332681
'''Return a string representative of the class''' if isinstance(klass, string_types): return klass return klass.__module__ + '.' + klass.__name__
def class_string(self, klass)
Return a string representative of the class
4.240696
3.757591
1.128568
'''Either create a new job in the provided queue with the provided attributes, or move that job into that queue. If the job is being serviced by a worker, subsequent attempts by that worker to either `heartbeat` or `complete` the job should fail and return `false`. The `priority...
def put(self, klass, data, priority=None, tags=None, delay=None, retries=None, jid=None, depends=None)
Either create a new job in the provided queue with the provided attributes, or move that job into that queue. If the job is being serviced by a worker, subsequent attempts by that worker to either `heartbeat` or `complete` the job should fail and return `false`. The `priority` argument ...
7.25086
1.934774
3.747652
'''Place a recurring job in this queue''' return self.client('recur', self.name, jid or uuid.uuid4().hex, self.class_string(klass), json.dumps(data), 'interval', interval, offset, 'priority', priority or 0, 'tags', json.dumps(tags o...
def recur(self, klass, data, interval, offset=0, priority=None, tags=None, retries=None, jid=None)
Place a recurring job in this queue
4.735325
4.384655
1.079977
'''Passing in the queue from which to pull items, the current time, when the locks for these returned items should expire, and the number of items to be popped off.''' results = [Job(self.client, **job) for job in json.loads( self.client('pop', self.name, self.worker_name, co...
def pop(self, count=None)
Passing in the queue from which to pull items, the current time, when the locks for these returned items should expire, and the number of items to be popped off.
11.1985
3.409158
3.284829
'''Similar to the pop command, except that it merely peeks at the next items''' results = [Job(self.client, **rec) for rec in json.loads( self.client('peek', self.name, count or 1))] if count is None: return (len(results) and results[0]) or None return res...
def peek(self, count=None)
Similar to the pop command, except that it merely peeks at the next items
8.650903
5.680457
1.522924
'''Return the current statistics for a given queue on a given date. The results are returned are a JSON blob:: { 'total' : ..., 'mean' : ..., 'variance' : ..., 'histogram': [ ... ] ...
def stats(self, date=None)
Return the current statistics for a given queue on a given date. The results are returned are a JSON blob:: { 'total' : ..., 'mean' : ..., 'variance' : ..., 'histogram': [ ... ] } ...
8.864495
1.691598
5.240309
with open(step.source_path, 'r') as f: code = f.read() try: cauldron.display.markdown(code, **project.shared.fetch(None)) return {'success': True} except Exception as err: return dict( success=False, html_message=templating.render_template( ...
def run( project: 'projects.Project', step: 'projects.ProjectStep' ) -> dict
Runs the markdown file and renders the contents to the notebook display :param project: :param step: :return: A run response dictionary containing
6.02914
5.418957
1.112602
if len(list(COMMANDS.keys())) > 0 and not reload: return COMMANDS COMMANDS.clear() for key in dir(commands): e = getattr(commands, key) if e and hasattr(e, 'NAME') and hasattr(e, 'DESCRIPTION'): COMMANDS[e.NAME] = e return dict(COMMANDS.items())
def fetch(reload: bool = False) -> dict
Returns a dictionary containing all of the available Cauldron commands currently registered. This data is cached for performance. Unless the reload argument is set to True, the command list will only be generated the first time this function is called. :param reload: Whether or not to disregard...
3.758917
3.648559
1.030247
use_remote = ( remote_connection.active and hasattr(command_module, 'execute_remote') ) return ( command_module.execute_remote if use_remote else command_module.execute )
def get_command_from_module( command_module, remote_connection: environ.RemoteConnection )
Returns the execution command to use for the specified module, which may be different depending upon remote connection :param command_module: :param remote_connection: :return:
4.559847
4.081838
1.117106
response = Response() cmds = fetch() if command_name and command_name in cmds: parser, result = parse.get_parser( cmds[command_name], parse.explode_line(raw_args), dict() ) if parser is not None: out = parser.format_help() ...
def show_help(command_name: str = None, raw_args: str = '') -> Response
Prints the basic command help to the console
7.900677
7.807332
1.011956
'''1) Get a reference to the module 2) Check the file that module's imported from 3) If that file's been updated, force a reload of that module return it''' mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]: mod = g...
def _import(klass)
1) Get a reference to the module 2) Check the file that module's imported from 3) If that file's been updated, force a reload of that module return it
5.220637
3.286928
1.588303
'''Load the module containing your class, and run the appropriate method. For example, if this job was popped from the queue ``testing``, then this would invoke the ``testing`` staticmethod of your class.''' try: method = getattr(self.klass, self.queue_name, ...
def process(self)
Load the module containing your class, and run the appropriate method. For example, if this job was popped from the queue ``testing``, then this would invoke the ``testing`` staticmethod of your class.
3.096568
2.367523
1.307936
'''Move this job out of its existing state and into another queue. If a worker has been given this job, then that worker's attempts to heartbeat that job will fail. Like ``Queue.put``, this accepts a delay, and dependencies''' logger.info('Moving %s to %s from %s', se...
def move(self, queue, delay=0, depends=None)
Move this job out of its existing state and into another queue. If a worker has been given this job, then that worker's attempts to heartbeat that job will fail. Like ``Queue.put``, this accepts a delay, and dependencies
9.955073
3.43499
2.898138
'''Turn this job in as complete, optionally advancing it to another queue. Like ``Queue.put`` and ``move``, it accepts a delay, and dependencies''' if nextq: logger.info('Advancing %s to %s from %s', self.jid, nextq, self.queue_name) return self.cl...
def complete(self, nextq=None, delay=None, depends=None)
Turn this job in as complete, optionally advancing it to another queue. Like ``Queue.put`` and ``move``, it accepts a delay, and dependencies
4.661241
2.76625
1.68504
'''Renew the heartbeat, if possible, and optionally update the job's user data.''' logger.debug('Heartbeating %s (ttl = %s)', self.jid, self.ttl) try: self.expires_at = float(self.client('heartbeat', self.jid, self.client.worker_name, json.dumps(self.data)) or 0) ...
def heartbeat(self)
Renew the heartbeat, if possible, and optionally update the job's user data.
7.04901
4.775193
1.476173
'''Mark the particular job as failed, with the provided type, and a more specific message. By `type`, we mean some phrase that might be one of several categorical modes of failure. The `message` is something more job-specific, like perhaps a traceback. This method should __not__...
def fail(self, group, message)
Mark the particular job as failed, with the provided type, and a more specific message. By `type`, we mean some phrase that might be one of several categorical modes of failure. The `message` is something more job-specific, like perhaps a traceback. This method should __not__ be used to...
12.498707
1.664746
7.507874