text
stringlengths
18
773k
def add_shell_action(sub_parser: ArgumentParser) -> ArgumentParser: """Populates the sub parser with the shell arguments""" sub_parser.add_argument( '-p', '--project', dest='project_directory', type=str, default=None ) sub_parser.add_argument( '-l', '--log', ...
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. """ parser = ArgumentParser(descri...
def running(self, offset=0, count=25): '''Return all the currently-running jobs''' return self.client('jobs', 'running', self.name, offset, count)
def stalled(self, offset=0, count=25): '''Return all the currently-stalled jobs''' return self.client('jobs', 'stalled', self.name, offset, count)
def scheduled(self, offset=0, count=25): '''Return all the currently-scheduled jobs''' return self.client('jobs', 'scheduled', self.name, offset, count)
def depends(self, offset=0, count=25): '''Return all the currently dependent jobs''' return self.client('jobs', 'depends', self.name, offset, count)
def recurring(self, offset=0, count=25): '''Return all the recurring jobs''' return self.client('jobs', 'recurring', self.name, offset, count)
def class_string(self, klass): '''Return a string representative of the class''' if isinstance(klass, string_types): return klass return klass.__module__ + '.' + klass.__name__
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 w...
def recur(self, klass, data, interval, offset=0, priority=None, tags=None, retries=None, jid=None): '''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), ...
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.''' results = [Job(self.client, **job) for job in json.loads( self.client('pop', self...
def peek(self, count=None): '''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]...
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': [ ...
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 """ with open(step.source_path, 'r') ...
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. ...
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: ""...
def show_help(command_name: str = None, raw_args: str = '') -> Response: """ Prints the basic command help to the console """ response = Response() cmds = fetch() if command_name and command_name in cmds: parser, result = parse.get_parser( cmds[command_name], parse.expl...
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''' mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]:...
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.''' try: method = getattr(self.klass, self.qu...
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''' logger....
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''' if nextq: logger.info('Advancing %s to %s from %s', se...
def heartbeat(self): '''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.dum...
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. ...
def retry(self, delay=0, group=None, message=None): '''Retry this job in a little bit, in the same queue. This is meant for the times when you detect a transient failure yourself''' args = ['retry', self.jid, self.queue_name, self.worker_name, delay] if group is not None and message is n...
def undepend(self, *args, **kwargs): '''Remove specific (or all) job dependencies from this job: job.remove(jid1, jid2) job.remove(all=True)''' if kwargs.get('all', False): return self.client('depends', self.jid, 'off', 'all') or False else: retur...
def has_extension(file_path: str, *args: typing.Tuple[str]) -> bool: """ Checks to see if the given file path ends with any of the specified file extensions. If a file extension does not begin with a '.' it will be added automatically :param file_path: The path on which the extensions will ...
def get_docstring(target) -> str: """ Retrieves the documentation string from the target object and returns it after removing insignificant whitespace :param target: The object for which the doc string should be retrieved :return: The cleaned documentation string for the target. If ...
def get_doc_entries(target: typing.Callable) -> list: """ Gets the lines of documentation from the given target, which are formatted so that each line is a documentation entry. :param target: :return: A list of strings containing the documentation block entries """ raw = get_docstr...
def parse_function( name: str, target: typing.Callable ) -> typing.Union[None, dict]: """ Parses the documentation for a function, which is specified by the name of the function and the function itself. :param name: Name of the function to parse :param target: The fu...
def variable(name: str, target: property) -> typing.Union[None, dict]: """ :param name: :param target: :return: """ if hasattr(target, 'fget'): doc = parse_function(name, target.fget) if doc: doc['read_only'] = bool(target.fset is None) return doc re...
def read_all(self) -> str: """ Reads the current state of the buffer and returns a string those contents :return: A string for the current state of the print buffer contents """ try: buffered_bytes = self.bytes_buffer.getvalue() if buf...
def flush_all(self) -> str: """ :return: """ # self.bytes_buffer.seek(0) # contents = self.bytes_buffer.read() # self.bytes_buffer.truncate(0) # self.bytes_buffer.seek(0) # if contents is None: # return '' contents = self.by...
def create_data(step: 'projects.ProjectStep') -> STEP_DATA: """ Creates the data object that stores the step information in the notebook results JavaScript file. :param step: Project step for which to create the data :return: Step data tuple containing scaffold data structure for th...
def get_cached_data( step: 'projects.ProjectStep' ) -> typing.Union[None, STEP_DATA]: """ Attempts to load and return the cached step data for the specified step. If not cached data exists, or the cached data is corrupt, a None value is returned instead. :param step: The step for wh...
def initialize_logging_path(path: str = None) -> str: """ Initializes the logging path for running the project. If no logging path is specified, the current directory will be used instead. :param path: Path to initialize for logging. Can be either a path to a file or a path to a directo...
def run_project( project_directory: str, output_directory: str = None, log_path: str = None, shared_data: dict = None, reader_path: str = None, reload_project_libraries: bool = False ) -> ExecutionResult: """ Opens, executes and closes a Cauldron project in a sing...
def stop(self, sig=signal.SIGINT): '''Stop all the workers, and then wait for them''' for cpid in self.sandboxes: logger.warn('Stopping %i...' % cpid) try: os.kill(cpid, sig) except OSError: # pragma: no cover logger.exception('Error s...
def spawn(self, **kwargs): '''Return a new worker for a child process''' copy = dict(self.kwargs) copy.update(kwargs) # Apparently there's an issue with importing gevent in the parent # process and then using it int he child. This is meant to relieve that # problem by all...
def run(self): '''Run this worker''' self.signals(('TERM', 'INT', 'QUIT')) # Divide up the jobs that we have to divy up between the workers. This # produces evenly-sized groups of jobs resume = self.divide(self.resume, self.count) for index in range(self.count): ...
def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT): self.stop(signum) os._exit(0)
def get_stack_frames(error_stack: bool = True) -> list: """ Returns a list of the current stack frames, which are pruned focus on the Cauldron code where the relevant information resides. """ cauldron_path = environ.paths.package() resources_path = environ.paths.resources() frames = ( ...
def format_stack_frame(stack_frame, project: 'projects.Project') -> dict: """ Formats a raw stack frame into a dictionary formatted for render templating and enriched with information from the currently open project. :param stack_frame: A raw stack frame to turn into an enriched version for te...
def get_formatted_stack_frame( project: 'projects.Project', error_stack: bool = True ) -> list: """ Returns a list of the stack frames formatted for user display that has been enriched by the project-specific data. :param project: The currently open project used to enrich t...
def arg_type_to_string(arg_type) -> str: """ Converts the argument type to a string :param arg_type: :return: String representation of the argument type. Multiple return types are turned into a comma delimited list of type names """ union_params = ( getattr(arg_type, '_...
def merge_components( *components: typing.List[typing.Union[list, tuple, COMPONENT]] ) -> COMPONENT: """ Merges multiple COMPONENT instances into a single one by merging the lists of includes and files. Has support for elements of the components arguments list to be lists or tuples of COMPONENT ...
def flatten_reducer( flattened_list: list, entry: typing.Union[list, tuple, COMPONENT] ) -> list: """ Flattens a list of COMPONENT instances to remove any lists or tuples of COMPONENTS contained within the list :param flattened_list: The existing flattened list that has been pop...
def combine_lists_reducer( key: str, merged_list: list, component: COMPONENT ) -> list: """ Reducer function to combine the lists for the specified key into a single, flat list :param key: The key on the COMPONENT instances to operate upon :param merged_list: ...
def listen(self): '''Listen for events as they come in''' try: self._pubsub.subscribe(self._channels) for message in self._pubsub.listen(): if message['type'] == 'message': yield message finally: self._channels = []
def thread(self): '''Run in a thread''' thread = threading.Thread(target=self.listen) thread.start() try: yield self finally: self.unlisten() thread.join()
def listen(self): '''Listen for events''' for message in Listener.listen(self): logger.debug('Message: %s', message) # Strip off the 'namespace' from the channel channel = message['channel'][len(self.namespace):] func = self._callbacks.get(channel) ...
def on(self, evt, func): '''Set a callback handler for a pubsub event''' if evt not in self._callbacks: raise NotImplementedError('callback "%s"' % evt) else: self._callbacks[evt] = func
def get(self, option, default=None): '''Get a particular option, or the default if it's missing''' val = self[option] return (val is None and default) or val
def pop(self, option, default=None): '''Just like `dict.pop`''' val = self[option] del self[option] return (val is None and default) or val
def update(self, other=(), **kwargs): '''Just like `dict.update`''' _kwargs = dict(kwargs) _kwargs.update(other) for key, value in _kwargs.items(): self[key] = value
def touch_project(): """ Touches the project to trigger refreshing its cauldron.json state. """ r = Response() project = cd.project.get_internal_project() if project: project.refresh() else: r.fail( code='NO_PROJECT', message='No open project to refre...
def fetch_synchronize_status(): """ Returns the synchronization status information for the currently opened project """ r = Response() project = cd.project.get_internal_project() if not project: r.fail( code='NO_PROJECT', message='No open project on which to ...
def download_file(filename: str): """ downloads the specified project file if it exists """ project = cd.project.get_internal_project() source_directory = project.source_directory if project else None if not filename or not project or not source_directory: return '', 204 path = os.path.re...
def get_project_source_path(path: str) -> str: """ Converts the given path into a project source path, to the cauldron.json file. If the path already points to a cauldron.json file, the path is returned without modification. :param path: The path to convert into a project source path ""...
def load_project_definition(path: str) -> dict: """ Load the cauldron.json project definition file for the given path. The path can be either a source path to the cauldron.json file or the source directory where a cauldron.json file resides. :param path: The source path or directory where t...
def simplify_path(path: str, path_prefixes: list = None) -> str: """ Simplifies package paths by replacing path prefixes with values specified in the replacements list :param path: :param path_prefixes: :return: """ test_path = '{}'.format(path if path else '') replacements = (path...
def module_to_package_data( name: str, entry, path_prefixes: list = None ) -> typing.Union[dict, None]: """ Converts a module entry into a package data dictionary with information about the module. including version and location on disk :param name: :param entry: :param ...
def get_system_data() -> typing.Union[None, dict]: """ Returns information about the system in which Cauldron is running. If the information cannot be found, None is returned instead. :return: Dictionary containing information about the Cauldron system, whic includes: * name ...
def remove(path: str, max_retries: int = 3) -> bool: """ Removes the specified path from the local filesystem if it exists. Directories will be removed along with all files and folders within them as well as files. :param path: The location of the file or folder to remove. :param max_re...
def end(code: int): """ Ends the application with the specified error code, adding whitespace to the end of the console log output for clarity :param code: The integer status code to apply on exit. If the value is non-zero, indicating an error, a message will be printed to the console t...
def folder(self) -> typing.Union[str, None]: """ The folder, relative to the project source_directory, where the file resides :return: """ if 'folder' in self.data: return self.data.get('folder') elif self.project_folder: if callable(self...
def project_exists(response: 'environ.Response', path: str) -> bool: """ Determines whether or not a project exists at the specified path :param response: :param path: :return: """ if os.path.exists(path): return True response.fail( code='PROJECT_NOT_FOUND', me...
def update_recent_paths(response, path): """ :param response: :param path: :return: """ try: recent_paths = environ.configs.fetch('recent_paths', []) if path in recent_paths: recent_paths.remove(path) recent_paths.insert(0, path) environ.configs.put...
def split_line(line: str) -> typing.Tuple[str, str]: """ Separates the raw line string into two strings: (1) the command and (2) the argument(s) string :param line: :return: """ index = line.find(' ') if index == -1: return line.lower(), '' return line[:index].lower(), lin...
def render_stop_display(step: 'projects.ProjectStep', message: str): """Renders a stop action to the Cauldron display.""" stack = render_stack.get_formatted_stack_frame( project=step.project, error_stack=False ) try: names = [frame['filename'] for frame in stack] index =...
def id(self) -> typing.Union[str, None]: """Identifier for the project.""" return self._project.id if self._project else None
def display(self) -> typing.Union[None, report.Report]: """The display report for the current project.""" return ( self._project.current_step.report if self._project and self._project.current_step else None )
def shared(self) -> typing.Union[None, SharedCache]: """The shared display object associated with this project.""" return self._project.shared if self._project else None
def settings(self) -> typing.Union[None, SharedCache]: """The settings associated with this project.""" return self._project.settings if self._project else None
def title(self) -> typing.Union[None, str]: """The title of this project.""" return self._project.title if self._project else None
def title(self, value: typing.Union[None, str]): """ Modifies the title of the project, which is initially loaded from the `cauldron.json` file. """ if not self._project: raise RuntimeError('Failed to assign title to an unloaded project') self._project.title =...
def load(self, project: typing.Union[projects.Project, None]): """Connects this object to the specified source project.""" self._project = project
def path(self, *args: typing.List[str]) -> typing.Union[None, str]: """ Creates an absolute path in the project source directory from the relative path components. :param args: Relative components for creating a path within the project source directory :r...
def stop(self, message: str = None, silent: bool = False): """ Stops the execution of the project at the current step immediately without raising an error. Use this to abort running the project in situations where some critical branching action should prevent the project from con...
def get_internal_project( self, timeout: float = 1 ) -> typing.Union['projects.Project', None]: """ Attempts to return the internally loaded project. This function prevents race condition issues where projects are loaded via threads because the internal loop w...
def _step(self) -> typing.Union[None, 'projects.ProjectStep']: """ Internal access to the source step. Should not be used outside of Cauldron development. :return: The ProjectStep instance that this ExposedStep represents """ import cauldron try: ...
def stop( self, message: str = None, silent: bool = False, halt: bool = False ): """ Stops the execution of the current step immediately without raising an error. Use this to abort the step running process if you want to return early. ...
def write_to_console(self, message: str): """ Writes the specified message to the console stdout without including it in the notebook display. """ if not self._step: raise ValueError( 'Cannot write to the console stdout on an uninitialized step' ...
def render_to_console(self, message: str, **kwargs): """ Renders the specified message to the console using Jinja2 template rendering with the kwargs as render variables. The message will also be dedented prior to rendering in the same fashion as other Cauldron template rendering...
def get_operations(): """ This will break things if you upgrade Django to 1.8 having already applied this migration in 1.7. Since this is for a demo site it doesn't really matter (simply blow away the DB if you want to go to 1.8) Our demo site is a unusual in that we want to run it's tests (for integra...
def create(project: 'projects.Project') -> COMPONENT: """ :return: """ try: from bokeh.resources import Resources as BokehResources bokeh_resources = BokehResources(mode='absolute') except Exception: bokeh_resources = None if bokeh_resources is None: environ.log...
def last_update_time(self) -> float: """The last time at which the report was modified.""" stdout = self.stdout_interceptor stderr = self.stderr_interceptor return max([ self._last_update_time, stdout.last_write_time if stdout else 0, stderr.last_writ...
def results_cache_path(self) -> str: """ Location where step report is cached between sessions to prevent loss of display data between runs. """ if not self.project: return '' return os.path.join( self.project.results_path, '.cache', ...
def clear(self) -> 'Report': """ Clear all user-data stored in this instance and reset it to its originally loaded state :return: The instance that was called for method chaining """ self.body = [] self.data = SharedCache() self.files = Shared...
def append_body(self, dom: str): """ Appends the specified HTML-formatted DOM string to the currently stored report body for the step. """ self.flush_stdout() self.body.append(dom) self._last_update_time = time.time()
def read_stdout(self): """ Reads the current state of the print buffer (if it exists) and returns a body-ready dom object of those contents without adding them to the actual report body. This is useful for creating intermediate body values for display while the method is still ex...
def flush_stdout(self): """ Empties the standard out redirect buffer and renders the contents to the body as a preformatted text box. """ try: contents = self.stdout_interceptor.flush_all() except Exception: return if len(contents) > 0: ...
def import_class(klass): '''Import the named class and return that class''' mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]: mod = getattr(mod, segment) return getattr(mod, klass.rpartition('.')[2])
def create( project: 'projects.Project', include_path: str ) -> COMPONENT: """ Creates a COMPONENT instance for the project component specified by the include path :param project: The project in which the component resides :param include_path: The relative path withi...
def create_many( project: 'projects.Project', include_paths: typing.List[str] ) -> COMPONENT: """ Creates a single COMPONENT instance for all of the specified project include paths :param project: Project where the components reside :param include_paths: A list of re...
def to_web_include( project: 'projects.Project', file_path: str ) -> WEB_INCLUDE: """ Converts the given file_path into a WEB_INCLUDE instance that represents the deployed version of this file to be loaded into the results project page :param project: Project in which the fi...
def attempt_file_write( path: str, contents: typing.Union[str, bytes], mode: str = 'w', offset: int = 0 ) -> typing.Union[None, Exception]: """ Attempts to write the specified contents to a file and returns None if successful, or the raised exception if writing failed. ...
def write_file( path: str, contents, mode: str = 'w', retry_count: int = 3, offset: int = 0 ) -> typing.Tuple[bool, typing.Union[None, Exception]]: """ Writes the specified contents to a file, with retry attempts if the write operation fails. This is useful to prevent...
def attempt_json_write( path: str, contents: dict, mode: str = 'w' ) -> typing.Union[None, Exception]: """ Attempts to write the specified JSON content to file. :param path: The path to the file where the JSON serialized content will be written. :param contents: ...
def write_json_file( path: str, contents: dict, mode: str = 'w', retry_count: int = 3 ) -> typing.Tuple[bool, typing.Union[None, Exception]]: """ Writes the specified dictionary to a file as a JSON-serialized string, with retry attempts if the write operation fails. This is ...
def reformat(source: str) -> str: """ Formats the source string to strip newlines on both ends and dedents the the entire string :param source: The string to reformat """ value = source if source else '' return dedent(value.strip('\n')).strip()