output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Reducer function to combine the lists for the specified key into a single list of values populated by previous calls to the this .
Make a summary of the following Python 3 code 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 t...
As a Python code translator, you convert algorithms and pseudocode into Python.
Listen for events as they come in
Make a summary of the following Python 3 code 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 fin...
As a Python code composer, you craft elegant and concise scripts.
Run in a thread
How would you explain what the following Python 3 function does def thread(self): '''Run in a thread''' thread = threading.Thread(target=self.listen) thread.start() try: yield self finally: self.unlisten() thread.join()
As a Python code analyst, you investigate and solve complex coding mysteries
Set a callback handler for a pubsub event
Explain what the following Python 3 code does 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
As a python code expert, you are capable of creating scripts from specifications.
Get a particular option or the default if it s missing
Can you tell what is the following Python 3 function doing 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
As a python code expert, you are capable of creating scripts from specifications.
Just like dict. pop
Given the following Python 3 function, write the documentation def pop(self, option, default=None): '''Just like `dict.pop`''' val = self[option] del self[option] return (val is None and default) or val
As a Python code analyst, you investigate and solve complex coding mysteries
Touches the project to trigger refreshing its cauldron. json state.
Explain what the following Python 3 code does def touch_project(): 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( ...
As a python code expert, you are capable of creating scripts from specifications.
Returns the synchronization status information for the currently opened project
Explain what the following Python 3 code does def fetch_synchronize_status(): 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(pro...
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function that can download the specified file if it exists
You are a Python code analyst, evaluating scripts for potential improvements.
Converts the given path into a project source path to the cauldron. json file.
Explain what the following Python 3 code does def get_project_source_path(path: str) -> str: path = environ.paths.clean(path) if not path.endswith('cauldron.json'): return os.path.join(path, 'cauldron.json') return path
You are a Python code generator, capable of creating scripts from specifications.
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...
How would you code a function in Python 3 to load the cauldron. json project definition file for the given path.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you implement a function in Python 3 that simplifies a path by replacing path prefixes with values specified by path_prefixes in the list of path_prefixes.
As a Python code translator, you convert algorithms and pseudocode into Python.
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 ...
How would you code a function in Python 3 to convert a module entry into a package data dictionary with information about the module.
As a Python code composer, you craft elegant and concise scripts.
Returns a dictionary containing information about the Cauldron system.
Make a summary of the following Python 3 code def get_system_data() -> typing.Union[None, dict]: 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_pref...
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes the specified path from the local filesystem if it exists.
Can you generate the documentation for the following Python 3 function def remove(path: str, max_retries: int = 3) -> bool: 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_retrie...
As a Python code analyst, you investigate and solve complex coding mysteries
Ends the application with the specified error code.
Make a summary of the following Python 3 code def end(code: int): print('\n') if code != 0: log('Failed with status code: {}'.format(code), whitespace=1) sys.exit(code)
You are a Python code generator, capable of creating scripts from specifications.
Returns the folder of the file that is used to store the file.
How would you explain what the following Python 3 function does def folder(self) -> typing.Union[str, None]: if 'folder' in self.data: return self.data.get('folder') elif self.project_folder: if callable(self.project_folder): return self.project_folder() ...
You are a Python code analyst, evaluating scripts for potential improvements.
Determines whether or not a project exists at the specified path.
Here you have a function in Python 3, explain what it does def project_exists(response: 'environ.Response', path: str) -> bool: if os.path.exists(path): return True response.fail( code='PROJECT_NOT_FOUND', message='The project path does not exist', path=path ).console( ...
As a Python code composer, you craft elegant and concise scripts.
Updates the recent paths of the current project.
Make a summary of the following Python 3 code def update_recent_paths(response, path): 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_...
You are a Python code analyst, evaluating scripts for potential improvements.
Splits the raw line into two strings.
Can you tell what is the following Python 3 function doing def split_line(line: str) -> typing.Tuple[str, str]: index = line.find(' ') if index == -1: return line.lower(), '' return line[:index].lower(), line[index:].strip()
As a Python code translator, you convert algorithms and pseudocode into Python.
Renders a stop action to the Cauldron display.
Here you have a function in Python 3, explain what it does def render_stop_display(step: 'projects.ProjectStep', message: str): stack = render_stack.get_formatted_stack_frame( project=step.project, error_stack=False ) try: names = [frame['filename'] for frame in stack] index...
As a Python code translator, you convert algorithms and pseudocode into Python.
def id(self) -> typing.Union[str, None]: """Identifier for the project.""" return self._project.id if self._project else None
Write a Python 3 function for identifying for the project.
You are a Python code generator, capable of creating scripts from specifications.
The display report for the current project.
Make a summary of the following Python 3 code def display(self) -> typing.Union[None, report.Report]: return ( self._project.current_step.report if self._project and self._project.current_step else None )
As a Python code composer, you craft elegant and concise scripts.
The shared display object associated with this project.
Can you tell what is the following Python 3 function doing def shared(self) -> typing.Union[None, SharedCache]: return self._project.shared if self._project else None
As a python code expert, you are capable of creating scripts from specifications.
The settings associated with this project.
Explain what the following Python 3 code does def settings(self) -> typing.Union[None, SharedCache]: return self._project.settings if self._project else None
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the title of the project.
Can you generate a brief explanation for the following Python 3 code def title(self, value: typing.Union[None, str]): if not self._project: raise RuntimeError('Failed to assign title to an unloaded project') self._project.title = value
As a Python code translator, you convert algorithms and pseudocode into Python.
Connects this object to the specified source project.
Here you have a function in Python 3, explain what it does def load(self, project: typing.Union[projects.Project, None]): self._project = project
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function for creating an absolute path to the specified file or directory within the project source directory.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 script for stopping the execution of the project at the current step immediately holding the action.
As a Python code analyst, you investigate and solve complex coding mysteries
Attempts to return the internal project.
Make a summary of the following Python 3 code 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 v...
You are a Python code generator, capable of creating scripts from specifications.
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. ...
How would you code a function in Python 3 to stop execution of the current node in the current notebook.
You are a Python code generator, capable of creating scripts from specifications.
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' ...
Can you implement a function in Python 3 that writes the specified message to the console stdout.
As a Python code translator, you convert algorithms and pseudocode into Python.
Renders the specified message to the console using Jinja2 template.
Given the following Python 3 function, write the documentation def render_to_console(self, message: str, **kwargs): rendered = templating.render(message, **kwargs) return self.write_to_console(rendered)
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to return a list of operations that can be performed on the current site.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Write a Python 3 function that can create a new component.
As a Python code translator, you convert algorithms and pseudocode into Python.
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', ...
Write a Python 3 script to return the path where the step report is cached between sessions and runs.
You are a Python code analyst, evaluating scripts for potential improvements.
Clear all user - data stored in this instance and reset it to its original state.
Can you generate a brief explanation for the following Python 3 code def clear(self) -> 'Report': self.body = [] self.data = SharedCache() self.files = SharedCache() self._last_update_time = time.time() return self
You are a Python code analyst, evaluating scripts for potential improvements.
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()
Create a Python 3 function for appending the specified HTML - formatted DOM string to the current report body.
As a Python code composer, you craft elegant and concise scripts.
Reads the current state of the print buffer and returns the contents of the print buffer as a preformatted string.
Can you generate a brief explanation for the following Python 3 code def read_stdout(self): try: contents = self.stdout_interceptor.read_all() except Exception as err: contents = '' return render_texts.preformatted_text(contents)
You are a Python code generator, capable of creating scripts from specifications.
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: ...
How would you code a function in Python 3 to flush the standard out redirect buffer and renders the contents to the body as a preformatted text box.
You are a Python code generator, capable of creating scripts from specifications.
Import the named class and return that class
How would you explain what the following Python 3 function does 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])
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a COMPONENT instance for the project component specified by the include path.
Explain what the following Python 3 code does 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...
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a single COMPONENT instance for all of the specified project and include_paths.
Explain what the following Python 3 code does 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 ...
You are a Python code generator, capable of creating scripts from specifications.
Converts the given file_path into a WEB_INCLUDE instance that represents the deployed version of this file.
Can you generate a brief explanation for the following Python 3 code 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 ...
You are a Python code generator, capable of creating scripts from specifications.
Attempts to write the contents of the specified file to a file and returns None if the file write operation failed.
Given the following Python 3 function, write the documentation 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 ...
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you create a Python 3 function that writes the contents of the specified contents to the specified file.
You are a Python code architect, reviewing and designing scalable and efficient code
Attempts to write the specified JSON content to the specified file.
Explain what the following Python 3 code does 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 con...
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Can you write a function in Python 3 where it writes the contents of a dictionary to a JSON - serialized file.
As a python code expert, you are capable of creating scripts from specifications.
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()
Can you write a function in Python 3 where it formats the source string to strip newlines on both ends and dedents the entire string
You are a Python code generator, capable of creating scripts from specifications.
Returns the jinja2 templating environment updated with the most recent cauldron environment configurations
Can you generate a brief explanation for the following Python 3 code def get_environment() -> Environment: env = JINJA_ENVIRONMENT loader = env.loader resource_path = environ.configs.make_path( 'resources', 'templates', override_key='template_path' ) if not loader: env.fil...
As a Python code composer, you craft elegant and concise scripts.
Renders a template string using Jinja2 and Cauldron templating.
How would you explain what the following Python 3 function does def render(template: typing.Union[str, Template], **kwargs): if not hasattr(template, 'render'): template = get_environment().from_string(textwrap.dedent(template)) return template.render( cauldron_template_uid=make_template_uid()...
As a Python code analyst, you investigate and solve complex coding mysteries
Renders a file at the specified absolute path.
Can you generate a brief explanation for the following Python 3 code def render_file(path: str, **kwargs): with open(path, 'r') as f: contents = f.read() return get_environment().from_string(contents).render( cauldron_template_uid=make_template_uid(), **kwargs )
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 script for rendering the template with the given filename from within Cauldron s base template folder.
As a Python code composer, you craft elegant and concise scripts.
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 """...
Can you implement a function in Python 3 that cleans the specified path by expanding shorthand elements redirecting to the real path for symbolic links and removing any relative components from .
You are a Python code analyst, evaluating scripts for potential improvements.
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...
How would you code a function in Python 3 to return an absolute path to a file or folder within the cauldron package containing the relative path elements specified by the args.
As a Python code composer, you craft elegant and concise scripts.
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...
How would you code a function in Python 3 to request confirmation of the specified question and returns that result
You are a Python code generator, capable of creating scripts from specifications.
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...
Implement a Python 3 function for returning the last opened project path if such a path exists.
As a Python code composer, you craft elegant and concise scripts.
Create the dedicated path if it does not exist
Make a summary of the following Python 3 code def before_save(file_or_dir): dir_name = os.path.dirname(os.path.abspath(file_or_dir)) if not os.path.exists(dir_name): os.makedirs(dir_name)
You are a Python code architect, reviewing and designing scalable and efficient code
This function extracts the data from a categorical data set and stores it in a file.
Given the following Python 3 function, write the documentation 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. :p...
You are a Python code generator, capable of creating scripts from specifications.
Convert a 2D int array into a list of categorical transactions.
How would you explain what the following Python 3 function does 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) ...
You are a Python code architect, reviewing and designing scalable and efficient code
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: """ ...
Write a Python 3 script to return a logical array representing whether entries in x satisfied the rules denoted by features and categories.
You are a Python code generator, capable of creating scripts from specifications.
Returns the status information for every file within the project source directory and its shared library folders.
Can you generate a brief explanation for the following Python 3 code def of_project(project: 'projects.Project') -> dict: source_directory = project.source_directory libraries_status = [ {} if d.startswith(source_directory) else of_directory(d) for d in project.library_directories ] re...
As a Python code composer, you craft elegant and concise scripts.
Returns a dictionary containing the status information for the specified file at the specified path.
How would you explain what the following Python 3 function does def of_file(path: str, root_directory: str = None) -> dict: 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 di...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Create a Python 3 function to return a dictionary containing status information for all files within the specified directory and its descendants.
As a Python code composer, you craft elegant and concise scripts.
Execute the run command locally within this cauldron environment.
Can you tell what is the following Python 3 function doing 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_stat...
You are a Python code architect, reviewing and designing scalable and efficient code
Loads all demo fixtures.
Can you generate a brief explanation for the following Python 3 code def loadalldatas(): dependency_order = ['common', 'profiles', 'blog', 'democomments'] for app in dependency_order: project.recursive_load(os.path.join(paths.project_paths.manage_root, app))
As a Python code composer, you craft elegant and concise scripts.
Returns a JSON representation of the current status of the currently opened project.
Explain what the following Python 3 code does 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( ...
You are a Python code analyst, evaluating scripts for potential improvements.
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....
Write a Python 3 script to clean the current step.
As a Python code composer, you craft elegant and concise scripts.
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: ...
Create a Python 3 function to append a timestamp integer to the given slug ensuring that the result is less than the specified max_length.
You are a Python code analyst, evaluating scripts for potential improvements.
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: ...
Write a Python 3 function that can run jobs popping one after another
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Write a Python 3 script for initializing the cauldron library by confirming that it can be imported by importlib.
You are a Python code analyst, evaluating scripts for potential improvements.
Executes the cauldron command
Can you generate a brief explanation for the following Python 3 code def run(arguments: typing.List[str] = None): 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_...
As a python code expert, you are capable of creating scripts from specifications.
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...
How would you code a function in Python 3 to return either the linked or not - linked profile name.
As a Python code translator, you convert algorithms and pseudocode into Python.
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'...
Can you implement a function in Python 3 that echoes the project steps.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
How would you implement a function in Python 3 that explodes a filename into a dictionary containing the name of the file without extension and the extension of the file.
You are a Python code generator, capable of creating scripts from specifications.
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) ...
Implement a function in Python 3 to create a new COMPONENT instance for the given project.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Can you create a Python 3 function that returns whether or not the current working directory is a Cauldron project directory which contains a cauldron. json file.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function for loading a shared data from a JSON file stored on disk
As a Python code analyst, you investigate and solve complex coding mysteries
Displays the current version
Can you generate the documentation for the following Python 3 function def run_version(args: dict) -> int: version = environ.package_settings.get('version', 'unknown') print('VERSION: {}'.format(version)) return 0
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
How would you code a function in Python 3 to run a batch operation for the given arguments
As a Python code analyst, you investigate and solve complex coding mysteries
Run the shell sub command
Make a summary of the following Python 3 code def run_shell(args: dict) -> int: 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() retur...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Implement a Python 3 function for running the specified command action and returns the return code for exit.
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of all running steps.
Can you tell what is the following Python 3 function doing 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 = writi...
You are a Python code analyst, evaluating scripts for potential improvements.
Parses the arguments for the cauldron server
Here you have a function in Python 3, explain what it does 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))
As a python code expert, you are capable of creating scripts from specifications.
Creates an argument parser populated with the arg formats for the server command.
Make a summary of the following Python 3 code def create_parser(arg_parser: ArgumentParser = None) -> ArgumentParser: parser = arg_parser or ArgumentParser() parser.description = 'Cauldron kernel server' parser.add_argument( '-p', '--port', dest='port', type=int, default=50...
As a Python code analyst, you investigate and solve complex coding mysteries
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 } }...
Can you create a Python 3 function that matches a Tree structure with the given query rules.
As a Python code composer, you craft elegant and concise scripts.
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 ...
How would you implement a function in Python 3 that crosses product of all contexts in a list of contexts
As a python code expert, you are capable of creating scripts from specifications.
Recursively matches a Tree structure with rules and returns a list of all contexts that are matched by the rules.
Make a summary of the following Python 3 code def match_rules_context_multi(tree, rules, parent_context={}): all_contexts = [] for template, match_rules in rules.items(): context = parent_context.copy() if match_template(tree, template, context): child_contextss = [] if n...
As a Python code composer, you craft elegant and concise scripts.
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...
Create a Python 3 function for checking if match string matches Tree structure
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if a stack of tokens matches the Tree structure
Here you have a function in Python 3, explain what it does def match_tokens(tree, tokens, args): arg_type_to_func = { 'r': get_raw_lower, 'R': get_raw, 'o': get_object_lower, 'O': get_object, } if len(tokens) == 0: return True if not isinstance(tree, Tree): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the object in the tree.
Can you tell what is the following Python 3 function doing def get_object(tree): if isinstance(tree, Tree): if tree.label() == 'DT' or tree.label() == 'POS': return '' words = [] for child in tree: words.append(get_object(child)) return ' '.join([_f for _f in ...
As a python code expert, you are capable of creating scripts from specifications.
Get the exact words in lowercase in the tree object.
Can you tell what is the following Python 3 function doing def get_raw(tree): if isinstance(tree, Tree): words = [] for child in tree: words.append(get_raw(child)) return ' '.join(words) else: return tree
As a Python code composer, you craft elegant and concise scripts.
Initializes the modules and the PySpark libraries for the current notebook.
Can you tell what is the following Python 3 function doing def initialize(spark_home_path: str = None): if not spark_home_path: spark_home_path = os.environ.get('SPARK_HOME') spark_home_path = environ.paths.clean(spark_home_path) if not os.path.exists(spark_home_path): raise FileNotFoundE...
You are a Python code architect, reviewing and designing scalable and efficient code
Whether or not this project is remote
Explain what the following Python 3 code does def is_remote_project(self) -> bool: project_path = environ.paths.clean(self.source_directory) return project_path.find('cd-remote-project') != -1
As a Python code composer, you craft elegant and concise scripts.
Returns a list of directories to all of the library locations that are needed by the project.
Make a summary of the following Python 3 code def library_directories(self) -> typing.List[str]: def listify(value): return [value] if isinstance(value, str) else list(value) # If this is a project running remotely remove external library # folders as the remote shared libraries fol...
As a Python code composer, you craft elegant and concise scripts.
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 )
Write a Python 3 function for returning the URL that will open this project s results file in the browser.
You are a Python code architect, reviewing and designing scalable and efficient code
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')
How would you implement a function in Python 3 that returns the directory where the project results files will be written
You are a Python code architect, reviewing and designing scalable and efficient code
Refreshes the project s cauldron. json definition file for the project and populates the project with the loaded data.
Here you have a function in Python 3, explain what it does def refresh(self, force: bool = False) -> bool: lm = self.last_modified is_newer = lm is not None and lm >= os.path.getmtime(self.source_path) if not force and is_newer: return False old_definition = self.settings.f...
As a Python code translator, you convert algorithms and pseudocode into Python.
Renders a preformatted text box.
Make a summary of the following Python 3 code def preformatted_text(source: str) -> str: 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)) )
You are a Python code generator, capable of creating scripts from specifications.
Renders a markdown file and returns the HTML for the notebook display.
Given the following Python 3 function, write the documentation 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...
You are a Python code architect, reviewing and designing scalable and efficient code