code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''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 not None: args.append(group) ...
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
7.757163
2.833513
2.737649
'''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: return self.client('depends', self.jid, 'o...
def undepend(self, *args, **kwargs)
Remove specific (or all) job dependencies from this job: job.remove(jid1, jid2) job.remove(all=True)
5.873527
2.957974
1.985658
def add_dot(extension): return ( extension if extension.startswith('.') else '.{}'.format(extension) ) return any([ file_path.endswith(add_dot(extension)) for extension in args ])
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 be tested for a match :param args: One or more extensions to test for...
5.135654
3.899364
1.317049
raw = getattr(target, '__doc__') if raw is None: return '' return textwrap.dedent(raw)
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 no doc string exists an empty string w...
4.794288
4.786713
1.001582
raw = get_docstring(target) if not raw: return [] raw_lines = [ line.strip() for line in raw.replace('\r', '').split('\n') ] def compactify(compacted: list, entry: str) -> list: chars = entry.strip() if not chars: return compacted ...
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
3.240938
3.348086
0.967997
if not hasattr(target, '__code__'): return None lines = get_doc_entries(target) docs = ' '.join(filter(lambda line: not line.startswith(':'), lines)) params = parse_params(target, lines) returns = parse_returns(target, lines) return dict( name=getattr(target, '__name__'),...
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 function to parse into documentation :return: A dictionary containing documentation for the specified fu...
3.197074
3.19294
1.001295
if hasattr(target, 'fget'): doc = parse_function(name, target.fget) if doc: doc['read_only'] = bool(target.fset is None) return doc return dict( name=name, description=get_docstring(target) )
def variable(name: str, target: property) -> typing.Union[None, dict]
:param name: :param target: :return:
3.834344
4.011289
0.955888
try: buffered_bytes = self.bytes_buffer.getvalue() if buffered_bytes is None: return '' return buffered_bytes.decode(self.source_encoding) except Exception as err: return 'Redirect Buffer Error: {}'.format(err)
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
5.624929
5.06997
1.10946
# 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.bytes_buffer.getvalue() self.bytes_buffer.truncate(0) s...
def flush_all(self) -> str
:return:
2.787243
2.499817
1.114979
return STEP_DATA( name=step.definition.name, status=step.status(), has_error=False, body=None, data=dict(), includes=[], cauldron_version=list(environ.version_info), file_writes=[] )
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 the step output. The dictionary must then be populated with data f...
12.025361
12.677664
0.948547
cache_path = step.report.results_cache_path if not os.path.exists(cache_path): return None out = create_data(step) try: with open(cache_path, 'r') as f: cached_data = json.load(f) except Exception: return None file_writes = [ file_io.entry_fro...
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 which the cached data should be loaded :return: Either a step data structure containing the cac...
3.835521
4.202992
0.912569
path = environ.paths.clean(path if path else '.') if os.path.isdir(path) and os.path.exists(path): path = os.path.join(path, 'cauldron_run.log') elif os.path.exists(path): os.remove(path) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(d...
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 directory. If a directory is specified, the log file written will...
3.12757
2.932716
1.066441
log_path = initialize_logging_path(log_path) logger.add_output_path(log_path) def on_complete( command_response: environ.Response, project_data: SharedCache = None, message: str = None ) -> ExecutionResult: environ.modes.remove(environ.modes.SINGLE_RUN) ...
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 single command in production mode (non-interactive). :param project_directory: Directory where the project to run is located :param output_directory: Directory where the project display data will be saved :param log_path: Path t...
2.8772
2.886936
0.996627
'''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 stopping %s...' % cpid) # W...
def stop(self, sig=signal.SIGINT)
Stop all the workers, and then wait for them
3.450076
3.275849
1.053185
'''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 allowing `klass` to be specifi...
def spawn(self, **kwargs)
Return a new worker for a child process
7.112658
6.339663
1.12193
'''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): # The sandbo...
def run(self)
Run this worker
3.76052
3.715908
1.012006
self.stop(signum) os._exit(0)
def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT)
Signal handler for this process
20.002552
9.196253
2.175076
cauldron_path = environ.paths.package() resources_path = environ.paths.resources() frames = ( list(traceback.extract_tb(sys.exc_info()[-1])) if error_stack else traceback.extract_stack() ).copy() def is_cauldron_code(test_filename: str) -> bool: if not test_fil...
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.
2.982322
2.785618
1.070614
filename = stack_frame.filename if filename.startswith(project.source_directory): filename = filename[len(project.source_directory) + 1:] location = stack_frame.name if location == '<module>': location = None return dict( filename=filename, location=location, ...
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 templating. :param project: The currently open project, which is used to con...
2.498436
2.541402
0.983094
return [ format_stack_frame(f, project) for f in get_stack_frames(error_stack=error_stack) ]
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 the stack data. :param error_stack: Whether or not to return the error stack. When True the stack of the ...
3.733675
3.541116
1.054378
union_params = ( getattr(arg_type, '__union_params__', None) or getattr(arg_type, '__args__', None) ) if union_params and isinstance(union_params, (list, tuple)): return ', '.join([arg_type_to_string(item) for item in union_params]) try: return arg_type.__name__ ...
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
2.708175
2.645742
1.023598
flat_components = functools.reduce(flatten_reducer, components, []) return COMPONENT( includes=functools.reduce( functools.partial(combine_lists_reducer, 'includes'), flat_components, [] ), files=functools.reduce( functools.partial(co...
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 instances as well. :param components: :return:
3.34129
2.931284
1.139872
if hasattr(entry, 'includes') and hasattr(entry, 'files'): flattened_list.append(entry) elif entry: flattened_list.extend(entry) return flattened_list
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 populated from previous calls of this reducer function :param entry: An entry to be reduced. Either a COMPONE...
4.242215
4.118358
1.030074
merged_list.extend(getattr(component, key)) return merged_list
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: The accumulated list of values populated by previous calls to this reducer function :param component: T...
6.937247
8.849487
0.783915
'''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 listen(self)
Listen for events as they come in
5.188445
4.642274
1.117652
'''Run in a thread''' thread = threading.Thread(target=self.listen) thread.start() try: yield self finally: self.unlisten() thread.join()
def thread(self)
Run in a thread
5.167415
5.521938
0.935797
'''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) if func: ...
def listen(self)
Listen for events
5.0181
5.435128
0.923272
'''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 on(self, evt, func)
Set a callback handler for a pubsub event
6.500299
4.910436
1.323772
'''Get a particular option, or the default if it's missing''' val = self[option] return (val is None and default) or val
def get(self, option, default=None)
Get a particular option, or the default if it's missing
7.554262
5.958491
1.267815
'''Just like `dict.pop`''' val = self[option] del self[option] return (val is None and default) or val
def pop(self, option, default=None)
Just like `dict.pop`
6.947902
5.299824
1.310968
'''Just like `dict.update`''' _kwargs = dict(kwargs) _kwargs.update(other) for key, value in _kwargs.items(): self[key] = value
def update(self, other=(), **kwargs)
Just like `dict.update`
4.070003
3.275725
1.242474
r = Response() project = cd.project.get_internal_project() if project: project.refresh() else: r.fail( code='NO_PROJECT', message='No open project to refresh' ) return r.update( sync_time=sync_status.get('time', 0) ).flask_serialize(...
def touch_project()
Touches the project to trigger refreshing its cauldron.json state.
9.542528
7.641234
1.24882
r = Response() project = cd.project.get_internal_project() if not project: r.fail( code='NO_PROJECT', message='No open project on which to retrieve status' ) else: with open(project.source_path, 'r') as f: definition = json.load(f) ...
def fetch_synchronize_status()
Returns the synchronization status information for the currently opened project
5.712125
5.528994
1.033122
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.realpath(os.path.join( source_directory, '..', '__cauldron_downloads'...
def download_file(filename: str)
downloads the specified project file if it exists
4.063419
3.545697
1.146014
path = environ.paths.clean(path) if not path.endswith('cauldron.json'): return os.path.join(path, 'cauldron.json') return path
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
6.018672
4.957428
1.214071
source_path = get_project_source_path(path) if not os.path.exists(source_path): raise FileNotFoundError('Missing project file: {}'.format(source_path)) with open(source_path, 'r') as f: out = json.load(f) project_folder = os.path.split(os.path.dirname(source_path))[-1] if 'id...
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 the definition file will be loaded
2.565906
2.658772
0.965072
test_path = '{}'.format(path if path else '') replacements = (path_prefixes if path_prefixes else []).copy() replacements.append(('~', os.path.expanduser('~'))) for key, value in replacements: if test_path.startswith(value): return '{}{}'.format(key, test_path[len(value):]) ...
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:
3.569388
3.376024
1.057276
if name.find('.') > -1: # Not interested in sub-packages, only root ones return None version = getattr(entry, '__version__', None) version = version if not hasattr(version, 'version') else version.version location = getattr(entry, '__file__', sys.exec_prefix) if version is No...
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 path_prefixes: :return:
5.009923
4.774168
1.049381
site_packages = get_site_packages() path_prefixes = [('[SP]', p) for p in site_packages] path_prefixes.append(('[CORE]', sys.exec_prefix)) packages = [ module_to_package_data(name, entry, path_prefixes) for name, entry in list(sys.modules.items()) ] python_data = dict( ...
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 * location * version
3.931647
3.979036
0.98809
if not path: return False if not os.path.exists(path): return True remover = os.remove if os.path.isfile(path) else shutil.rmtree for attempt in range(max_retries): try: remover(path) return True except Exception: # Pause briefl...
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_retries: The number of times to retry before giving up. ...
3.702725
3.55649
1.041118
print('\n') if code != 0: log('Failed with status code: {}'.format(code), whitespace=1) sys.exit(code)
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 to inform the user that t...
9.406757
7.237939
1.299646
if 'folder' in self.data: return self.data.get('folder') elif self.project_folder: if callable(self.project_folder): return self.project_folder() else: return self.project_folder return None
def folder(self) -> typing.Union[str, None]
The folder, relative to the project source_directory, where the file resides :return:
3.135831
3.305152
0.948771
if os.path.exists(path): return True response.fail( code='PROJECT_NOT_FOUND', message='The project path does not exist', path=path ).console( .format(path=path) ) return False
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:
5.673057
5.48515
1.034257
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(recent_paths=recent_paths[:10], persists=True) environ.configs.save() except Exception as ...
def update_recent_paths(response, path)
:param response: :param path: :return:
4.814124
4.74183
1.015246
index = line.find(' ') if index == -1: return line.lower(), '' return line[:index].lower(), line[index:].strip()
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:
3.111964
3.548444
0.876994
stack = render_stack.get_formatted_stack_frame( project=step.project, error_stack=False ) try: names = [frame['filename'] for frame in stack] index = names.index(os.path.realpath(__file__)) frame = stack[index - 1] except Exception: frame = {} s...
def render_stop_display(step: 'projects.ProjectStep', message: str)
Renders a stop action to the Cauldron display.
5.441072
5.024842
1.082834
return self._project.id if self._project else None
def id(self) -> typing.Union[str, None]
Identifier for the project.
9.68222
6.017115
1.609114
return ( self._project.current_step.report if self._project and self._project.current_step else None )
def display(self) -> typing.Union[None, report.Report]
The display report for the current project.
5.905385
4.722906
1.250371
return self._project.shared if self._project else None
def shared(self) -> typing.Union[None, SharedCache]
The shared display object associated with this project.
13.492185
8.099268
1.665852
return self._project.settings if self._project else None
def settings(self) -> typing.Union[None, SharedCache]
The settings associated with this project.
14.751563
9.491817
1.554135
return self._project.title if self._project else None
def title(self) -> typing.Union[None, str]
The title of this project.
10.542074
6.819201
1.54594
if not self._project: raise RuntimeError('Failed to assign title to an unloaded project') self._project.title = value
def title(self, value: typing.Union[None, str])
Modifies the title of the project, which is initially loaded from the `cauldron.json` file.
10.984925
6.651945
1.651385
self._project = project
def load(self, project: typing.Union[projects.Project, None])
Connects this object to the specified source project.
61.553101
16.675142
3.691309
if not self._project: return None return environ.paths.clean(os.path.join( self._project.source_directory, *args ))
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 :return: An absolute path to the specified file or directory within the ...
6.285366
6.225265
1.009654
me = self.get_internal_project() if not me or not me.current_step: return if not silent: render_stop_display(me.current_step, message) raise UserAbortError(halt=True)
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 continuing to run. :param message: A custom display message t...
12.039877
9.183728
1.311001
count = int(timeout / 0.1) for _ in range(count): project = self.internal_project if project: return project time.sleep(0.1) return self.internal_project
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 will try to continuously load the internal project until it is available or until the timeout is reached. :param timeout: ...
3.11049
3.616076
0.860184
import cauldron try: return cauldron.project.get_internal_project().current_step except Exception: return None
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
5.425908
5.268898
1.029799
step = self._step if not step: return if not silent: render_stop_display(step, message) raise UserAbortError(halt=halt)
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. :param message: A custom display message to include in the display for the stop action. This message is ignored if silent...
13.923869
11.180399
1.245382
if not self._step: raise ValueError( 'Cannot write to the console stdout on an uninitialized step' ) interceptor = self._step.report.stdout_interceptor interceptor.write_source('{}'.format(message))
def write_to_console(self, message: str)
Writes the specified message to the console stdout without including it in the notebook display.
15.284691
13.070827
1.169374
rendered = templating.render(message, **kwargs) return self.write_to_console(rendered)
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 actions. :param message: Template string to be rend...
7.363174
8.738993
0.842566
compatible = (1, 8) <= DJANGO_VERSION < (1, 10) if not compatible: return [] return [ migrations.AlterField( model_name='user', name='groups', field=models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=Tru...
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 integration testing) in multiple Django v...
1.804844
1.717269
1.050997
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(BOKEH_WARNING) return COMPONENT([], []) return definitions.merge...
def create(project: 'projects.Project') -> COMPONENT
:return:
3.875785
3.593096
1.078676
stdout = self.stdout_interceptor stderr = self.stderr_interceptor return max([ self._last_update_time, stdout.last_write_time if stdout else 0, stderr.last_write_time if stderr else 0, ])
def last_update_time(self) -> float
The last time at which the report was modified.
4.738167
4.002588
1.183776
if not self.project: return '' return os.path.join( self.project.results_path, '.cache', 'steps', '{}.json'.format(self.id) )
def results_cache_path(self) -> str
Location where step report is cached between sessions to prevent loss of display data between runs.
4.685076
3.799672
1.233021
self.body = [] self.data = SharedCache() self.files = SharedCache() self._last_update_time = time.time() return self
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
8.466272
9.733727
0.869787
self.flush_stdout() self.body.append(dom) self._last_update_time = time.time()
def append_body(self, dom: str)
Appends the specified HTML-formatted DOM string to the currently stored report body for the step.
8.417177
7.334983
1.147539
try: contents = self.stdout_interceptor.read_all() except Exception as err: contents = '' return render_texts.preformatted_text(contents)
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 executing. :return: A do...
12.499339
12.924111
0.967133
try: contents = self.stdout_interceptor.flush_all() except Exception: return if len(contents) > 0: self.body.append(render_texts.preformatted_text(contents)) self._last_update_time = time.time() return contents
def flush_stdout(self)
Empties the standard out redirect buffer and renders the contents to the body as a preformatted text box.
7.857002
5.771981
1.361232
'''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 import_class(klass)
Import the named class and return that class
2.975171
3.086242
0.964011
source_path = environ.paths.clean( os.path.join(project.source_directory, include_path) ) if not os.path.exists(source_path): return COMPONENT([], []) if os.path.isdir(source_path): glob_path = os.path.join(source_path, '**', '*') include_paths = glob.iglob(glob_pa...
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 within the project where the component resides :return: The created COMPONENT instance
3.102931
3.068516
1.011216
return definitions.merge_components(*map( functools.partial(create, project), include_paths ))
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 relative paths within the project directory to files or directories that should be included in the project :retu...
11.384787
9.919134
1.14776
if not file_path.endswith('.css') and not file_path.endswith('.js'): return None slug = file_path[len(project.source_directory):] url = '/{}' \ .format(slug) \ .replace('\\', '/') \ .replace('//', '/') return WEB_INCLUDE(name=':project:{}'.format(url), src=url)
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 file_path resides :param file_path: Absolute path to the source file for which the WEB_INCLUDE insta...
3.866931
4.122833
0.937931
try: data = contents.encode() except Exception: data = contents if offset > 0: with open(path, 'rb') as f: existing = f.read(offset) else: existing = None append = 'a' in mode write_mode = 'wb' if offset > 0 or not append else 'ab' try: ...
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. :param path: The path to the file that will be written :param contents: The contents of the file to write :param mode: The mode in which the file wil...
2.34174
2.388596
0.980384
error = None for i in range(retry_count): error = attempt_file_write(path, contents, mode, offset) if error is None: return True, None time.sleep(0.2) return False, error
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 OS related write collisions with files that are regularly written to and read from quickly. :param path: The path to the file that will be written :param contents: Th...
2.604356
2.926934
0.88979
try: with open(path, mode) as f: json.dump(contents, f) return None except Exception as error: return error
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: The JSON data to write to the file :param mode: The mode used to open the file where the content will be written. :r...
2.108926
2.130976
0.989652
error = None for i in range(retry_count): error = attempt_json_write(path, contents, mode) if error is None: return True, None time.sleep(0.2) return False, error
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 useful to prevent OS related write collisions with files that are regularly written to and read from quickly. :param path: The path to the file that will be wr...
2.681904
2.991873
0.896396
value = source if source else '' return dedent(value.strip('\n')).strip()
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
14.414437
13.357223
1.079149
env = JINJA_ENVIRONMENT loader = env.loader resource_path = environ.configs.make_path( 'resources', 'templates', override_key='template_path' ) if not loader: env.filters['id'] = get_id env.filters['latex'] = get_latex if not loader or resource_path not i...
def get_environment() -> Environment
Returns the jinja2 templating environment updated with the most recent cauldron environment configurations :return:
6.767589
6.881991
0.983377
if not hasattr(template, 'render'): template = get_environment().from_string(textwrap.dedent(template)) return template.render( cauldron_template_uid=make_template_uid(), **kwargs )
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 rendering :return: The rendered template string
5.571217
4.494063
1.239684
with open(path, 'r') as f: contents = f.read() return get_environment().from_string(contents).render( cauldron_template_uid=make_template_uid(), **kwargs )
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 arguments that should be passed to Jinja2 for renderin...
5.94303
4.683052
1.269051
return get_environment().get_template(template_name).render( cauldron_template_uid=make_template_uid(), **kwargs )
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 folder. :param kwargs: Any elements passed to Jinja2 f...
9.361626
7.417591
1.262084
if not path or path == '.': path = os.curdir if path.startswith('~'): path = os.path.expanduser(path) return os.path.realpath(os.path.abspath(path))
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
3.107718
3.070483
1.012127
return clean(os.path.join(os.path.dirname(__file__), '..', *args))
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
8.122677
9.409483
0.863244
result = input('{question} [{yes}/{no}]:'.format( question=question, yes='(Y)' if default else 'Y', no='N' if default else '(N)' )) if not result: return default if result[0].lower() in ['y', 't', '1']: return True return False
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 value
3.094438
3.228134
0.958584
recent_paths = environ.configs.fetch('recent_paths', []) if len(recent_paths) < 1: response.fail( code='NO_RECENT_PROJECTS', message='No projects have been opened recently' ).console() return None return recent_paths[0]
def fetch_last(response: Response) -> typing.Union[str, None]
Returns the last opened project path if such a path exists
6.753292
5.205137
1.297428
dir_name = os.path.dirname(os.path.abspath(file_or_dir)) if not os.path.exists(dir_name): os.makedirs(dir_name)
def before_save(file_or_dir)
make sure that the dedicated path exists (create if not exist) :param file_or_dir: :return: None
1.826106
1.951387
0.935799
# Safely cast data types x = x.astype(np.int, casting='safe') y = y.astype(np.int, casting='safe') labels = np.unique(y) labels = np.arange(np.max(labels) + 1) # assert max(labels) + 1 == len(labels) mine = get_fim_method(method) x_by_labels = [] for label in labels: ...
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, n_features] :param y: 1D np.ndarray, label array of shape [n_instances, ] :param data_filename: the path to store data file :param label_filename: the path to store label fil...
2.693592
2.672648
1.007836
# type: (np.ndarray) -> List assert len(x.shape) == 2 transactions = [] for entry in x: transactions.append(['x%d=%d' % (i, val) for i, val in enumerate(entry)]) return transactions
def categorical2transactions(x)
Convert a 2D int array into a transaction list: [ ['x0=1', 'x1=0', ...], ... ] :param x: :return:
3.911176
4.107326
0.952244
satisfied = [] if features[0] == -1 and len(features) == 1: # Default rule, all satisfied return np.ones(x.shape[0], dtype=bool) for idx, cat in zip(features, categories): # Every single condition needs to be satisfied. satisfied.append(x[:, idx] == cat) return funct...
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:
4.261973
4.361938
0.977083
source_directory = project.source_directory libraries_status = [ {} if d.startswith(source_directory) else of_directory(d) for d in project.library_directories ] return dict( project=of_directory(source_directory), libraries=libraries_status )
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 containing: - project: the status information for all fil...
6.300786
3.566781
1.766519
slug = ( path if root_directory is None else path[len(root_directory):].lstrip(os.sep) ) if not os.path.exists(path) or os.path.isdir(path): return dict( size=-1, modified=-1, path=slug ) size = os.path.getsize(path) ...
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 status information should be generated :param root_directory...
2.542406
2.375088
1.070447
glob_path = os.path.join(directory, '**/*') root = root_directory if root_directory else directory results = filter( lambda result: (result['modified'] != -1), [of_file(path, root) for path in glob.iglob(glob_path, recursive=True)] ) return dict([(result['path'], result) for re...
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 root_directory: Directory relative to which all file status paths are relate...
3.829733
3.732983
1.025918
skip_reload = ( skip_library_reload or environ.modes.has(environ.modes.TESTING) ) if not skip_reload: runner.reload_libraries() environ.log_header('RUNNING', 5) steps_run = [] if single_step: # If the user specifies the single step flag, only run one step....
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...
Execute the run command locally within this cauldron environment :param context: :param project: :param project_steps: :param force: :param continue_after: :param single_step: :param limit: :param print_status: :param skip_library_reload: Whether or not to skip reloading all...
4.097027
4.138941
0.989873
dependency_order = ['common', 'profiles', 'blog', 'democomments'] for app in dependency_order: project.recursive_load(os.path.join(paths.project_paths.manage_root, app))
def loadalldatas()
Loads all demo fixtures.
16.588503
14.416616
1.150652
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_ERROR', message='Unabl...
def project_status()
...
4.508708
4.251534
1.06049
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.get_step(step_name) if not step: ...
def clean_step(step_name: str)
...
3.542195
3.405177
1.040238
timestamp = str(int(time.time())) ts_len = len(timestamp) + 1 while len(slug) + ts_len > max_length: slug = '-'.join(slug.split('-')[:-1]) slug = '-'.join([slug, timestamp]) return slug
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.
2.573736
2.545574
1.011063
# Restrict slugs to their maximum number of chars, but don't split mid-word self.slug = slugify(self.title) while len(self.slug) > 255: self.slug = '-'.join(self.slug.split('-')[:-1]) # Is the same slug as another entry? if Entry.objects.filter(slug=self.slu...
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.
4.725717
4.11212
1.149217
'''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: self.jid = None...
def run(self)
Run jobs, popping one after another
7.04422
5.962246
1.181471
cauldron_module = get_cauldron_module() if cauldron_module is not None: return cauldron_module sys.path.append(ROOT_DIRECTORY) cauldron_module = get_cauldron_module() if cauldron_module is not None: return cauldron_module raise ImportError(' '.join(( 'Unable to i...
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.
3.422047
2.795031
1.224332