output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Create the task using the injector initialization.
Make a summary of the following Python 3 code def _create_result(self, cls): # type:(Callable)->Tuple[Any, Callable] """ Create the task using the injector initialization. :param cls: :return: """ task = instantiate(cls) logging.getLogger(__name__).debug("...
You are a Python code generator, capable of creating scripts from specifications.
def abi_to_fasta(input, output): ''' Converts ABI or AB1 files to FASTA format. Args: input (str): Path to a file or directory containing abi/ab1 files or zip archives of abi/ab1 files output (str): Path to a directory for the output FASTA files ''' direcs = [input, ]...
Can you implement a function in Python 3 that converts ABI or AB1 files to FASTA format.
As a python code expert, you are capable of creating scripts from specifications.
Extends an instance with new_class.
Can you tell what is the following Python 3 function doing def extend(instance, new_class): instance.__class__ = type( '%s_extended_with_%s' % (instance.__class__.__name__, new_class.__name__), (new_class, instance.__class__,), {} )
You are a Python code analyst, evaluating scripts for potential improvements.
Generates a list of models for Backbone Javascript applications.
Given the following Python 3 function, write the documentation def generate_js_models(module, models, collection_prefix, model_prefix, model_fn, collection_fn, marker, integrate, js_file): # type: (str, str, str, str, str, str, str, bool, str) -> Union[str, None] """Generate models for Ba...
You are a Python code generator, capable of creating scripts from specifications.
def _map_table_name(self, model_names): """ Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class, tak si to namapujme """ for model in model_names: if isinstance(model, tuple): model = model[0] try: model_cls = get...
Write a Python 3 script for mapping the model names to the corresponding table name.
You are a Python code generator, capable of creating scripts from specifications.
Push a message to the cache.
Explain what the following Python 3 code does def push_msg(self, channel_id, msg): if type(msg) is not str: msg = urlencode(msg) return self.push(channel_id, msg)
You are a Python code architect, reviewing and designing scalable and efficient code
Push an object to the cache.
How would you explain what the following Python 3 function does def push_object(self, channel_id, obj): return self.push(channel_id, json.dumps(obj).replace('"', '\\"'))
As a Python code translator, you convert algorithms and pseudocode into Python.
def push(self, channel_id, data): """Push message with POST ``data`` for ``channel_id`` """ channel_path = self.channel_path(channel_id) response = requests.post(channel_path, data) return response.json()
Implement a Python 3 function for pushing a message with POST data for channel_id
You are a Python code generator, capable of creating scripts from specifications.
def delete_channel(self, channel_id): """Deletes channel """ req = requests.delete(self.channel_path(channel_id)) return req
Write a Python 3 function for deleting a channel from the cache
As a Python code translator, you convert algorithms and pseudocode into Python.
def slugify(value, allow_unicode=False): """Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. :param value: string :param allow_unicode: allow utf8 characters :type allow_unicode: bool :return: slugified string :rtype: str :Example:...
How would you implement a function in Python 3 that normalizes string converts to lowercase removes non - alpha characters removes non - alpha characters removes spaces to hyphens.
As a Python code translator, you convert algorithms and pseudocode into Python.
Encode string to be used in urls ( percent encoding.
Explain what the following Python 3 code does def urlencode(query): if hasattr(urllib, 'parse'): return urllib.parse.urlencode(query) else: return urllib.urlencode(query)
As a Python code translator, you convert algorithms and pseudocode into Python.
Initializes the application objects for the given base application level.
Here you have a function in Python 3, explain what it does def initialize(): from zsl.interface.web.performers.default import create_not_found_mapping from zsl.interface.web.performers.resource import create_resource_mapping create_not_found_mapping() create_resource_mapping()
You are a Python code architect, reviewing and designing scalable and efficient code
Alias for Flask. run
Can you generate a brief explanation for the following Python 3 code def run_web(self, flask, host='127.0.0.1', port=5000, **options): # type: (Zsl, str, int, **Any)->None """Alias for Flask.run""" return flask.run( host=flask.config.get('FLASK_HOST', host), port=flask.co...
As a Python code analyst, you investigate and solve complex coding mysteries
Execute a command in the cache.
Make a summary of the following Python 3 code def execute_command(self, command, args=None): if args is None: args = {} command_fn = self.commands[command] return command_fn(**args)
As a python code expert, you are capable of creating scripts from specifications.
Returns a new dispatcher which will switch all command functions with bounded methods of given instance.
Here you have a function in Python 3, explain what it does def bound(self, instance): bounded_dispatcher = CommandDispatcher() bounded_dispatcher.commands = self.commands.copy() for name in self.commands: method = getattr(instance, name, None) if method and inspect.ism...
As a python code expert, you are capable of creating scripts from specifications.
def compress_and_upload(data, compressed_file, s3_path, multipart_chunk_size_mb=500, method='gz', delete=False, access_key=None, secret_key=None): ''' Compresses data and uploads to S3. S3 upload uses ``s3cmd``, so you must either: 1) Manually configure ``s3cmd`` prior to use (typically using ...
How would you code a function in Python 3 to compress data and uploads to S3.
You are a Python code architect, reviewing and designing scalable and efficient code
def put(f, s3_path, multipart_chunk_size_mb=500, logger=None): ''' Uploads a single file to S3, using s3cmd. Args: f (str): Path to a single file. s3_path (str): The S3 path, with the filename omitted. The S3 filename will be the basename of the ``f``. For example:: ...
Implement a function in Python 3 to upload a single file to S3 using s3cmd.
As a Python code analyst, you investigate and solve complex coding mysteries
def compress(d, output, fmt='gz', logger=None): ''' Creates a compressed/uncompressed tar file. Args: d: Can be one of three things: 1. the path to a single file, as a string 2. the path to a single directory, as a string 3. an iterable of file or directory p...
Write a Python 3 function that can compress a set of files or directories.
As a Python code composer, you craft elegant and concise scripts.
Configure s3cmd prior to first use.
Given the following Python 3 function, write the documentation def configure(access_key=None, secret_key=None, logger=None): ''' Configures s3cmd prior to first use. If no arguments are provided, you will be prompted to enter the access key and secret key interactively. Args: access_key (...
As a Python code translator, you convert algorithms and pseudocode into Python.
def required_params(data, *r_params): """Check if given parameters are in the given dict, if not raise an exception. :param data: data to check :type data: dict :param r_params: required parameters :raises RequestException: if params not in data """ if not reduce(lambda still_valid, pa...
Create a Python 3 function for checking if given parameters are in the given dict raises RequestException if not
You are a Python code generator, capable of creating scripts from specifications.
def safe_args(fn, args): """Check if ``args`` as a dictionary has the required parameters of ``fn`` function and filter any waste parameters so ``fn`` can be safely called with them. :param fn: function object :type fn: Callable :param args: dictionary of parameters :type args: dict :re...
Can you write a function in Python 3 where it checks if args as a dictionary has the required parameters of fn and filter any waste parameters so fn can be safely called with them.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a pymongo Database object.
How would you explain what the following Python 3 function does def get_db(db, ip='localhost', port=27017, user=None, password=None): ''' Returns a pymongo Database object. .. note: Both ``user`` and ``password`` are required when connecting to a MongoDB database that has authentication en...
As a Python code composer, you craft elegant and concise scripts.
def get_collections(db, collection=None, prefix=None, suffix=None): ''' Returns a sorted list of collection names found in ``db``. Arguments: db (Database): A pymongo Database object. Can be obtained with ``get_db``. collection (str): Name of a collection. If the collection is...
Can you implement a function in Python 3 that returns a sorted list of collection names found in a MongoDB database.
As a Python code translator, you convert algorithms and pseudocode into Python.
def rename_collection(db, collection, new_name): ''' Renames a MongoDB collection. Arguments: db (Database): A pymongo Database object. Can be obtained with ``get_db``. collection (str): Name of the collection to be renamed. new_name (str, func): ``new_name`` can be o...
How would you code a function in Python 3 to rename a MongoDB collection.
As a Python code translator, you convert algorithms and pseudocode into Python.
def update(field, value, db, collection, match=None): ''' Updates MongoDB documents. Sets ``field`` equal to ``value`` for all documents that meet ``match`` criteria. Arguments: field (str): Field to update. value (str): Update value. db (Database): A pymongo Database ob...
Write a Python 3 script to update the value of the field in the specified collection with the given value.
As a python code expert, you are capable of creating scripts from specifications.
def mongoimport(json, database, ip='localhost', port=27017, user=None, password=None, delim='_', delim1=None, delim2=None, delim_occurance=1, delim1_occurance=1, delim2_occurance=1): ''' Performs mongoimport on one or more json files. Args: ...
Implement a function in Python 3 to perform mongoimport on one or more json files. Args: json: Can be one of several things: - path to a single JSON file - an iterable (list or tuple) of one or more JSON file paths - path to a directory containing one or more JSON files database (str): Name of the database into which t...
You are a Python code analyst, evaluating scripts for potential improvements.
def index(db, collection, fields, directions=None, desc=False, background=False): ''' Builds a simple (single field) or complex (multiple fields) index on a single collection in a MongoDB database. Args: db (Database): A pymongo Database object. collection (str): Collection name. ...
How would you implement a function in Python 3 that builds a simple or complex index on a single collection.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the configuration file path for the given profile.
Explain what the following Python 3 code does def get_settings_from_profile(profile, profile_dir=None): # type: (str, Any)->str """"Returns the configuration file path for the given profile. :param profile: Profile name to be used. :param profile_dir: The directory where the profile configuration file...
You are a Python code architect, reviewing and designing scalable and efficient code
def _configure(self, config_object=None): # type: (Any) -> None """Read the configuration from config files. Loads the default settings and the profile settings if available. Check :func:`.set_profile`. :param config_object: This parameter is the configuration decscr...
Implement a function in Python 3 to read the configuration from config files.
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_app_module(self): # type: () -> Callable """Returns a module which binds the current app and configuration. :return: configuration callback :rtype: Callable """ def configure(binder): # type: (Binder) -> Callable binder.bind(ServiceAppli...
Can you create a Python 3 function that returns a function which binds the current app and configuration.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _configure_injector(self, modules): """Create the injector and install the modules. There is a necessary order of calls. First we have to bind `Config` and `Zsl`, then we need to register the app into the global stack and then we can install all other modules, which can use `Zsl` an...
Create a Python 3 function for creating the injector and install the modules.
As a Python code translator, you convert algorithms and pseudocode into Python.
def configure(self, binder): # type: (Binder) -> None """Initializer of the cache - creates the Redis cache module as the default cache infrastructure. The module is bound to `RedisCacheModule` and `CacheModule` keys. The initializer also creates `RedisIdHelper` and bounds it to ...
Can you write a function in Python 3 where it creates the Redis cache module and RedisIdHelper classes.
As a Python code composer, you craft elegant and concise scripts.
Decorator for error handling.
Explain what the following Python 3 code does def error_handler(f): @wraps(f) def error_handling_function(*args, **kwargs): @inject(error_config=ErrorConfiguration) def get_error_configuration(error_config): # type:(ErrorConfiguration)->ErrorConfiguration return error_co...
You are a Python code architect, reviewing and designing scalable and efficient code
A property decorator that returns a property that will be evaluated once.
Can you tell what is the following Python 3 function doing def lazy_property(func): ''' Wraps a property to provide lazy evaluation. Eliminates boilerplate. Also provides for setting and deleting the property. Use as you would use the @property decorator:: # OLD: class MyClass(): ...
As a python code expert, you are capable of creating scripts from specifications.
A coroutine function that returns a sequence of objects.
Given the following Python 3 function, write the documentation def coroutine(func): ''' Initializes a coroutine -- essentially it just takes a generator function and calls generator.next() to get things going. ''' def start(*args, **kwargs): cr = func(*args, **kwargs) cr.next() ...
As a Python code composer, you craft elegant and concise scripts.
Returns the sequence as a FASTA - formatted string
Can you tell what is the following Python 3 function doing def fasta(self): ''' str: Returns the sequence, as a FASTA-formatted string Note: The FASTA string is built using ``Sequence.id`` and ``Sequence.sequence``. ''' if not self._fasta: self._fasta = '>{}\n{}'.for...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the sequence as a FASTQ - formatted string
Make a summary of the following Python 3 code def fastq(self): ''' str: Returns the sequence, as a FASTQ-formatted string If ``Sequence.qual`` is ``None``, then ``None`` will be returned instead of a FASTQ string ''' if self.qual is None: self._fastq = None ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a string representation of the sequence in FASTA format.
How would you explain what the following Python 3 function does def region(self, start=0, end=None): ''' Returns a region of ``Sequence.sequence``, in FASTA format. If called without kwargs, the entire sequence will be returned. Args: start (int): Start position of the reg...
You are a Python code analyst, evaluating scripts for potential improvements.
def underscore_to_camelcase(value, first_upper=True): """Transform string from underscore_string to camelCase. :param value: string with underscores :param first_upper: the result will have its first character in upper case :type value: str :return: string in CamelCase or camelCase according to the...
How would you code a function in Python 3 to transform string from underscore_string to camelCase.
You are a Python code architect, reviewing and designing scalable and efficient code
Simple method to get stripped text from node or default string if None is given.
Can you generate a brief explanation for the following Python 3 code def et_node_to_string(et_node, default=''): return str(et_node.text).strip() if et_node is not None and et_node.text else default
As a Python code composer, you craft elegant and concise scripts.
Generate random string. :param size: Length of the returned string. Default is 6. :param chars: List of the usable characters. Default is string.ascii_uppercase + string.digits. :type size: int :type chars: str :return: The random string. :rtype: str
How would you explain what the following Python 3 function does def generate_random_string(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size))
You are a Python code generator, capable of creating scripts from specifications.
def addslashes(s, escaped_chars=None): """Add slashes for given characters. Default is for ``\`` and ``'``. :param s: string :param escaped_chars: list of characters to prefix with a slash ``\`` :return: string with slashed characters :rtype: str :Example: >>> addslashes("'") "...
Can you create a Python 3 function that adds slashes for given characters. Default is for \ and \.
As a Python code translator, you convert algorithms and pseudocode into Python.
Joins the given values using the given delimiter.
Can you tell what is the following Python 3 function doing def join_list(values, delimiter=', ', transform=None): # type: (Union[List[str], str], str)->str if transform is None: transform = _identity if values is not None and not isinstance(values, (str, bytes)): values = delimiter.join(tra...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function will align a list of sequences with MAFFT.
Can you generate a brief explanation for the following Python 3 code def mafft(sequences=None, alignment_file=None, fasta=None, fmt='fasta', threads=-1, as_file=False, reorder=True, print_stdout=False, print_stderr=False, mafft_bin=None): ''' Performs multiple sequence alignment with MAFFT. Args:...
You are a Python code architect, reviewing and designing scalable and efficient code
This function will align a list of sequences with MUSCLE using the MUSCLE command line tool.
How would you explain what the following Python 3 function does def muscle(sequences=None, alignment_file=None, fasta=None, fmt='fasta', as_file=False, maxiters=None, diags=False, gap_open=None, gap_extend=None, muscle_bin=None): ''' Performs multiple sequence alignment with MUSCLE. Args: ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a string that can be used to align a sequence with a local pairwise alignment.
Given the following Python 3 function, write the documentation def local_alignment(query, target=None, targets=None, match=3, mismatch=-2, gap_open=-5, gap_extend=-2, matrix=None, aa=False, gap_open_penalty=None, gap_extend_penalty=None): ''' Striped Smith-Waterman local pairwise alignment. Args: ...
You are a Python code architect, reviewing and designing scalable and efficient code
This function calculates a global pairwise alignment of the given sequence.
Explain what the following Python 3 code does def global_alignment(query, target=None, targets=None, match=3, mismatch=-2, gap_open=-5, gap_extend=-2, score_match=None, score_mismatch=None, score_gap_open=None, score_gap_extend=None, matrix=None, aa=False): ''' Needleman-Wunch global pairwise al...
As a Python code composer, you craft elegant and concise scripts.
def dot_alignment(sequences, seq_field=None, name_field=None, root=None, root_name=None, cluster_threshold=0.75, as_fasta=False, just_alignment=False): ''' Creates a dot alignment (dots indicate identity, mismatches are represented by the mismatched residue) for a list of sequences. Args: ...
Write a Python 3 script for returning a list of dot aligned sequences for a list of sequences.
As a Python code composer, you craft elegant and concise scripts.
Fetches the given class.
Explain what the following Python 3 code does def fetch_class(full_class_name): (module_name, class_name) = full_class_name.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, class_name)
You are a Python code architect, reviewing and designing scalable and efficient code
Verify exercises of the type MultipleChoiceExercise
Here you have a function in Python 3, explain what it does def has_chosen(state, correct, msgs): ctxt = {} exec(state.student_code, globals(), ctxt) sel_indx = ctxt["selected_option"] if sel_indx != correct: state.report(Feedback(msgs[sel_indx - 1])) else: state.reporter.success_msg...
You are a Python code architect, reviewing and designing scalable and efficient code
Run multiple subtests. Return original state.
Explain what the following Python 3 code does def multi(state, *tests): for test in iter_tests(tests): # assume test is function needing a state argument # partial state so reporter can test state.do_test(partial(test, state)) # return original state, so can be chained return state
As a Python code analyst, you investigate and solve complex coding mysteries
Run multiple sub - tests that fail. Returns original state so can be chained.
Explain what the following Python 3 code does def check_not(state, *tests, msg): for test in iter_tests(tests): try: test(state) except TestFail: # it fails, as expected, off to next one continue return state.report(Feedback(msg)) # return original st...
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_or(state, *tests): """Test whether at least one SCT passes. If all of the tests fail, the feedback of the first test will be presented to the student. Args: state: State instance describing student and solution code, can be omitted if used with Ex() tests: one or more sub-SCTs to...
How would you code a function in Python 3 to test whether at least one SCT passes.
You are a Python code generator, capable of creating scripts from specifications.
def check_correct(state, check, diagnose): """Allows feedback from a diagnostic SCT, only if a check SCT fails. Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). check: An sct chain that must succeed. diagnose: An sct chain to run if the...
Implement a Python 3 function for allowing feedback from a diagnostic SCT only if a check SCT fails.
You are a Python code analyst, evaluating scripts for potential improvements.
def required_attributes(element, *attributes): """Check element for required attributes. Raise ``NotValidXmlException`` on error. :param element: ElementTree element :param attributes: list of attributes names to check :raises NotValidXmlException: if some argument is missing """ if not reduce(...
Create a Python 3 function for checking element for required attributes. Raise NotValidXmlException on error.
As a python code expert, you are capable of creating scripts from specifications.
def required_elements(element, *children): """Check element (``xml.etree.ElementTree.Element``) for required children, defined as XPath. Raise ``NotValidXmlException`` on error. :param element: ElementTree element :param children: list of XPaths to check :raises NotValidXmlException: if some child ...
Write a Python 3 script for checking element for required children defined as XPath. Raise NotValidXmlException on error.
You are a Python code architect, reviewing and designing scalable and efficient code
def required_items(element, children, attributes): """Check an xml element to include given attributes and children. :param element: ElementTree element :param children: list of XPaths to check :param attributes: list of attributes names to check :raises NotValidXmlException: if some argument is mi...
Write a Python 3 script for checking an xml element to include given attributes and children.
You are a Python code architect, reviewing and designing scalable and efficient code
For an ElementTree element extract specified attributes.
Explain what the following Python 3 code does def attrib_to_dict(element, *args, **kwargs): if len(args) > 0: return {key: element.get(key) for key in args} if len(kwargs) > 0: return {new_key: element.get(old_key) for new_key, old_key in viewitems(kwargs)} return element.attrib
As a Python code composer, you craft elegant and concise scripts.
Load and parse an xml by given xml_path and return its root.
Given the following Python 3 function, write the documentation def get_xml_root(xml_path): r = requests.get(xml_path) root = ET.fromstring(r.content) return root
As a Python code composer, you craft elegant and concise scripts.
def element_to_int(element, attribute=None): """Convert ``element`` object to int. If attribute is not given, convert ``element.text``. :param element: ElementTree element :param attribute: attribute name :type attribute: str :returns: integer :rtype: int """ if attribute is not None: ...
Can you write a function in Python 3 where it converts element object to int.
You are a Python code analyst, evaluating scripts for potential improvements.
def create_el(name, text=None, attrib=None): """Create element with given attributes and set element.text property to given text value (if text is not None) :param name: element name :type name: str :param text: text node value :type text: str :param attrib: attributes :type attrib: dic...
Implement a Python 3 function for creating element with given attributes and set element. text property to given text value
You are a Python code generator, capable of creating scripts from specifications.
def modules(cls): """Collect all the public class attributes. All class attributes should be a DI modules, this method collects them and returns as a list. :return: list of DI modules :rtype: list[Union[Module, Callable]] """ members = inspect.getmembers(cls, la...
Can you create a Python 3 function that collects all the public class attributes. This method returns as a list of DI modules.
As a python code expert, you are capable of creating scripts from specifications.
Gets sequences and assigns them to the appropriate mAb pair.
Explain what the following Python 3 code does def get_pairs(db, collection, experiment=None, subject=None, group=None, name='seq_id', delim=None, delim_occurance=1, pairs_only=False, h_selection_func=None, l_selection_func=None): ''' Gets sequences and assigns them to the appropriate mAb pair, based on the ...
You are a Python code generator, capable of creating scripts from specifications.
Assigns sequences to the appropriate mAb pair based on the sequence name.
Make a summary of the following Python 3 code def assign_pairs(seqs, name='seq_id', delim=None, delim_occurance=1, pairs_only=False, h_selection_func=None, l_selection_func=None): ''' Assigns sequences to the appropriate mAb pair, based on the sequence name. Inputs: ::seqs:: is a list...
As a python code expert, you are capable of creating scripts from specifications.
Removes duplicate sequences from a list of Pair objects.
Can you generate a brief explanation for the following Python 3 code def deduplicate(pairs, aa=False, ignore_primer_regions=False): ''' Removes duplicate sequences from a list of Pair objects. If a Pair has heavy and light chains, both chains must identically match heavy and light chains from another P...
As a python code expert, you are capable of creating scripts from specifications.
Refine the 5 end of a truncated sequence with germline nucleotides.
Here you have a function in Python 3, explain what it does def _refine_v(seq, species): ''' Completes the 5' end of a a truncated sequence with germline nucleotides. Input is a MongoDB dict (seq) and the species. ''' vgerm = germlines.get_germline(seq['v_gene']['full'], species) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _refine_j(seq, species): ''' Completes the 3' end of a a truncated sequence with germline nucleotides. Input is a MongoDB dict (seq) and the species. ''' jgerm = germlines.get_germline(seq['j_gene']['full'], species) aln = global_alignment(seq['vdj_nt'], jgerm) ...
How would you implement a function in Python 3 that refines the 3 end of a truncated sequence with germline nucleotides.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the sequence pair as a string.
Explain what the following Python 3 code does def fasta(self, key='vdj_nt', append_chain=True): ''' Returns the sequence pair as a fasta string. If the Pair object contains both heavy and light chain sequences, both will be returned as a single string. By default, the fasta string conta...
You are a Python code architect, reviewing and designing scalable and efficient code
def cmap_from_color(color, dark=False): ''' Generates a matplotlib colormap from a single color. Colormap will be built, by default, from white to ``color``. Args: color: Can be one of several things: 1. Hex code 2. HTML color name 3. RGB tuple da...
Can you create a Python 3 function that generates a matplotlib colormap from a single color.
As a Python code translator, you convert algorithms and pseudocode into Python.
Truncates a colormap such that the new colormap consists of a subset of the colormap.
Can you tell what is the following Python 3 function doing def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=256): cmap = get_cmap(cmap) name = "%s-trunc-%.2g-%.2g" % (cmap.name, minval, maxval) return colors.LinearSegmentedColormap.from_list( name, cmap(np.linspace(minval, maxval, n)))
You are a Python code generator, capable of creating scripts from specifications.
def stack_colormap(lower, upper, n=256): """ Stacks two colormaps (``lower`` and ``upper``) such that low half -> ``lower`` colors, high half -> ``upper`` colors Args: lower (colormap): colormap for the lower half of the stacked colormap. upper (colormap): colormap for the upper half of the...
Write a Python 3 script to return a new colormap that stacks two colormaps.
As a Python code composer, you craft elegant and concise scripts.
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted Recording when the function is used.
Make a summary of the following Python 3 code def deprecated(func): @functools.wraps(func) def decorated(*args, **kwargs): warnings.warn_explicit( "Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, filename=func.__code__.co_filename...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the AppModel with the nested_fields attached.
How would you explain what the following Python 3 function does def nested_model(model, nested_fields): # type: (ModelBase, Any)->Optional[AppModel] if model is None: return None app_model = model.get_app_model() is_dict = isinstance(nested_fields, dict) for field in nested_fields: ...
As a Python code composer, you craft elegant and concise scripts.
def check_node( state, name, index=0, missing_msg="Check the {ast_path}. Could not find the {index}{node_name}.", priority=None, ): """Select a node from abstract syntax tree (AST), using its name and index position. Args: state: State instance describing student and solution code. ...
How would you implement a function in Python 3 that selects a node from abstract syntax tree using its name and index position.
As a Python code composer, you craft elegant and concise scripts.
def check_edge( state, name, index=0, missing_msg="Check the {ast_path}. Could not find the {index}{field_name}.", ): """Select an attribute from an abstract syntax tree (AST) node, using the attribute name. Args: state: State instance describing student and solution code. Can be omitte...
How would you code a function in Python 3 to check the edge of the student and solution code.
You are a Python code analyst, evaluating scripts for potential improvements.
def has_code( state, text, incorrect_msg="Check the {ast_path}. The checker expected to find {text}.", fixed=False, ): """Test whether the student code contains text. Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). text : text ...
Write a Python 3 function that can test whether the student code contains text.
You are a Python code analyst, evaluating scripts for potential improvements.
Test whether the student and solution code have identical AST representations.
Can you generate the documentation for the following Python 3 function def has_equal_ast( state, incorrect_msg="Check the {ast_path}. {extra}", sql=None, start=["expression", "subquery", "sql_script"][0], exact=None, ): """Test whether the student and solution code have identical AST representat...
You are a Python code generator, capable of creating scripts from specifications.
def cache_model(key_params, timeout='default'): """ Caching decorator for app models in task.perform """ def decorator_fn(fn): return CacheModelDecorator().decorate(key_params, timeout, fn) return decorator_fn
Write a Python 3 function that can cache decorator for app models in task.perform
You are a Python code architect, reviewing and designing scalable and efficient code
def cache_page(key_params, timeout='default'): """ Cache a page (slice) of a list of AppModels """ def decorator_fn(fn): d = CachePageDecorator() return d.decorate(key_params, timeout, fn) return decorator_fn
Implement a Python 3 function for caching a page of a list of AppModels
As a Python code composer, you craft elegant and concise scripts.
def create_key_for_data(prefix, data, key_params): """ From ``data`` params in task create corresponding key with help of ``key_params`` (defined in decorator) """ d = data.get_data() values = [] for k in key_params: if k in d and type(d[k]) is list: values.append("{0}:{1}".f...
Write a Python 3 script to create a key for the data in task.
As a Python code composer, you craft elegant and concise scripts.
def items_differ(jsonitems, dbitems, subfield_dict): """ check whether or not jsonitems and dbitems differ """ # short circuit common cases if len(jsonitems) == len(dbitems) == 0: # both are empty return False elif len(jsonitems) != len(dbitems): # if lengths differ, they're def...
Implement a Python 3 function for checking whether or not jsonitems and dbitems differ
As a Python code analyst, you investigate and solve complex coding mysteries
def resolve_json_id(self, json_id, allow_no_match=False): """ Given an id found in scraped JSON, return a DB id for the object. params: json_id: id from json allow_no_match: just return None if id can't be resolved returns: ...
Can you implement a function in Python 3 that gives an id found in scraped JSON return a DB id for the object.
You are a Python code architect, reviewing and designing scalable and efficient code
def import_directory(self, datadir): """ import a JSON directory into the database """ def json_stream(): # load all json, mapped by json_id for fname in glob.glob(os.path.join(datadir, self._type + '_*.json')): with open(fname) as f: yield js...
Write a Python 3 function that can import a JSON directory into the database
You are a Python code generator, capable of creating scripts from specifications.
Filter the import stream to remove duplicates and map duplicates
Can you generate a brief explanation for the following Python 3 code def _prepare_imports(self, dicts): """ filters the import stream to remove duplicates also serves as a good place to override if anything special has to be done to the order of the import stream (see OrganizationImporter) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def import_data(self, data_items): """ import a bunch of dicts together """ # keep counts of all actions record = { 'insert': 0, 'update': 0, 'noop': 0, 'start': utcnow(), 'records': { 'insert': [], 'update': [], ...
How would you implement a function in Python 3 that imports a bunch of dicts together
As a Python code analyst, you investigate and solve complex coding mysteries
function used by import_data
Explain what the following Python 3 code does def import_item(self, data): what = 'noop' # remove the JSON _id (may still be there if called directly) data.pop('_id', None) # add fields/etc. data = self.apply_transformers(data) data = self.prepare_for_db(data) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _update_related(self, obj, related, subfield_dict): """ update DB objects related to a base object obj: a base object to create related related: dict mapping field names to lists of related objects subfield_list: where to get the next layer of s...
Can you implement a function in Python 3 that updates DB objects related to a base object.
As a Python code composer, you craft elegant and concise scripts.
def _create_related(self, obj, related, subfield_dict): """ create DB objects related to a base object obj: a base object to create related related: dict mapping field names to lists of related objects subfield_list: where to get the next layer of s...
Write a Python 3 function that can create DB objects related to a base object obj.
You are a Python code generator, capable of creating scripts from specifications.
Add an edge to the tree.
Can you tell what is the following Python 3 function doing def add_edge(self, fro, to): self.add_node(fro) self.add_node(to) self.edges[fro].add(to)
As a Python code translator, you convert algorithms and pseudocode into Python.
def prune_node(self, node, remove_backrefs=False): """ remove node `node` from the network (including any edges that may have been pointing at `node`). """ if not remove_backrefs: for fro, connections in self.edges.items(): if node in self.edges[fro]: ...
How would you code a function in Python 3 to remove a node from the network.
As a Python code composer, you craft elegant and concise scripts.
Return an iterable of nodes toplogically sorted to correctly import dependencies before leaf nodes.
Can you generate the documentation for the following Python 3 function def sort(self): while self.nodes: iterated = False for node in self.leaf_nodes(): iterated = True self.prune_node(node) yield node if not iterated: ...
You are a Python code generator, capable of creating scripts from specifications.
Return a dot - representation of the tree.
Can you tell what is the following Python 3 function doing def dot(self): buff = "digraph graphname {" for fro in self.edges: for to in self.edges[fro]: buff += "%s -> %s;" % (fro, to) buff += "}" return buff
You are a Python code architect, reviewing and designing scalable and efficient code
This method returns the shortest unique cycles that are found in the network.
Explain what the following Python 3 code does def cycles(self): def walk_node(node, seen): """ Walk each top-level node we know about, and recurse along the graph. """ if node in seen: yield (node,) return s...
As a Python code translator, you convert algorithms and pseudocode into Python.
Save object to disk as JSON.
Given the following Python 3 function, write the documentation def save_object(self, obj): obj.pre_save(self.jurisdiction.jurisdiction_id) filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-') self.info('save %s %s as %s', obj._type, obj, filename) self.debug(json.dump...
You are a Python code generator, capable of creating scripts from specifications.
Validate that we have a valid object.
How would you explain what the following Python 3 function does def validate(self, schema=None): if schema is None: schema = self._schema type_checker = Draft3Validator.TYPE_CHECKER.redefine( "datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime)) ) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_source(self, url, *, note=''): """ Add a source URL from which data was collected """ new = {'url': url, 'note': note} self.sources.append(new)
Can you write a function in Python 3 where it adds a source URL from which data was collected
You are a Python code architect, reviewing and designing scalable and efficient code
Evolve a population without tree sequence recordings.
Make a summary of the following Python 3 code def evolve_genomes(rng, pop, params, recorder=None): import warnings # Test parameters while suppressing warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") # Will throw exception if anything is wrong: params.validate...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _initializeIndividualTable(pop, tc): """ Returns node ID -> individual map """ # First, alive individuals: individal_nodes = {} for i in range(pop.N): individal_nodes[2*i] = i individal_nodes[2*i+1] = i metadata_strings = _generate_individual_metadata(pop.diploid_metadata...
Can you create a Python 3 function that initializes the individual table with the metadata of the given pop.
As a Python code analyst, you investigate and solve complex coding mysteries
Converts fwdpy11. TableCollection to an anatomy. TreeSequence
Can you tell what is the following Python 3 function doing def dump_tables_to_tskit(pop): node_view = np.array(pop.tables.nodes, copy=True) node_view['time'] -= node_view['time'].max() node_view['time'][np.where(node_view['time'] != 0.0)[0]] *= -1.0 edge_view = np.array(pop.tables.edges, copy=False) ...
You are a Python code generator, capable of creating scripts from specifications.
Function to establish default parameters for a single - locus simulation for standard pop - gen modeling scenarios.
Explain what the following Python 3 code does def mslike(pop, **kwargs): import fwdpy11 if isinstance(pop, fwdpy11.DiploidPopulation) is False: raise ValueError("incorrect pop type: " + str(type(pop))) defaults = {'simlen': 10*pop.N, 'beg': 0.0, 'end': 1.0, ...
You are a Python code analyst, evaluating scripts for potential improvements.