output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def stream_to_packet(data): """ Chop a stream of data into MODBUS packets. :param data: stream of data :returns: a tuple of the data that is a packet with the remaining data, or ``None`` """ if len(data) < 6: return None # unpack the length pktlen = struct.unpack(">H", ...
Can you write a function in Python 3 where it chops a stream of data into MODBUS packets.
As a python code expert, you are capable of creating scripts from specifications.
def to_primitive(value, convert_instances=False, convert_datetime=True, level=0, max_depth=3): """Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. ...
Write a Python 3 function for converting a complex object into a primitive object.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_vowel(syll): '''Return the firstmost vowel in 'syll'.''' return re.search(r'([ieaouäöy]{1})', syll, flags=FLAGS).group(1).upper()
Can you create a Python 3 function that returns the first most vowel in syllll.
As a Python code composer, you craft elegant and concise scripts.
Return True if syllll is light.
Can you generate a brief explanation for the following Python 3 code def is_light(syll): '''Return True if 'syll' is light.''' return re.match(r'(^|[^ieaouäöy]+)[ieaouäöy]{1}$', syll, flags=FLAGS)
You are a Python code architect, reviewing and designing scalable and efficient code
Assign primary and secondary stress to syllabified_simplex_word.
Can you tell what is the following Python 3 function doing def stress(syllabified_simplex_word): '''Assign primary and secondary stress to 'syllabified_simplex_word'.''' syllables = syllabified_simplex_word.split('.') stressed = '\'' + syllables[0] # primary stress try: n = 0 medial = ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def sonseq(word): '''Return True if 'word' does not violate sonority sequencing.''' parts = re.split(r'([ieaouäöy]+)', word, flags=re.I | re.U) onset, coda = parts[0], parts[-1] # simplex onset Finnish complex onset if len(onset) <= 1 or onset.lower() in ONSETS: # simplex coda ...
Write a Python 3 script for returning True if word violates sonority sequencing.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return True if the word s vowels agree in frontness or backness.
Can you generate the documentation for the following Python 3 function def harmonic(word): '''Return True if the word's vowels agree in frontness/backness.''' depth = {'ä': 0, 'ö': 0, 'y': 0, 'a': 1, 'o': 1, 'u': 1} vowels = filter(lambda ch: is_front(ch) or is_back(ch), word) depths = (depth[x.lower()]...
You are a Python code architect, reviewing and designing scalable and efficient code
Updates this task type on the saltant server.
Explain what the following Python 3 code does def put(self): return self.manager.put( id=self.id, name=self.name, description=self.description, command_to_run=self.command_to_run, environment_variables=self.environment_variables, required_a...
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a new instance of the executable task type.
Explain what the following Python 3 code does def create( self, name, command_to_run, description="", environment_variables=None, required_arguments=None, required_arguments_default_values=None, json_file_option=None, extra_data_to_post=None, )...
You are a Python code architect, reviewing and designing scalable and efficient code
def put( self, id, name, description, command_to_run, environment_variables, required_arguments, required_arguments_default_values, json_file_option, extra_data_to_put=None, ): """Updates a task type on the saltant server. ...
Can you write a function in Python 3 where it updates a task type on the saltant server.
You are a Python code architect, reviewing and designing scalable and efficient code
def reporter(self, analysistype='genesippr'): """ Creates a report of the genesippr results :param analysistype: The variable to use when accessing attributes in the metadata object """ logging.info('Creating {} report'.format(analysistype)) # Create a dictionary to link ...
Can you create a Python 3 function that creates a report of the genesippr results for each sample in the runmetadata object
You are a Python code architect, reviewing and designing scalable and efficient code
def genusspecific(self, analysistype='genesippr'): """ Creates simplified genus-specific reports. Instead of the % ID and the fold coverage, a simple +/- scheme is used for presence/absence :param analysistype: The variable to use when accessing attributes in the metadata object ...
How would you implement a function in Python 3 that creates a simplified genus - specific report for each gene in the target genus
You are a Python code generator, capable of creating scripts from specifications.
def gdcsreporter(self, analysistype='GDCS'): """ Creates a report of the GDCS results :param analysistype: The variable to use when accessing attributes in the metadata object """ logging.info('Creating {} report'.format(analysistype)) # Initialise list to store all the G...
Write a Python 3 script to create a GDCS report of the results of the GDCS analysis
As a python code expert, you are capable of creating scripts from specifications.
def sixteensreporter(self, analysistype='sixteens_full'): """ Creates a report of the results :param analysistype: The variable to use when accessing attributes in the metadata object """ # Create the path in which the reports are stored make_path(self.reportpath) ...
How would you code a function in Python 3 to create a report of the results of the sixteens analyses
You are a Python code generator, capable of creating scripts from specifications.
def confindr_reporter(self, analysistype='confindr'): """ Creates a final report of all the ConFindr results """ # Initialise the data strings data = 'Strain,Genus,NumContamSNVs,ContamStatus,PercentContam,PercentContamSTD\n' with open(os.path.join(self.reportpath, analysi...
Write a Python 3 function for creating a final report of all the ConFindr results
As a Python code composer, you craft elegant and concise scripts.
def methodreporter(self): """ Create final reports collating results from all the individual iterations through the method pipeline """ # Ensure that the analyses are set to complete self.analysescomplete = True # Reset the report path to original value self.repor...
How would you code a function in Python 3 to create final reports collating results from all the individual iterations through the method pipeline.
You are a Python code architect, reviewing and designing scalable and efficient code
def main(self): """ Run the methods required to create the genesippr report summary image """ self.dataframe_setup() self.figure_populate(self.outputfolder, self.image_report, self.header_list, ...
Can you create a Python 3 function that runs the methods required to create the genesippr report summary image
As a Python code translator, you convert algorithms and pseudocode into Python.
def data_sanitise(self, inputstring, header=None): """ Format the data to be consistent with heatmaps :param inputstring: string containing data to be formatted :param header: class of the data - certain categories have specific formatting requirements :return: the formatted outp...
Can you create a Python 3 function that sanitizes the data to be consistent with heatmaps.
As a Python code analyst, you investigate and solve complex coding mysteries
def dataframe_setup(self): """ Set-up a report to store the desired header: sanitized string combinations """ # Initialise a dictionary to store the sanitized headers and strings genesippr_dict = dict() # Try to open all the reports - use pandas to extract the results fro...
Write a Python 3 script for setting up a dataframe for the desired header and string combinations of the genesippr and confindr reports.
As a Python code composer, you craft elegant and concise scripts.
def figure_populate(outputpath, csv, xlabels, ylabels, analysistype, description, fail=False): """ Create the report image from the summary report created in self.dataframesetup :param outputpath: Path in which the outputs are to be created :param csv: Name of the report file from which ...
Write a Python 3 script to create the plot from the summary report and populate the plot with the data frame
As a Python code analyst, you investigate and solve complex coding mysteries
def add_usr_local_bin_to_path(log=False): """ adds /usr/local/bin to $PATH """ if log: bookshelf2.logging_helpers.log_green('inserts /usr/local/bin into PATH') with settings(hide('warnings', 'running', 'stdout', 'stderr'), capture=True): try: sudo('echo "export...
Can you implement a function in Python 3 that adds the user s local bin to the PATH
As a Python code translator, you convert algorithms and pseudocode into Python.
cuisine dir_attribs does not do sudo so we implement our own Taxonomy
Can you tell what is the following Python 3 function doing def dir_attribs(location, mode=None, owner=None, group=None, recursive=False, use_sudo=False): """ cuisine dir_attribs doesn't do sudo, so we implement our own Updates the mode/owner/group for the given remote directory.""" args ...
You are a Python code generator, capable of creating scripts from specifications.
def dir_exists(location, use_sudo=False): """Tells if there is a remote directory at the given location.""" with settings(hide('running', 'stdout', 'stderr'), warn_only=True): if use_sudo: # convert return code 0 to True return not bool(sudo('test -d %s' % (location)).return_code...
Can you create a Python 3 function that tells if there is a remote directory at the given location.
As a python code expert, you are capable of creating scripts from specifications.
disables env reset on sudo
Make a summary of the following Python 3 code def disable_env_reset_on_sudo(log=False): if log: bookshelf2.logging_helpers.log_green('disabling env reset on sudo') file_append('/etc/sudoers', 'Defaults:%wheel !env_reset,!secure_path', use_sudo=True, parti...
You are a Python code architect, reviewing and designing scalable and efficient code
def disable_requiretty_on_sudoers(log=False): """ allow sudo calls through ssh without a tty """ if log: bookshelf2.logging_helpers.log_green( 'disabling requiretty on sudo calls') comment_line('/etc/sudoers', '^Defaults.*requiretty', use_sudo=True) return True
Can you create a Python 3 function that allows sudo calls through ssh without a tty
You are a Python code architect, reviewing and designing scalable and efficient code
Updates the mode owner group for the remote file at the given location.
Make a summary of the following Python 3 code def file_attribs(location, mode=None, owner=None, group=None, use_sudo=False, recursive=True): """Updates the mode/owner/group for the remote file at the given location.""" retu...
As a Python code composer, you craft elegant and concise scripts.
def os_release(): """ returns /etc/os-release in a dictionary """ with settings(hide('warnings', 'running', 'stderr'), warn_only=True, capture=True): release = {} data = run('cat /etc/os-release') for line in data.split('\n'): if not line: c...
Can you implement a function in Python 3 that returns a dictionary of all available OS - related resources
As a Python code composer, you craft elegant and concise scripts.
returns the linux distribution in lower case
How would you explain what the following Python 3 function does def linux_distribution(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): data = os_release() return(data['ID'])
You are a Python code analyst, evaluating scripts for potential improvements.
def lsb_release(): """ returns /etc/lsb-release in a dictionary """ with settings(hide('warnings', 'running'), capture=True): _lsb_release = {} data = sudo('cat /etc/lsb-release') for line in data.split('\n'): if not line: continue parts = line.sp...
Can you write a function in Python 3 where it returns a dictionary of all the items in the lsb - release file
As a Python code translator, you convert algorithms and pseudocode into Python.
def ansi_format( self, width=64, height=12 ): """Return a human readable ANSI-terminal printout of the stats. width Custom width for the graph (in characters). height Custom height for the graph (in characters). """ from mrcrowbar.ansi import format_bar_...
Can you implement a function in Python 3 that returns a human readable ANSI - terminal printout of the stats.
As a Python code analyst, you investigate and solve complex coding mysteries
Updates this task whitelist on the saltant server.
Make a summary of the following Python 3 code def put(self): return self.manager.put( id=self.id, name=self.name, description=self.description, whitelisted_container_task_types=( self.whitelisted_container_task_types ), whit...
As a python code expert, you are capable of creating scripts from specifications.
def create( self, name, description="", whitelisted_container_task_types=None, whitelisted_executable_task_types=None, ): """Create a task whitelist. Args: name (str): The name of the task whitelist. description (str, optional): A desc...
Write a Python 3 script for creating a new entry in the task whitelist.
You are a Python code architect, reviewing and designing scalable and efficient code
Enable logging to stderr. Useful for shell sessions. level Logging threshold. Defaults to WARNING.
How would you explain what the following Python 3 function does def enable_logging( level='WARNING' ): log = logging.getLogger( 'mrcrowbar' ) log.setLevel( level ) out = logging.StreamHandler() out.setLevel( level ) form = logging.Formatter( '[%(levelname)s] %(name)s - %(message)s' ) out.setForm...
As a python code expert, you are capable of creating scripts from specifications.
def find_all_iter( source, substring, start=None, end=None, overlap=False ): """Iterate through every location a substring can be found in a source string. source The source string to search. start Start offset to read from (default: start) end End offset to stop reading at (d...
Write a Python 3 function that can iterate through every location a substring can be found in a source string.
You are a Python code generator, capable of creating scripts from specifications.
Return every location a substring can be found in a source string.
How would you explain what the following Python 3 function does def find_all( source, substring, start=None, end=None, overlap=False ): return [x for x in find_all_iter( source, substring, start, end, overlap )]
As a python code expert, you are capable of creating scripts from specifications.
Perform a basic diff between two equal - sized binary strings and returns a list of tuples denoting the differences.
Can you generate a brief explanation for the following Python 3 code def basic_diff( source1, source2, start=None, end=None ): start = start if start is not None else 0 end = end if end is not None else min( len( source1 ), len( source2 ) ) end_point = min( end, len( source1 ), len( source2 ) ) pointer...
You are a Python code architect, reviewing and designing scalable and efficient code
Return an iterator over the contents of a byte string in tabular hexadecimal format.
Given the following Python 3 function, write the documentation def hexdump_iter( source, start=None, end=None, length=None, major_len=8, minor_len=4, colour=True, address_base=None ): assert is_bytes( source ) start, end = bounds( start, end, length, len( source ) ) start = max( start, 0 ) end = min( e...
As a Python code composer, you craft elegant and concise scripts.
def hexdump( source, start=None, end=None, length=None, major_len=8, minor_len=4, colour=True, address_base=None ): """Print the contents of a byte string in tabular hexadecimal/ASCII format. source The byte string to print. start Start offset to read from (default: start) end ...
Create a Python 3 function to print the contents of a byte string in tabular hexadecimal format.
You are a Python code architect, reviewing and designing scalable and efficient code
Return an iterator over the differences between two byte strings in tabular hexadecimal or ASCII format.
Here you have a function in Python 3, explain what it does def hexdump_diff_iter( source1, source2, start=None, end=None, length=None, major_len=8, minor_len=4, colour=True, before=2, after=2, address_base=None ): stride = minor_len*major_len start = start if start is not None else 0 end = end if end is not...
As a Python code analyst, you investigate and solve complex coding mysteries
def hexdump_diff( source1, source2, start=None, end=None, length=None, major_len=8, minor_len=4, colour=True, before=2, after=2, address_base=None ): """Returns the differences between two byte strings in tabular hexadecimal/ASCII format. source1 The first byte string source. source2 The s...
Can you implement a function in Python 3 that returns the differences between two byte strings in tabular hexadecimal format.
As a python code expert, you are capable of creating scripts from specifications.
def unpack_bits( byte ): """Expand a bitfield into a 64-bit int (8 bool bytes).""" longbits = byte & (0x00000000000000ff) longbits = (longbits | (longbits<<28)) & (0x0000000f0000000f) longbits = (longbits | (longbits<<14)) & (0x0003000300030003) longbits = (longbits | (longbits<<7)) & (0x01010101010...
Write a Python 3 function for expanding a bitfield into a 64 - bit int.
As a Python code composer, you craft elegant and concise scripts.
Crunch a 64 - bit int into a bitfield.
Can you generate a brief explanation for the following Python 3 code def pack_bits( longbits ): byte = longbits & (0x0101010101010101) byte = (byte | (byte>>7)) & (0x0003000300030003) byte = (byte | (byte>>14)) & (0x0000000f0000000f) byte = (byte | (byte>>28)) & (0x00000000000000ff) return byte
You are a Python code generator, capable of creating scripts from specifications.
def pixdump_iter( source, start=None, end=None, length=None, width=64, height=None, palette=None ): """Return the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading a...
Implement a function in Python 3 to return an iterator that returns the contents of a byte string as a 256 colour image.
You are a Python code architect, reviewing and designing scalable and efficient code
Print the contents of a byte string as a 256 colour image.
Can you tell what is the following Python 3 function doing def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ): for line in pixdump_iter( source, start, end, length, width, height, palette ): print( line )
As a Python code analyst, you investigate and solve complex coding mysteries
def set_offset( self, offset ): """Set the current read offset (in bytes) for the instance.""" assert offset in range( len( self.buffer ) ) self.pos = offset self._fill_buffer()
Write a Python 3 function that can set the current read offset for the instance.
As a python code expert, you are capable of creating scripts from specifications.
def get_bits( self, count ): """Get an integer containing the next [count] bits from the source.""" result = 0 for i in range( count ): if self.bits_remaining <= 0: self._fill_buffer() if self.bits_reverse: bit = (1 if (self.current_bits & ...
Can you create a Python 3 function that gets an integer containing the next count bits from the source.
As a Python code translator, you convert algorithms and pseudocode into Python.
def put_bits( self, value, count ): """Push bits into the target. value Integer containing bits to push, ordered from least-significant bit to most-significant bit. count Number of bits to push to the target. """ for _ in range( count ): ...
Write a Python 3 script for pushing bits into the target.
As a python code expert, you are capable of creating scripts from specifications.
def get_buffer( self ): """Return a byte string containing the target as currently written.""" last_byte = self.current_bits if (self.bits_remaining < 8) else None result = self.output if last_byte is not None: result = bytearray( result ) result.append( last_byt...
Write a Python 3 function for returning a byte string containing the target as currently written.
You are a Python code generator, capable of creating scripts from specifications.
def get_for_update(self, connection_name='DEFAULT', **kwargs): """ http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=update#sqlalchemy.orm.query.Query.with_for_update # noqa """ if not kwargs: raise InvalidQueryError( "Can not execute a query wit...
Create a Python 3 function to get a record for updating.
As a Python code translator, you convert algorithms and pseudocode into Python.
Syllabify the given word whether simplex or complex.
Can you generate the documentation for the following Python 3 function def syllabify(word, compound=None): '''Syllabify the given word, whether simplex or complex.''' if compound is None: compound = bool(re.search(r'(-| |=)', word)) syllabify = _syllabify_compound if compound else _syllabify sy...
As a Python code analyst, you investigate and solve complex coding mysteries
def convert_case(name): """Converts name from CamelCase to snake_case""" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Can you write a function in Python 3 where it converts name from CamelCase to snake_case
As a python code expert, you are capable of creating scripts from specifications.
def table_name(self): """Pluralises the class_name using utterly simple algo and returns as table_name""" if not self.class_name: raise ValueError else: tbl_name = ModelCompiler.convert_case(self.class_name) last_letter = tbl_name[-1] if last_letter in ("y...
Write a Python 3 script for pluralising the class_name using utterly simple algo and returns as table_name
As a Python code analyst, you investigate and solve complex coding mysteries
Returns non - postgres types referenced in user supplied model
Can you generate a brief explanation for the following Python 3 code def basic_types(self): if not self.foreign_key_definitions: return self.standard_types else: tmp = self.standard_types tmp.append('ForeignKey') return tmp
You are a Python code analyst, evaluating scripts for potential improvements.
def primary_keys(self): """Returns the primary keys referenced in user supplied model""" res = [] for column in self.column_definitions: if 'primary_key' in column.keys(): tmp = column.get('primary_key', None) res.append(column['name']) if tmp else Fal...
Can you implement a function in Python 3 that returns the primary keys referenced in user supplied model
You are a Python code generator, capable of creating scripts from specifications.
Returns compiled named imports required for the model
Can you tell what is the following Python 3 function doing def compiled_named_imports(self): res = [] if self.postgres_types: res.append( ALCHEMY_TEMPLATES.named_import.safe_substitute( module='sqlalchemy.dialects.postgresql', labels=",...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns compiled named imports required for the model
Can you generate the documentation for the following Python 3 function def compiled_orm_imports(self): module = 'sqlalchemy.orm' labels = [] if self.relationship_definitions: labels.append("relationship") return ALCHEMY_TEMPLATES.named_import.safe_substitute(module=module, la...
As a Python code composer, you craft elegant and concise scripts.
def compiled_columns(self): """Returns compiled column definitions""" def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type'): if arg_name in ('server_default', 'server_onupdate'): ...
Implement a Python 3 function for returning compiled column definitions
As a Python code composer, you craft elegant and concise scripts.
Returns compiled foreign key definitions
How would you explain what the following Python 3 function does def compiled_foreign_keys(self): def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type', 'reference'): if arg_name in ('server_d...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns compiled relationship definitions for all tables in the database
Explain what the following Python 3 code does def compiled_relationships(self): def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type', 'reference', 'class'): if arg_name in ('back_populates',...
As a Python code composer, you craft elegant and concise scripts.
def columns(self): """Return names of all the addressable columns (including foreign keys) referenced in user supplied model""" res = [col['name'] for col in self.column_definitions] res.extend([col['name'] for col in self.foreign_key_definitions]) return res
Can you implement a function in Python 3 that returns names of all the addressable columns referenced in user supplied model
You are a Python code architect, reviewing and designing scalable and efficient code
Returns compiled init function
Explain what the following Python 3 code does def compiled_init_func(self): def get_column_assignment(column_name): return ALCHEMY_TEMPLATES.col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): return ALCHEMY_TEMPLATES.func_arg.safe_substitute(a...
As a python code expert, you are capable of creating scripts from specifications.
Returns compiled update function
Can you generate a brief explanation for the following Python 3 code def compiled_update_func(self): def get_not_none_col_assignment(column_name): return ALCHEMY_TEMPLATES.not_none_col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): return ALCH...
As a Python code composer, you craft elegant and concise scripts.
def compiled_hash_func(self): """Returns compiled hash function based on hash of stringified primary_keys. This isn't the most efficient way""" def get_primary_key_str(pkey_name): return "str(self.{})".format(pkey_name) hash_str = "+ ".join([get_primary_key_str(n) for n in ...
How would you implement a function in Python 3 that returns compiled hash function based on hash of stringified primary keys.
As a Python code analyst, you investigate and solve complex coding mysteries
def compiled_model(self): """Returns compile ORM class for the user supplied model""" return ALCHEMY_TEMPLATES.model.safe_substitute(class_name=self.class_name, table_name=self.table_name, colum...
How would you code a function in Python 3 to return the compiled ORM class for the user supplied model
You are a Python code generator, capable of creating scripts from specifications.
Updates this task queue on the saltant server.
Explain what the following Python 3 code does def put(self): return self.manager.put( id=self.id, name=self.name, description=self.description, private=self.private, runs_executable_tasks=self.runs_executable_tasks, runs_docker_container_ta...
As a python code expert, you are capable of creating scripts from specifications.
def get(self, id=None, name=None): """Get a task queue. Either the id xor the name of the task type must be specified. Args: id (int, optional): The id of the task type to get. name (str, optional): The name of the task type to get. Returns: :class:...
Write a Python 3 function that can get a task queue by id or name.
As a python code expert, you are capable of creating scripts from specifications.
def create( self, name, description="", private=False, runs_executable_tasks=True, runs_docker_container_tasks=True, runs_singularity_container_tasks=True, active=True, whitelists=None, ): """Create a task queue. Args: ...
Write a Python 3 function for creating a new task queue.
You are a Python code architect, reviewing and designing scalable and efficient code
Partially updates a task queue on the saltant server.
Can you generate the documentation for the following Python 3 function def patch( self, id, name=None, description=None, private=None, runs_executable_tasks=None, runs_docker_container_tasks=None, runs_singularity_container_tasks=None, active=None,...
As a python code expert, you are capable of creating scripts from specifications.
def put( self, id, name, description, private, runs_executable_tasks, runs_docker_container_tasks, runs_singularity_container_tasks, active, whitelists, ): """Updates a task queue on the saltant server. Args: ...
Write a Python 3 script to update a task queue on the saltant server.
You are a Python code architect, reviewing and designing scalable and efficient code
Run the required methods in the appropriate order
Can you generate a brief explanation for the following Python 3 code def main(self): self.targets() self.bait(k=49) self.reversebait(maskmiddle='t', k=19) self.subsample_reads()
You are a Python code generator, capable of creating scripts from specifications.
Create the GenObject for the analysis type and create the hash file for baiting
How would you explain what the following Python 3 function does def targets(self): for sample in self.runmetadata: if sample.general.bestassemblyfile != 'NA': setattr(sample, self.analysistype, GenObject()) sample[self.analysistype].runanalysis = True ...
You are a Python code architect, reviewing and designing scalable and efficient code
Sets the targets folder and creates the mapping file for all the targets
Given the following Python 3 function, write the documentation def targets(self): logging.info('Performing analysis with {} targets folder'.format(self.analysistype)) for sample in self.runmetadata: if sample.general.bestassemblyfile != 'NA': sample[self.analysistype].targetp...
You are a Python code analyst, evaluating scripts for potential improvements.
def runner(self): """ Run the necessary methods in the correct order """ logging.info('Starting {} analysis pipeline'.format(self.analysistype)) if not self.pipeline: # If the metadata has been passed from the method script, self.pipeline must still be false in order ...
Can you create a Python 3 function that runs the necessary methods in the correct order for the current sample.
As a Python code composer, you craft elegant and concise scripts.
Subsample 1000 reads from the baited files
Can you generate a brief explanation for the following Python 3 code def subsample(self): # Create the threads for the analysis logging.info('Subsampling FASTQ reads') for _ in range(self.cpus): threads = Thread(target=self.subsamplethreads, args=()) threads.setDaemon(Tru...
You are a Python code architect, reviewing and designing scalable and efficient code
Convert the subsampled reads to FASTA format using reformat. sh
Can you generate the documentation for the following Python 3 function def fasta(self): logging.info('Converting FASTQ files to FASTA format') # Create the threads for the analysis for _ in range(self.cpus): threads = Thread(target=self.fastathreads, args=()) threads.setD...
As a Python code composer, you craft elegant and concise scripts.
def makeblastdb(self): """ Makes blast database files from targets as necessary """ # Iterate through the samples to set the bait file. for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != 'NA': # Remove the file extension ...
Create a Python 3 function for making blast database files from targets as necessary
You are a Python code analyst, evaluating scripts for potential improvements.
Run BLAST analyses against the NCBI 16S reference database
Can you tell what is the following Python 3 function doing def blast(self): logging.info('BLASTing FASTA files against {} database'.format(self.analysistype)) for _ in range(self.cpus): threads = Thread(target=self.blastthreads, args=()) threads.setDaemon(True) thread...
As a python code expert, you are capable of creating scripts from specifications.
def blastparse(self): """ Parse the blast results, and store necessary data in dictionaries in sample object """ logging.info('Parsing BLAST results') # Load the NCBI 16S reference database as a dictionary for sample in self.runmetadata.samples: if sample.gene...
Can you create a Python 3 function that parses the BLAST results and store necessary data in dictionary objects in sample object
You are a Python code generator, capable of creating scripts from specifications.
Creates a report of the results of the current sample
Can you generate the documentation for the following Python 3 function def reporter(self): # Create the path in which the reports are stored make_path(self.reportpath) logging.info('Creating {} report'.format(self.analysistype)) # Initialise the header and data strings header = '...
As a Python code analyst, you investigate and solve complex coding mysteries
add_listener - 创建 event listener
Can you generate the documentation for the following Python 3 function def add_listener(self, evt_name, fn): self._listeners.setdefault(evt_name, []) listeners = self.__get_listeners(evt_name) listeners.append(fn)
As a Python code analyst, you investigate and solve complex coding mysteries
remove_listener - remove a listener function from an event.
Can you generate the documentation for the following Python 3 function def remove_listener(self, evt_name, fn, remove_all=False): listeners = self.__get_listeners(evt_name) if not self.has_listener(evt_name, fn): raise ObservableError( "function %r does not exist in the %r ev...
As a Python code analyst, you investigate and solve complex coding mysteries
check if a listener exists
Can you generate the documentation for the following Python 3 function def has_listener(self, evt_name, fn): listeners = self.__get_listeners(evt_name) return fn in listeners
You are a Python code generator, capable of creating scripts from specifications.
def fire_event(self, evt_name, *args, **kwargs): """触发事件 :params evt_name: 事件名称 :params args: 给事件接受者的参数 :params kwargs: 给事件接受者的参数 """ listeners = self.__get_listeners(evt_name) evt = self.generate_event(evt_name) for listener in listeners: lis...
How would you code a function in Python 3 to fire event to all listeners
As a Python code analyst, you investigate and solve complex coding mysteries
Create a server EC2 instance.
Make a summary of the following Python 3 code def create_server_ec2(connection, region, disk_name, disk_size, ami, key_pair, instance_type, tags={}, ...
You are a Python code generator, capable of creating scripts from specifications.
destroys an EBS volume
Can you generate the documentation for the following Python 3 function def destroy_ebs_volume(connection, region, volume_id, log=False): if ebs_volume_exists(connection, region, volume_id): if log: log_yellow('destroying EBS volume ...') try: connection.delete_volume(volume_...
As a Python code composer, you craft elegant and concise scripts.
terminate the EC2 instance
Can you tell what is the following Python 3 function doing def destroy_ec2(connection, region, instance_id, log=False): data = get_ec2_info(connection=connection, instance_id=instance_id, region=region) instance = connection.terminate_instances(instance_ids=[dat...
You are a Python code analyst, evaluating scripts for potential improvements.
Shutdown an EC2 instance
Here you have a function in Python 3, explain what it does def down_ec2(connection, instance_id, region, log=False): # get the instance_id from the state file, and stop the instance instance = connection.stop_instances(instance_ids=instance_id)[0] while instance.state != "stopped": if log: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def ebs_volume_exists(connection, region, volume_id): """ finds out if a ebs volume exists """ for vol in connection.get_all_volumes(): if vol.id == volume_id: return True return False
How would you implement a function in Python 3 that returns True if a ebs volume exists
You are a Python code architect, reviewing and designing scalable and efficient code
queries EC2 for details about a particular instance_id WorkItem
Given the following Python 3 function, write the documentation def get_ec2_info(connection, instance_id, region, username=None): """ queries EC2 for details about a particular instance_id """ instance = connection.get_only_instances( filters={'insta...
You are a Python code generator, capable of creating scripts from specifications.
boot an ec2 instance
Here you have a function in Python 3, explain what it does def up_ec2(connection, region, instance_id, wait_for_ssh_available=True, log=False, timeout=600): """ boots an existing ec2_instance """ # boot the ec2 instance instance = connection.start_inst...
As a Python code translator, you convert algorithms and pseudocode into Python.
Extract sequences from a file.
Make a summary of the following Python 3 code def seqs_from_file(filename, exit_on_err=False, return_qual=False): # VALIDATE INPUT if not isinstance(filename, str): msg = 'Filename has to be a string.' if exit_on_err: sys.stderr.write('Error: %s\n'%msg) sys.exit(1) else: raise ...
As a python code expert, you are capable of creating scripts from specifications.
Open a file and return a file object.
Can you generate a brief explanation for the following Python 3 code def open_(filename, mode=None, compresslevel=9): if filename[-3:] == '.gz': if mode is None: mode = 'rt' return closing(gzip.open(filename, mode, compresslevel)) else: if mode is None: mode = 'r' return open(filename, mod...
As a Python code analyst, you investigate and solve complex coding mysteries
def load_json(json_object): ''' Load json from file or file name ''' content = None if isinstance(json_object, str) and os.path.exists(json_object): with open_(json_object) as f: try: content = json.load(f) except Exception as e: debug.log("Warning: Content of '%...
Can you create a Python 3 function that loads json from file or file name
As a Python code translator, you convert algorithms and pseudocode into Python.
def sort2groups(array, gpat=['_R1','_R2']): """ Sort an array of strings to groups by patterns """ groups = [REGroup(gp) for gp in gpat] unmatched = [] for item in array: matched = False for m in groups: if m.match(item): matched = True break if not matched...
Can you write a function in Python 3 where it sorts an array of strings to groups by patterns
You are a Python code generator, capable of creating scripts from specifications.
Sort an array of strings to groups by alphabetically continuous distribution
Can you generate a brief explanation for the following Python 3 code def sort_and_distribute(array, splits=2): if not isinstance(array, (list,tuple)): raise TypeError("array must be a list") if not isinstance(splits, int): raise TypeError("splits must be an integer") remaining = sorted(array) if sys.version...
As a Python code composer, you craft elegant and concise scripts.
This function creates a directory and returns the path.
Explain what the following Python 3 code does def mkpath(filepath, permissions=0o777): # Converting string of octal to integer, if string is given. if isinstance(permissions, str): permissions = sum([int(x)*8**i for i,x in enumerate(reversed(permissions))]) # Creating directory if not os.path.exists(f...
As a Python code composer, you craft elegant and concise scripts.
This function creates a zipfile located in zipFilePath with the files in file_list.
Can you tell what is the following Python 3 function doing def create_zip_dir(zipfile_path, *file_list): try: if isinstance(file_list, (list, tuple)): #unfolding list of list or tuple if len(file_list) == 1: if isinstance(file_list[0], (list, tuple)): file_list = file_list[0] #conver...
As a Python code composer, you craft elegant and concise scripts.
This function will zip the files created in the runroot directory and all subdirectories of the runroot directory.
Make a summary of the following Python 3 code def file_zipper(root_dir): # FINDING AND ZIPPING UNZIPPED FILES for root, dirs, files in os.walk(root_dir, topdown=False): if root != "": if root[-1] != '/': root += '/' for current_file in files: filepath = "%s/%s"%(root, current_f...
You are a Python code analyst, evaluating scripts for potential improvements.
This function will move a file from one path to another.
Make a summary of the following Python 3 code def move_file(src, dst): # Sanity checkpoint src = re.sub('[^\w/\-\.\*]', '', src) dst = re.sub('[^\w/\-\.\*]', '', dst) if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', dst)) < 5: debug.log("Error: Moving file failed. Provided paths are inval...
You are a Python code generator, capable of creating scripts from specifications.
This function will copy a file from one path to another.
Can you generate the documentation for the following Python 3 function def copy_file(src, dst, ignore=None): # Sanity checkpoint src = re.sub('[^\w/\-\.\*]', '', src) dst = re.sub('[^\w/\-\.\*]', '', dst) if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', dst)) < 5: debug.log("Error: Copyin...
As a Python code translator, you convert algorithms and pseudocode into Python.