text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(self): """ Validates single instance. Returns boolean value and store errors in self.errors """
self.errors = [] for field in self.get_all_field_names_declared_by_user(): getattr(type(self), field).is_valid(self, type(self), field) field_errors = getattr(type(self), field).errors(self) self.errors.extend(field_errors) return len(self.errors) == 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(self): """ Run the analyses using the inputted values for forward and reverse read length. However, if not all strains pass the quality thresholds, cont...
logging.info('Starting {} analysis pipeline'.format(self.analysistype)) self.createobjects() # Run the genesipping analyses self.methods() # Determine if the analyses are complete self.complete() self.additionalsipping() # Update the report object ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def methods(self): """ Run the typing methods """
self.contamination_detection() ReportImage(self, 'confindr') self.run_genesippr() ReportImage(self, 'genesippr') self.run_sixteens() self.run_mash() self.run_gdcs() ReportImage(self, 'gdcs')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contamination_detection(self): """ Calculate the levels of contamination in the reads """
self.qualityobject = quality.Quality(self) self.qualityobject.contamination_finder(input_path=self.sequencepath, report_path=self.reportpath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_genesippr(self): """ Run the genesippr analyses """
GeneSippr(args=self, pipelinecommit=self.commit, startingtime=self.starttime, scriptpath=self.homepath, analysistype='genesippr', cutoff=0.95, pipeline=False, revbait=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_sixteens(self): """ Run the 16S analyses using the filtered database """
SixteensFull(args=self, pipelinecommit=self.commit, startingtime=self.starttime, scriptpath=self.homepath, analysistype='sixteens_full', cutoff=0.985)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_mash(self): """ Run MASH to determine the closest refseq genomes """
self.pipeline = True mash.Mash(inputobject=self, analysistype='mash')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def protected_view(view, info): """allows adding `protected=True` to a view_config`"""
if info.options.get('protected'): def wrapper_view(context, request): response = _advice(request) if response is not None: return response else: return view(context, request) return wrapper_view return view
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkInstalledPip(package, speak=True, speakSimilar=True): """checks if a given package is installed on pip"""
packages = sorted([i.key for i in pip.get_installed_distributions()]) installed = package in packages similar = None if not installed: similar = [pkg for pkg in packages if package in pkg] if speak: speakInstalledPackages(package, "pip", installed, similar, speakSimilar) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkInstalledBrew(package, similar=True, speak=True, speakSimilar=True): """checks if a given package is installed on homebrew"""
packages = subprocess.check_output(['brew', 'list']).split() installed = package in packages similar = [] if not installed: similar = [pkg for pkg in packages if package in pkg] if speak: speakInstalledPackages(package, "homebrew", installed, similar, speakSimilar) return (ins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def placeholders(cls,dic): """Placeholders for fields names and value binds"""
keys = [str(x) for x in dic] entete = ",".join(keys) placeholders = ",".join(cls.named_style.format(x) for x in keys) entete = f"({entete})" placeholders = f"({placeholders})" return entete, placeholders
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(table, datas, avoid_conflict=False): """ Insert row from datas :param table: Safe table name :param datas: List of dicts. :param avoid_conflict: Allow...
if avoid_conflict: debut = """INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} ON CONFLICT DO NOTHING""" else: debut = """INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} RETURNING *""" l = [abstractRequetesSQL.formate(debut, table=table, INSERT=d, args=d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(cls,table, dic, Id): """ Update row with Id from table. Set fields given by dic."""
if dic: req = "UPDATE {table} SET {SET} WHERE id = " + cls.named_style.format('__id') + " RETURNING * " r = abstractRequetesSQL.formate(req, SET=dic, table=table, args=dict(dic, __id=Id)) return MonoExecutant(r) return MonoExecutant((f"SELECT * FROM {table} WHERE id...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cree(table, dic, avoid_conflict=False): """ Create ONE row from dic and returns the entry created """
if avoid_conflict: req = """ INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} ON CONFLICT DO NOTHING RETURNING *""" else: req = """ INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} RETURNING *""" r = abstractRequetesSQL.formate(req, table=table, INSERT=di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trace(self, context, obj): """Enumerate the children of the given object, as would be visible and utilized by dispatch."""
root = obj if isroutine(obj): yield Crumb(self, root, endpoint=True, handler=obj, options=opts(obj)) return for name, attr in getmembers(obj if isclass(obj) else obj.__class__): if name == '__getattr__': sig = signature(attr) path = '{' + list(sig.parameters.keys())[1] + '}' reta = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def main(argv=None): ''' Main entry-point for calling layouts directly as a program. ''' # Prep argparse ap = argparse.ArgumentParser( description='Basic query options for Python HID-IO Layouts repository', ) ap.add_argument('--list', action='store_true', help='List available layout ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def retrieve_github_cache(self, github_path, version, cache_dir, token): ''' Retrieves a cache of the layouts git repo from GitHub @param github_path: Location of the git repo on GitHub (e.g. hid-io/layouts) @param version: git reference for the version to download (e.g. master) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_layout(self, name): ''' Returns the layout with the given name ''' layout_chain = [] # Retrieve initial layout file try: json_data = self.json_files[self.layout_names[name]] except KeyError: log.error('Could not find layout: %s', n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dict_merge(self, merge_to, merge_in): ''' Recursively merges two dicts Overwrites any non-dictionary items merge_to <- merge_in Modifies merge_to dictionary @param merge_to: Base dictionary to merge into @param merge_in: Dictionary that may overwrite element...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def squash_layouts(self, layouts): ''' Returns a squashed layout The first element takes precedence (i.e. left to right). Dictionaries are recursively merged, overwrites only occur on non-dictionary entries. [0,1] 0: test: 'my data' 1: test: 's...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dict(self, name, key_caps=False, value_caps=False): ''' Returns a JSON dict @key_caps: Converts all dictionary keys to uppercase @value_caps: Converts all dictionary values to uppercase @return: JSON item (may be a variable, list or dictionary) ''' # Invalid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def locale(self): ''' Do a lookup for the locale code that is set for this layout. NOTE: USB HID specifies only 35 different locales. If your layout does not fit, it should be set to Undefined/0 @return: Tuple (<USB HID locale code>, <name>) ''' name = self.json_data['h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def compose(self, text, minimal_clears=False, no_clears=False): ''' Returns the sequence of combinations necessary to compose given text. If the text expression is not possible with the given layout an ComposeException is thrown. Iterate over the string, converting each character into ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def genus_specific(self): """ For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S analyses have been pe...
# Initialise a variable to store whether the necessary analyses have already been performed closestrefseqgenus = False for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != 'NA': try: closestrefseqgenus = sample.general.clo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(): """Tell iTunes to pause"""
if not settings.platformCompatible(): return False (output, error) = subprocess.Popen(["osascript", "-e", PAUSE], stdout=subprocess.PIPE).communicate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume(): """Tell iTunes to resume"""
if not settings.platformCompatible(): return False (output, error) = subprocess.Popen(["osascript", "-e", RESUME], stdout=subprocess.PIPE).communicate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip(): """Tell iTunes to skip a song"""
if not settings.platformCompatible(): return False (output, error) = subprocess.Popen(["osascript", "-e", SKIP], stdout=subprocess.PIPE).communicate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def service_provider(*services): """ This is a class decorator that declares a class to provide a set of services. It is expected that the class has a no-arg con...
def real_decorator(clazz): instance = clazz() for service in services: global_lookup.add(service, instance) return clazz return real_decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wsp(word): '''Return the number of unstressed heavy syllables.''' HEAVY = r'[ieaAoO]{1}[\.]*(u|y)[^ieaAoO]+(\.|$)' # # if the word is not monosyllabic, lop off the final syllable, which is # # extrametrical # if '.' in word: # word = word[:word.rindex('.')] # gather the indices of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_object_ns(name_space, import_str, *args, **kwargs): """Tries to import object from default namespace. Imports a class and return an instance of it, fi...
import_value = "%s.%s" % (name_space, import_str) try: return import_class(import_value)(*args, **kwargs) except ImportError: return import_class(import_str)(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_vagrant_plugin(plugin, use_sudo=False): """ install vagrant plugin """
cmd = 'vagrant plugin install %s' % plugin with settings(hide('running', 'stdout')): if use_sudo: if plugin not in sudo('vagrant plugin list'): sudo(cmd) else: if plugin not in run('vagrant plugin list'): run(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cree_widgets(self): """Create widgets and store them in self.widgets"""
for t in self.FIELDS: if type(t) is str: attr, kwargs = t, {} else: attr, kwargs = t[0], t[1].copy() self.champs.append(attr) is_editable = kwargs.pop("is_editable", self.is_editable) args = [self.acces[attr], is_editab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cree_ws_lecture(self, champs_ligne): """Alternative to create read only widgets. They should be set after."""
for c in champs_ligne: label = ASSOCIATION[c][0] w = ASSOCIATION[c][3](self.acces[c], False) w.setObjectName("champ-lecture-seule-details") self.widgets[c] = (w, label)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preservesurrogates(s): """ Function for splitting a string into a list of characters, preserving surrogate pairs. In python 2, unicode characters above 0x100...
if not isinstance(s, six.text_type): raise TypeError(u"String to split must be of type 'unicode'!") surrogates_regex_str = u"[{0}-{1}][{2}-{3}]".format(HIGH_SURROGATE_START, HIGH_SURROGATE_END, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unichr(i): """ Helper function for taking a Unicode scalar value and returning a Unicode character. :param s: Unicode scalar value to convert. :return: Unic...
if not isinstance(i, int): raise TypeError try: return six.unichr(i) except ValueError: # Workaround the error "ValueError: unichr() arg not in range(0x10000) (narrow Python build)" return struct.pack("i", i).decode("utf-32")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_nr_prefix(i): """ Helper function for looking up the derived name prefix associated with a Unicode scalar value. :param i: Unicode scalar value. :return...
for lookup_range, prefix_string in _nr_prefix_strings.items(): if i in lookup_range: return prefix_string raise ValueError("No prefix string associated with {0}!".format(i))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def casefold(s, fullcasefold=True, useturkicmapping=False): """ Function for performing case folding. This function will take the input string s and return a cop...
if not isinstance(s, six.text_type): raise TypeError(u"String to casefold must be of type 'unicode'!") lookup_order = "CF" if not fullcasefold: lookup_order = "CS" if useturkicmapping: lookup_order = "T" + lookup_order return u"".join([casefold_map.lookup(c, lookup_order=loo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup(self, c, lookup_order="CF"): """ Function to lookup a character in the casefold map. The casefold map has four sub-tables, the 'C' or common table, th...
if not isinstance(c, six.text_type): raise TypeError(u"Character to lookup must be of type 'unicode'!") for d in lookup_order: try: return self._casefold_map[d][c] except KeyError: pass return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rank(syllabifications): '''Rank syllabifications.''' # def key(s): # word = s[0] # w = wsp(word) # p = pk_prom(word) # n = nuc(word) # t = w + p + n # print('%s\twsp: %s\tpk: %s\tnuc: %s\ttotal: %s' % (word, w, p, n, t)) # return w + p + n # syl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Purge a single fastly url """
parser = OptionParser(description= "Purge a single url from fastly.") parser.add_option("-k", "--key", dest="apikey", default="", help="fastly api key") parser.add_option("-H", "--host", dest="host", help="host to purge from") parser.add_option(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populate(self, obj=None, section=None, parse_types=True): """Set attributes in ``obj`` with ``setattr`` from the all values in ``section``. """
section = self.default_section if section is None else section obj = Settings() if obj is None else obj is_dict = isinstance(obj, dict) for k, v in self.get_options(section).items(): if parse_types: if v == 'None': v = None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_calling_module(self): """Get the last module in the call stack that is not this module or ``None`` if the call originated from this module. """
for frame in inspect.stack(): mod = inspect.getmodule(frame[0]) logger.debug(f'calling module: {mod}') if mod is not None: mod_name = mod.__name__ if mod_name != __name__: return mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_filename(self, resource_name, module_name=None): """Return a resource based on a file name. This uses the ``pkg_resources`` package first to find th...
if module_name is None: mod = self._get_calling_module() logger.debug(f'calling module: {mod}') if mod is not None: mod_name = mod.__name__ if module_name is None: module_name = __name__ if pkg_resources.resource_exists(mod_name, r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_options(self, section='default', opt_keys=None, vars=None): """ Get all options for a section. If ``opt_keys`` is given return only options with those ke...
vars = vars if vars else self.default_vars conf = self.parser opts = {} if opt_keys is None: if conf is None: opt_keys = {} else: if not self.robust or conf.has_section(section): opt_keys = conf.options(section)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_option(self, name, section=None, vars=None, expect=None): """Return an option from ``section`` with ``name``. :param section: section in the ini file to ...
vars = vars if vars else self.default_vars if section is None: section = self.default_section opts = self.get_options(section, opt_keys=[name], vars=vars) if opts: return opts[name] else: if self._narrow_expect(expect): raise V...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_option_list(self, name, section=None, vars=None, expect=None, separator=','): """Just like ``get_option`` but parse as a list using ``split``. """
val = self.get_option(name, section, vars, expect) return val.split(separator) if val else []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_option_int(self, name, section=None, vars=None, expect=None): """Just like ``get_option`` but parse as an integer."""
val = self.get_option(name, section, vars, expect) if val: return int(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_option_float(self, name, section=None, vars=None, expect=None): """Just like ``get_option`` but parse as a float."""
val = self.get_option(name, section, vars, expect) if val: return float(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_option_path(self, name, section=None, vars=None, expect=None): """Just like ``get_option`` but return a ``pathlib.Path`` object of the string. """
val = self.get_option(name, section, vars, expect) return Path(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def property_get( prop, instance, **kwargs ): """Wrapper for property reads which auto-dereferences Refs if required. prop A Ref (which gets dereferenced and ret...
if isinstance( prop, Ref ): return prop.get( instance, **kwargs ) return prop
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def property_set( prop, instance, value, **kwargs ): """Wrapper for property writes which auto-deferences Refs. prop A Ref (which gets dereferenced and the targe...
if isinstance( prop, Ref ): return prop.set( instance, value, **kwargs ) raise AttributeError( "can't change value of constant {} (context: {})".format( prop, instance ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get( self, instance, **kwargs ): """Return an attribute from an object using the Ref path. instance The object instance to traverse. """
target = instance for attr in self._path: target = getattr( target, attr ) return target
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set( self, instance, value, **kwargs ): """Set an attribute on an object using the Ref path. instance The object instance to traverse. value The value to set...
if not self._allow_write: raise AttributeError( "can't set Ref directly, allow_write is disabled" ) target = instance for attr in self._path[:-1]: target = getattr( target, attr ) setattr( target, self._path[-1], value ) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def traverse_until_fixpoint(predicate, tree): """Traverses the tree again and again until it is not modified."""
old_tree = None tree = simplify(tree) while tree and old_tree != tree: old_tree = tree tree = tree.traverse(predicate) if not tree: return None tree = simplify(tree) return tree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fasta(self): """ Create FASTA files of the PointFinder results to be fed into PointFinder """
logging.info('Extracting FASTA sequences matching PointFinder database') for sample in self.runmetadata.samples: # Ensure that there are sequence data to extract from the GenObject if GenObject.isattr(sample[self.analysistype], 'sequences'): # Set the name of the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_pointfinder(self): """ Run PointFinder on the FASTA sequences extracted from the raw reads """
logging.info('Running PointFinder on FASTA files') for i in range(len(self.runmetadata.samples)): # Start threads threads = Thread(target=self.pointfinder_threads, args=()) # Set the daemon to True - something to do with thread management threads.setDaemo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_pointfinder(self): """ Create summary reports for the PointFinder outputs """
# Create the nested dictionary that stores the necessary values for creating summary reports self.populate_summary_dict() # Clear out any previous reports for organism in self.summary_dict: for report in self.summary_dict[organism]: try: o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sequence_prep(self): """ Create metadata objects for all PacBio assembly FASTA files in the sequencepath. Create individual subdirectories for each sample. R...
# Create a sorted list of all the FASTA files in the sequence path strains = sorted(glob(os.path.join(self.fastapath, '*.fa*'.format(self.fastapath)))) for sample in strains: # Create the object metadata = MetadataObject() # Set the sample name to be the file...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assembly_length(self): """ Use SeqIO.parse to extract the total number of bases in each assembly file """
for sample in self.metadata: # Only determine the assembly length if is has not been previously calculated if not GenObject.isattr(sample, 'assembly_length'): # Create the assembly_length attribute, and set it to 0 sample.assembly_length = 0 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_reads(self): """ For each PacBio assembly, sample reads from corresponding FASTQ files for appropriate forward and reverse lengths and sequencing dept...
logging.info('Read sampling') for sample in self.metadata: # Iterate through all the desired depths of coverage for depth in self.read_depths: for read_pair in self.read_lengths: # Set the name of the output directory sampl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_genesippr(self): """ Run GeneSippr on each of the samples """
from pathlib import Path home = str(Path.home()) logging.info('GeneSippr') # These unfortunate hard coded paths appear to be necessary miniconda_path = os.path.join(home, 'miniconda3') miniconda_path = miniconda_path if os.path.isdir(miniconda_path) else os.path.join(hom...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_level(self, level): """ Set the logging level of this logger. :param level: must be an int or a str. """
for handler in self.__coloredlogs_handlers: handler.setLevel(level=level) self.logger.setLevel(level=level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_logger(self, disabled=True): """ Disable all logging calls. """
# Disable standard IO streams if disabled: sys.stdout = _original_stdout sys.stderr = _original_stderr else: sys.stdout = self.__stdout_stream sys.stderr = self.__stderr_stream # Disable handlers self.logger.disabled = disabled
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redirect_stdout(self, enabled=True, log_level=logging.INFO): """ Redirect sys.stdout to file-like object. """
if enabled: if self.__stdout_wrapper: self.__stdout_wrapper.update_log_level(log_level=log_level) else: self.__stdout_wrapper = StdOutWrapper(logger=self, log_level=log_level) self.__stdout_stream = self.__stdout_wrapper else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redirect_stderr(self, enabled=True, log_level=logging.ERROR): """ Redirect sys.stderr to file-like object. """
if enabled: if self.__stderr_wrapper: self.__stderr_wrapper.update_log_level(log_level=log_level) else: self.__stderr_wrapper = StdErrWrapper(logger=self, log_level=log_level) self.__stderr_stream = self.__stderr_wrapper else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def use_file(self, enabled=True, file_name=None, level=logging.WARNING, when='d', interval=1, backup_count=30, delay=False, utc=False, at_time=None, log_format=No...
if enabled: if not self.__file_handler: assert file_name, 'File name is missing!' # Create new TimedRotatingFileHandler instance kwargs = { 'filename': file_name, 'when': when, 'interval': i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def use_loggly(self, enabled=True, loggly_token=None, loggly_tag=None, level=logging.WARNING, log_format=None, date_format=None): """ Enable handler for sending ...
if enabled: if not self.__loggly_handler: assert loggly_token, 'Loggly token is missing!' # Use logger name for default Loggly tag if not loggly_tag: loggly_tag = self.name # Create new LogglyHandler instance ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_...
if not isinstance(level, int): if logging.raiseExceptions: raise TypeError('Level must be an integer!') else: return if self.logger.isEnabledFor(level=level): """ Low-level logging routine which creates a LogRecord and the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self): """ Flush the buffer, if applicable. """
if self.__buffer.tell() > 0: # Write the buffer to log # noinspection PyProtectedMember self.__logger._log(level=self.__log_level, msg=self.__buffer.getvalue().strip(), record_filter=StdErrWrapper.__filter_record) # Remove the old b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(self, record): """Uses contextstring if request_id is set, otherwise default."""
# NOTE(sdague): default the fancier formating params # to an empty string so we don't throw an exception if # they get used for key in ('instance', 'color'): if key not in record.__dict__: record.__dict__[key] = '' if record.__dict__.get('request_id'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formatException(self, exc_info, record=None): """Format exception output with CONF.logging_exception_prefix."""
if not record: return logging.Formatter.formatException(self, exc_info) stringbuffer = cStringIO.StringIO() traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], None, stringbuffer) lines = stringbuffer.getvalue().split('\n') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_interface(self, interface): """Add update toolbar callback to the interface"""
self.interface = interface self.interface.callbacks.update_toolbar = self._update self._update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update(self): """Update the display of button after querying data from interface"""
self.clear() self._set_boutons_communs() if self.interface: self.addSeparator() l_actions = self.interface.get_actions_toolbar() self._set_boutons_interface(l_actions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_response(self, status, content_type, response): """Shortcut for making a response to the client's request."""
headers = [('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'), ('Access-Control-Allow-Headers', 'Content-Type'), ('Access-Control-Max-Age', '86400'), ('Content-type', content_type) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_request(self, request): """Processes a request."""
try: request = Request.from_json(request.read().decode()) except ValueError: raise ClientError('Data is not valid JSON.') except KeyError: raise ClientError('Missing mandatory field in request object.') except AttributeNotProvided as exc: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_post(self): """Extracts the request, feeds the module, and returns the response."""
request = self.environ['wsgi.input'] try: return self.process_request(request) except ClientError as exc: return self.on_client_error(exc) except BadGateway as exc: return self.on_bad_gateway(exc) except InvalidConfig: raise ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self): """Handles dispatching of the request."""
method_name = 'on_' + self.environ['REQUEST_METHOD'].lower() method = getattr(self, method_name, None) if method: return method() else: return self.on_bad_method()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialised( self ): """Tuple containing the contents of the Block."""
klass = self.__class__ return ((klass.__module__, klass.__name__), tuple( (name, field.serialise( self._field_data[name], parent=self ) ) for name, field in klass._fields.items()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_data( self, source ): """Clone data from another Block. source Block instance to copy from. """
klass = self.__class__ assert isinstance( source, klass ) for name in klass._fields: self._field_data[name] = getattr( source, name )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_data( self, raw_buffer ): """Import data from a byte array. raw_buffer Byte array to import from. """
klass = self.__class__ if raw_buffer: assert common.is_bytes( raw_buffer ) # raw_buffer = memoryview( raw_buffer ) self._field_data = {} for name in klass._fields: if raw_buffer: self._field_data[name] = klass._fields[name].get_from_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_data( self ): """Export data to a byte array."""
klass = self.__class__ output = bytearray( b'\x00'*self.get_size() ) # prevalidate all data before export. # this is important to ensure that any dependent fields # are updated beforehand, e.g. a count referenced # in a BlockField queue = [] for name in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_deps( self ): """Update dependencies on all the fields on this Block instance."""
klass = self.__class__ for name in klass._fields: self.update_deps_on_field( name ) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate( self ): """Validate all the fields on this Block instance."""
klass = self.__class__ for name in klass._fields: self.validate_field( name ) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, path, compressed=True, exist_ok=False): """ Save the GADDAG to file. Args: path: path to save the GADDAG to. compressed: compress the saved GADDAG...
path = os.path.expandvars(os.path.expanduser(path)) if os.path.isfile(path) and not exist_ok: raise OSError(17, os.strerror(17), path) if os.path.isdir(path): path = os.path.join(path, "out.gdg") if compressed: bytes_written = cgaddag.gdg_save_compr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, path): """ Load a GADDAG from file, replacing the words currently in this GADDAG. Args: path: path to saved GADDAG to be loaded. """
path = os.path.expandvars(os.path.expanduser(path)) gdg = cgaddag.gdg_load(path.encode("ascii")) if not gdg: errno = ctypes.c_int.in_dll(ctypes.pythonapi, "errno").value raise OSError(errno, os.strerror(errno), path) self.__del__() self.gdg = gdg.conten...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def starts_with(self, prefix): """ Find all words starting with a prefix. Args: prefix: A prefix to be searched for. Returns: A list of all words found. """
prefix = prefix.lower() found_words = [] res = cgaddag.gdg_starts_with(self.gdg, prefix.encode(encoding="ascii")) tmp = res while tmp: word = tmp.contents.str.decode("ascii") found_words.append(word) tmp = tmp.contents.next cgaddag....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains(self, sub): """ Find all words containing a substring. Args: sub: A substring to be searched for. Returns: A list of all words found. """
sub = sub.lower() found_words = set() res = cgaddag.gdg_contains(self.gdg, sub.encode(encoding="ascii")) tmp = res while tmp: word = tmp.contents.str.decode("ascii") found_words.add(word) tmp = tmp.contents.next cgaddag.gdg_destroy_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ends_with(self, suffix): """ Find all words ending with a suffix. Args: suffix: A suffix to be searched for. Returns: A list of all words found. """
suffix = suffix.lower() found_words = [] res = cgaddag.gdg_ends_with(self.gdg, suffix.encode(encoding="ascii")) tmp = res while tmp: word = tmp.contents.str.decode("ascii") found_words.append(word) tmp = tmp.contents.next cgaddag.gd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_word(self, word): """ Add a word to the GADDAG. Args: word: A word to be added to the GADDAG. """
word = word.lower() if not (word.isascii() and word.isalpha()): raise ValueError("Invalid character in word '{}'".format(word)) word = word.encode(encoding="ascii") result = cgaddag.gdg_add_word(self.gdg, word) if result == 1: raise ValueError("Invalid ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formatLog(source="", level="", title="", data={}): """ Similar to format, but takes additional reserved params to promote logging best-practices :param level...
# consistently output empty string for unset params, because null values differ by language source = "" if source is None else source level = "" if level is None else level title = "" if title is None else title if not type(data) is dict: data = {} data['source'] = source data['level'] = level d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _str_to_list(value, separator): """Convert a string to a list with sanitization."""
value_list = [item.strip() for item in value.split(separator)] value_list_sanitized = builtins.list(filter(None, value_list)) if len(value_list_sanitized) > 0: return value_list_sanitized else: raise ValueError('Invalid list variable.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(name, value): """Write a raw env value. A ``None`` value clears the environment variable. Args: name: The environment variable name value: The value to...
if value is not None: environ[name] = builtins.str(value) elif environ.get(name): del environ[name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(name, default=None, allow_none=False, fallback=None): """Read the raw env value. Read the raw environment variable or use the default. If the value is n...
raw_value = environ.get(name) if raw_value is None and fallback is not None: if not isinstance(fallback, builtins.list) and not isinstance(fallback, builtins.tuple): fallback = [fallback] for fall in fallback: raw_value = environ.get(fall) if raw_value is no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def str(name, default=None, allow_none=False, fallback=None): """Get a string based environment value or the default. Args: name: The environment variable name d...
value = read(name, default, allow_none, fallback=fallback) if value is None and allow_none: return None else: return builtins.str(value).strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bool(name, default=None, allow_none=False, fallback=None): """Get a boolean based environment value or the default. Args: name: The environment variable name...
value = read(name, default, allow_none, fallback=fallback) if isinstance(value, builtins.bool): return value elif isinstance(value, builtins.int): return True if value > 0 else False elif value is None and allow_none: return None else: value_str = builtins.str(value)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int(name, default=None, allow_none=False, fallback=None): """Get a string environment value or the default. Args: name: The environment variable name default...
value = read(name, default, allow_none, fallback=fallback) if isinstance(value, builtins.str): value = value.strip() if value is None and allow_none: return None else: return builtins.int(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(name, default=None, allow_none=False, fallback=None, separator=','): """Get a list of strings or the default. The individual list elements are whitespac...
value = read(name, default, allow_none, fallback=fallback) if isinstance(value, builtins.list): return value elif isinstance(value, builtins.str): return _str_to_list(value, separator) elif value is None and allow_none: return None else: return [builtins.str(value)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def includeme(config): """this function adds some configuration for the application"""
config.add_route('references', '/references') _add_referencer(config.registry) config.add_view_deriver(protected_resources.protected_view) config.add_renderer('json_item', json_renderer) config.scan()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_referencer(registry): """ Gets the Referencer from config and adds it to the registry. """
referencer = registry.queryUtility(IReferencer) if referencer is not None: return referencer ref = registry.settings['urireferencer.referencer'] url = registry.settings['urireferencer.registry_url'] r = DottedNameResolver() registry.registerUtility(r.resolve(ref)(url), IReferencer) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_referencer(registry): """ Get the referencer class :rtype: pyramid_urireferencer.referencer.AbstractReferencer """
# Argument might be a config or request regis = getattr(registry, 'registry', None) if regis is None: regis = registry return regis.queryUtility(IReferencer)