text
stringlengths
18
773k
def get_environment() -> Environment: """ Returns the jinja2 templating environment updated with the most recent cauldron environment configurations :return: """ env = JINJA_ENVIRONMENT loader = env.loader resource_path = environ.configs.make_path( 'resources', 'templates', ...
def render(template: typing.Union[str, Template], **kwargs): """ Renders a template string using Jinja2 and the Cauldron templating environment. :param template: The string containing the template to be rendered :param kwargs: Any named arguments to pass to Jinja2 for use in renderi...
def render_file(path: str, **kwargs): """ Renders a file at the specified absolute path. The file can reside anywhere on the local disk as Cauldron's template environment path searching is ignored. :param path: Absolute path to a template file to render :param kwargs: Named argu...
def render_template(template_name: str, **kwargs): """ Renders the template file with the given filename from within Cauldron's template environment folder. :param template_name: The filename of the template to render. Any path elements should be relative to Cauldron's root template fol...
def clean(path: str) -> str: """ Cleans the specified path by expanding shorthand elements, redirecting to the real path for symbolic links, and removing any relative components to return a complete, absolute path to the specified location. :param path: The source path to be cleaned """...
def package(*args: str) -> str: """ Creates an absolute path to a file or folder within the cauldron package using the relative path elements specified by the args. :param args: Zero or more relative path elements that describe a file or folder within the reporting """ return c...
def confirm(question: str, default: bool = True) -> bool: """ Requests confirmation of the specified question and returns that result :param question: The question to print to the console for the confirmation :param default: The default value if the user hits enter without entering a va...
def fetch_last(response: Response) -> typing.Union[str, None]: """ Returns the last opened project path if such a path exists """ recent_paths = environ.configs.fetch('recent_paths', []) if len(recent_paths) < 1: response.fail( code='NO_RECENT_PROJECTS', message='No project...
def before_save(file_or_dir): """ make sure that the dedicated path exists (create if not exist) :param file_or_dir: :return: None """ dir_name = os.path.dirname(os.path.abspath(file_or_dir)) if not os.path.exists(dir_name): os.makedirs(dir_name)
def categorical2pysbrl_data( x, y, data_filename, label_filename, method='eclat', supp=0.05, zmin=1, zmax=3): """ Run a frequent item mining algorithm to extract candidate rules. :param x: 2D np.ndarray, categorical data of shape [n_instances, ...
def categorical2transactions(x): # type: (np.ndarray) -> List """ Convert a 2D int array into a transaction list: [ ['x0=1', 'x1=0', ...], ... ] :param x: :return: """ assert len(x.shape) == 2 transactions = [] for entry in x: transact...
def rule_satisfied(x, features, categories): """ return a logical array representing whether entries in x satisfied the rules denoted by features and categories :param x: a categorical 2D array :param features: a list of feature indices :param categories: a list of categories :return: """ ...
def of_project(project: 'projects.Project') -> dict: """ Returns the file status information for every file within the project source directory and its shared library folders. :param project: The project for which the status information should be generated :return: A dictionary cont...
def of_file(path: str, root_directory: str = None) -> dict: """ Returns a dictionary containing status information for the specified file including when its name relative to the root directory, when it was last modified and its size. :param path: The absolute path to the file for which the ...
def of_directory(directory: str, root_directory: str = None) -> dict: """ Returns a dictionary containing status entries recursively for all files within the specified directory and its descendant directories. :param directory: The directory in which to retrieve status information :param ro...
def run_local( context: cli.CommandContext, project: projects.Project, project_steps: typing.List[projects.ProjectStep], force: bool, continue_after: bool, single_step: bool, limit: int, print_status: bool, skip_library_reload: bool = False ) -> en...
def loadalldatas(): """Loads all demo fixtures.""" dependency_order = ['common', 'profiles', 'blog', 'democomments'] for app in dependency_order: project.recursive_load(os.path.join(paths.project_paths.manage_root, app))
def project_status(): """...""" r = Response() try: project = cauldron.project.get_internal_project() if project: r.update(project=project.status()) else: r.update(project=None) except Exception as err: r.fail( code='PROJECT_STATUS_ERR...
def clean_step(step_name: str): """...""" r = Response() project = cauldron.project.get_internal_project() if not project: return flask.jsonify(r.fail( code='PROJECT_FETCH_ERROR', message='No project is currently open' ).response.serialize()) step = project....
def _insert_timestamp(self, slug, max_length=255): """Appends a timestamp integer to the given slug, yet ensuring the result is less than the specified max_length. """ timestamp = str(int(time.time())) ts_len = len(timestamp) + 1 while len(slug) + ts_len > max_length: ...
def _slugify_title(self): """Slugify the Entry title, but ensure it's less than the maximum number of characters. This method also ensures that a slug is unique by appending a timestamp to any duplicate slugs. """ # Restrict slugs to their maximum number of chars, but don't split...
def run(self): '''Run jobs, popping one after another''' # Register our signal handlers self.signals() with self.listener(): for job in self.jobs(): # If there was no job to be had, we should sleep a little bit if not job: ...
def initialize(): """ Initializes the cauldron library by confirming that it can be imported by the importlib library. If the attempt to import it fails, the system path will be modified and the attempt retried. If both attempts fail, an import error will be raised. """ cauldron_module = ge...
def run(arguments: typing.List[str] = None): """Executes the cauldron command""" initialize() from cauldron.invoke import parser from cauldron.invoke import invoker args = parser.parse(arguments) exit_code = invoker.run(args.get('command'), args) sys.exit(exit_code)
def author_display(author, *args): """Returns either the linked or not-linked profile name.""" # Call get_absolute_url or a function returning none if not defined url = getattr(author, 'get_absolute_url', lambda: None)() # get_short_name or unicode representation short_name = getattr(author, 'get_s...
def echo_steps(response: Response, project: Project): """ :param response: :param project: :return: """ if len(project.steps) < 1: response.update( steps=[] ).notify( kind='SUCCESS', code='ECHO_STEPS', message='No steps in project'...
def explode_filename(name: str, scheme: str) -> dict: """ Removes any path components from the input filename and returns a dictionary containing the name of the file without extension and the extension (if an extension exists) :param name: :param scheme: :return: """ if not scheme...
def create(project: 'projects.Project') -> COMPONENT: """ :param project: :return: """ source_path = get_source_path() if not source_path: return COMPONENT([], []) output_slug = 'components/plotly/plotly.min.js' output_path = os.path.join(project.output_directory, output_slug) ...
def in_project_directory() -> bool: """ Returns whether or not the current working directory is a Cauldron project directory, which contains a cauldron.json file. """ current_directory = os.path.realpath(os.curdir) project_path = os.path.join(current_directory, 'cauldron.json') return os.pat...
def load_shared_data(path: typing.Union[str, None]) -> dict: """Load shared data from a JSON file stored on disk""" if path is None: return dict() if not os.path.exists(path): raise FileNotFoundError('No such shared data file "{}"'.format(path)) try: with open(path, 'r') as fp...
def run_version(args: dict) -> int: """Displays the current version""" version = environ.package_settings.get('version', 'unknown') print('VERSION: {}'.format(version)) return 0
def run_batch(args: dict) -> int: """Runs a batch operation for the given arguments""" batcher.run_project( project_directory=args.get('project_directory'), log_path=args.get('logging_path'), output_directory=args.get('output_directory'), shared_data=load_shared_data(args.get('s...
def run_shell(args: dict) -> int: """Run the shell sub command""" if args.get('project_directory'): return run_batch(args) shell = CauldronShell() if in_project_directory(): shell.cmdqueue.append('open "{}"'.format(os.path.realpath(os.curdir))) shell.cmdloop() return 0
def run(action: str, args: dict) -> int: """ Runs the specified command action and returns the return status code for exit. :param action: The action to run :param args: The arguments parsed for the specified action """ if args.get('show_version_info'): return ru...
def get_running_step_changes(write: bool = False) -> list: """...""" project = cd.project.get_internal_project() running_steps = list(filter( lambda step: step.is_running, project.steps )) def get_changes(step): step_data = writing.step_writer.serialize(step) if wr...
def parse( args: typing.List[str] = None, arg_parser: ArgumentParser = None ) -> dict: """Parses the arguments for the cauldron server""" parser = arg_parser or create_parser() return vars(parser.parse_args(args))
def create_parser(arg_parser: ArgumentParser = None) -> ArgumentParser: """ Creates an argument parser populated with the arg formats for the server command. """ parser = arg_parser or ArgumentParser() parser.description = 'Cauldron kernel server' parser.add_argument( '-p', '--port...
def match_rules(tree, rules, fun=None, multi=False): """Matches a Tree structure with the given query rules. Query rules are represented as a dictionary of template to action. Action is either a function, or a dictionary of subtemplate parameter to rules:: rules = { 'template' : { 'key': rules } }...
def match_rules_context(tree, rules, parent_context={}): """Recursively matches a Tree structure with rules and returns context Args: tree (Tree): Parsed tree structure rules (dict): See match_rules parent_context (dict): Context of parent call Returns: dict: Context matched...
def cross_context(contextss): """ Cross product of all contexts [[a], [b], [c]] -> [[a] x [b] x [c]] """ if not contextss: return [] product = [{}] for contexts in contextss: tmp_product = [] for c in contexts: for ce in product: c_copy ...
def match_rules_context_multi(tree, rules, parent_context={}): """Recursively matches a Tree structure with rules and returns context Args: tree (Tree): Parsed tree structure rules (dict): See match_rules parent_context (dict): Context of parent call Returns: dict: Context m...
def match_template(tree, template, args=None): """Check if match string matches Tree structure Args: tree (Tree): Parsed Tree structure of a sentence template (str): String template to match. Example: "( S ( NP ) )" Returns: bool: If they match or not """ tokens = get_to...
def match_tokens(tree, tokens, args): """Check if stack of tokens matches the Tree structure Special matching rules that can be specified in the template:: ':label': Label a token, the token will be returned as part of the context with key 'label'. '-@': Additional single letter argument d...
def get_tokens(tokens): """Recursively gets tokens from a match list Args: tokens : List of tokens ['(', 'S', '(', 'NP', ')', ')'] Returns: Stack of tokens """ tokens = tokens[1:-1] ret = [] start = 0 stack = 0 for i in range(len(tokens)): if tokens[i] ==...
def get_object(tree): """Get the object in the tree object. Method should remove unnecessary letters and words:: the a/an 's Args: tree (Tree): Parsed tree structure Returns: Resulting string of tree ``(Ex: "red car")`` """ if isinstance(tree, Tree)...
def get_raw(tree): """Get the exact words in lowercase in the tree object. Args: tree (Tree): Parsed tree structure Returns: Resulting string of tree ``(Ex: "The red car")`` """ if isinstance(tree, Tree): words = [] for child in tree: words.append(get...
def initialize(spark_home_path: str = None): """ Registers and initializes the PySpark library dependencies so that the pyspark package can be imported and used within the notebook. If you specify the path to the spark home folder, the PySpark libraries from that location will be loaded. If a value...
def is_remote_project(self) -> bool: """Whether or not this project is remote""" project_path = environ.paths.clean(self.source_directory) return project_path.find('cd-remote-project') != -1
def library_directories(self) -> typing.List[str]: """ The list of directories to all of the library locations """ def listify(value): return [value] if isinstance(value, str) else list(value) # If this is a project running remotely remove external library # ...
def results_path(self) -> str: """The path where the project results will be written""" def possible_paths(): yield self._results_path yield self.settings.fetch('path_results') yield environ.configs.fetch('results_directory') yield environ.paths.results(s...
def url(self) -> str: """ Returns the URL that will open this project results file in the browser :return: """ return 'file://{path}?id={id}'.format( path=os.path.join(self.results_path, 'project.html'), id=self.uuid )
def output_directory(self) -> str: """ Returns the directory where the project results files will be written """ return os.path.join(self.results_path, 'reports', self.uuid, 'latest')
def refresh(self, force: bool = False) -> bool: """ Loads the cauldron.json definition file for the project and populates the project with the loaded data. Any existing data will be overwritten, if the new definition file differs from the previous one. If the project has already...
def preformatted_text(source: str) -> str: """Renders preformatted text box""" environ.abort_thread() if not source: return '' source = render_utils.html_escape(source) return '<pre class="preformatted-textbox">{text}</pre>'.format( text=str(textwrap.dedent(source)) )
def markdown( source: str = None, source_path: str = None, preserve_lines: bool = False, font_size: float = None, **kwargs ) -> dict: """ Renders a markdown file with support for Jinja2 templating. Any keyword arguments will be passed to Jinja2 for templating prior to...
def populate_extra_files(): """ Creates a list of non-python data files to include in package distribution """ out = ['cauldron/settings.json'] for entry in glob.iglob('cauldron/resources/examples/**/*', recursive=True): out.append(entry) for entry in glob.iglob('cauldron/resources/te...
def create_rename_entry( step: 'projects.ProjectStep', insertion_index: int = None, stash_path: str = None ) -> typing.Union[None, STEP_RENAME]: """ Creates a STEP_RENAME for the given ProjectStep instance :param step: The ProjectStep instance for which the STEP_RENAME will ...
def synchronize_step_names( project: 'projects.Project', insert_index: int = None ) -> Response: """ :param project: :param insert_index: """ response = Response() response.returned = dict() if not project.naming_scheme: return response create_mapper_func = fun...
def assemble_url( endpoint: str, remote_connection: 'environ.RemoteConnection' = None ) -> str: """ Assembles a fully-resolved remote connection URL from the given endpoint and remote_connection structure. If the remote_connection is omitted, the global remote_connection object stored in...
def parse_http_response(http_response: HttpResponse) -> 'environ.Response': """ Returns a Cauldron response object parsed from the serialized JSON data specified in the http_response argument. If the response doesn't contain valid Cauldron response data, an error Cauldron response object is returned...
def send_request( endpoint: str, data: dict = None, remote_connection: 'environ.RemoteConnection' = None, method: str = None, timeout: int = 10, max_retries: int = 10, **kwargs ) -> 'environ.Response': """ Sends a request to the remote kernel specified by ...
def view(route: str): """ Retrieves the contents of the file specified by the view route if it exists. """ project = cauldron.project.get_internal_project() results_path = project.results_path if project else None if not project or not results_path: return '', 204 path = os.path...
def save( project: 'projects.Project', write_list: typing.List[tuple] = None ) -> typing.List[tuple]: """ Computes the file write list for the current state of the project if no write_list was specified in the arguments, and then writes each entry in that list to disk. :param projec...
def list_asset_writes( project: 'projects.Project' ) -> typing.List[file_io.FILE_COPY_ENTRY]: """ Returns a list containing the file/directory writes that should be executed to deploy the project assets to the results folder. If the project has no assets an empty list is returned. :param pr...
def add_library_path(path: str) -> bool: """ Adds the path to the Python system path if not already added and the path exists. :param path: The path to add to the system paths :return: Whether or not the path was added. Only returns False if the path was not added because it...
def remove_library_path(path: str) -> bool: """ Removes the path from the Python system path if it is found in the system paths. :param path: The path to remove from the system paths :return: Whether or not the path was removed. """ if path in sys.path: sys.path.rem...
def close(): """...""" os.chdir(os.path.expanduser('~')) project = cauldron.project.internal_project if not project: return False [remove_library_path(path) for path in project.library_directories] remove_library_path(project.source_directory) cauldron.project.unload() return T...
def reload_libraries(library_directories: list = None): """ Reload the libraries stored in the project's local and shared library directories """ directories = library_directories or [] project = cauldron.project.get_internal_project() if project: directories += project.library_direc...
def complete( response: Response, project: typing.Union[Project, None], starting: ProjectStep = None, force: bool = False, limit: int = -1 ) -> list: """ Runs the entire project, writes the results files, and returns the URL to the report file :param response: ...
def elapsed_time(self) -> float: """ The number of seconds that has elapsed since the step started running if the step is still running. Or, if the step has already finished running, the amount of time that elapsed during the last execution of the step. """ curren...
def get_elapsed_timestamp(self) -> str: """ A human-readable version of the elapsed time for the last execution of the step. The value is derived from the `ProjectStep.elapsed_time` property. """ t = self.elapsed_time minutes = int(t / 60) seconds = int(t ...
def get_dom(self) -> str: """ Retrieves the current value of the DOM for the step """ if self.is_running: return self.dumps() if self.dom is not None: return self.dom dom = self.dumps() self.dom = dom return dom
def dumps(self) -> str: """Writes the step information to an HTML-formatted string""" code_file_path = os.path.join( self.project.source_directory, self.filename ) code = dict( filename=self.filename, path=code_file_path, code=r...
def retry(*excepts): '''A decorator to specify a bunch of exceptions that should be caught and the job retried. It turns out this comes up with relative frequency''' @decorator.decorator def new_func(func, job): '''No docstring''' try: func(job) except tuple(excepts):...
def tracked(self): '''Return an array of job objects that are being tracked''' results = json.loads(self.client('track')) results['jobs'] = [Job(self, **job) for job in results['jobs']] return results
def tagged(self, tag, offset=0, count=25): '''Return the paginated jids of jobs tagged with a tag''' return json.loads(self.client('tag', 'get', tag, offset, count))
def failed(self, group=None, start=0, limit=25): '''If no group is provided, this returns a JSON blob of the counts of the various types of failures known. If a type is provided, returns paginated job objects affected by that kind of failure.''' if not group: return json.load...
def get(self, *jids): '''Return jobs objects for all the jids''' if jids: return [ Job(self.client, **j) for j in json.loads(self.client('multiget', *jids))] return []
def title(cls, message=None): '''Set the title of the process''' if message == None: return getproctitle() else: setproctitle('qless-py-worker %s' % message) logger.info(message)
def divide(cls, jobs, count): '''Divide up the provided jobs into count evenly-sized groups''' jobs = list(zip(*zip_longest(*[iter(jobs)] * count))) # If we had no jobs to resume, then we get an empty list jobs = jobs or [()] * count for index in range(count): # Filte...
def clean(cls, path): '''Clean up all the files in a provided path''' for pth in os.listdir(path): pth = os.path.abspath(os.path.join(path, pth)) if os.path.isdir(pth): logger.debug('Removing directory %s' % pth) shutil.rmtree(pth) else...
def sandbox(cls, path): '''Ensures path exists before yielding, cleans up after''' # Ensure the path exists and is clean try: os.makedirs(path) logger.debug('Making %s' % path) except OSError: if not os.path.isdir(path): raise f...
def resumable(self): '''Find all the jobs that we'd previously been working on''' # First, find the jids of all the jobs registered to this client. # Then, get the corresponding job objects jids = self.client.workers[self.client.worker_name]['jobs'] jobs = self.client.jobs.get(*j...
def jobs(self): '''Generator for all the jobs''' # If we should resume work, then we should hand those out first, # assuming we can still heartbeat them for job in self.resume: try: if job.heartbeat(): yield job except exception...
def listener(self): '''Listen for pubsub messages relevant to this worker in a thread''' channels = ['ql:w:' + self.client.worker_name] listener = Listener(self.client.redis, channels) thread = threading.Thread(target=self.listen, args=(listener,)) thread.start() try: ...
def listen(self, listener): '''Listen for events that affect our ownership of a job''' for message in listener.listen(): try: data = json.loads(message['data']) if data['event'] in ('canceled', 'lock_lost', 'put'): self.kill(data['jid']) ...
def signals(self, signals=('QUIT', 'USR1', 'USR2')): '''Register our signal handler''' for sig in signals: signal.signal(getattr(signal, 'SIG' + sig), self.handler)
def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum == signal.SIGQUIT: # QUIT - Finish processing, but don't do any more work after that self.stop() elif signum == signal.SIGUSR1: # USR1 - Print the backtrace ...
def truncate_entry_titles(apps, schema_editor): """This function will truncate the values of Entry.title so they are 255 characters or less. """ Entry = apps.get_model("andablog", "Entry") for entry in Entry.objects.all(): # Truncate to 255 characters (or less) but keep whole words intact. ...
def process(self, job): '''Process a job''' sandbox = self.sandboxes.pop(0) try: with Worker.sandbox(sandbox): job.sandbox = sandbox job.process() finally: # Delete its entry from our greenlets mapping self.greenlets.pop...
def kill(self, jid): '''Stop the greenlet processing the provided jid''' greenlet = self.greenlets.get(jid) if greenlet is not None: logger.warn('Lost ownership of %s' % jid) greenlet.kill()
def run(self): '''Work on jobs''' # Register signal handlers self.signals() # Start listening with self.listener(): try: generator = self.jobs() while not self.shutdown: self.pool.wait_available() ...
def init_db_conn(connection_name, connection_string, scopefunc=None): """ Initialize a postgresql connection by each connection string defined in the configuration file """ engine = create_engine(connection_string) session = scoped_session(sessionmaker(), scopefunc=scopefunc) session.configu...
def initialize(g, app): """ If postgresql url is defined in configuration params a scoped session will be created """ if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']: # Database connection established for console commands for k, v in app.config['DATABASES']['...
def load_extensions_from_config(**config): """ Loads extensions """ extensions = [] if 'EXTENSIONS' in config: for ext in config['EXTENSIONS']: try: extensions.append(locate(ext)) except Exception as e: print(e) return extensions
def set_request(self, r): """ Appends request object to the globals dict """ for k in self.environments.keys(): self.environments[k].globals['REQUEST'] = r
def init_db_conn(connection_name, HOSTS=None): """ Initialize a redis connection by each connection string defined in the configuration file """ el = elasticsearch.Elasticsearch(hosts=HOSTS) el_pool.connections[connection_name] = ElasticSearchClient(el)
def parse_tags(targs): """ Tags can be in the forma key:value or simply value """ tags = {} for t in targs: split_tag = t.split(':') if len(split_tag) > 1: tags['tag:' + split_tag[0]] = split_tag[1] else: tags['tag:' + split_tag[0]] = '' return tag...
def json_response(self, status=200, data={}, headers={}): ''' To set flask to inject specific headers on response request, such as CORS_ORIGIN headers ''' mimetype = 'application/json' header_dict = {} for k, v in headers.items(): header_dict[k] =...
def template_response(self, template_name, headers={}, **values): """ Constructs a response, allowing custom template name and content_type """ response = make_response( self.render_template(template_name, **values)) for field, value in headers.items(): r...