text
stringlengths
18
773k
def run( project: 'projects.Project', step: 'projects.ProjectStep', ) -> dict: """ Carries out the execution of the step python source file by loading it into an artificially created module and then executing that module and returning the result. :param project: The currentl...
def render_syntax_error( project: 'projects.Project', error: SyntaxError ) -> dict: """ Renders a SyntaxError, which has a shallow, custom stack trace derived from the data included in the error, instead of the standard stack trace pulled from the exception frames. :param project: ...
def render_error( project: 'projects.Project', error: Exception, stack: typing.List[dict] = None ) -> dict: """ Renders an Exception to an error response that includes rendered text and html error messages for display. :param project: Currently open project. :param e...
def execute(asynchronous: bool = False): """ :param asynchronous: Whether or not to allow asynchronous command execution that returns before the command is complete with a run_uid that can be used to track the continued execution of the command until completion. """ r = Response(...
def abort(): """...""" uid_list = list(server_runner.active_execution_responses.keys()) while len(uid_list) > 0: uid = uid_list.pop() response = server_runner.active_execution_responses.get(uid) if not response: continue try: del server_runner.activ...
def remove_key(key: str, persists: bool = True): """ Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param persists: """ environ.configs.remove(key, include_persists=persists) environ.configs.save()...
def set_key(key: str, value: typing.List[str], persists: bool = True): """ Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param value: :param persists: """ if key.endswith('_path') or key.endswith(...
def save(self) -> 'Configuration': """ Saves the configuration settings object to the current user's home directory :return: """ data = self.load().persistent if data is None: return self directory = os.path.dirname(self._source_path) ...
def _get_userinfo(self): """ Get a dictionary that pulls together information about the poster safely for both authenticated and non-authenticated comments. This dict will have ``name``, ``email``, and ``url`` fields. """ if not hasattr(self, "_userinfo"): us...
def get_as_text(self): """ Return this comment as plain text. Useful for emails. """ d = { 'user': self.user or self.name, 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_...
def entry_from_dict( data: dict ) -> typing.Union[FILE_WRITE_ENTRY, FILE_COPY_ENTRY]: """ Converts the given data dictionary into either a file write or file copy entry depending on the keys in the dictionary. The dictionary should contain either ('path', 'contents') keys for file write entries ...
def deploy(files_list: typing.List[tuple]): """ Iterates through the specified files_list and copies or writes each entry depending on whether its a file copy entry or a file write entry. :param files_list: A list of file write entries and file copy entries """ def deploy_entry(entry): ...
def make_output_directory(output_path: str) -> str: """ Creates the parent directory or directories for the specified output path if they do not already exist to prevent incomplete directory path errors during copying/writing operations. :param output_path: The path of the destination file ...
def copy(copy_entry: FILE_COPY_ENTRY): """ Copies the specified file from its source location to its destination location. """ source_path = environ.paths.clean(copy_entry.source) output_path = environ.paths.clean(copy_entry.destination) copier = shutil.copy2 if os.path.isfile(source_path) e...
def write(write_entry: FILE_WRITE_ENTRY): """ Writes the contents of the specified file entry to its destination path. """ output_path = environ.paths.clean(write_entry.path) make_output_directory(output_path) writer.write_file(output_path, write_entry.contents)
def enable(step: 'projects.ProjectStep'): """ Create a print equivalent function that also writes the output to the project page. The write_through is enabled so that the TextIOWrapper immediately writes all of its input data directly to the underlying BytesIO buffer. This is needed so that we can s...
def restore_default_configuration(): """ Restores the sys.stdout and the sys.stderr buffer streams to their default values without regard to what step has currently overridden their values. This is useful during cleanup outside of the running execution block """ def restore(target, default_valu...
def create( project: 'projects.Project', destination_directory, destination_filename: str = None ) -> file_io.FILE_WRITE_ENTRY: """ Creates a FILE_WRITE_ENTRY for the rendered HTML file for the given project that will be saved in the destination directory with the given filename....
def run_container(): """Runs an interactive container""" os.chdir(my_directory) cmd = [ 'docker', 'run', '-it', '--rm', '-v', '{}:/cauldron'.format(my_directory), '-p', '5010:5010', 'cauldron_app', '/bin/bash' ] return os.system(' '.join(cmd))
def run(): """Execute the Cauldron container command""" command = sys.argv[1].strip().lower() print('[COMMAND]:', command) if command == 'test': return run_test() elif command == 'build': return run_build() elif command == 'up': return run_container() elif command =...
def gatekeeper(func): """ This function is used to handle authorization code authentication of protected endpoints. This form of authentication is not recommended because it's not very secure, but can be used in places where SSH tunneling or similar strong connection security is not possible. ...
def inspect(source: dict): """ Inspects the data and structure of the source dictionary object and adds the results to the display for viewing. :param source: A dictionary object to be inspected. :return: """ r = _get_report() r.append_body(render.inspect(source))
def header(header_text: str, level: int = 1, expand_full: bool = False): """ Adds a text header to the display with the specified level. :param header_text: The text to display in the header. :param level: The level of the header, which corresponds to the html header levels, suc...
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: ...
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...
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 ...
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 ...
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 s...
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: ...
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 t...
def whitespace(lines: float = 1.0): """ Adds the specified number of lines of whitespace. :param lines: The number of lines of whitespace to show. """ r = _get_report() r.append_body(render.whitespace(lines)) r.stdout_interceptor.write_source('\n')
def 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 asset...
def html(dom: str): """ A string containing a valid HTML snippet. :param dom: The HTML string to add to the display. """ r = _get_report() r.append_body(render.html(dom)) r.stdout_interceptor.write_source('[ADDED] HTML\n')
def 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 tr...
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 fig...
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 num...
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. ...
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 itera...
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: ...
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 ...
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 ...
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 ar...
def elapsed(): """ Displays the elapsed time since the step started running. """ environ.abort_thread() step = _cd.project.get_internal_project().current_step r = _get_report() r.append_body(render.elapsed_time(step.elapsed_time)) result = '[ELAPSED]: {}\n'.format(timedelta(seconds=step...
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 na...
def get_module_name(module: types.ModuleType) -> str: """ Returns the name of the specified module by looking up its name in multiple ways to prevent incompatibility issues. :param module: A module object for which to retrieve the name. """ try: return module.__spec__.name e...
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...
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 newe...
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: ...
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...
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...
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 ...
def get_arg_names(target) -> typing.List[str]: """ Gets the list of named arguments for the target function :param target: Function for which the argument names will be retrieved """ code = getattr(target, '__code__') if code is None: return [] arg_count = code.co_argcoun...
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 descripti...
def explode_line(argument_line: str) -> typing.Tuple[str, str]: """ Returns a tuple containing the parameter name and the description parsed from the given argument line """ parts = tuple(argument_line.split(' ', 1)[-1].split(':', 1)) return parts if len(parts) > 1 else (parts[0], '')
def update_base_image(path: str): """Pulls the latest version of the base image""" with open(path, 'r') as file_handle: contents = file_handle.read() regex = re.compile('from\s+(?P<source>[^\s]+)', re.IGNORECASE) matches = regex.findall(contents) if not matches: return None ma...
def build(path: str) -> dict: """Builds the container from the specified docker file path""" update_base_image(path) match = file_pattern.search(os.path.basename(path)) build_id = match.group('id') tags = [ '{}:{}-{}'.format(HUB_PREFIX, version, build_id), '{}:latest-{}'.format(HUB_P...
def publish(build_entry: dict): """Publishes the specified build entry to docker hub""" for tag in build_entry['tags']: print('[PUSHING]:', tag) os.system('docker push {}'.format(tag))
def parse() -> dict: """Parse command line arguments""" parser = ArgumentParser() parser.add_argument('-p', '--publish', action='store_true', default=False) return vars(parser.parse_args())
def run(): """Execute the build process""" args = parse() build_results = [build(p) for p in glob.iglob(glob_path)] if not args['publish']: return for entry in build_results: publish(entry)
def elapsed_time(seconds: float) -> str: """Displays the elapsed time since the current step started running.""" environ.abort_thread() parts = ( '{}'.format(timedelta(seconds=seconds)) .rsplit('.', 1) ) hours, minutes, seconds = parts[0].split(':') return templating.render_templ...
def image( rendered_path: str, width: int = None, height: int = None, justify: str = None ) -> str: """Renders an image block""" environ.abort_thread() return templating.render_template( 'image.html', path=rendered_path, width=width, height=hei...
def get_environment_info() -> dict: """ Information about Cauldron and its Python interpreter. :return: A dictionary containing information about the Cauldron and its Python environment. This information is useful when providing feedback and bug reports. """ data = _environ....
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 ...
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 Pyth...
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 continu...
def deserialize(serial_data: dict) -> 'Response': """ Converts a serialized dictionary response to a Response object """ 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('succe...
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. """ thread = ...
def is_running(self) -> bool: """Specifies whether or not the thread is running""" 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 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. """ async def run_command(): try: self.result = sel...
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. ...
def from_request(request=None) -> dict: """ Fetches the arguments for the current Flask application request """ 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 ...
def print_rule(rule, feature_names=None, category_names=None, label="label", support=None): # type: (Rule, List[Union[str, None]], List[Union[List[str], None]], str, List[int]) -> str """ print the rule in a nice way :param rule: An instance of Rule :param feature_names: a list of n_features feature...
def rule_str2rule(rule_str, prob): # type: (str, float) -> Rule """ 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 """ if rule_str...
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. """ satisfied = [] if self.is_default(): retu...
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: """ verbose = self.verbose # Create temporary files data_file = tempfile.Name...
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: """ self._rule_pool = [([], [])] + raw_rules self._rule_list = []...
def compute_support(self, x, y): # type: (np.ndarray, np.ndarray) -> np.ndarray """ 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 ...
def caught_matrix(self, x): # type: (np.ndarray) -> np.ndarray """ 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 i...
def decision_path(self, x): # type: (np.ndarray) -> np.ndarray """ 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 ...
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: ...
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 th...
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 variab...
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 fil...
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 """ tree = list(self.parser.raw_parse(line))[0] tree = ...
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 ...
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. """ if not chunk_data: return b'' ...
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_s...
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 ...
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 ar...
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 ...
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...
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: """ ...
def add_to_message(data, indent_level=0) -> list: """Adds data to the message object""" message = [] if isinstance(data, str): message.append(indent( dedent(data.strip('\n')).strip(), indent_level * ' ' )) return message for line in data: offset...
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. """ if not has(mode_id): _current_modes.append(mode_id) return _current_modes.copy()
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. """ had_mode = has(mode_id) if had_mode:...
def clone(client): '''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 pretty(timings, label): '''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')) p...
def start(self): '''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 stop(self): '''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...
def display(self): '''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()