Instruction:
Make a summary of the following Python 3 code
def homology_report(seq1, seq2, strand1, strand2, cutoff=0, min_tm=63.0,
                    top_two=False, max_size=500):
    '''Given two sequences (seq1 and seq2), report the size of all perfect
    matches between the 3' end of the top strand of seq1 and the 3' end of
    either strand of seq2. In short, in a Gibson reaction, what would bind the
    desired part of seq1, given a seq2?

    :param seq1: Sequence for which to test 3\' binding of a single strand to
                 seq2.
    :type seq1: coral.DNA
    :param seq2: Sequence for which to test 3\' binding of each strand to seq1.
    :type seq1: coral.DNA
    :param strand1: w (watson) or c (crick) - which strand of seq1 is being
                        tested.
    :type strand1ed: str
    :param strand2: w (watson) or c (crick) - which strand of seq2 is being
                        tested.
    :type strand2ed: str
    :param cutoff: size cutoff for the report - if a match is lower, it's
                   ignored
    :type cutoff: int
    :param min_tm: Minimum tm value cutoff - matches below are ignored.
    :type min_tm: float
    :param top_two: Return the best two matches
    :type top_two: bool
    :param max_size: Maximum overlap size (increases speed)
    :type max_size: int
    :returns: List of left and right identities.
    :rtype: list of ints

    '''
    # Ensure that strand 1 is Watson and strand 2 is Crick
    if strand1 == 'c':
        seq1 = seq1.reverse_complement()
    if strand2 == 'w':
        seq2 = seq2.reverse_complement()
    # Generate all same-length 5' ends of seq1 and 3' ends of seq2 within
    # maximum homology length
    # TODO: If strings aren't used here, gen_chunks takes forever. Suggests a
    # need to optimize coral.DNA subsetting
    seq1_str = str(seq1)
    seq2_str = str(seq2)

    def gen_chunks(s1, s2):
        chunks1 = [seq1_str[-(i + 1):] for i in range(min(len(seq1_str),
                                                          max_size))]
        chunks2 = [seq2_str[:(i + 1)] for i in range(min(len(seq2_str),
                                                         max_size))]
        return chunks1, chunks2

    seq1_chunks, seq2_chunks = gen_chunks(seq1_str, seq2_str)

    # Check for exact matches from terminal end to terminal end
    target_matches = []
    for i, (s1, s2) in enumerate(zip(seq1_chunks, seq2_chunks)):
        s1len = len(s1)
        # Inefficient! (reverse complementing a bunch of times)
        # Don't calculate tm once base tm has been reached.
        # TODO: Go through logic here again and make sure the order of checking
        # makes sense
        if s1 == s2:
            logger.debug('Found Match: {}'.format(str(s1)))
            if s1len >= cutoff:
                tm = coral.analysis.tm(seq1[-(i + 1):])
                logger.debug('Match tm: {} C'.format(tm))
                if tm >= min_tm:
                    target_matches.append(s1len)
                elif tm >= min_tm - 4:
                    msg = 'One overlap had a Tm of {} C.'.format(tm)
                    warnings.warn(msg)
                    target_matches.append(s1len)

    target_matches.sort()
    if not top_two:
        return 0 if not target_matches else target_matches[0]
    else:
        return 0 if not target_matches else target_matches[0:2]

Response:
Report the size of all perfect
    matches between the 3 end of the top strand of seq1 and seq2.


Instruction:
Write a Python 3 function that can
get a sequence from Yeast genome. org.

Response:
def fetch_yeast_locus_sequence(locus_name, flanking_size=0):
    '''Acquire a sequence from SGD http://www.yeastgenome.org.

    :param locus_name: Common name or systematic name for the locus (e.g. ACT1
                       or YFL039C).
    :type locus_name: str
    :param flanking_size: The length of flanking DNA (on each side) to return
    :type flanking_size: int

    '''
    from intermine.webservice import Service

    service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')

    # Get a new query on the class (table) you will be querying:
    query = service.new_query('Gene')

    if flanking_size > 0:

        # The view specifies the output columns
        # secondaryIdentifier: the systematic name (e.g. YFL039C)
        # symbol: short name (e.g. ACT1)
        # length: sequence length
        # flankingRegions.direction: Upstream or downstream (or both) of locus
        # flankingRegions.sequence.length: length of the flanking regions
        # flankingRegions.sequence.residues: sequence of the flanking regions
        query.add_view('secondaryIdentifier', 'symbol', 'length',
                       'flankingRegions.direction',
                       'flankingRegions.sequence.length',
                       'flankingRegions.sequence.residues')

        # You can edit the constraint values below
        query.add_constraint('flankingRegions.direction', '=', 'both',
                             code='A')
        query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae',
                             code='B')
        query.add_constraint('flankingRegions.distance', '=',
                             '{:.1f}kb'.format(flanking_size / 1000.),
                             code='C')
        # Uncomment and edit the code below to specify your own custom logic:
        query.set_logic('A and B and C')

        # TODO: What to do when there's more than one result?
        first_result = query.rows().next()
        # FIXME: Use logger module instead
        # print first_result['secondaryIdentifier']
        # print first_result['symbol'], row['length']
        # print first_result['flankingRegions.direction']
        # print first_result['flankingRegions.sequence.length']
        # print first_result['flankingRegions.sequence.residues']

        seq = coral.DNA(first_result['flankingRegions.sequence.residues'])
        # TODO: add more metadata

    elif flanking_size == 0:
        # The view specifies the output columns
        query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol',
                       'name', 'sgdAlias', 'organism.shortName',
                       'sequence.length', 'sequence.residues', 'description',
                       'qualifier')

        query.add_constraint('status', 'IS NULL', code='D')
        query.add_constraint('status', '=', 'Active', code='C')
        query.add_constraint('qualifier', 'IS NULL', code='B')
        query.add_constraint('qualifier', '!=', 'Dubious', code='A')
        query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae',
                             code='E')

        # Your custom constraint logic is specified with the code below:
        query.set_logic('(A or B) and (C or D) and E')

        first_result = query.rows().next()
        seq = coral.DNA(first_result['sequence.residues'])
    else:
        print 'Problem with the flanking region size....'
        seq = coral.DNA('')

    return seq


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_yeast_sequence(chromosome, start, end, reverse_complement=False):
    '''Acquire a sequence from SGD http://www.yeastgenome.org
    :param chromosome: Yeast chromosome.
    :type chromosome: int
    :param start: A biostart.
    :type start: int
    :param end: A bioend.
    :type end: int
    :param reverse_complement: Get the reverse complement.
    :type revervse_complement: bool
    :returns: A DNA sequence.
    :rtype: coral.DNA

    '''
    import requests

    if start != end:
        if reverse_complement:
            rev_option = '-REV'
        else:
            rev_option = ''
        param_url = '&chr=' + str(chromosome) + '&beg=' + str(start) + \
                    '&end=' + str(end) + '&rev=' + rev_option
        url = 'http://www.yeastgenome.org/cgi-bin/getSeq?map=a2map' + \
            param_url

        res = requests.get(url)
        # ok... sadely, I contacted SGD and they haven;t implemented this so
        # I have to parse their yeastgenome page, but
        # it is easy between the raw sequence is between <pre> tags!

        # warning that's for the first < so we need +5!
        begin_index = res.text.index('<pre>')

        end_index = res.text.index('</pre>')
        sequence = res.text[begin_index + 5:end_index]
        sequence = sequence.replace('\n', '').replace('\r', '')
    else:
        sequence = ''

    return coral.DNA(sequence)

Response: Acquire a sequence from Yeast genome.


Instruction:
Implement a Python 3 function for
acquiring the location of a gene from Yeast genome. org.

Response:
def get_yeast_gene_location(gene_name):
    '''Acquire the location of a gene from SGD http://www.yeastgenome.org
    :param gene_name: Name of the gene.
    :type gene_name: string
    :returns location: [int: chromosome, int:biostart, int:bioend, int:strand]
    :rtype location: list

    '''
    from intermine.webservice import Service
    service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')

    # Get a new query on the class (table) you will be querying:
    query = service.new_query('Gene')

    # The view specifies the output columns
    query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol',
                   'name', 'organism.shortName',
                   'chromosome.primaryIdentifier',
                   'chromosomeLocation.start', 'chromosomeLocation.end',
                   'chromosomeLocation.strand')

    # Uncomment and edit the line below (the default) to select a custom sort
    # order:
    # query.add_sort_order('Gene.primaryIdentifier', 'ASC')

    # You can edit the constraint values below
    query.add_constraint('organism.shortName', '=', 'S. cerevisiae',
                         code='B')
    query.add_constraint('Gene', 'LOOKUP', gene_name, code='A')

    # Uncomment and edit the code below to specify your own custom logic:
    # query.set_logic('A and B')
    chromosomes = {'chrI': 1,
                   'chrII': 2,
                   'chrIII': 3,
                   'chrIV': 4,
                   'chrV': 5,
                   'chrVI': 6,
                   'chrVII': 7,
                   'chrVIII': 8,
                   'chrIX': 9,
                   'chrX': 10,
                   'chrXI': 11,
                   'chrXII': 12,
                   'chrXIII': 13,
                   'chrXIV': 14,
                   'chrXV': 15,
                   'chrXVI': 16}
    first_result = query.rows().next()

    return [chromosomes[first_result['chromosome.primaryIdentifier']],
            first_result['chromosomeLocation.start'],
            first_result['chromosomeLocation.end'],
            int(first_result['chromosomeLocation.strand'])]


Instruction:
How would you code a function in Python 3 to
retrieve systematic yeast gene id from the common name.

Response:
def get_gene_id(gene_name):
    '''Retrieve systematic yeast gene name from the common name.

    :param gene_name: Common name for yeast gene (e.g. ADE2).
    :type gene_name: str
    :returns: Systematic name for yeast gene (e.g. YOR128C).
    :rtype: str

    '''
    from intermine.webservice import Service

    service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')

    # Get a new query on the class (table) you will be querying:
    query = service.new_query('Gene')

    # The view specifies the output columns
    query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol',
                   'name', 'sgdAlias', 'crossReferences.identifier',
                   'crossReferences.source.name')

    # Uncomment and edit the line below (the default) to select a custom sort
    # order:
    # query.add_sort_order('Gene.primaryIdentifier', 'ASC')

    # You can edit the constraint values below
    query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B')
    query.add_constraint('Gene', 'LOOKUP', gene_name, code='A')

    # Uncomment and edit the code below to specify your own custom logic:
    # query.set_logic('A and B')

    for row in query.rows():
        gid = row['secondaryIdentifier']
    return gid


Instruction:
Can you generate the documentation for the following Python 3 function
def get_yeast_promoter_ypa(gene_name):
    '''Retrieve promoter from Yeast Promoter Atlas
    (http://ypa.csbb.ntu.edu.tw).

    :param gene_name: Common name for yeast gene.
    :type gene_name: str
    :returns: Double-stranded DNA sequence of the promoter.
    :rtype: coral.DNA

    '''
    import requests

    loc = get_yeast_gene_location(gene_name)
    gid = get_gene_id(gene_name)
    ypa_baseurl = 'http://ypa.csbb.ntu.edu.tw/do'
    params = {'act': 'download',
              'nucle': 'InVitro',
              'right': str(loc[2]),
              'left': str(loc[1]),
              'gene': str(gid),
              'chr': str(loc[0])}

    response = requests.get(ypa_baseurl, params=params)
    text = response.text
    # FASTA records are just name-sequence pairs split up by > e.g.
    # >my_dna_name
    # GACGATA
    # TODO: most of this is redundant, as we just want the 2nd record
    record_split = text.split('>')
    record_split.pop(0)
    parsed = []
    for record in record_split:
        parts = record.split('\n')
        sequence = coral.DNA(''.join(parts[1:]))
        sequence.name = parts[0]
        parsed.append(sequence)

    return parsed[1]

Response:
Retrieve promoter from Yeast Promoter Atlas
   .


Instruction:
Create a Python 3 function for
growing equidistant overlaps until they meet specified constraints.

Response:
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min,
                   min_exception):
    '''Grows equidistant overlaps until they meet specified constraints.

    :param dna: Input sequence.
    :type dna: coral.DNA
    :param melting_temp: Ideal Tm of the overlaps, in degrees C.
    :type melting_temp: float
    :param require_even: Require that the number of oligonucleotides is even.
    :type require_even: bool
    :param length_max: Maximum oligo size (e.g. 60bp price point cutoff)
                       range.
    :type length_range: int
    :param overlap_min: Minimum overlap size.
    :type overlap_min: int
    :param min_exception: In order to meet melting_temp and overlap_min
                          settings, allow overlaps less than overlap_min to
                          continue growing above melting_temp.
    :type min_exception: bool
    :returns: Oligos, their overlapping regions, overlap Tms, and overlap
              indices.
    :rtype: tuple

    '''
    # TODO: prevent growing overlaps from bumping into each other -
    # should halt when it happens, give warning, let user decide if they still
    # want the current construct
    # Another option would be to start over, moving the starting positions
    # near the problem region a little farther from each other - this would
    # put the AT-rich region in the middle of the spanning oligo

    # Try bare minimum number of oligos
    oligo_n = len(dna) // length_max + 1

    # Adjust number of oligos if even number required
    if require_even:
        oligo_increment = 2
        if oligo_n % 2 == 1:
            oligo_n += 1
    else:
        oligo_increment = 1

    # Increase oligo number until the minimum oligo_len is less than length_max
    while float(len(dna)) / oligo_n > length_max:
        oligo_n += oligo_increment

    # Loop until all overlaps meet minimum Tm and length
    tm_met = False
    len_met = False

    while(not tm_met or not len_met):
        # Calculate initial number of overlaps
        overlap_n = oligo_n - 1

        # Place overlaps approximately equidistant over sequence length
        overlap_interval = float(len(dna)) / oligo_n
        starts = [int(overlap_interval * (i + 1)) for i in range(overlap_n)]
        ends = [index + 1 for index in starts]

        # Fencepost for while loop
        # Initial overlaps (1 base) and their tms
        overlaps = [dna[start:end] for start, end in zip(starts, ends)]
        overlap_tms = [coral.analysis.tm(overlap) for overlap in overlaps]
        index = overlap_tms.index(min(overlap_tms))
        # Initial oligos - includes the 1 base overlaps.
        # All the oligos are in the same direction - reverse
        # complementation of every other one happens later
        oligo_starts = [0] + starts
        oligo_ends = ends + [len(dna)]
        oligo_indices = [oligo_starts, oligo_ends]

        oligos = [dna[start:end] for start, end in zip(*oligo_indices)]

        # Oligo won't be maxed in first pass. tm_met and len_met will be false
        maxed = False

        while not (tm_met and len_met) and not maxed:
            # Recalculate overlaps and their Tms
            overlaps = _recalculate_overlaps(dna, overlaps, oligo_indices)
            # Tm calculation is bottleneck - only recalculate changed overlap
            overlap_tms[index] = coral.analysis.tm(overlaps[index])
            # Find lowest-Tm overlap and its index.
            index = overlap_tms.index(min(overlap_tms))
            # Move overlap at that index
            oligos = _expand_overlap(dna, oligo_indices, index, oligos,
                                     length_max)
            # Regenerate conditions
            maxed = any([len(x) == length_max for x in oligos])
            tm_met = all([x >= melting_temp for x in overlap_tms])
            if min_exception:
                len_met = True
            else:
                len_met = all([len(x) >= overlap_min for x in overlaps])

        # TODO: add test for min_exception case (use rob's sequence from
        # 20130624 with 65C Tm)
        if min_exception:
            len_met = all([len(x) >= overlap_min for x in overlaps])

            # See if len_met is true - if so do nothing
            if len_met:
                break
            else:
                while not len_met and not maxed:
                    # Recalculate overlaps and their Tms
                    overlaps = _recalculate_overlaps(dna, overlaps,
                                                     oligo_indices)
                    # Overlap to increase is the shortest one
                    overlap_lens = [len(overlap) for overlap in overlaps]
                    index = overlap_lens.index(min(overlap_lens))
                    # Increase left or right oligo
                    oligos = _expand_overlap(dna, oligo_indices, index, oligos,
                                             length_max)
                    # Recalculate conditions
                    maxed = any([len(x) == length_max for x in oligos])
                    len_met = all([len(x) >= overlap_min for x in overlaps])

                # Recalculate tms to reflect any changes (some are redundant)
                overlap_tms[index] = coral.analysis.tm(overlaps[index])

                # Outcome could be that len_met happened *or* maxed out
                # length of one of the oligos. If len_met happened, should be
                # done so long as tm_met has been satisfied. If maxed happened,
                # len_met will not have been met, even if tm_met is satisfied,
                # and script will reattempt with more oligos

        oligo_n += oligo_increment

    # Calculate location of overlaps
    overlap_indices = [(oligo_indices[0][x + 1], oligo_indices[1][x]) for x in
                       range(overlap_n)]

    return oligos, overlaps, overlap_tms, overlap_indices


Instruction:
Given the following Python 3 function, write the documentation
def _recalculate_overlaps(dna, overlaps, oligo_indices):
    '''Recalculate overlap sequences based on the current overlap indices.

    :param dna: Sequence being split into oligos.
    :type dna: coral.DNA
    :param overlaps: Current overlaps - a list of DNA sequences.
    :type overlaps: coral.DNA list
    :param oligo_indices: List of oligo indices (starts and stops).
    :type oligo_indices: list
    :returns: Overlap sequences.
    :rtype: coral.DNA list

    '''
    for i, overlap in enumerate(overlaps):
        first_index = oligo_indices[0][i + 1]
        second_index = oligo_indices[1][i]
        overlap = dna[first_index:second_index]
        overlaps[i] = overlap

    return overlaps

Response: Recalculate the overlaps of the current sequence based on the current overlap indices.


Instruction:
How would you implement a function in Python 3 that
gives an overlap to increase increases smaller oligo.

Response:
def _expand_overlap(dna, oligo_indices, index, oligos, length_max):
    '''Given an overlap to increase, increases smaller oligo.

    :param dna: Sequence being split into oligos.
    :type dna: coral.DNA
    :param oligo_indices: index of oligo starts and stops
    :type oligo_indices: list
    :param index: index of the oligo
    :type index: int
    :param left_len: length of left oligo
    :type left_len: int
    :param right_len: length of right oligo
    :type right_len: int
    :param length_max: length ceiling
    :type length_max: int
    :returns: New oligo list with one expanded.
    :rtype: list

    '''
    left_len = len(oligos[index])
    right_len = len(oligos[index + 1])

    # If one of the oligos is max size, increase the other one
    if right_len == length_max:
        oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right')
    elif left_len == length_max:
        oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left')
    else:
        if left_len > right_len:
            oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left')
        else:
            oligo_indices[1] = _adjust_overlap(oligo_indices[1], index,
                                               'right')

    # Recalculate oligos from start and end indices
    oligos = [dna[start:end] for start, end in zip(*oligo_indices)]

    return oligos


Instruction:
Explain what the following Python 3 code does
def _adjust_overlap(positions_list, index, direction):
    '''Increase overlap to the right or left of an index.

    :param positions_list: list of overlap positions
    :type positions_list: list
    :param index: index of the overlap to increase.
    :type index: int
    :param direction: which side of the overlap to increase - left or right.
    :type direction: str
    :returns: A list of overlap positions (2-element lists)
    :rtype: list
    :raises: ValueError if direction isn't \'left\' or \'right\'.

    '''
    if direction == 'left':
        positions_list[index + 1] -= 1
    elif direction == 'right':
        positions_list[index] += 1
    else:
        raise ValueError('direction must be \'left\' or \'right\'.')
    return positions_list

Response: Increase the overlap to the right or left of an index.


Instruction:
How would you implement a function in Python 3 that
designs the overlapping oligos and sequences Tms and indices of their respective overlapping regions.

Response:
def design_assembly(self):
        '''Design the overlapping oligos.

        :returns: Assembly oligos, and the sequences, Tms, and indices of their
                  overlapping regions.
        :rtype: dict

        '''
        # Input parameters needed to design the oligos
        length_range = self.kwargs['length_range']
        oligo_number = self.kwargs['oligo_number']
        require_even = self.kwargs['require_even']
        melting_temp = self.kwargs['tm']
        overlap_min = self.kwargs['overlap_min']
        min_exception = self.kwargs['min_exception']
        start_5 = self.kwargs['start_5']

        if len(self.template) < length_range[0]:
            # If sequence can be built with just two oligos, do that
            oligos = [self.template, self.template.reverse_complement()]
            overlaps = [self.template]
            overlap_tms = [coral.analysis.tm(self.template)]
            assembly_dict = {'oligos': oligos, 'overlaps': overlaps,
                             'overlap_tms': overlap_tms}

            self.oligos = assembly_dict['oligos']
            self.overlaps = assembly_dict['overlaps']
            self.overlap_tms = assembly_dict['overlap_tms']
            return assembly_dict

        if oligo_number:
            # Make first attempt using length_range[1] and see what happens
            step = 3  # Decrease max range by this amount each iteration

            length_max = length_range[1]
            current_oligo_n = oligo_number + 1
            oligo_n_met = False
            above_min_len = length_max > length_range[0]
            if oligo_n_met or not above_min_len:
                raise Exception('Failed to design assembly.')
            while not oligo_n_met and above_min_len:
                # Starting with low range and going up doesnt work for longer
                # sequence (overlaps become longer than 80)
                assembly = _grow_overlaps(self.template, melting_temp,
                                          require_even, length_max,
                                          overlap_min, min_exception)
                current_oligo_n = len(assembly[0])
                if current_oligo_n > oligo_number:
                    break
                length_max -= step
                oligo_n_met = current_oligo_n == oligo_number
        else:
            assembly = _grow_overlaps(self.template, melting_temp,
                                      require_even, length_range[1],
                                      overlap_min, min_exception)

        oligos, overlaps, overlap_tms, overlap_indices = assembly

        if start_5:
            for i in [x for x in range(len(oligos)) if x % 2 == 1]:
                oligos[i] = oligos[i].reverse_complement()
        else:
            for i in [x for x in range(len(oligos)) if x % 2 == 0]:
                oligos[i] = oligos[i].reverse_complement()

        # Make single-stranded
        oligos = [oligo.top for oligo in oligos]

        assembly_dict = {'oligos': oligos,
                         'overlaps': overlaps,
                         'overlap_tms': overlap_tms,
                         'overlap_indices': overlap_indices}

        self.oligos = assembly_dict['oligos']
        self.overlaps = assembly_dict['overlaps']
        self.overlap_tms = assembly_dict['overlap_tms']
        self.overlap_indices = assembly_dict['overlap_indices']

        for i in range(len(self.overlap_indices) - 1):
            # TODO: either raise an exception or prevent this from happening
            # at all
            current_start = self.overlap_indices[i + 1][0]
            current_end = self.overlap_indices[i][1]
            if current_start <= current_end:
                self.warning = 'warning: overlapping overlaps!'
                print self.warning

        self._has_run = True
        return assembly_dict


Instruction:
Can you generate a brief explanation for the following Python 3 code
def primers(self, tm=60):
        '''Design primers for amplifying the assembled sequence.

        :param tm: melting temperature (lower than overlaps is best).
        :type tm: float
        :returns: Primer list (the output of coral.design.primers).
        :rtype: list

        '''
        self.primers = coral.design.primers(self.template, tm=tm)
        return self.primers

Response: Design primers for amplifying the assembled sequence.


Instruction:
Implement a function in Python 3 to
write assembly oligos and primers to a CSV file.

Response:
def write(self, path):
        '''Write assembly oligos and (if applicable) primers to csv.

        :param path: path to csv file, including .csv extension.
        :type path: str

        '''
        with open(path, 'wb') as oligo_file:
            oligo_writer = csv.writer(oligo_file, delimiter=',',
                                      quoting=csv.QUOTE_MINIMAL)
            oligo_writer.writerow(['name', 'oligo', 'notes'])
            for i, oligo in enumerate(self.oligos):
                name = 'oligo {}'.format(i + 1)
                oligo_len = len(oligo)
                if i != len(self.oligos) - 1:
                    oligo_tm = self.overlap_tms[i]
                    notes = 'oligo length: {}, '.format(oligo_len) + \
                            'overlap Tm: {:.2f}'.format(oligo_tm)
                else:
                    notes = 'oligo length: {}'.format(oligo_len)
                oligo_writer.writerow([name, oligo, notes])
            if self.primers:
                for i, (primer, melt) in enumerate(self.primers):
                    oligo_writer.writerow(['primer {}'.format(i + 1),
                                           primer,
                                           'Tm: {:.2f}'.format(melt)])


Instruction:
Can you implement a function in Python 3 that
writes genbank map that highlights overlaps.

Response:
def write_map(self, path):
        '''Write genbank map that highlights overlaps.

        :param path: full path to .gb file to write.
        :type path: str

        '''
        starts = [index[0] for index in self.overlap_indices]
        features = []
        for i, start in enumerate(starts):
            stop = start + len(self.overlaps[i])
            name = 'overlap {}'.format(i + 1)
            feature_type = 'misc'
            strand = 0
            features.append(coral.Feature(name, start, stop, feature_type,
                                          strand=strand))
        seq_map = coral.DNA(self.template, features=features)
        coral.seqio.write_dna(seq_map, path)


Instruction:
How would you code a function in Python 3 to
extract a coding sequence from an RNA sequence.

Response:
def coding_sequence(rna):
    '''Extract coding sequence from an RNA template.

    :param seq: Sequence from which to extract a coding sequence.
    :type seq: coral.RNA
    :param material: Type of sequence ('dna' or 'rna')
    :type material: str
    :returns: The first coding sequence (start codon -> stop codon) matched
              from 5' to 3'.
    :rtype: coral.RNA
    :raises: ValueError if rna argument has no start codon.
             ValueError if rna argument has no stop codon in-frame with the
             first start codon.

    '''
    if isinstance(rna, coral.DNA):
        rna = transcribe(rna)
    codons_left = len(rna) // 3
    start_codon = coral.RNA('aug')
    stop_codons = [coral.RNA('uag'), coral.RNA('uga'), coral.RNA('uaa')]
    start = None
    stop = None
    valid = [None, None]
    index = 0
    while codons_left:
        codon = rna[index:index + 3]
        if valid[0] is None:
            if codon in start_codon:
                start = index
                valid[0] = True
        else:
            if codon in stop_codons:
                stop = index + 3
                valid[1] = True
                break
        index += 3
        codons_left -= 1

    if valid[0] is None:
        raise ValueError('Sequence has no start codon.')
    elif stop is None:
        raise ValueError('Sequence has no stop codon.')
    coding_rna = rna[start:stop]

    return coding_rna


Instruction:
How would you explain what the following Python 3 function does
def update(self):
        '''Update definitions.'''
        # Download http://rebase.neb.com/rebase/link_withref to tmp
        self._tmpdir = tempfile.mkdtemp()
        try:
            self._rebase_file = self._tmpdir + '/rebase_file'
            print 'Downloading latest enzyme definitions'
            url = 'http://rebase.neb.com/rebase/link_withref'
            header = {'User-Agent': 'Mozilla/5.0'}
            req = urllib2.Request(url, headers=header)
            con = urllib2.urlopen(req)
            with open(self._rebase_file, 'wb') as rebase_file:
                rebase_file.write(con.read())
            # Process into self._enzyme_dict
            self._process_file()
        except urllib2.HTTPError, e:
            print 'HTTP Error: {} {}'.format(e.code, url)
            print 'Falling back on default enzyme list'
            self._enzyme_dict = coral.constants.fallback_enzymes
        except urllib2.URLError, e:
            print 'URL Error: {} {}'.format(e.reason, url)
            print 'Falling back on default enzyme list'
            self._enzyme_dict = coral.constants.fallback_enzymes
        # Process into RestrictionSite objects? (depends on speed)
        print 'Processing into RestrictionSite instances.'
        self.restriction_sites = {}
        # TODO: make sure all names are unique
        for key, (site, cuts) in self._enzyme_dict.iteritems():
            # Make a site
            try:
                r = coral.RestrictionSite(coral.DNA(site), cuts, name=key)
                # Add it to dict with name as key
                self.restriction_sites[key] = r
            except ValueError:
                # Encountered ambiguous sequence, have to ignore it until
                # coral.DNA can handle ambiguous DNA
                pass

Response: Update the internal state of the object.


Instruction:
Can you create a Python 3 function that
processes the rebase file into a dict with name and cut site information.

Response:
def _process_file(self):
        '''Process rebase file into dict with name and cut site information.'''
        print 'Processing file'
        with open(self._rebase_file, 'r') as f:
            raw = f.readlines()
        names = [line.strip()[3:] for line in raw if line.startswith('<1>')]
        seqs = [line.strip()[3:] for line in raw if line.startswith('<5>')]
        if len(names) != len(seqs):
            raise Exception('Found different number of enzyme names and '
                            'sequences.')
        self._enzyme_dict = {}
        for name, seq in zip(names, seqs):
            if '?' in seq:
                # Is unknown sequence, don't keep it
                pass
            elif seq.startswith('(') and seq.endswith(')'):
                # Has four+ cut sites, don't keep it
                pass
            elif '^' in seq:
                # Has reasonable internal cut sites, keep it
                top_cut = seq.index('^')
                bottom_cut = len(seq) - top_cut - 1
                site = seq.replace('^', '')
                self._enzyme_dict[name] = (site, (top_cut, bottom_cut))
            elif seq.endswith(')'):
                # Has reasonable external cut sites, keep it
                # (4-cutter also starts with '(')
                # separate site and cut locations
                site, cuts = seq.split('(')
                cuts = cuts.replace(')', '')
                top_cut, bottom_cut = [int(x) + len(site) for x in
                                       cuts.split('/')]
                self._enzyme_dict[name] = (site, (top_cut, bottom_cut))
        shutil.rmtree(self._tmpdir)


Instruction:
Here you have a function in Python 3, explain what it does
def copy(self):
        '''Create a copy of the current instance.

        :returns: A safely editable copy of the current sequence.
        :rtype: coral.Peptide

        '''
        return type(self)(str(self._sequence), features=self.features,
                          run_checks=False)

Response: Create a safely editable copy of the current instance.


Instruction:
Make a summary of the following Python 3 code
def convert_sequence(seq, to_material):
    '''Translate a DNA sequence into peptide sequence.

    The following conversions are supported:
        Transcription (seq is DNA, to_material is 'rna')
        Reverse transcription (seq is RNA, to_material is 'dna')
        Translation (seq is RNA, to_material is 'peptide')

    :param seq: DNA or RNA sequence.
    :type seq: coral.DNA or coral.RNA
    :param to_material: material to which to convert ('rna', 'dna', or
                        'peptide').
    :type to_material: str
    :returns: sequence of type coral.sequence.[material type]

    '''
    if isinstance(seq, coral.DNA) and to_material == 'rna':
        # Transcribe

        # Can't transcribe a gap
        if '-' in seq:
            raise ValueError('Cannot transcribe gapped DNA')
        # Convert DNA chars to RNA chars
        origin = ALPHABETS['dna'][:-1]
        destination = ALPHABETS['rna']
        code = dict(zip(origin, destination))
        converted = ''.join([code.get(str(k), str(k)) for k in seq])
        # Instantiate RNA object
        converted = coral.RNA(converted)
    elif isinstance(seq, coral.RNA):
        if to_material == 'dna':
            # Reverse transcribe
            origin = ALPHABETS['rna']
            destination = ALPHABETS['dna'][:-1]
            code = dict(zip(origin, destination))
            converted = ''.join([code.get(str(k), str(k)) for k in seq])
            # Instantiate DNA object
            converted = coral.DNA(converted)
        elif to_material == 'peptide':
            # Translate
            seq_list = list(str(seq))
            # Convert to peptide until stop codon is found.
            converted = []
            while True:
                if len(seq_list) >= 3:
                    base_1 = seq_list.pop(0)
                    base_2 = seq_list.pop(0)
                    base_3 = seq_list.pop(0)
                    codon = ''.join(base_1 + base_2 + base_3).upper()
                    amino_acid = CODONS[codon]
                    # Stop when stop codon is found
                    if amino_acid == '*':
                        break
                    converted.append(amino_acid)
                else:
                    break
            converted = ''.join(converted)
            converted = coral.Peptide(converted)
    else:
        msg1 = 'Conversion from '
        msg2 = '{0} to {1} is not supported.'.format(seq.__class__.__name__,
                                                     to_material)
        raise ValueError(msg1 + msg2)

    return converted

Response: Translate a DNA sequence into peptide sequence.


Instruction:
Implement a Python 3 function for
finding the frequency of G and C in the current sequence.

Response:
def gc(self):
        '''Find the frequency of G and C in the current sequence.'''
        gc = len([base for base in self.seq if base == 'C' or base == 'G'])
        return float(gc) / len(self)


Instruction:
Write a Python 3 script to
determine whether two sequences are the same just at different rotations.

Response:
def is_rotation(self, other):
        '''Determine whether two sequences are the same, just at different
        rotations.

        :param other: The sequence to check for rotational equality.
        :type other: coral.sequence._sequence.Sequence

        '''
        if len(self) != len(other):
            return False

        for i in range(len(self)):
            if self.rotate(i) == other:
                return True

        return False


Instruction:
How would you explain what the following Python 3 function does
def linearize(self, index=0):
        '''Linearize the Sequence at an index.

        :param index: index at which to linearize.
        :type index: int
        :returns: A linearized version of the current sequence.
        :rtype: coral.sequence._sequence.Sequence
        :raises: ValueError if the input is a linear sequence.

        '''
        if not self.circular and index != 0:
            raise ValueError('Cannot relinearize a linear sequence.')
        copy = self.copy()
        # Snip at the index
        if index:
            return copy[index:] + copy[:index]
        copy.circular = False

        return copy

Response: Linearize the Sequence at an index.


Instruction:
Given the following Python 3 function, write the documentation
def locate(self, pattern):
        '''Find sequences matching a pattern.

        :param pattern: Sequence for which to find matches.
        :type pattern: str
        :returns: Indices of pattern matches.
        :rtype: list of ints

        '''
        if self.circular:
            if len(pattern) >= 2 * len(self):
                raise ValueError('Search pattern longer than searchable ' +
                                 'sequence.')
            seq = self + self[:len(pattern) - 1]
            return super(NucleicAcid, seq).locate(pattern)
        else:
            return super(NucleicAcid, self).locate(pattern)

Response: Find sequences matching a pattern.


Instruction:
Can you write a function in Python 3 where it
calculates the molecular weight of the current sequence in amu.

Response:
def mw(self):
        '''Calculate the molecular weight.

        :returns: The molecular weight of the current sequence in amu.
        :rtype: float

        '''
        counter = collections.Counter(self.seq.lower())
        mw_a = counter['a'] * 313.2
        mw_t = counter['t'] * 304.2
        mw_g = counter['g'] * 289.2
        mw_c = counter['c'] * 329.2
        mw_u = counter['u'] * 306.2

        if self.material == 'dna':
            return mw_a + mw_t + mw_g + mw_c + 79.0
        else:
            return mw_a + mw_u + mw_g + mw_c + 159.0


Instruction:
Can you write a function in Python 3 where it
rotates the current sequence by n bases.

Response:
def rotate(self, n):
        '''Rotate Sequence by n bases.

        :param n: Number of bases to rotate.
        :type n: int
        :returns: The current sequence reoriented at `index`.
        :rtype: coral.sequence._sequence.Sequence
        :raises: ValueError if applied to linear sequence or `index` is
                 negative.

        '''
        if not self.circular and n != 0:
            raise ValueError('Cannot rotate a linear sequence')
        else:
            rotated = self[-n:] + self[:-n]
            return rotated.circularize()


Instruction:
Given the following Python 3 function, write the documentation
def five_resect(dna, n_bases):
    '''Remove bases from 5' end of top strand.

    :param dna: Sequence to resect.
    :type dna: coral.DNA
    :param n_bases: Number of bases cut back.
    :type n_bases: int
    :returns: DNA sequence resected at the 5' end by n_bases.
    :rtype: coral.DNA

    '''
    new_instance = dna.copy()
    if n_bases >= len(dna):
        new_instance.top.seq = ''.join(['-' for i in range(len(dna))])
    else:
        new_instance.top.seq = '-' * n_bases + str(dna)[n_bases:]

    new_instance = _remove_end_gaps(new_instance)

    return new_instance

Response: Remove bases from 5 end of top strand.


Instruction:
Create a Python 3 function for
removing double - stranded gaps from ends of the sequence.

Response:
def _remove_end_gaps(sequence):
    '''Removes double-stranded gaps from ends of the sequence.

    :returns: The current sequence with terminal double-strand gaps ('-')
              removed.
    :rtype: coral.DNA

    '''
    # Count terminal blank sequences
    def count_end_gaps(seq):
        gap = coral.DNA('-')
        count = 0
        for base in seq:
            if base == gap:
                count += 1
            else:
                break

        return count

    top_left = count_end_gaps(sequence.top)
    top_right = count_end_gaps(reversed(sequence.top))
    bottom_left = count_end_gaps(reversed(sequence.bottom))
    bottom_right = count_end_gaps(sequence.bottom)

    # Trim sequence
    left_index = min(top_left, bottom_left)
    right_index = len(sequence) - min(top_right, bottom_right)

    return sequence[left_index:right_index]


Instruction:
Can you implement a function in Python 3 that
does a Needleman - Wunsch alignment against a reference sequence.

Response:
def needle(reference, query, gap_open=-15, gap_extend=0,
           matrix=submat.DNA_SIMPLE):
    '''Do a Needleman-Wunsch alignment.

    :param reference: Reference sequence.
    :type reference: coral.DNA
    :param query: Sequence to align against the reference.
    :type query: coral.DNA
    :param gapopen: Penalty for opening a gap.
    :type gapopen: float
    :param gapextend: Penalty for extending a gap.
    :type gapextend: float
    :param matrix: Matrix to use for alignment - options are DNA_simple (for
                   DNA) and BLOSUM62 (for proteins).
    :type matrix: str
    :returns: (aligned reference, aligned query, score)
    :rtype: tuple of two coral.DNA instances and a float

    '''
    # Align using cython Needleman-Wunsch
    aligned_ref, aligned_res = aligner(str(reference),
                                       str(query),
                                       gap_open=gap_open,
                                       gap_extend=gap_extend,
                                       method='global_cfe',
                                       matrix=matrix.matrix,
                                       alphabet=matrix.alphabet)

    # Score the alignment
    score = score_alignment(aligned_ref, aligned_res, gap_open, gap_extend,
                            matrix.matrix, matrix.alphabet)

    return cr.DNA(aligned_ref), cr.DNA(aligned_res), score


Instruction:
Implement a function in Python 3 to
create a multiple sequence alignment based on aligning every result sequence against the reference and then inserting gaps until every aligned result sequence is identical

Response:
def needle_msa(reference, results, gap_open=-15, gap_extend=0,
               matrix=submat.DNA_SIMPLE):
    '''Create a multiple sequence alignment based on aligning every result
    sequence against the reference, then inserting gaps until every aligned
    reference is identical

    '''
    gap = '-'
    # Convert alignments to list of strings
    alignments = []
    for result in results:
        ref_dna, res_dna, score = needle(reference, result, gap_open=gap_open,
                                         gap_extend=gap_extend,
                                         matrix=matrix)
        alignments.append([str(ref_dna), str(res_dna), score])

    def insert_gap(sequence, position):
        return sequence[:position] + gap + sequence[position:]

    i = 0
    while True:
        # Iterate over 'columns' in every reference
        refs = [alignment[0][i] for alignment in alignments]

        # If there's a non-unanimous gap, insert gap into alignments
        gaps = [ref == gap for ref in refs]
        if any(gaps) and not all(gaps):
            for alignment in alignments:
                if alignment[0][i] != gap:
                    alignment[0] = insert_gap(alignment[0], i)
                    alignment[1] = insert_gap(alignment[1], i)

        # If all references match, we're all done
        alignment_set = set(alignment[0] for alignment in alignments)
        if len(alignment_set) == 1:
            break

        # If we've reach the end of some, but not all sequences, add end gap
        lens = [len(alignment[0]) for alignment in alignments]
        if i + 1 in lens:
            for alignment in alignments:
                if len(alignment[0]) == i + 1:
                    alignment[0] = alignment[0] + gap
                    alignment[1] = alignment[1] + gap

        i += 1

        if i > 20:
            break

    # Convert into MSA format
    output_alignment = [cr.DNA(alignments[0][0])]
    for alignment in alignments:
        output_alignment.append(cr.DNA(alignment[1]))

    return output_alignment


Instruction:
Can you tell what is the following Python 3 function doing
def needle_multi(references, queries, gap_open=-15, gap_extend=0,
                 matrix=submat.DNA_SIMPLE):
    '''Batch process of sequencing split over several cores. Acts just like
    needle but sequence inputs are lists.

    :param references: References sequence.
    :type references: coral.DNA list
    :param queries: Sequences to align against the reference.
    :type queries: coral.DNA list
    :param gap_open: Penalty for opening a gap.
    :type gap_open: float
    :param gap_extend: Penalty for extending a gap.
    :type gap_extend: float
    :param matrix: Matrix to use for alignment - options are DNA_simple (for
                   DNA) and BLOSUM62 (for proteins).
    :type matrix: str
    :returns: a list of the same output as coral.sequence.needle
    :rtype: list

    '''
    pool = multiprocessing.Pool()
    try:
        args_list = [[ref, que, gap_open, gap_extend, matrix] for ref, que in
                     zip(references, queries)]
        aligned = pool.map(run_needle, args_list)
    except KeyboardInterrupt:
        print('Caught KeyboardInterrupt, terminating workers')
        pool.terminate()
        pool.join()
        raise KeyboardInterrupt

    return aligned

Response: This function is used to split a sequence into multiple cores.


Instruction:
Here you have a function in Python 3, explain what it does
def import_global(
        name, modules=None, exceptions=DummyException, locals_=None,
        globals_=None, level=-1):
    '''Import the requested items into the global scope

    WARNING! this method _will_ overwrite your global scope
    If you have a variable named "path" and you call import_global('sys')
    it will be overwritten with sys.path

    Args:
        name (str): the name of the module to import, e.g. sys
        modules (str): the modules to import, use None for everything
        exception (Exception): the exception to catch, e.g. ImportError
        `locals_`: the `locals()` method (in case you need a different scope)
        `globals_`: the `globals()` method (in case you need a different scope)
        level (int): the level to import from, this can be used for
        relative imports
    '''
    frame = None
    try:
        # If locals_ or globals_ are not given, autodetect them by inspecting
        # the current stack
        if locals_ is None or globals_ is None:
            import inspect
            frame = inspect.stack()[1][0]

            if locals_ is None:
                locals_ = frame.f_locals

            if globals_ is None:
                globals_ = frame.f_globals

        try:
            name = name.split('.')

            # Relative imports are supported (from .spam import eggs)
            if not name[0]:
                name = name[1:]
                level = 1

            # raise IOError((name, level))
            module = __import__(
                name=name[0] or '.',
                globals=globals_,
                locals=locals_,
                fromlist=name[1:],
                level=max(level, 0),
            )

            # Make sure we get the right part of a dotted import (i.e.
            # spam.eggs should return eggs, not spam)
            try:
                for attr in name[1:]:
                    module = getattr(module, attr)
            except AttributeError:
                raise ImportError('No module named ' + '.'.join(name))

            # If no list of modules is given, autodetect from either __all__
            # or a dir() of the module
            if not modules:
                modules = getattr(module, '__all__', dir(module))
            else:
                modules = set(modules).intersection(dir(module))

            # Add all items in modules to the global scope
            for k in set(dir(module)).intersection(modules):
                if k and k[0] != '_':
                    globals_[k] = getattr(module, k)
        except exceptions as e:
            return e
    finally:
        # Clean up, just to be sure
        del name, modules, exceptions, locals_, globals_, frame

Response: Import the requested items into the global scope.


Instruction:
Given the following Python 3 function, write the documentation
def camel_to_underscore(name):
    '''Convert camel case style naming to underscore style naming

    If there are existing underscores they will be collapsed with the
    to-be-added underscores. Multiple consecutive capital letters will not be
    split except for the last one.

    >>> camel_to_underscore('SpamEggsAndBacon')
    'spam_eggs_and_bacon'
    >>> camel_to_underscore('Spam_and_bacon')
    'spam_and_bacon'
    >>> camel_to_underscore('Spam_And_Bacon')
    'spam_and_bacon'
    >>> camel_to_underscore('__SpamAndBacon__')
    '__spam_and_bacon__'
    >>> camel_to_underscore('__SpamANDBacon__')
    '__spam_and_bacon__'
    '''
    output = []
    for i, c in enumerate(name):
        if i > 0:
            pc = name[i - 1]
            if c.isupper() and not pc.isupper() and pc != '_':
                # Uppercase and the previous character isn't upper/underscore?
                # Add the underscore
                output.append('_')
            elif i > 3 and not c.isupper():
                # Will return the last 3 letters to check if we are changing
                # case
                previous = name[i - 3:i]
                if previous.isalpha() and previous.isupper():
                    output.insert(len(output) - 1, '_')

        output.append(c.lower())

    return ''.join(output)

Response: Convert camel case style naming to underscore style naming


Instruction:
Here you have a function in Python 3, explain what it does
def timesince(dt, default='just now'):
    '''
    Returns string representing 'time since' e.g.
    3 days ago, 5 hours ago etc.

    >>> now = datetime.datetime.now()
    >>> timesince(now)
    'just now'
    >>> timesince(now - datetime.timedelta(seconds=1))
    '1 second ago'
    >>> timesince(now - datetime.timedelta(seconds=2))
    '2 seconds ago'
    >>> timesince(now - datetime.timedelta(seconds=60))
    '1 minute ago'
    >>> timesince(now - datetime.timedelta(seconds=61))
    '1 minute and 1 second ago'
    >>> timesince(now - datetime.timedelta(seconds=62))
    '1 minute and 2 seconds ago'
    >>> timesince(now - datetime.timedelta(seconds=120))
    '2 minutes ago'
    >>> timesince(now - datetime.timedelta(seconds=121))
    '2 minutes and 1 second ago'
    >>> timesince(now - datetime.timedelta(seconds=122))
    '2 minutes and 2 seconds ago'
    >>> timesince(now - datetime.timedelta(seconds=3599))
    '59 minutes and 59 seconds ago'
    >>> timesince(now - datetime.timedelta(seconds=3600))
    '1 hour ago'
    >>> timesince(now - datetime.timedelta(seconds=3601))
    '1 hour and 1 second ago'
    >>> timesince(now - datetime.timedelta(seconds=3602))
    '1 hour and 2 seconds ago'
    >>> timesince(now - datetime.timedelta(seconds=3660))
    '1 hour and 1 minute ago'
    >>> timesince(now - datetime.timedelta(seconds=3661))
    '1 hour and 1 minute ago'
    >>> timesince(now - datetime.timedelta(seconds=3720))
    '1 hour and 2 minutes ago'
    >>> timesince(now - datetime.timedelta(seconds=3721))
    '1 hour and 2 minutes ago'
    >>> timesince(datetime.timedelta(seconds=3721))
    '1 hour and 2 minutes ago'
    '''
    if isinstance(dt, datetime.timedelta):
        diff = dt
    else:
        now = datetime.datetime.now()
        diff = abs(now - dt)

    periods = (
        (diff.days / 365, 'year', 'years'),
        (diff.days % 365 / 30, 'month', 'months'),
        (diff.days % 30 / 7, 'week', 'weeks'),
        (diff.days % 7, 'day', 'days'),
        (diff.seconds / 3600, 'hour', 'hours'),
        (diff.seconds % 3600 / 60, 'minute', 'minutes'),
        (diff.seconds % 60, 'second', 'seconds'),
    )

    output = []
    for period, singular, plural in periods:
        if int(period):
            if int(period) == 1:
                output.append('%d %s' % (period, singular))
            else:
                output.append('%d %s' % (period, plural))

    if output:
        return '%s ago' % ' and '.join(output[:2])

    return default

Response: Returns a string representing time since


Instruction:
Can you generate the documentation for the following Python 3 function
def timedelta_to_seconds(delta):
    '''Convert a timedelta to seconds with the microseconds as fraction

    Note that this method has become largely obsolete with the
    `timedelta.total_seconds()` method introduced in Python 2.7.

    >>> from datetime import timedelta
    >>> '%d' % timedelta_to_seconds(timedelta(days=1))
    '86400'
    >>> '%d' % timedelta_to_seconds(timedelta(seconds=1))
    '1'
    >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1))
    '1.000001'
    >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1))
    '0.000001'
    '''
    # Only convert to float if needed
    if delta.microseconds:
        total = delta.microseconds * 1e-6
    else:
        total = 0
    total += delta.seconds
    total += delta.days * 60 * 60 * 24
    return total

Response: Convert a timedelta to seconds with the microseconds as fraction


Instruction:
Explain what the following Python 3 code does
def format_time(timestamp, precision=datetime.timedelta(seconds=1)):
    '''Formats timedelta/datetime/seconds

    >>> format_time('1')
    '0:00:01'
    >>> format_time(1.234)
    '0:00:01'
    >>> format_time(1)
    '0:00:01'
    >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
    '2000-01-02 03:04:05'
    >>> format_time(datetime.date(2000, 1, 2))
    '2000-01-02'
    >>> format_time(datetime.timedelta(seconds=3661))
    '1:01:01'
    >>> format_time(None)
    '--:--:--'
    >>> format_time(format_time)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    TypeError: Unknown type ...

    '''
    precision_seconds = precision.total_seconds()

    if isinstance(timestamp, six.string_types + six.integer_types + (float, )):
        try:
            castfunc = six.integer_types[-1]
            timestamp = datetime.timedelta(seconds=castfunc(timestamp))
        except OverflowError:  # pragma: no cover
            timestamp = None

    if isinstance(timestamp, datetime.timedelta):
        seconds = timestamp.total_seconds()
        # Truncate the number to the given precision
        seconds = seconds - (seconds % precision_seconds)

        return str(datetime.timedelta(seconds=seconds))
    elif isinstance(timestamp, datetime.datetime):
        # Python 2 doesn't have the timestamp method
        if hasattr(timestamp, 'timestamp'):  # pragma: no cover
            seconds = timestamp.timestamp()
        else:
            seconds = timedelta_to_seconds(timestamp - epoch)

        # Truncate the number to the given precision
        seconds = seconds - (seconds % precision_seconds)

        try:  # pragma: no cover
            if six.PY3:
                dt = datetime.datetime.fromtimestamp(seconds)
            else:
                dt = datetime.datetime.utcfromtimestamp(seconds)
        except ValueError:  # pragma: no cover
            dt = datetime.datetime.max
        return str(dt)
    elif isinstance(timestamp, datetime.date):
        return str(timestamp)
    elif timestamp is None:
        return '--:--:--'
    else:
        raise TypeError('Unknown type %s: %r' % (type(timestamp), timestamp))

Response: Formats a datetime object to be used in the log file.


Instruction:
Write a Python 3 script to
get the current size of your terminal.

Response:
def get_terminal_size():  # pragma: no cover
    '''Get the current size of your terminal

    Multiple returns are not always a good idea, but in this case it greatly
    simplifies the code so I believe it's justified. It's not the prettiest
    function but that's never really possible with cross-platform code.

    Returns:
        width, height: Two integers containing width and height
    '''

    try:
        # Default to 79 characters for IPython notebooks
        from IPython import get_ipython
        ipython = get_ipython()
        from ipykernel import zmqshell
        if isinstance(ipython, zmqshell.ZMQInteractiveShell):
            return 79, 24
    except Exception:  # pragma: no cover
        pass

    try:
        # This works for Python 3, but not Pypy3. Probably the best method if
        # it's supported so let's always try
        import shutil
        w, h = shutil.get_terminal_size()
        if w and h:
            # The off by one is needed due to progressbars in some cases, for
            # safety we'll always substract it.
            return w - 1, h
    except Exception:  # pragma: no cover
        pass

    try:
        w = int(os.environ.get('COLUMNS'))
        h = int(os.environ.get('LINES'))
        if w and h:
            return w, h
    except Exception:  # pragma: no cover
        pass

    try:
        import blessings
        terminal = blessings.Terminal()
        w = terminal.width
        h = terminal.height
        if w and h:
            return w, h
    except Exception:  # pragma: no cover
        pass

    try:
        w, h = _get_terminal_size_linux()
        if w and h:
            return w, h
    except Exception:  # pragma: no cover
        pass

    try:
        # Windows detection doesn't always work, let's try anyhow
        w, h = _get_terminal_size_windows()
        if w and h:
            return w, h
    except Exception:  # pragma: no cover
        pass

    try:
        # needed for window's python in cygwin's xterm!
        w, h = _get_terminal_size_tput()
        if w and h:
            return w, h
    except Exception:  # pragma: no cover
        pass

    return 79, 24


Instruction:
Here you have a function in Python 3, explain what it does
def Attach(self, Protocol=5, Wait=True):
        try:
            self._Api.protocol = Protocol
            self._Api.attach(self.Timeout, Wait)
        except SkypeAPIError:
            self.ResetCache()
            raise

Response: Establishes a connection to Skype.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def Call(self, Id=0):
        o = Call(self, Id)
        o.Status # Test if such a call exists.
        return o

Response: Queries a call object.


Instruction:
Make a summary of the following Python 3 code
def ChangeUserStatus(self, Status):
        if self.CurrentUserStatus.upper() == Status.upper():
            return
        self._ChangeUserStatus_Event = threading.Event()
        self._ChangeUserStatus_Status = Status.upper()
        self.RegisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus)
        self.CurrentUserStatus = Status
        self._ChangeUserStatus_Event.wait()
        self.UnregisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus)
        del self._ChangeUserStatus_Event, self._ChangeUserStatus_Status

Response: Changes the online status for the current user.


Instruction:
How would you implement a function in Python 3 that
queries a chat object.

Response:
def Chat(self, Name=''):
        """Queries a chat object.

        :Parameters:
          Name : str
            Chat name.

        :return: A chat object.
        :rtype: `chat.Chat`
        """
        o = Chat(self, Name)
        o.Status # Tests if such a chat really exists.
        return o


Instruction:
Can you generate the documentation for the following Python 3 function
def ClearCallHistory(self, Username='ALL', Type=chsAllCalls):
        cmd = 'CLEAR CALLHISTORY %s %s' % (str(Type), Username)
        self._DoCommand(cmd, cmd)

Response: Clears the call history for the specified user.


Instruction:
Implement a Python 3 function for
creating an API command object.

Response:
def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1):
        """Creates an API command object.

        :Parameters:
          Command : unicode
            Command string.
          Reply : unicode
            Expected reply. By default any reply is accepted (except errors which raise an
            `SkypeError` exception).
          Block : bool
            If set to True, `SendCommand` method waits for a response from Skype API before
            returning.
          Timeout : float, int or long
            Timeout. Used if Block == True. Timeout may be expressed in milliseconds if the type
            is int or long or in seconds (or fractions thereof) if the type is float.
          Id : int
            Command Id. The default (-1) means it will be assigned automatically as soon as the
            command is sent.

        :return: A command object.
        :rtype: `Command`

        :see: `SendCommand`
        """
        from api import Command as CommandClass
        return CommandClass(Command, Reply, Block, Timeout, Id)


Instruction:
Make a summary of the following Python 3 code
def Conference(self, Id=0):
        o = Conference(self, Id)
        if Id <= 0 or not o.Calls:
            raise SkypeError(0, 'Unknown conference')
        return o

Response: Queries a call conference object.


Instruction:
Write a Python 3 function for
creating a chat with one or more users.

Response:
def CreateChatWith(self, *Usernames):
        """Creates a chat with one or more users.

        :Parameters:
          Usernames : str
            One or more Skypenames of the users.

        :return: A chat object
        :rtype: `Chat`

        :see: `Chat.AddMembers`
        """
        return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1])


Instruction:
Here you have a function in Python 3, explain what it does
def CreateGroup(self, GroupName):
        groups = self.CustomGroups
        self._DoCommand('CREATE GROUP %s' % tounicode(GroupName))
        for g in self.CustomGroups:
            if g not in groups and g.DisplayName == GroupName:
                return g
        raise SkypeError(0, 'Group creating failed')

Response: Creates a custom contact group.


Instruction:
Can you implement a function in Python 3 that
creates an SMS message.

Response:
def CreateSms(self, MessageType, *TargetNumbers):
        """Creates an SMS message.

        :Parameters:
          MessageType : `enums`.smsMessageType*
            Message type.
          TargetNumbers : str
            One or more target SMS numbers.

        :return: An sms message object.
        :rtype: `SmsMessage`
        """
        return SmsMessage(self, chop(self._DoCommand('CREATE SMS %s %s' % (MessageType, ', '.join(TargetNumbers))), 2)[1])


Instruction:
Can you create a Python 3 function that
queries the greeting used as voicemail.

Response:
def Greeting(self, Username=''):
        """Queries the greeting used as voicemail.

        :Parameters:
          Username : str
            Skypename of the user.

        :return: A voicemail object.
        :rtype: `Voicemail`
        """
        for v in self.Voicemails:
            if Username and v.PartnerHandle != Username:
                continue
            if v.Type in (vmtDefaultGreeting, vmtCustomGreeting):
                return v


Instruction:
Can you tell what is the following Python 3 function doing
def Message(self, Id=0):
        o = ChatMessage(self, Id)
        o.Status # Test if such an id is known.
        return o

Response: Queries a chat message object.


Instruction:
Make a summary of the following Python 3 code
def PlaceCall(self, *Targets):
        calls = self.ActiveCalls
        reply = self._DoCommand('CALL %s' % ', '.join(Targets))
        # Skype for Windows returns the call status which gives us the call Id;
        if reply.startswith('CALL '):
            return Call(self, chop(reply, 2)[1])
        # On linux we get 'OK' as reply so we search for the new call on
        # list of active calls.
        for c in self.ActiveCalls:
            if c not in calls:
                return c
        raise SkypeError(0, 'Placing call failed')

Response: Places a call to a single user or creates a conference call.


Instruction:
How would you explain what the following Python 3 function does
def Property(self, ObjectType, ObjectId, PropName, Set=None):
        return self._Property(ObjectType, ObjectId, PropName, Set)

Response: Queries or sets the properties of an object.


Instruction:
Write a Python 3 script to
send an API command.

Response:
def SendCommand(self, Command):
        """Sends an API command.

        :Parameters:
          Command : `Command`
            Command to send. Use `Command` method to create a command.
        """
        try:
            self._Api.send_command(Command)
        except SkypeAPIError:
            self.ResetCache()
            raise


Instruction:
How would you implement a function in Python 3 that
creates and sends an SMS message.

Response:
def SendSms(self, *TargetNumbers, **Properties):
        """Creates and sends an SMS message.

        :Parameters:
          TargetNumbers : str
            One or more target SMS numbers.
          Properties
            Message properties. Properties available are same as `SmsMessage` object properties.

        :return: An sms message object. The message is already sent at this point.
        :rtype: `SmsMessage`
        """
        sms = self.CreateSms(smsMessageTypeOutgoing, *TargetNumbers)
        for name, value in Properties.items():
            if isinstance(getattr(sms.__class__, name, None), property):
                setattr(sms, name, value)
            else:
                raise TypeError('Unknown property: %s' % prop)
        sms.Send()
        return sms


Instruction:
Can you create a Python 3 function that
sends a voicemail to a specified user.

Response:
def SendVoicemail(self, Username):
        """Sends a voicemail to a specified user.

        :Parameters:
          Username : str
            Skypename of the user.

        :note: Should return a `Voicemail` object. This is not implemented yet.
        """
        if self._Api.protocol >= 6:
            self._DoCommand('CALLVOICEMAIL %s' % Username)
        else:
            self._DoCommand('VOICEMAIL %s' % Username)


Instruction:
Explain what the following Python 3 code does
def User(self, Username=''):
        if not Username:
            Username = self.CurrentUserHandle
        o = User(self, Username)
        o.OnlineStatus # Test if such a user exists.
        return o

Response: Queries a user object.


Instruction:
Here you have a function in Python 3, explain what it does
def Voicemail(self, Id):
        o = Voicemail(self, Id)
        o.Type # Test if such a voicemail exists.
        return o

Response: Queries the voicemail object.


Instruction:
Can you generate the documentation for the following Python 3 function
def Connect(self, Username, WaitConnected=False):
        if WaitConnected:
            self._Connect_Event = threading.Event()
            self._Connect_Stream = [None]
            self._Connect_Username = Username
            self._Connect_ApplicationStreams(self, self.Streams)
            self._Owner.RegisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams)
            self._Alter('CONNECT', Username)
            self._Connect_Event.wait()
            self._Owner.UnregisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams)
            try:
                return self._Connect_Stream[0]
            finally:
                del self._Connect_Stream, self._Connect_Event, self._Connect_Username
        else:
            self._Alter('CONNECT', Username)

Response: Connects application to user.


Instruction:
Given the following Python 3 function, write the documentation
def SendDatagram(self, Text, Streams=None):
        if Streams is None:
            Streams = self.Streams
        for s in Streams:
            s.SendDatagram(Text)

Response: Sends a datagram to the application streams.


Instruction:
Here you have a function in Python 3, explain what it does
def SendDatagram(self, Text):
        self.Application._Alter('DATAGRAM', '%s %s' % (self.Handle, tounicode(Text)))

Response: Sends a datagram to the stream.


Instruction:
Explain what the following Python 3 code does
def Write(self, Text):
        self.Application._Alter('WRITE', '%s %s' % (self.Handle, tounicode(Text)))

Response: Writes data to the stream.


Instruction:
Can you generate the documentation for the following Python 3 function
def CreateEvent(self, EventId, Caption, Hint):
        self._Skype._DoCommand('CREATE EVENT %s CAPTION %s HINT %s' % (tounicode(EventId),
            quote(tounicode(Caption)), quote(tounicode(Hint))))
        return PluginEvent(self._Skype, EventId)

Response: Creates a custom event displayed in Skype s events pane.


Instruction:
Create a Python 3 function for
creating custom menu item in Skype client s Do More menus.

Response:
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True,
                       ContactType=pluginContactTypeAll, MultipleContacts=False):
        """Creates custom menu item in Skype client's "Do More" menus.

        :Parameters:
          MenuItemId : unicode
            Unique identifier for the menu item.
          PluginContext : `enums`.pluginContext*
            Menu item context. Allows to choose in which client windows will the menu item appear.
          CaptionText : unicode
            Caption text.
          HintText : unicode
            Hint text (optional). Shown when mouse hoovers over the menu item.
          IconPath : unicode
            Path to the icon (optional).
          Enabled : bool
            Initial state of the menu item. True by default.
          ContactType : `enums`.pluginContactType*
            In case of `enums.pluginContextContact` tells which contacts the menu item should appear
            for. Defaults to `enums.pluginContactTypeAll`.
          MultipleContacts : bool
            Set to True if multiple contacts should be allowed (defaults to False).

        :return: Menu item object.
        :rtype: `PluginMenuItem`
        """
        cmd = 'CREATE MENU_ITEM %s CONTEXT %s CAPTION %s ENABLED %s' % (tounicode(MenuItemId), PluginContext,
            quote(tounicode(CaptionText)), cndexp(Enabled, 'true', 'false'))
        if HintText:
            cmd += ' HINT %s' % quote(tounicode(HintText))
        if IconPath:
            cmd += ' ICON %s' % quote(path2unicode(IconPath))
        if MultipleContacts:
            cmd += ' ENABLE_MULTIPLE_CONTACTS true'
        if PluginContext == pluginContextContact:
            cmd += ' CONTACT_TYPE_FILTER %s' % ContactType
        self._Skype._DoCommand(cmd)
        return PluginMenuItem(self._Skype, MenuItemId, CaptionText, HintText, Enabled)


Instruction:
Can you generate the documentation for the following Python 3 function
def Focus(self):
        self._Skype._Api.allow_focus(self._Skype.Timeout)
        self._Skype._DoCommand('FOCUS')

Response: Brings the client window into focus.


Instruction:
How would you explain what the following Python 3 function does
def OpenDialog(self, Name, *Params):
        self._Skype._Api.allow_focus(self._Skype.Timeout)
        params = filter(None, (str(Name),) + Params)
        self._Skype._DoCommand('OPEN %s' % tounicode(' '.join(params)))

Response:
Open dialog. Use this method to open dialogs added in newer Skype versions if there is no
        dedicated method in Skype4Py.

        :Parameters:
          Name : str
            Dialog name.
          Params : unicode
            One or more optional parameters.


Instruction:
How would you code a function in Python 3 to
open an IM Message dialog.

Response:
def OpenMessageDialog(self, Username, Text=u''):
        """Opens "Send an IM Message" dialog.

        :Parameters:
          Username : str
            Message target.
          Text : unicode
            Message text.
        """
        self.OpenDialog('IM', Username, tounicode(Text))


Instruction:
Write a Python 3 script for
starting Skype application. :Parameters: Minimized : bool If True, Skype is started minimized in system tray. Nosplash : bool If True, no splash screen is displayed upon startup.

Response:
def Start(self, Minimized=False, Nosplash=False):
        """Starts Skype application.

        :Parameters:
          Minimized : bool
            If True, Skype is started minimized in system tray.
          Nosplash : bool
            If True, no splash screen is displayed upon startup.
        """
        self._Skype._Api.startup(Minimized, Nosplash)


Instruction:
Can you create a Python 3 function that
starts the thread associated with this API object.

Response:
def start(self):
        """
        Start the thread associated with this API object.
        Ensure that the call is made no more than once,
        to avoid raising a RuntimeError.
        """
        if not self.thread_started:
            super(SkypeAPI, self).start()
            self.thread_started = True


Instruction:
Create a Python 3 function to
enable multithreading support in Xlib and PyGTK.

Response:
def threads_init(gtk=True):
    """Enables multithreading support in Xlib and PyGTK.
    See the module docstring for more info.

    :Parameters:
      gtk : bool
        May be set to False to skip the PyGTK module.
    """
    # enable X11 multithreading
    x11.XInitThreads()
    if gtk:
        from gtk.gdk import threads_init
        threads_init()


Instruction:
Create a Python 3 function for
returning Skype window ID or None if Skype not running.

Response:
def get_skype(self):
        """Returns Skype window ID or None if Skype not running."""
        skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True)
        if not skype_inst:
            return
        type_ret = Atom()
        format_ret = c_int()
        nitems_ret = c_ulong()
        bytes_after_ret = c_ulong()
        winp = pointer(Window())
        fail = x11.XGetWindowProperty(self.disp, self.win_root, skype_inst,
                            0, 1, False, 33, byref(type_ret), byref(format_ret),
                            byref(nitems_ret), byref(bytes_after_ret), byref(winp))
        if not fail and format_ret.value == 32 and nitems_ret.value == 1:
            return winp.contents.value


Instruction:
Can you tell what is the following Python 3 function doing
def Join(self, Id):
        #self._Alter('JOIN_CONFERENCE', Id)
        reply = self._Owner._DoCommand('SET CALL %s JOIN_CONFERENCE %s' % (self.Id, Id),
            'CALL %s CONF_ID' % self.Id)
        return Conference(self._Owner, reply.split()[-1])

Response: Joins with another call to form a conference.


Instruction:
Write a Python 3 function for
setting user avatar picture from file.

Response:
def Avatar(self, Id=1, Set=None):
        """Sets user avatar picture from file.

        :Parameters:
          Id : int
            Optional avatar Id.
          Set : str
            New avatar file name.

        :deprecated: Use `LoadAvatarFromFile` instead.
        """
        from warnings import warn
        warn('Settings.Avatar: Use Settings.LoadAvatarFromFile instead.', DeprecationWarning, stacklevel=2)
        if Set is None:
            raise TypeError('Argument \'Set\' is mandatory!')
        self.LoadAvatarFromFile(Set, Id)


Instruction:
Here you have a function in Python 3, explain what it does
def LoadAvatarFromFile(self, Filename, AvatarId=1):
        s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename))
        self._Skype._DoCommand('SET %s' % s, s)

Response: Loads user avatar picture from file.


Instruction:
Can you tell what is the following Python 3 function doing
def RingTone(self, Id=1, Set=None):
        if Set is None:
            return unicode2path(self._Skype._Property('RINGTONE', Id, ''))
        self._Skype._Property('RINGTONE', Id, '', path2unicode(Set))

Response: Returns or sets a ringtone.


Instruction:
How would you code a function in Python 3 to
enable or disables a ringtone.

Response:
def RingToneStatus(self, Id=1, Set=None):
        """Enables/disables a ringtone.

        :Parameters:
          Id : int
            Ringtone Id
          Set : bool
            True/False if the ringtone should be enabled/disabled or None if the current status
            should be queried.

        :return: Current status if Set=None, None otherwise.
        :rtype: bool
        """
        if Set is None:
            return (self._Skype._Property('RINGTONE', Id, 'STATUS') == 'ON')
        self._Skype._Property('RINGTONE', Id, 'STATUS', cndexp(Set, 'ON', 'OFF'))


Instruction:
Create a Python 3 function for
saving user avatar picture to file.

Response:
def SaveAvatarToFile(self, Filename, AvatarId=1):
        """Saves user avatar picture to file.

        :Parameters:
          Filename : str
            Destination path.
          AvatarId : int
            Avatar Id
        """
        s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename))
        self._Skype._DoCommand('GET %s' % s, s)


Instruction:
Write a Python 3 script to
save user avatar to a file.

Response:
def SaveAvatarToFile(self, Filename, AvatarId=1):
        """Saves user avatar to a file.

        :Parameters:
          Filename : str
            Destination path.
          AvatarId : int
            Avatar Id.
        """
        s = 'USER %s AVATAR %s %s' % (self.Handle, AvatarId, path2unicode(Filename))
        self._Owner._DoCommand('GET %s' % s, s)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def SetBuddyStatusPendingAuthorization(self, Text=u''):
        self._Property('BUDDYSTATUS', '%d %s' % (budPendingAuthorization, tounicode(Text)), Cache=False)

Response: Sets the BuddyStatus property to enums. budPendingAuthorization additionally specifying the authorization text.


Instruction:
Make a summary of the following Python 3 code
def StreamWrite(stream, *obj):
    stream.Write(base64.encodestring(pickle.dumps(obj)))

Response: Writes Python object to Skype application stream.


Instruction:
How would you explain what the following Python 3 function does
def ApplicationReceiving(self, app, streams):

        # we should only proceed if we are in TCP mode
        if stype != socket.SOCK_STREAM:
            return

        # handle all streams
        for stream in streams:
            # read object from the stream
            obj = StreamRead(stream)
            if obj:
                if obj[0] == cmdData:
                    # data were received, reroute it to the tunnel based on the tunnel ID
                    try:
                        TCPTunnel.threads[obj[1]].send(obj[2])
                    except KeyError:
                        pass
                elif obj[0] == cmdConnect:
                    # a connection request received, connect the socket
                    n = obj[1]
                    sock = socket.socket(type=stype)
                    try:
                        sock.connect(addr)
                        # start the tunnel thread
                        TCPTunnel(sock, stream, n).start()
                    except socket.error, e:
                        # connection failed, send an error report back through the stream
                        print 'error (%s): %s' % (n, e)
                        StreamWrite(stream, cmdError, n, tuple(e))
                        StreamWrite(stream, cmdDisconnect, n)
                elif obj[0] == cmdDisconnect:
                    # an disconnection request received, close the tunnel
                    try:
                        TCPTunnel.threads[obj[1]].close()
                    except KeyError:
                        pass
                elif obj[0] == cmdError:
                    # connection failed on the other side, display the error
                    print 'error (%s): %s' % obj[1:2]

Response: Called when the list of streams with data ready to be read changes.


Instruction:
Implement a function in Python 3 to
call when a datagram is received over a stream.

Response:
def ApplicationDatagram(self, app, stream, text):
        """Called when a datagram is received over a stream."""

        # we should only proceed if we are in UDP mode
        if stype != socket.SOCK_DGRAM:
            return

        # decode the data
        data = base64.decodestring(text)

        # open an UDP socket
        sock = socket.socket(type=stype)

        # send the data
        try:
            sock.sendto(data, addr)
        except socket.error, e:
            print 'error: %s' % e


Instruction:
Here you have a function in Python 3, explain what it does
def chop(s, n=1, d=None):

    spl = s.split(d, n)
    if len(spl) == n:
        spl.append(s[:0])
    if len(spl) != n + 1:
        raise ValueError('chop: Could not chop %d words from \'%s\'' % (n, s))
    return spl

Response: Chops initial words from a string and returns a list of n first words and rest of the string.


Instruction:
Can you implement a function in Python 3 that
converts a string or comma - separated ARG = a value or ARG = value2 strings into a dictionary.

Response:
def args2dict(s):
    """Converts a string or comma-separated 'ARG="a value"' or 'ARG=value2' strings
    into a dictionary.

    :Parameters:
      s : str or unicode
        Input string.

    :return: ``{'ARG': 'value'}`` dictionary.
    :rtype: dict
    """

    d = {}
    while s:
        t, s = chop(s, 1, '=')
        if s.startswith('"'):
            # XXX: This function is used to parse strings from Skype. The question is,
            # how does Skype escape the double-quotes. The code below implements the
            # VisualBasic technique ("" -> ").
            i = 0
            while True:
                i = s.find('"', i+1)
                try:
                    if s[i+1] != '"':
                        break
                    else:
                        i += 1
                except IndexError:
                    break
            if i > 0:
                d[t] = s[1:i].replace('""', '"')
                if s[i+1:i+3] == ', ':
                    i += 2
                s = s[i+1:]
            else:
                d[t] = s
                break
        else:
            i = s.find(', ')
            if i >= 0:
                d[t] = s[:i]
                s = s[i+2:]
            else:
                d[t] = s
                break
    return d


Instruction:
How would you code a function in Python 3 to
call all event handlers defined for given Event.

Response:
def _CallEventHandler(self, Event, *Args, **KwArgs):
        """Calls all event handlers defined for given Event, additional parameters
        will be passed unchanged to event handlers, all event handlers are fired on
        separate threads.

        :Parameters:
          Event : str
            Name of the event.
          Args
            Positional arguments for the event handlers.
          KwArgs
            Keyword arguments for the event handlers.
        """
        if Event not in self._EventHandlers:
            raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
        args = map(repr, Args) + ['%s=%s' % (key, repr(value)) for key, value in KwArgs.items()]
        self.__Logger.debug('calling %s: %s', Event, ', '.join(args))
        # Get a list of handlers for this event.
        try:
            handlers = [self._DefaultEventHandlers[Event]]
        except KeyError:
            handlers = []
        try:
            handlers.append(getattr(self._EventHandlerObject, Event))
        except AttributeError:
            pass
        handlers.extend(self._EventHandlers[Event])
        # Proceed only if there are handlers.
        if handlers:
            # Get the last thread for this event.
            after = self._EventThreads.get(Event, None)
            # Create a new thread, pass the last one to it so it can wait until it is finished.
            thread = EventSchedulerThread(Event, after, handlers, Args, KwArgs)
            # Store a weak reference to the new thread for this event.
            self._EventThreads[Event] = thread
            # Start the thread.
            thread.start()


Instruction:
Given the following Python 3 function, write the documentation
def RegisterEventHandler(self, Event, Target):
        if not callable(Target):
            raise TypeError('%s is not callable' % repr(Target))
        if Event not in self._EventHandlers:
            raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
        if Target in self._EventHandlers[Event]:
            return False
        self._EventHandlers[Event].append(Target)
        self.__Logger.info('registered %s: %s', Event, repr(Target))
        return True

Response: Registers any callable as an event handler.


Instruction:
Here you have a function in Python 3, explain what it does
def UnregisterEventHandler(self, Event, Target):
        if not callable(Target):
            raise TypeError('%s is not callable' % repr(Target))
        if Event not in self._EventHandlers:
            raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__))
        if Target in self._EventHandlers[Event]:
            self._EventHandlers[Event].remove(Target)
            self.__Logger.info('unregistered %s: %s', Event, repr(Target))
            return True
        return False

Response: Unregisters an event handler previously registered with RegisterEventHandler.


Instruction:
Make a summary of the following Python 3 code
def _SetEventHandlerObject(self, Object):
        self._EventHandlerObject = Object
        self.__Logger.info('set object: %s', repr(Object))

Response: Registers an object as events handler.


Instruction:
Here you have a function in Python 3, explain what it does
def _AddEvents(cls, Class):
        def make_event(event):
            return property(lambda self: self._GetDefaultEventHandler(event),
                             lambda self, Value: self._SetDefaultEventHandler(event, Value))
        for event in dir(Class):
            if not event.startswith('_'):
                setattr(cls, 'On%s' % event, make_event(event))
                cls._EventNames.append(event)

Response: Adds events based on the attributes of the given class.


Instruction:
Here you have a function in Python 3, explain what it does
def AddMembers(self, *Members):
        self._Alter('ADDMEMBERS', ', '.join([x.Handle for x in Members]))

Response: Adds new members to the chat.


Instruction:
Can you write a function in Python 3 where it
sends a chat message.

Response:
def SendMessage(self, MessageText):
        """Sends a chat message.

        :Parameters:
          MessageText : unicode
            Message text

        :return: Message object
        :rtype: `ChatMessage`
        """
        return ChatMessage(self._Owner, chop(self._Owner._DoCommand('CHATMESSAGE %s %s' % (self.Name,
            tounicode(MessageText))), 2)[1])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def SetPassword(self, Password, Hint=''):
        if ' ' in Password:
            raise ValueError('Password mut be one word')
        self._Alter('SETPASSWORD', '%s %s' % (tounicode(Password), tounicode(Hint)))

Response: Sets the chat password.


Instruction:
Create a Python 3 function to
check if the new role can be applied to the member.

Response:
def CanSetRoleTo(self, Role):
        """Checks if the new role can be applied to the member.

        :Parameters:
          Role : `enums`.chatMemberRole*
            New chat member role.

        :return: True if the new role can be applied, False otherwise.
        :rtype: bool
        """
        t = self._Owner._Alter('CHATMEMBER', self.Id, 'CANSETROLETO', Role,
                               'ALTER CHATMEMBER CANSETROLETO')
        return (chop(t, 1)[-1] == 'TRUE')


Instruction:
How would you explain what the following Python 3 function does
def Connect(self, Skype):
        self._Skype = Skype
        self._Skype.RegisterEventHandler('CallStatus', self._CallStatus)
        del self._Channels[:]

Response: Connects this call channel manager instance to Skype.


Instruction:
Given the following Python 3 function, write the documentation
def CreateApplication(self, ApplicationName=None):
        if ApplicationName is not None:
            self.Name = tounicode(ApplicationName)
        self._App = self._Skype.Application(self.Name)
        self._Skype.RegisterEventHandler('ApplicationStreams', self._ApplicationStreams)
        self._Skype.RegisterEventHandler('ApplicationReceiving', self._ApplicationReceiving)
        self._Skype.RegisterEventHandler('ApplicationDatagram', self._ApplicationDatagram)
        self._App.Create()
        self._CallEventHandler('Created', self)

Response: Creates an application context.


Instruction:
Write a Python 3 function that can
send a text message over the current channel.

Response:
def SendTextMessage(self, Text):
        """Sends a text message over channel.

        :Parameters:
          Text : unicode
            Text to send.
        """
        if self.Type == cctReliable:
            self.Stream.Write(Text)
        elif self.Type == cctDatagram:
            self.Stream.SendDatagram(Text)
        else:
            raise SkypeError(0, 'Cannot send using %s channel type' & repr(self.Type))


Instruction:
Given the following Python 3 function, write the documentation
def TextToAttachmentStatus(self, Text):
        conv = {'UNKNOWN': enums.apiAttachUnknown,
                'SUCCESS': enums.apiAttachSuccess,
                'PENDING_AUTHORIZATION': enums.apiAttachPendingAuthorization,
                'REFUSED': enums.apiAttachRefused,
                'NOT_AVAILABLE': enums.apiAttachNotAvailable,
                'AVAILABLE': enums.apiAttachAvailable}
        try:
            return self._TextTo('api', conv[Text.upper()])
        except KeyError:
            raise ValueError('Bad text')

Response:
Converts a unicode unicode
 getTerm unicode unicode


Instruction:
Explain what the following Python 3 code does
def TextToBuddyStatus(self, Text):
        conv = {'UNKNOWN': enums.budUnknown,
                'NEVER_BEEN_FRIEND': enums.budNeverBeenFriend,
                'DELETED_FRIEND': enums.budDeletedFriend,
                'PENDING_AUTHORIZATION': enums.budPendingAuthorization,
                'FRIEND': enums.budFriend}
        try:
            return self._TextTo('bud', conv[Text.upper()])
        except KeyError:
            raise ValueError('Bad text')

Response:
Converts unicode unicode
            to Buddy status code.


Instruction:
Can you write a function in Python 3 where it
adds a dynamic composite field to the current composite_fields dictionary.

Response:
def add_composite_field(self, name, field):
        """
        Add a dynamic composite field to the already existing ones and
        initialize it appropriatly.
        """
        self.composite_fields[name] = field
        self._init_composite_field(name, field)


Instruction:
Write a Python 3 script for
returning the form instance for the given field name.

Response:
def get_composite_field_value(self, name):
        """
        Return the form/formset instance for the given field name.
        """
        field = self.composite_fields[name]
        if hasattr(field, 'get_form'):
            return self.forms[name]
        if hasattr(field, 'get_formset'):
            return self.formsets[name]


Instruction:
Given the following Python 3 function, write the documentation
def _init_composite_fields(self):
        # The base_composite_fields class attribute is the *class-wide*
        # definition of fields. Because a particular *instance* of the class
        # might want to alter self.composite_fields, we create
        # self.composite_fields here by copying base_composite_fields.
        # Instances should always modify self.composite_fields; they should not
        # modify base_composite_fields.
        self.composite_fields = copy.deepcopy(self.base_composite_fields)
        self.forms = OrderedDict()
        self.formsets = OrderedDict()
        for name, field in self.composite_fields.items():
            self._init_composite_field(name, field)

Response: Setup the forms and formsets.


Instruction:
Create a Python 3 function for
cleaning the form including all formsets and add errors to the errors dict.

Response:
def full_clean(self):
        """
        Clean the form, including all formsets and add formset errors to the
        errors dict. Errors of nested forms and formsets are only included if
        they actually contain errors.
        """
        super(SuperFormMixin, self).full_clean()
        for field_name, composite in self.forms.items():
            composite.full_clean()
            if not composite.is_valid() and composite._errors:
                self._errors[field_name] = ErrorDict(composite._errors)
        for field_name, composite in self.formsets.items():
            composite.full_clean()
            if not composite.is_valid() and composite._errors:
                self._errors[field_name] = ErrorList(composite._errors)


Instruction:
Given the following Python 3 function, write the documentation
def save(self, commit=True):
        saved_obj = self.save_form(commit=commit)
        self.save_forms(commit=commit)
        self.save_formsets(commit=commit)
        return saved_obj

Response: Save the current state of the object to the database.


Instruction:
Can you create a Python 3 function that
saves all formsets. If ``commit=False``, it will modify the form's ``save_m2m()`` so that it also calls the formsets' ``save_m2m()`` methods.

Response:
def save_formsets(self, commit=True):
        """
        Save all formsets. If ``commit=False``, it will modify the form's
        ``save_m2m()`` so that it also calls the formsets' ``save_m2m()``
        methods.
        """
        saved_composites = []
        for name, composite in self.formsets.items():
            field = self.composite_fields[name]
            if hasattr(field, 'save'):
                field.save(self, name, composite, commit=commit)
                saved_composites.append(composite)

        self._extend_save_m2m('save_formsets_m2m', saved_composites)


Instruction:
Write a Python 3 script for
returning the prefix that is used for the formset.

Response:
def get_prefix(self, form, name):
        """
        Return the prefix that is used for the formset.
        """
        return '{form_prefix}{prefix_name}-{field_name}'.format(
            form_prefix=form.prefix + '-' if form.prefix else '',
            prefix_name=self.prefix_name,
            field_name=name)


Instruction:
How would you explain what the following Python 3 function does
def get_initial(self, form, name):

        if hasattr(form, 'initial'):
            return form.initial.get(name, None)
        return None

Response: Get the initial data that was passed into the superform for thisCOOKIE.


Instruction:
Given the following Python 3 function, write the documentation
def get_kwargs(self, form, name):
        kwargs = {
            'prefix': self.get_prefix(form, name),
            'initial': self.get_initial(form, name),
        }
        kwargs.update(self.default_kwargs)
        return kwargs

Response: Returns the keyword arguments that are used to instantiate the formset.


Instruction:
Given the following Python 3 function, write the documentation
def get_form(self, form, name):
        kwargs = self.get_kwargs(form, name)
        form_class = self.get_form_class(form, name)
        composite_form = form_class(
            data=form.data if form.is_bound else None,
            files=form.files if form.is_bound else None,
            **kwargs)
        return composite_form

Response: Get an instance of the form.


Instruction:
Explain what the following Python 3 code does
def get_kwargs(self, form, name):
        kwargs = super(ModelFormField, self).get_kwargs(form, name)
        instance = self.get_instance(form, name)
        kwargs.setdefault('instance', instance)
        kwargs.setdefault('empty_permitted', not self.required)
        return kwargs

Response: Returns the keyword arguments that are used to instantiate the formset.


Instruction:
Make a summary of the following Python 3 code
def shall_save(self, form, name, composite_form):
        if composite_form.empty_permitted and not composite_form.has_changed():
            return False
        return True

Response: Return True if the given form and name shall be saved.