output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Displays the elapsed time since the current step started running.
Given the following Python 3 function, write the documentation def elapsed(): environ.abort_thread() step = _cd.project.get_internal_project().current_step r = _get_report() r.append_body(render.elapsed_time(step.elapsed_time)) result = '[ELAPSED]: {}\n'.format(timedelta(seconds=step.elapsed_time))...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_module(name: str) -> typing.Union[types.ModuleType, None]: """ Retrieves the loaded module for the given module name or returns None if no such module has been loaded. :param name: The name of the module to be retrieved :return: Either the loaded module with the specified na...
Create a Python 3 function to retrieve the loaded module with the given name or returns None if no such module has been loaded.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the name of the specified module in a bunch of ways to prevent incompatibility issues.
Can you tell what is the following Python 3 function doing def get_module_name(module: types.ModuleType) -> str: try: return module.__spec__.name except AttributeError: return module.__name__
You are a Python code generator, capable of creating scripts from specifications.
Executes the reload of the specified module if the source file that it was loaded from was modified more recently than the specified time.
Here you have a function in Python 3, explain what it does def do_reload(module: types.ModuleType, newer_than: int) -> bool: path = getattr(module, '__file__') directory = getattr(module, '__path__', [None])[0] if path is None and directory: path = os.path.join(directory, '__init__.py') last_m...
As a Python code analyst, you investigate and solve complex coding mysteries
def reload_children(parent_module: types.ModuleType, newer_than: int) -> bool: """ Reloads all imported children of the specified parent module object :param parent_module: A module object whose children should be refreshed if their currently loaded versions are out of date. :param newe...
How would you implement a function in Python 3 that reloads all imported children of the specified parent module object.
You are a Python code architect, reviewing and designing scalable and efficient code
def reload_module( module: typing.Union[str, types.ModuleType], recursive: bool, force: bool ) -> bool: """ Reloads the specified module, which can either be a module object or a string name of a module. Will not reload a module that has not been imported :param module: ...
Write a Python 3 function that can reload the specified module.
You are a Python code analyst, evaluating scripts for potential improvements.
def refresh( *modules: typing.Union[str, types.ModuleType], recursive: bool = False, force: bool = False ) -> bool: """ Checks the specified module or modules for changes and reloads them if they have been changed since the module was first imported or last refreshed. :param...
How would you code a function in Python 3 to reload the specified modules and returns True if any of them were refreshed False otherwise.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_args_index(target) -> int: """ Returns the index of the "*args" parameter if such a parameter exists in the function arguments or -1 otherwise. :param target: The target function for which the args index should be determined :return: The arguments index if it exists or -1 if...
Write a Python 3 function that can return the index of the "*args" parameter if such a parameter exists in the or - 1 otherwise.
As a Python code composer, you craft elegant and concise scripts.
Returns the index of the kwargs parameter if such a parameter exists in the .
Make a summary of the following Python 3 code def get_kwargs_index(target) -> int: code = target.__code__ if not bool(code.co_flags & inspect.CO_VARKEYWORDS): return -1 return ( code.co_argcount + code.co_kwonlyargcount + (1 if code.co_flags & inspect.CO_VARARGS else 0) ...
As a Python code composer, you craft elegant and concise scripts.
Gets the list of named arguments for the target function
Make a summary of the following Python 3 code def get_arg_names(target) -> typing.List[str]: code = getattr(target, '__code__') if code is None: return [] arg_count = code.co_argcount kwarg_count = code.co_kwonlyargcount args_index = get_args_index(target) kwargs_index = get_kwargs_in...
As a Python code analyst, you investigate and solve complex coding mysteries
def create_argument(target, name, description: str = '') -> dict: """ Creates a dictionary representation of the parameter :param target: The function object in which the parameter resides :param name: The name of the parameter :param description: The documentation descripti...
Write a Python 3 script for creating a dictionary representation of the parameter with the given name and description.
You are a Python code architect, reviewing and designing scalable and efficient code
Explode a line of a parameter line into a tuple containing the parameter name and the description parsed from the given argument line.
Explain what the following Python 3 code does def explode_line(argument_line: str) -> typing.Tuple[str, str]: parts = tuple(argument_line.split(' ', 1)[-1].split(':', 1)) return parts if len(parts) > 1 else (parts[0], '')
As a Python code translator, you convert algorithms and pseudocode into Python.
Pulls the latest version of the base image
Explain what the following Python 3 code does def update_base_image(path: str): with open(path, 'r') as file_handle: contents = file_handle.read() regex = re.compile('from\s+(?P<source>[^\s]+)', re.IGNORECASE) matches = regex.findall(contents) if not matches: return None match = m...
You are a Python code analyst, evaluating scripts for potential improvements.
def build(path: str) -> dict: """Builds the container from the specified docker file path""" update_base_image(path) match = file_pattern.search(os.path.basename(path)) build_id = match.group('id') tags = [ '{}:{}-{}'.format(HUB_PREFIX, version, build_id), '{}:latest-{}'.format(HUB_P...
Implement a function in Python 3 to build the container from the specified docker file path
As a python code expert, you are capable of creating scripts from specifications.
Publishes the specified build entry to docker hub
Can you tell what is the following Python 3 function doing def publish(build_entry: dict): for tag in build_entry['tags']: print('[PUSHING]:', tag) os.system('docker push {}'.format(tag))
As a python code expert, you are capable of creating scripts from specifications.
Parse command line arguments
Can you generate the documentation for the following Python 3 function def parse() -> dict: parser = ArgumentParser() parser.add_argument('-p', '--publish', action='store_true', default=False) return vars(parser.parse_args())
As a Python code analyst, you investigate and solve complex coding mysteries
Execute the build process
Can you generate the documentation for the following Python 3 function def run(): args = parse() build_results = [build(p) for p in glob.iglob(glob_path)] if not args['publish']: return for entry in build_results: publish(entry)
You are a Python code architect, reviewing and designing scalable and efficient code
def elapsed_time(seconds: float) -> str: """Displays the elapsed time since the current step started running.""" environ.abort_thread() parts = ( '{}'.format(timedelta(seconds=seconds)) .rsplit('.', 1) ) hours, minutes, seconds = parts[0].split(':') return templating.render_templ...
Can you create a Python 3 function that displays the elapsed time since the current step started running.
As a Python code translator, you convert algorithms and pseudocode into Python.
Renders an image block
How would you explain what the following Python 3 function does def image( rendered_path: str, width: int = None, height: int = None, justify: str = None ) -> str: """Renders an image block""" environ.abort_thread() return templating.render_template( 'image.html', ...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_environment_info() -> dict: """ Information about Cauldron and its Python interpreter. :return: A dictionary containing information about the Cauldron and its Python environment. This information is useful when providing feedback and bug reports. """ data = _environ....
How would you implement a function in Python 3 that returns a dictionary containing information about the Cauldron and its Python interpreter and Python environment.
You are a Python code architect, reviewing and designing scalable and efficient code
Run the cauldron http server used to interact with cauldron from a remote host.
Given the following Python 3 function, write the documentation def run_server(port=5010, debug=False, **kwargs): from cauldron.cli.server import run run.execute(port=port, debug=debug, **kwargs)
You are a Python code architect, reviewing and designing scalable and efficient code
def run_project( project_directory: str, output_directory: str = None, logging_path: str = None, reader_path: str = None, reload_project_libraries: bool = False, **kwargs ) -> ExecutionResult: """ Runs a project as a single command directly within the current Pyth...
Create a Python 3 function to run a single project as a single command directly within the current Python interpreter.
As a Python code composer, you craft elegant and concise scripts.
Joins the thread associated with the response.
How would you explain what the following Python 3 function does def join(self, timeout: float = None) -> bool: try: self.thread.join(timeout) return True except AttributeError: return False
As a Python code composer, you craft elegant and concise scripts.
Converts a serialized dictionary response to a Response object.
Explain what the following Python 3 code does def deserialize(serial_data: dict) -> 'Response': r = Response(serial_data.get('id')) r.data.update(serial_data.get('data', {})) r.ended = serial_data.get('ended', False) r.failed = not serial_data.get('success', True) def load_mess...
As a Python code analyst, you investigate and solve complex coding mysteries
def is_running(self) -> bool: """Specifies whether or not the thread is running""" return ( self._has_started and self.is_alive() or self.completed_at is None or (datetime.utcnow() - self.completed_at).total_seconds() < 0.5 )
Can you implement a function in Python 3 that specifies whether or not the thread is running.
You are a Python code architect, reviewing and designing scalable and efficient code
def run(self): """ Executes the Cauldron command in a thread to prevent long-running computations from locking the main Cauldron thread, which is needed to serve and print status information. """ async def run_command(): try: self.result = sel...
Write a Python 3 script for executing the Cauldron command in a thread and returns the result.
You are a Python code generator, capable of creating scripts from specifications.
Aborts the running command by stopping the event loop.
Can you generate the documentation for the following Python 3 function def abort_running(self) -> bool: if not self._loop: return False try: self._loop.stop() return True except Exception: return False finally: self.completed_...
You are a Python code architect, reviewing and designing scalable and efficient code
def from_request(request=None) -> dict: """ Fetches the arguments for the current Flask application request """ request = request if request else flask_request try: json_args = request.get_json(silent=True) except Exception: json_args = None try: get_args = request.values ...
Write a Python 3 script to fetch the arguments for the current Flask application request
As a Python code composer, you craft elegant and concise scripts.
Print a rule in a nice way.
Can you tell what is the following Python 3 function doing def print_rule(rule, feature_names=None, category_names=None, label="label", support=None): # type: (Rule, List[Union[str, None]], List[Union[List[str], None]], str, List[int]) -> str """ print the rule in a nice way :param rule: An instance of ...
You are a Python code architect, reviewing and designing scalable and efficient code
A helper function that converts the resulting string returned from C function to the Rule object
How would you explain what the following Python 3 function does def rule_str2rule(rule_str, prob): # type: (str, float) -> Rule """ A helper function that converts the resulting string returned from C function to the Rule object :param rule_str: a string representing the rule :param prob: the outpu...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a 2D array of pure categorical data representing whether the rule is fired by each input data.
Make a summary of the following Python 3 code def is_satisfied(self, x_cat): satisfied = [] if self.is_default(): return np.ones(x_cat.shape[0], dtype=bool) for idx, cat in self.clauses: satisfied.append(x_cat[:, idx] == cat) return reduce(np.logical_and, satisfie...
As a Python code composer, you craft elegant and concise scripts.
Fits the SBrl model on the given data and returns the model parameters and labels.
Can you generate a brief explanation for the following Python 3 code def fit(self, x, y): verbose = self.verbose # Create temporary files data_file = tempfile.NamedTemporaryFile("w+b", delete=False) label_file = tempfile.NamedTemporaryFile("w+b", delete=False) start = time.time(...
You are a Python code architect, reviewing and designing scalable and efficient code
A helper function that converts the results returned from C function to the equivalent Python object.
Can you generate a brief explanation for the following Python 3 code def from_raw(self, rule_ids, outputs, raw_rules): self._rule_pool = [([], [])] + raw_rules self._rule_list = [] for i, idx in enumerate(rule_ids): rule = Rule([Clause(f, c) for f, c in zip(*self._rule_pool[idx])], o...
As a Python code analyst, you investigate and solve complex coding mysteries
def compute_support(self, x, y): # type: (np.ndarray, np.ndarray) -> np.ndarray """ Calculate the support for the rules. The support of each rule is a list of `n_classes` integers: [l1, l2, ...]. Each integer represents the number of data of label i that is caught by this rule ...
Can you write a function in Python 3 where it computes the support for the rules.
As a Python code analyst, you investigate and solve complex coding mysteries
compute the caught matrix of x
Make a summary of the following Python 3 code def caught_matrix(self, x): # type: (np.ndarray) -> np.ndarray """ compute the caught matrix of x Each rule has an array of bools, showing whether each instances is caught by this rule :param x: 2D np.ndarray (n_instances, n_features)...
As a Python code translator, you convert algorithms and pseudocode into Python.
def decision_path(self, x): # type: (np.ndarray) -> np.ndarray """ compute the decision path of the rule list on x :param x: x should be already transformed :return: return a np.ndarray of shape [n_rules, n_instances] of type bool, representing whether an ...
How would you code a function in Python 3 to compute the decision path of the rule list on x
As a Python code composer, you craft elegant and concise scripts.
Adds one or more variables to the cache.
Can you generate a brief explanation for the following Python 3 code def put(self, *args, **kwargs) -> 'SharedCache': environ.abort_thread() index = 0 while index < (len(args) - 1): key = args[index] value = args[index + 1] self._shared_cache_data[key] = val...
As a Python code analyst, you investigate and solve complex coding mysteries
def grab( self, *keys: typing.List[str], default_value=None ) -> typing.Tuple: """ Returns a tuple containing multiple values from the cache specified by the keys arguments :param keys: One or more variable names stored in the cache th...
Can you implement a function in Python 3 that returns a tuple containing multiple values from the cache specified by the keys arguments
You are a Python code analyst, evaluating scripts for potential improvements.
def fetch(self, key: typing.Union[str, None], default_value=None): """ Retrieves the value of the specified variable from the cache :param key: The name of the variable for which the value should be returned :param default_value: The value to return if the variab...
Implement a function in Python 3 to retrieve the value of the specified variable from the cache.
You are a Python code analyst, evaluating scripts for potential improvements.
def train_sbrl(data_file, label_file, lambda_=20, eta=2, max_iters=300000, n_chains=20, alpha=1, seed=None, verbose=0): """ The basic training function of the scalable bayesian rule list. Users are suggested to use SBRL instead of this function. It takes the paths of the pre-processed data and label fil...
Implement a function in Python 3 to train a SBRL rule list using the SBRL model.
You are a Python code architect, reviewing and designing scalable and efficient code
Parses a line into a tree object
Can you tell what is the following Python 3 function doing def parse(self, line): tree = list(self.parser.raw_parse(line))[0] tree = tree[0] return tree
You are a Python code generator, capable of creating scripts from specifications.
Packs the specified binary source data into a base64 encoded string for the base64 - encoded version of the source data.
Make a summary of the following Python 3 code def pack_chunk(source_data: bytes) -> str: if not source_data: return '' chunk_compressed = zlib.compress(source_data) return binascii.b2a_base64(chunk_compressed).decode('utf-8')
You are a Python code generator, capable of creating scripts from specifications.
Unpacks a previously packed chunk data back into the original bytes representation.
Given the following Python 3 function, write the documentation def unpack_chunk(chunk_data: str) -> bytes: if not chunk_data: return b'' chunk_compressed = binascii.a2b_base64(chunk_data.encode('utf-8')) return zlib.decompress(chunk_compressed)
As a Python code analyst, you investigate and solve complex coding mysteries
def get_file_chunk_count( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> int: """ Determines the number of chunks necessary to send the file for the given chunk size :param file_path: The absolute path to the file that will be synchronized in chunks :param chunk_s...
Implement a Python 3 function for determining the number of chunks needed to send the file for the given file size
As a Python code analyst, you investigate and solve complex coding mysteries
def read_file_chunks( file_path: str, chunk_size: int = DEFAULT_CHUNK_SIZE ) -> bytes: """ Reads the specified file in chunks and returns a generator where each returned chunk is a compressed base64 encoded string for sync transmission :param file_path: The path to the file ...
Create a Python 3 function for reading the specified file in chunks and returns a generator where each returned chunk is a base64 encoded string for sync transmission
You are a Python code generator, capable of creating scripts from specifications.
def write_file_chunk( file_path: str, packed_chunk: str, append: bool = True, offset: int = -1 ): """ Write or append the specified chunk data to the given file path, unpacking the chunk before writing. If the file does not yet exist, it will be created. Set the append ar...
How would you code a function in Python 3 to write the specified chunk to the given file path.
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds the specified path to the output logging paths if it is not already in the list of paths.
How would you explain what the following Python 3 function does def add_output_path(path: str = None) -> str: cleaned = paths.clean(path or os.getcwd()) if cleaned not in _logging_paths: _logging_paths.append(cleaned) return cleaned
As a Python code composer, you craft elegant and concise scripts.
def remove_output_path(path: str = None) -> str: """ Removes the specified path from the output logging paths if it is in the listed paths. :param path: The path to remove from the logging output paths. If the path is empty or no path is given, the current working directory will be used...
Create a Python 3 function to remove the specified path from the output logging paths if it is in the listed paths.
As a Python code translator, you convert algorithms and pseudocode into Python.
def log( message: typing.Union[str, typing.List[str]], whitespace: int = 0, whitespace_top: int = 0, whitespace_bottom: int = 0, indent_by: int = 0, trace: bool = True, file_path: str = None, append_to_file: bool = True, **kwargs ) -> str: """ ...
Write a Python 3 function that can log a message to the console.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_to_message(data, indent_level=0) -> list: """Adds data to the message object""" message = [] if isinstance(data, str): message.append(indent( dedent(data.strip('\n')).strip(), indent_level * ' ' )) return message for line in data: offset...
Write a Python 3 function that can add data to the message object
You are a Python code analyst, evaluating scripts for potential improvements.
def add(mode_id: str) -> list: """ Adds the specified mode identifier to the list of active modes and returns a copy of the currently active modes list. """ if not has(mode_id): _current_modes.append(mode_id) return _current_modes.copy()
Create a Python 3 function for adding the specified mode identifier to the list of currently active modes and returns a copy of the currently active modes list.
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes the specified mode identifier from the currently active modes and returns True if the operation was carried out.
Given the following Python 3 function, write the documentation def remove(mode_id: str) -> bool: had_mode = has(mode_id) if had_mode: _current_modes.remove(mode_id) return had_mode
You are a Python code analyst, evaluating scripts for potential improvements.
def clone(client): '''Clone the redis client to be slowlog-compatible''' kwargs = client.redis.connection_pool.connection_kwargs kwargs['parser_class'] = redis.connection.PythonParser pool = redis.connection.ConnectionPool(**kwargs) return redis.Redis(connection_pool=pool)
Write a Python 3 function for cloning the redis client to be slowlog - compatible
As a python code expert, you are capable of creating scripts from specifications.
Get ready for a profiling run
Can you tell what is the following Python 3 function doing def start(self): '''Get ready for a profiling run''' self._configs = self._client.config_get('slow-*') self._client.config_set('slowlog-max-len', 100000) self._client.config_set('slowlog-log-slower-than', 0) self._client....
As a python code expert, you are capable of creating scripts from specifications.
Stop the slowlog and collect our data
Can you generate the documentation for the following Python 3 function def stop(self): '''Set everything back to normal and collect our data''' for key, value in self._configs.items(): self._client.config_set(key, value) logs = self._client.execute_command('slowlog', 'get', 100000) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def display(self): '''Print the results of this profiling''' self.pretty(self._timings, 'Raw Redis Commands') print() for key, value in self._commands.items(): self.pretty(value, 'Qless "%s" Command' % key) print()
Write a Python 3 script for printing the results of this profiling
You are a Python code analyst, evaluating scripts for potential improvements.
def add_shell_action(sub_parser: ArgumentParser) -> ArgumentParser: """Populates the sub parser with the shell arguments""" sub_parser.add_argument( '-p', '--project', dest='project_directory', type=str, default=None ) sub_parser.add_argument( '-l', '--log', ...
Create a Python 3 function for populating the sub parser with the shell arguments
As a Python code composer, you craft elegant and concise scripts.
Parses the command line arguments and returns a dictionary containing the parsed arguments.
Given the following Python 3 function, write the documentation def parse(args: list = None) -> dict: parser = ArgumentParser(description='Cauldron command') parser.add_argument( 'command', nargs='?', default='shell', help='The Cauldron command action to execute' ) parse...
As a Python code analyst, you investigate and solve complex coding mysteries
Return all currently - running jobs
Here you have a function in Python 3, explain what it does def running(self, offset=0, count=25): '''Return all the currently-running jobs''' return self.client('jobs', 'running', self.name, offset, count)
As a Python code translator, you convert algorithms and pseudocode into Python.
def stalled(self, offset=0, count=25): '''Return all the currently-stalled jobs''' return self.client('jobs', 'stalled', self.name, offset, count)
Write a Python 3 function for returning all currently - stalled jobs
As a Python code composer, you craft elegant and concise scripts.
def scheduled(self, offset=0, count=25): '''Return all the currently-scheduled jobs''' return self.client('jobs', 'scheduled', self.name, offset, count)
Create a Python 3 function to return all currently - scheduled jobs
As a python code expert, you are capable of creating scripts from specifications.
Return all the currently dependent jobs
Explain what the following Python 3 code does def depends(self, offset=0, count=25): '''Return all the currently dependent jobs''' return self.client('jobs', 'depends', self.name, offset, count)
As a Python code translator, you convert algorithms and pseudocode into Python.
def recurring(self, offset=0, count=25): '''Return all the recurring jobs''' return self.client('jobs', 'recurring', self.name, offset, count)
Can you implement a function in Python 3 that returns all the recurring jobs
As a python code expert, you are capable of creating scripts from specifications.
def class_string(self, klass): '''Return a string representative of the class''' if isinstance(klass, string_types): return klass return klass.__module__ + '.' + klass.__name__
How would you code a function in Python 3 to return a string representative of the class
You are a Python code generator, capable of creating scripts from specifications.
def put(self, klass, data, priority=None, tags=None, delay=None, retries=None, jid=None, depends=None): '''Either create a new job in the provided queue with the provided attributes, or move that job into that queue. If the job is being serviced by a worker, subsequent attempts by that w...
Can you write a function in Python 3 where it puts a job into the provided queue.
As a Python code translator, you convert algorithms and pseudocode into Python.
Place a recurring job in this queue
Make a summary of the following Python 3 code def recur(self, klass, data, interval, offset=0, priority=None, tags=None, retries=None, jid=None): '''Place a recurring job in this queue''' return self.client('recur', self.name, jid or uuid.uuid4().hex, self.class_string(kl...
You are a Python code generator, capable of creating scripts from specifications.
def pop(self, count=None): '''Passing in the queue from which to pull items, the current time, when the locks for these returned items should expire, and the number of items to be popped off.''' results = [Job(self.client, **job) for job in json.loads( self.client('pop', self...
Write a Python 3 function that can pass in the queue from which to pull items the current time the current time when the locks for these items should expire and the number of items to be popped off.
As a python code expert, you are capable of creating scripts from specifications.
Return the current statistics for a given queue on a given date.
How would you explain what the following Python 3 function does def stats(self, date=None): '''Return the current statistics for a given queue on a given date. The results are returned are a JSON blob:: { 'total' : ..., 'mean' : ..., 'v...
As a Python code composer, you craft elegant and concise scripts.
Runs the markdown file and renders the contents to the notebook display
How would you explain what the following Python 3 function does def run( project: 'projects.Project', step: 'projects.ProjectStep' ) -> dict: """ Runs the markdown file and renders the contents to the notebook display :param project: :param step: :return: A run response dict...
You are a Python code generator, capable of creating scripts from specifications.
def fetch(reload: bool = False) -> dict: """ Returns a dictionary containing all of the available Cauldron commands currently registered. This data is cached for performance. Unless the reload argument is set to True, the command list will only be generated the first time this function is called. ...
Implement a function in Python 3 to return a dictionary containing all of the available Cauldron commands currently registered.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the execution command to use for the specified module
Explain what the following Python 3 code does def get_command_from_module( command_module, remote_connection: environ.RemoteConnection ): """ Returns the execution command to use for the specified module, which may be different depending upon remote connection :param command_module: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Prints the basic command help to the console
Explain what the following Python 3 code does def show_help(command_name: str = None, raw_args: str = '') -> Response: response = Response() cmds = fetch() if command_name and command_name in cmds: parser, result = parse.get_parser( cmds[command_name], parse.explode_line(ra...
As a Python code analyst, you investigate and solve complex coding mysteries
def _import(klass): '''1) Get a reference to the module 2) Check the file that module's imported from 3) If that file's been updated, force a reload of that module return it''' mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]:...
How would you code a function in Python 3 to import a class and check its modification time
As a python code expert, you are capable of creating scripts from specifications.
def process(self): '''Load the module containing your class, and run the appropriate method. For example, if this job was popped from the queue ``testing``, then this would invoke the ``testing`` staticmethod of your class.''' try: method = getattr(self.klass, self.qu...
Write a Python 3 script for loading the module containing your class and run the appropriate method.
You are a Python code analyst, evaluating scripts for potential improvements.
Move this job into another queue.
Can you generate the documentation for the following Python 3 function def move(self, queue, delay=0, depends=None): '''Move this job out of its existing state and into another queue. If a worker has been given this job, then that worker's attempts to heartbeat that job will fail. Like ``Queue.p...
As a Python code translator, you convert algorithms and pseudocode into Python.
Turn this job in as complete optionally advancing it to another queue. Like Queue. put and Move it accepts a delay and the dependencies.
Given the following Python 3 function, write the documentation def complete(self, nextq=None, delay=None, depends=None): '''Turn this job in as complete, optionally advancing it to another queue. Like ``Queue.put`` and ``move``, it accepts a delay, and dependencies''' if nextq: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Renew the heartbeat if possible and optionally update the job s user data.
Here you have a function in Python 3, explain what it does def heartbeat(self): '''Renew the heartbeat, if possible, and optionally update the job's user data.''' logger.debug('Heartbeating %s (ttl = %s)', self.jid, self.ttl) try: self.expires_at = float(self.client('heartbea...
You are a Python code generator, capable of creating scripts from specifications.
Mark the particular job as failed and return the id of the job that was cancelled or False on failure.
Can you tell what is the following Python 3 function doing def fail(self, group, message): '''Mark the particular job as failed, with the provided type, and a more specific message. By `type`, we mean some phrase that might be one of several categorical modes of failure. The `message` is ...
You are a Python code architect, reviewing and designing scalable and efficient code
def retry(self, delay=0, group=None, message=None): '''Retry this job in a little bit, in the same queue. This is meant for the times when you detect a transient failure yourself''' args = ['retry', self.jid, self.queue_name, self.worker_name, delay] if group is not None and message is n...
Can you write a function in Python 3 where it retries this job in a little bit in the same queue.
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes specific job dependencies from this job
Explain what the following Python 3 code does def undepend(self, *args, **kwargs): '''Remove specific (or all) job dependencies from this job: job.remove(jid1, jid2) job.remove(all=True)''' if kwargs.get('all', False): return self.client('depends', self.jid, 'off', '...
As a Python code translator, you convert algorithms and pseudocode into Python.
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 ...
Create a Python 3 function to check to see if the given file path ends with any of the specified file_extensions.
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Write a Python 3 script to return the documentation string for the given object.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the lines of documentation from the given target which are formatted by the user.
Can you tell what is the following Python 3 function doing def get_doc_entries(target: typing.Callable) -> list: raw = get_docstring(target) if not raw: return [] raw_lines = [ line.strip() for line in raw.replace('\r', '').split('\n') ] def compactify(compacted: list, en...
As a Python code composer, you craft elegant and concise scripts.
def parse_function( name: str, target: typing.Callable ) -> typing.Union[None, dict]: """ Parses the documentation for a function, which is specified by the name of the function and the function itself. :param name: Name of the function to parse :param target: The fu...
Create a Python 3 function to parse the documentation for a function.
As a Python code composer, you craft elegant and concise scripts.
Returns a dictionary with the value of a variable.
Can you generate the documentation for the following Python 3 function def variable(name: str, target: property) -> typing.Union[None, dict]: if hasattr(target, 'fget'): doc = parse_function(name, target.fget) if doc: doc['read_only'] = bool(target.fset is None) return doc ...
As a python code expert, you are capable of creating scripts from specifications.
def read_all(self) -> str: """ Reads the current state of the buffer and returns a string those contents :return: A string for the current state of the print buffer contents """ try: buffered_bytes = self.bytes_buffer.getvalue() if buf...
Can you create a Python 3 function that reads the current state of the buffer and returns a string that is the current state of the print buffer.
As a Python code composer, you craft elegant and concise scripts.
Flushes all the bytes in the buffer and returns the string.
Explain what the following Python 3 code does def flush_all(self) -> str: # 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_...
As a Python code composer, you craft elegant and concise scripts.
def create_data(step: 'projects.ProjectStep') -> STEP_DATA: """ Creates the data object that stores the step information in the notebook results JavaScript file. :param step: Project step for which to create the data :return: Step data tuple containing scaffold data structure for th...
Write a Python 3 function for creating the data object that stores the step information in the notebook results JavaScript file.
You are a Python code architect, reviewing and designing scalable and efficient code
Loads and returns the cached data for the specified step.
Here you have a function in Python 3, explain what it does 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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
def initialize_logging_path(path: str = None) -> str: """ Initializes the logging path for running the project. If no logging path is specified, the current directory will be used instead. :param path: Path to initialize for logging. Can be either a path to a file or a path to a directo...
How would you code a function in Python 3 to initialize the logging path for running the project.
As a Python code composer, you craft elegant and concise scripts.
Executes a Cauldron project in a single mode.
Can you generate a brief explanation for the following Python 3 code 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...
As a Python code translator, you convert algorithms and pseudocode into Python.
def stop(self, sig=signal.SIGINT): '''Stop all the workers, and then wait for them''' for cpid in self.sandboxes: logger.warn('Stopping %i...' % cpid) try: os.kill(cpid, sig) except OSError: # pragma: no cover logger.exception('Error s...
How would you implement a function in Python 3 that stops all the workers and then wait for them to finish.
As a python code expert, you are capable of creating scripts from specifications.
def spawn(self, **kwargs): '''Return a new worker for a child process''' copy = dict(self.kwargs) copy.update(kwargs) # Apparently there's an issue with importing gevent in the parent # process and then using it int he child. This is meant to relieve that # problem by all...
Create a Python 3 function for returning a new worker for a child process
You are a Python code generator, capable of creating scripts from specifications.
def handler(self, signum, frame): # pragma: no cover '''Signal handler for this process''' if signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT): self.stop(signum) os._exit(0)
Implement a Python 3 function for signaling handler for this process
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a list of the current stack frames.
Explain what the following Python 3 code does def get_stack_frames(error_stack: bool = True) -> list: 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_st...
You are a Python code generator, capable of creating scripts from specifications.
Formats a raw stack frame into a dictionary for templating and enriched with information from the currently open project.
Make a summary of the following Python 3 code def format_stack_frame(stack_frame, project: 'projects.Project') -> dict: filename = stack_frame.filename if filename.startswith(project.source_directory): filename = filename[len(project.source_directory) + 1:] location = stack_frame.name if locat...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a list of the stack frames formatted for user display that has been enriched by the project - specific data.
Here you have a function in Python 3, explain what it does 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 p...
As a Python code composer, you craft elegant and concise scripts.
def arg_type_to_string(arg_type) -> str: """ Converts the argument type to a string :param arg_type: :return: String representation of the argument type. Multiple return types are turned into a comma delimited list of type names """ union_params = ( getattr(arg_type, '_...
Write a Python 3 function for converting the argument type to a string representation of the argument type. Multiple return types are
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Create a Python 3 function to merge multiple COMPONENT instances into a single COMPONENT instance.
You are a Python code generator, capable of creating scripts from specifications.
Flattens a list of COMPONENT instances to remove any lists or tuples of COMPONENTS contained within the list
How would you explain what the following Python 3 function does 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 flatt...
As a python code expert, you are capable of creating scripts from specifications.