Instruction:
Can you write a function in Python 3 where it
rates song. Parameters: song (dict): A song dict. rating (int): 0 (not rated), 1 (thumbs down), or 5 (thumbs up). Returns: bool: ``True`` if successful, ``False`` if not.

Response:
def song_rate(self, song, rating):
		"""Rate song.

		Parameters:
			song (dict): A song dict.
			rating (int): 0 (not rated), 1 (thumbs down), or 5 (thumbs up).

		Returns:
			bool: ``True`` if successful, ``False`` if not.
		"""

		if 'storeId' in song:
			song_id = song['storeId']
		elif 'trackId' in song:
			song_id = song['trackId']
		else:
			song_id = song['id']

		event = mc_calls.ActivityRecordRealtime.rate(song_id, rating)
		response = self._call(
			mc_calls.ActivityRecordRealtime,
			event
		)

		return True if response.body['eventResults'][0]['code'] == 'OK' else False


Instruction:
How would you explain what the following Python 3 function does
def songs(self):

		song_list = []
		for chunk in self.songs_iter(page_size=49995):
			song_list.extend(chunk)

		return song_list

Response: Get a listing of library songs.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def songs_iter(self, *, page_size=250):

		start_token = None

		while True:
			response = self._call(
				mc_calls.TrackFeed,
				max_results=page_size,
				start_token=start_token
			)
			items = response.body.get('data', {}).get('items', [])

			if items:
				yield items

			start_token = response.body.get('nextPageToken')
			if start_token is None:
				break

Response: Get a paged iterator of library songs.


Instruction:
Can you write a function in Python 3 where it
gets information about a station.

Response:
def station(self, station_id, *, num_songs=25, recently_played=None):
		"""Get information about a station.

		Parameters:
			station_id (str): A station ID. Use 'IFL' for I'm Feeling Lucky.
			num_songs (int, Optional): The maximum number of songs to return from the station.
				Default: ``25``
			recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'}
				where ``id`` is a song ID and ``type`` is 0 for a library song and 1 for a store song.

		Returns:
			dict: Station information.
		"""

		station_info = {
			'station_id': station_id,
			'num_entries': num_songs,
			'library_content_only': False
		}

		if recently_played is not None:
			station_info['recently_played'] = recently_played

		response = self._call(
			mc_calls.RadioStationFeed,
			station_infos=[station_info]
		)
		station_feed = response.body.get('data', {}).get('stations', [])

		try:
			station = station_feed[0]
		except IndexError:
			station = {}

		return station


Instruction:
Make a summary of the following Python 3 code
def station_feed(self, *, num_songs=25, num_stations=4):

		response = self._call(
			mc_calls.RadioStationFeed,
			num_entries=num_songs,
			num_stations=num_stations
		)
		station_feed = response.body.get('data', {}).get('stations', [])

		return station_feed

Response:
Generate stations.

		Note:
			A Google Music subscription is required.

		Parameters:
			num_songs (int, Optional): The total number of songs to return. Default: ``25``
			num_stations (int, Optional): The number of stations to return when no station_infos is provided.
				Default: ``5``

		Returns:
			list: Station information dicts.


Instruction:
Write a Python 3 script to
get a listing of songs from a station.

Response:
def station_songs(self, station, *, num_songs=25, recently_played=None):
		"""Get a listing of songs from a station.

		Parameters:
			station (str): A station dict.
			num_songs (int, Optional): The maximum number of songs to return from the station. Default: ``25``
			recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'}
				where ``id`` is a song ID and ``type`` is 0 for a library song and 1 for a store song.

		Returns:
			list: Station song dicts.
		"""

		station_id = station['id']

		station = self.station(
			station_id,
			num_songs=num_songs,
			recently_played=recently_played
		)

		return station.get('tracks', [])


Instruction:
How would you explain what the following Python 3 function does
def stations(self, *, generated=True, library=True):

		station_list = []
		for chunk in self.stations_iter(page_size=49995):
			for station in chunk:
				if (
					(generated and not station.get('inLibrary'))
					or (library and station.get('inLibrary'))
				):
					station_list.append(station)

		return station_list

Response: Get a listing of library stations.


Instruction:
Can you generate the documentation for the following Python 3 function
def stations_iter(self, *, page_size=250):

		start_token = None

		while True:
			response = self._call(
				mc_calls.RadioStation,
				max_results=page_size,
				start_token=start_token
			)
			yield response.body.get('data', {}).get('items', [])

			start_token = response.body.get('nextPageToken')
			if start_token is None:
				break

Response: Get a paged iterator of library stations.


Instruction:
Write a Python 3 script to
get MP3 stream of a podcast episode library song station_song or store song.

Response:
def stream(self, item, *, device_id=None, quality='hi', session_token=None):
		"""Get MP3 stream of a podcast episode, library song, station_song, or store song.

		Note:
			Streaming requires a ``device_id`` from a valid, linked mobile device.

		Parameters:
			item (str): A podcast episode, library song, station_song, or store song.
				A Google Music subscription is required to stream store songs.
			device_id (str, Optional): A mobile device ID.
				Default: Use ``device_id`` of the :class:`MobileClient` instance.
			quality (str, Optional): Stream quality is one of ``'hi'`` (320Kbps), ``'med'`` (160Kbps), or ``'low'`` (128Kbps).
				Default: ``'hi'``.
			session_token (str): Session token from a station dict required for unsubscribed users to stream a station song.
				station['sessionToken'] as returend by :meth:`station` only exists for free accounts.

		Returns:
			bytes: An MP3 file.
		"""

		if device_id is None:
			device_id = self.device_id

		stream_url = self.stream_url(
			item,
			device_id=device_id,
			quality=quality,
			session_token=session_token
		)
		response = self.session.get(stream_url)
		audio = response.content

		return audio


Instruction:
Write a Python 3 function that can
get a URL to stream a podcast episode library song station_song or store song.

Response:
def stream_url(self, item, *, device_id=None, quality='hi', session_token=None):
		"""Get a URL to stream a podcast episode, library song, station_song, or store song.

		Note:
			Streaming requires a ``device_id`` from a valid, linked mobile device.

		Parameters:
			item (str): A podcast episode, library song, station_song, or store song.
				A Google Music subscription is required to stream store songs.
			device_id (str, Optional): A mobile device ID.
				Default: Use ``device_id`` of the :class:`MobileClient` instance.
			quality (str, Optional): Stream quality is one of ``'hi'`` (320Kbps), ``'med'`` (160Kbps), or ``'low'`` (128Kbps).
				Default: ``'hi'``.
			session_token (str): Session token from a station dict required for unsubscribed users to stream a station song.
				station['sessionToken'] as returend by :meth:`station` only exists for free accounts.

		Returns:
			str: A URL to an MP3 file.
		"""

		if device_id is None:
			device_id = self.device_id

		if 'episodeId' in item:  # Podcast episode.
			response = self._call(
				mc_calls.PodcastEpisodeStreamURL,
				item['episodeId'],
				quality=quality,
				device_id=device_id
			)
		elif 'wentryid' in item:  # Free account station song.
			response = self._call(
				mc_calls.RadioStationTrackStreamURL,
				item['storeId'],
				item['wentryid'],
				session_token,
				quality=quality,
				device_id=device_id
			)
		elif 'trackId' in item:  # Playlist song.
			response = self._call(
				mc_calls.TrackStreamURL,
				item['trackId'],
				quality=quality,
				device_id=device_id
			)
		elif 'storeId' in item and self.is_subscribed:  # Store song.
			response = self._call(
				mc_calls.TrackStreamURL,
				item['storeId'],
				quality=quality,
				device_id=device_id
			)
		elif 'id' in item:  # Library song.
			response = self._call(
				mc_calls.TrackStreamURL,
				item['id'],
				quality=quality,
				device_id=device_id
			)
		else:
			# TODO: Create an exception for not being subscribed or use a better builtin exception for this case.
			if 'storeId' in item and not self.is_subscribed:
				msg = "Can't stream a store song without a subscription."
			else:
				msg = "Item does not contain an ID field."

			raise ValueError(msg)

		try:
			stream_url = response.headers['Location']
		except KeyError:
			stream_url = response.body['url']

		return stream_url


Instruction:
Write a Python 3 script to
get a listing of Thumbs Up songs.

Response:
def thumbs_up_songs(self, *, library=True, store=True):
		"""Get a listing of 'Thumbs Up' store songs.

		Parameters:
			library (bool, Optional): Include 'Thumbs Up' songs from library.
				Default: True
			generated (bool, Optional): Include 'Thumbs Up' songs from store.
				Default: True

		Returns:
			list: Dicts of 'Thumbs Up' songs.
		"""

		thumbs_up_songs = []

		if library is True:
			thumbs_up_songs.extend(
				song
				for song in self.songs()
				if song.get('rating', '0') == '5'
			)

		if store is True:
			response = self._call(mc_calls.EphemeralTop)
			thumbs_up_songs.extend(response.body.get('data', {}).get('items', []))

		return thumbs_up_songs


Instruction:
Make a summary of the following Python 3 code
def top_charts(self):

		response = self._call(mc_calls.BrowseTopChart)
		top_charts = response.body

		return top_charts

Response: Get a listing of the default top charts.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def top_charts_for_genre(self, genre_id):

		response = self._call(mc_calls.BrowseTopChartForGenre, genre_id)
		top_chart_for_genre = response.body

		return top_chart_for_genre

Response: Get a listing of top charts for a top chart genre.


Instruction:
How would you explain what the following Python 3 function does
def top_charts_genres(self):

		response = self._call(mc_calls.BrowseTopChartGenres)
		top_chart_genres = response.body.get('genres', [])

		return top_chart_genres

Response: Get a listing of genres from the browse top charts tab.


Instruction:
How would you code a function in Python 3 to
read from stream applying the LT decoding algorithm to incoming encoded blocks until sufficiently many blocks have been received.

Response:
def run(stream=sys.stdin.buffer):
    """Reads from stream, applying the LT decoding algorithm
    to incoming encoded blocks until sufficiently many blocks
    have been received to reconstruct the entire file.
    """
    payload = decode.decode(stream)
    sys.stdout.write(payload.decode('utf8'))


Instruction:
Here you have a function in Python 3, explain what it does
def _split_file(f, blocksize):

    f_bytes = f.read()
    blocks = [int.from_bytes(f_bytes[i:i+blocksize].ljust(blocksize, b'0'), sys.byteorder)
            for i in range(0, len(f_bytes), blocksize)]
    return len(f_bytes), blocks

Response: Split file into blocksize chunks


Instruction:
Create a Python 3 function to
generate an infinite sequence of blocks to transmit to the receiver

Response:
def encoder(f, blocksize, seed=None, c=sampler.DEFAULT_C, delta=sampler.DEFAULT_DELTA):
    """Generates an infinite sequence of blocks to transmit
    to the receiver
    """

    # Generate seed if not provided
    if seed is None:
        seed = randint(0, 1 << 31 - 1)

    # get file blocks
    filesize, blocks = _split_file(f, blocksize)

    # init stream vars
    K = len(blocks)
    prng = sampler.PRNG(params=(K, delta, c))
    prng.set_seed(seed)

    # block generation loop
    while True:
        blockseed, d, ix_samples = prng.get_src_blocks()
        block_data = 0
        for ix in ix_samples:
            block_data ^= blocks[ix]

        # Generate blocks of XORed data in network byte order
        block = (filesize, blocksize, blockseed, int.to_bytes(block_data, blocksize, sys.byteorder))
        yield pack('!III%ss'%blocksize, *block)


Instruction:
Implement a Python 3 function for
reading block data from network into integer type

Response:
def _read_block(blocksize, stream):
    """Read block data from network into integer type
    """
    blockdata = stream.read(blocksize)
    return int.from_bytes(blockdata, 'big')


Instruction:
Make a summary of the following Python 3 code
def read_blocks(stream):
    while True:
        header = _read_header(stream)
        block  = _read_block(header[1], stream)
        yield (header, block)

Response: Generate parsed blocks from input stream


Instruction:
Write a Python 3 function that can
add a new check node and edges between that node and all the source nodes it connects resolving all messages passes as a result.

Response:
def add_block(self, nodes, data):
        """Adds a new check node and edges between that node and all
        source nodes it connects, resolving all message passes that
        become possible as a result.
        """

        # We can eliminate this source node
        if len(nodes) == 1:
            to_eliminate = list(self.eliminate(next(iter(nodes)), data))

            # Recursively eliminate all nodes that can now be resolved
            while len(to_eliminate):
                other, check = to_eliminate.pop()
                to_eliminate.extend(self.eliminate(other, check))
        else:

            # Pass messages from already-resolved source nodes
            for node in list(nodes):
                if node in self.eliminated:
                    nodes.remove(node)
                    data ^= self.eliminated[node]

            # Resolve if we are left with a single non-resolved source node
            if len(nodes) == 1:
                return self.add_block(nodes, data)
            else:

                # Add edges for all remaining nodes to this check
                check = CheckNode(nodes, data)
                for node in nodes:
                    self.checks[node].append(check)

        # Are we done yet?
        return len(self.eliminated) >= self.num_blocks


Instruction:
Can you tell what is the following Python 3 function doing
def eliminate(self, node, data):

        # Cache resolved value
        self.eliminated[node] = data
        others = self.checks[node]
        del self.checks[node]

        # Pass messages to all associated checks
        for check in others:
            check.check ^= data
            check.src_nodes.remove(node)

            # Yield all nodes that can now be resolved
            if len(check.src_nodes) == 1:
                yield (next(iter(check.src_nodes)), check.check)

Response: Resolves a source node passing the message to all associated checks


Instruction:
Write a Python 3 function that can
create and authenticate a Google Music mobile client.

Response:
def mobileclient(username=None, device_id=None, *, token=None, locale='en_US'):
	"""Create and authenticate a Google Music mobile client.

	>>> import google_music
	>>> mc = google_music.mobileclient('username')

	Parameters:
		username (str, Optional): Your Google Music username.
			This is used to store OAuth credentials for different accounts separately.
		device_id (str, Optional): A mobile device ID. Default: MAC address is used.
		token (dict, Optional): An OAuth token compatible with ``requests-oauthlib``.
		locale (str, Optional): `ICU <http://www.localeplanet.com/icu/>`__ locale used to localize some
			responses. This must be a locale supported by Android. Default: `'en_US'``.

	Returns:
		MobileClient: An authenticated :class:`~google_music.MobileClient` instance.
	"""

	return MobileClient(
		username,
		device_id,
		token=token,
		locale=locale
	)


Instruction:
Given the following Python 3 function, write the documentation
def _dendropy_to_dataframe(
    tree,
    add_node_labels=True,
    use_uids=True):
    """Convert Dendropy tree to Pandas dataframe."""
    # Maximum distance from root.
    tree.max_distance_from_root()

    # Initialize the data object.
    idx = []
    data = {
        'type': [],
        'id': [],
        'parent': [],
        'length': [],
        'label': [],
        'distance': []}

    if use_uids:
        data['uid'] = []

    # Add labels to internal nodes if set to true.
    if add_node_labels:
        for i, node in enumerate(tree.internal_nodes()):
            node.label = str(i)

    for node in tree.nodes():
        # Get node type
        if node.is_leaf():
            type_ = 'leaf'
            label = str(node.taxon.label).replace(' ', '_')
        elif node.is_internal():
            type_ = 'node'
            label = str(node.label)

        # Set node label and parent.
        id_ = label
        parent_node = node.parent_node
        length = node.edge_length
        distance = node.distance_from_root()

        # Is this node a root?
        if parent_node is None and length is None:
            parent_label = None
            parent_node = None
            length = 0
            distance = 0
            type_ = 'root'

        # Set parent node label
        elif parent_node.is_internal():
            parent_label = str(parent_node.label)

        else:
            raise Exception("Subtree is not attached to tree?")

        # Add this node to the data.
        data['type'].append(type_)
        data['id'].append(id_)
        data['parent'].append(parent_label)
        data['length'].append(length)
        data['label'].append(label)
        data['distance'].append(distance)

        if use_uids:
            data['uid'].append(get_random_id(10))

    # Construct dataframe.
    df = pandas.DataFrame(data)
    return df

Response: Convert Dendropy tree to Pandas dataframe.


Instruction:
Here you have a function in Python 3, explain what it does
def _read(
    filename=None,
    data=None,
    schema=None,
    add_node_labels=True,
    use_uids=True
    ):
    """Read a phylogenetic tree into a phylopandas.DataFrame.

    The resulting DataFrame has the following columns:
        - name: label for each taxa or node.
        - id: unique id (created by phylopandas) given to each node.
        - type: type of node (leaf, internal, or root).
        - parent: parent id. necessary for constructing trees.
        - length: length of branch from parent to node.
        - distance: distance from root.

    Parameters
    ----------
    filename: str (default is None)
        newick file to read into DataFrame.

    data: str (default is None)
        newick string to parse and read into DataFrame.

    add_node_labels: bool
        If true, labels the internal nodes with numbers.

    Returns
    -------
    df: phylopandas.DataFrame.
    """
    if filename is not None:
        # Use Dendropy to parse tree.
        tree = dendropy.Tree.get(
            path=filename,
            schema=schema,
            preserve_underscores=True)
    elif data is not None:
        tree = dendropy.Tree.get(
            data=data,
            schema=schema,
            preserve_underscores=True)
    else:
        raise Exception('No tree given?')

    df = _dendropy_to_dataframe(
        tree,
        add_node_labels=add_node_labels,
        use_uids=use_uids
    )
    return df

Response: Read a phylogenetic tree into a phylopandas. DataFrame.


Instruction:
Make a summary of the following Python 3 code
def _read_function(schema):
    def func(
        filename=None,
        data=None,
        add_node_labels=True,
        use_uids=True,
        **kwargs):
        # Use generic write class to write data.
        return _read(
            filename=filename,
            data=data,
            schema=schema,
            add_node_labels=add_node_labels,
            use_uids=use_uids,
            **kwargs
        )
    # Update docs
    func.__doc__ = _read_doc_template(schema)
    return func

Response: Add a read method for named schema to a class.


Instruction:
Can you generate the documentation for the following Python 3 function
def pandas_df_to_biopython_seqrecord(
    df,
    id_col='uid',
    sequence_col='sequence',
    extra_data=None,
    alphabet=None,
    ):
    """Convert pandas dataframe to biopython seqrecord for easy writing.

    Parameters
    ----------
    df : Dataframe
        Pandas dataframe to convert

    id_col : str
        column in dataframe to use as sequence label

    sequence_col str:
        column in dataframe to use as sequence data

    extra_data : list
        extra columns to use in sequence description line

    alphabet :
        biopython Alphabet object

    Returns
    -------
    seq_records :
        List of biopython seqrecords.
    """
    seq_records = []

    for i, row in df.iterrows():
        # Tries getting sequence data. If a TypeError at the seqrecord
        # creation is thrown, it is assumed that this row does not contain
        # sequence data and therefore the row is ignored.
        try:
            # Get sequence
            seq = Seq(row[sequence_col], alphabet=alphabet)

            # Get id
            id = row[id_col]

            # Build a description
            description = ""
            if extra_data is not None:
                description = " ".join([row[key] for key in extra_data])

            # Build a record
            record = SeqRecord(
                seq=seq,
                id=id,
                description=description,
            )
            seq_records.append(record)
        except TypeError:
            pass

    return seq_records

Response: Convert pandas dataframe to biopython seqrecord for easy writing.


Instruction:
Here you have a function in Python 3, explain what it does
def pandas_series_to_biopython_seqrecord(
    series,
    id_col='uid',
    sequence_col='sequence',
    extra_data=None,
    alphabet=None
    ):
    """Convert pandas series to biopython seqrecord for easy writing.

    Parameters
    ----------
    series : Series
        Pandas series to convert

    id_col : str
        column in dataframe to use as sequence label

    sequence_col : str
        column in dataframe to use as sequence data

    extra_data : list
        extra columns to use in sequence description line

    Returns
    -------
    seq_records :
        List of biopython seqrecords.
    """
    # Get sequence
    seq = Seq(series[sequence_col], alphabet=alphabet)

    # Get id
    id = series[id_col]

    # Build a description
    description = ""
    if extra_data is not None:
        description = " ".join([series[key] for key in extra_data])

    # Build a record
    record = SeqRecord(
        seq=seq,
        id=id,
        description=description,
    )

    seq_records = [record]
    return seq_records

Response: Convert pandas series to biopython seqrecord for easy writing.


Instruction:
Can you generate the documentation for the following Python 3 function
def _write_method(schema):
    def method(
        self,
        filename=None,
        schema=schema,
        id_col='uid',
        sequence_col='sequence',
        extra_data=None,
        alphabet=None,
        **kwargs):
        # Use generic write class to write data.
        return _write(
            self._data,
            filename=filename,
            schema=schema,
            id_col=id_col,
            sequence_col=sequence_col,
            extra_data=extra_data,
            alphabet=alphabet,
            **kwargs
        )
    # Update docs
    method.__doc__ = _write_doc_template(schema)
    return method

Response: Add a write method to a class.


Instruction:
Write a Python 3 function for
adding a write method to a class.

Response:
def _write_function(schema):
    """Add a write method for named schema to a class.
    """
    def func(
        data,
        filename=None,
        schema=schema,
        id_col='uid',
        sequence_col='sequence',
        extra_data=None,
        alphabet=None,
        **kwargs):
        # Use generic write class to write data.
        return _write(
            data,
            filename=filename,
            schema=schema,
            id_col=id_col,
            sequence_col=sequence_col,
            extra_data=extra_data,
            alphabet=alphabet,
            **kwargs
        )
    # Update docs
    func.__doc__ = _write_doc_template(schema)
    return func


Instruction:
Explain what the following Python 3 code does
def _read(
    filename,
    schema,
    seq_label='sequence',
    alphabet=None,
    use_uids=True,
    **kwargs):
    """Use BioPython's sequence parsing module to convert any file format to
    a Pandas DataFrame.

    The resulting DataFrame has the following columns:
        - name
        - id
        - description
        - sequence
    """
    # Check Alphabet if given
    if alphabet is None:
        alphabet = Bio.Alphabet.Alphabet()

    elif alphabet in ['dna', 'rna', 'protein', 'nucleotide']:
        alphabet = getattr(Bio.Alphabet, 'generic_{}'.format(alphabet))

    else:
        raise Exception(
            "The alphabet is not recognized. Must be 'dna', 'rna', "
            "'nucleotide', or 'protein'.")

    kwargs.update(alphabet=alphabet)

    # Prepare DataFrame fields.
    data = {
        'id': [],
        seq_label: [],
        'description': [],
        'label': []
    }
    if use_uids:
        data['uid'] = []

    # Parse Fasta file.
    for i, s in enumerate(SeqIO.parse(filename, format=schema, **kwargs)):
        data['id'].append(s.id)
        data[seq_label].append(str(s.seq))
        data['description'].append(s.description)
        data['label'].append(s.name)

        if use_uids:
            data['uid'].append(get_random_id(10))

    # Port to DataFrame.
    return pd.DataFrame(data)

Response: Use BioPython s sequence parsing module to convert any file format to a Pandas DataFrame.


Instruction:
Write a Python 3 function for
adding a read method to a class.

Response:
def _read_method(schema):
    """Add a write method for named schema to a class.
    """
    def func(
        self,
        filename,
        seq_label='sequence',
        alphabet=None,
        combine_on='uid',
        use_uids=True,
        **kwargs):
        # Use generic write class to write data.
        df0 = self._data
        df1 = _read(
            filename=filename,
            schema=schema,
            seq_label=seq_label,
            alphabet=alphabet,
            use_uids=use_uids,
            **kwargs
        )
        return df0.phylo.combine(df1, on=combine_on)

    # Update docs
    func.__doc__ = _read_doc_template(schema)
    return func


Instruction:
Implement a function in Python 3 to
add a read method for named schema to a class.

Response:
def _read_function(schema):
    """Add a write method for named schema to a class.
    """
    def func(
        filename,
        seq_label='sequence',
        alphabet=None,
        use_uids=True,
        **kwargs):
        # Use generic write class to write data.
        return _read(
            filename=filename,
            schema=schema,
            seq_label=seq_label,
            alphabet=alphabet,
            use_uids=use_uids,
            **kwargs
        )
    # Update docs
    func.__doc__ = _read_doc_template(schema)
    return func


Instruction:
Write a Python 3 function that can
read BLAST XML format.

Response:
def read_blast_xml(filename, **kwargs):
    """Read BLAST XML format."""
    # Read file.
    with open(filename, 'r') as f:
        blast_record = NCBIXML.read(f)

    # Prepare DataFrame fields.
    data = {'accession': [],
            'hit_def': [],
            'hit_id': [],
            'title': [],
            'length': [],
            'e_value': [],
            'sequence': []}

    # Get alignments from blast result.
    for i, s in enumerate(blast_record.alignments):
        data['accession'] = s.accession
        data['hit_def'] = s.hit_def
        data['hit_id'] = s.hit_id
        data['title'] = s.title
        data['length'] = s.length
        data['e_value'] = s.hsps[0].expect
        data['sequence'] = s.hsps[0].sbjct

    # Port to DataFrame.
    return pd.DataFrame(data)


Instruction:
Here you have a function in Python 3, explain what it does
def _pandas_df_to_dendropy_tree(
    df,
    taxon_col='uid',
    taxon_annotations=[],
    node_col='uid',
    node_annotations=[],
    branch_lengths=True,
    ):
    """Turn a phylopandas dataframe into a dendropy tree.

    Parameters
    ----------
    df : DataFrame
        DataFrame containing tree data.

    taxon_col : str (optional)
        Column in dataframe to label the taxon. If None, the index will be used.

    taxon_annotations : str
        List of columns to annotation in the tree taxon.

    node_col : str (optional)
        Column in dataframe to label the nodes. If None, the index will be used.

    node_annotations : str
        List of columns to annotation in the node taxon.

    branch_lengths : bool
        If True, inclues branch lengths.
    """
    if isinstance(taxon_col, str) is False:
        raise Exception("taxon_col must be a string.")

    if isinstance(node_col, str) is False:
        raise Exception("taxon_col must be a string.")

    # Construct a list of nodes from dataframe.
    taxon_namespace = dendropy.TaxonNamespace()
    nodes = {}
    for idx in df.index:
        # Get node data.
        data = df.loc[idx]

        # Get taxon for node (if leaf node).
        taxon = None
        if data['type'] == 'leaf':
            taxon = dendropy.Taxon(label=data[taxon_col])
            # Add annotations data.
            for ann in taxon_annotations:
                taxon.annotations.add_new(ann, data[ann])
            taxon_namespace.add_taxon(taxon)

        # Get label for node.
        label = data[node_col]

        # Get edge length.
        edge_length = None
        if branch_lengths is True:
            edge_length = data['length']

        # Build a node
        n = dendropy.Node(
            taxon=taxon,
            label=label,
            edge_length=edge_length
        )

        # Add node annotations
        for ann in node_annotations:
            n.annotations.add_new(ann, data[ann])

        nodes[idx] = n

    # Build branching pattern for nodes.
    root = None
    for idx, node in nodes.items():
        # Get node data.
        data = df.loc[idx]

        # Get children nodes
        children_idx = df[df['parent'] == data['id']].index
        children_nodes = [nodes[i] for i in children_idx]

        # Set child nodes
        nodes[idx].set_child_nodes(children_nodes)

        # Check if this is root.
        if data['parent'] is None:
            root = nodes[idx]

    # Build tree.
    tree = dendropy.Tree(
        seed_node=root,
        taxon_namespace=taxon_namespace
    )
    return tree

Response: Turn a phylopandas dataframe into a dendropy tree.


Instruction:
Implement a function in Python 3 to
write a phylopandas tree dataframe to various formats.

Response:
def _write(
    df,
    filename=None,
    schema='newick',
    taxon_col='uid',
    taxon_annotations=[],
    node_col='uid',
    node_annotations=[],
    branch_lengths=True,
    **kwargs
    ):
    """Write a phylopandas tree DataFrame to various formats.

    Parameters
    ----------
    df : DataFrame
        DataFrame containing tree data.

    filename : str
        filepath to write out tree. If None, will return string.

    schema : str
        tree format to write out.

    taxon_col : str (optional)
        Column in dataframe to label the taxon. If None, the index will be used.

    taxon_annotations : str
        List of columns to annotation in the tree taxon.

    node_col : str (optional)
        Column in dataframe to label the nodes. If None, the index will be used.

    node_annotations : str
        List of columns to annotation in the node taxon.

    branch_lengths : bool
        If True, inclues branch lengths.
    """
    tree = _pandas_df_to_dendropy_tree(
        df,
        taxon_col=taxon_col,
        taxon_annotations=taxon_annotations,
        node_col=node_col,
        node_annotations=node_annotations,
        branch_lengths=branch_lengths,
    )

    # Write out format
    print(schema)
    if filename is not None:
        tree.write(path=filename, schema=schema, suppress_annotations=False, **kwargs)
    else:
        return tree.as_string(schema=schema)


Instruction:
Make a summary of the following Python 3 code
def _write_method(schema):
    def method(
        self,
        filename=None,
        schema=schema,
        taxon_col='uid',
        taxon_annotations=[],
        node_col='uid',
        node_annotations=[],
        branch_lengths=True,
        **kwargs):
        # Use generic write class to write data.
        return _write(
            self._data,
            filename=filename,
            schema=schema,
            taxon_col=taxon_col,
            taxon_annotations=taxon_annotations,
            node_col=node_col,
            node_annotations=node_annotations,
            branch_lengths=branch_lengths,
            **kwargs
        )
    # Update docs
    method.__doc__ = _write_doc_template(schema)
    return method

Response: Add a write method to a class.


Instruction:
How would you implement a function in Python 3 that
adds a write method to a class.

Response:
def _write_function(schema):
    """Add a write method for named schema to a class.
    """
    def func(
        data,
        filename=None,
        schema=schema,
        taxon_col='uid',
        taxon_annotations=[],
        node_col='uid',
        node_annotations=[],
        branch_lengths=True,
        **kwargs):
        # Use generic write class to write data.
        return _write(
            data,
            filename=filename,
            schema=schema,
            taxon_col=taxon_col,
            taxon_annotations=taxon_annotations,
            node_col=node_col,
            node_annotations=node_annotations,
            branch_lengths=branch_lengths,
            **kwargs
        )
    # Update docs
    func.__doc__ = _write_doc_template(schema)
    return func


Instruction:
Can you write a function in Python 3 where it
generates a random alpha - numerical id.

Response:
def get_random_id(length):
    """Generate a random, alpha-numerical id."""
    alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits
    return ''.join(random.choice(alphabet) for _ in range(length))


Instruction:
Explain what the following Python 3 code does
def set_folder(self, folder):
        self.folder = folder
        self.templates.directories[0] = folder
        self.app.root_path = folder

Response: Sets the folder where the files to serve are located.


Instruction:
Create a Python 3 function to
launch a development web server.

Response:
def run(self, host='0.0.0.0', port=8080):
        """
        Launch a development web server.
        """
        waitress.serve(self.app, host=host, port=port)


Instruction:
Write a Python 3 function that can
get the content of a file in the specified folder

Response:
def get(self, path):
        """
        Get the content of a file, indentified by its path relative to the folder configured
        in PyGreen. If the file extension is one of the extensions that should be processed
        through Mako, it will be processed.
        """
        data = self.app.test_client().get("/%s" % path).data
        return data


Instruction:
How would you implement a function in Python 3 that
generates a complete static version of the web site.

Response:
def gen_static(self, output_folder):
        """
        Generates a complete static version of the web site. It will stored in
        output_folder.
        """
        files = []
        for l in self.file_listers:
            files += l()
        for f in files:
            _logger.info("generating %s" % f)
            content = self.get(f)
            loc = os.path.join(output_folder, f)
            d = os.path.dirname(loc)
            if not os.path.exists(d):
                os.makedirs(d)
            with open(loc, "wb") as file_:
                file_.write(content)


Instruction:
Explain what the following Python 3 code does
def cli(self, cmd_args=None):
        logging.basicConfig(level=logging.INFO, format='%(message)s')

        parser = argparse.ArgumentParser(description='PyGreen, micro web framework/static web site generator')
        subparsers = parser.add_subparsers(dest='action')

        parser_serve = subparsers.add_parser('serve', help='serve the web site')
        parser_serve.add_argument('-p', '--port', type=int, default=8080, help='port to serve on')
        parser_serve.add_argument('-f', '--folder', default=".", help='folder containg files to serve')
        parser_serve.add_argument('-d', '--disable-templates', action='store_true', default=False, help='just serve static files, do not use Mako')
        def serve():
            if args.disable_templates:
                self.template_exts = set([])
            self.run(port=args.port)
        parser_serve.set_defaults(func=serve)

        parser_gen = subparsers.add_parser('gen', help='generate a static version of the site')
        parser_gen.add_argument('output', help='folder to store the files')
        parser_gen.add_argument('-f', '--folder', default=".", help='folder containing files to generate')
        def gen():
            self.gen_static(args.output)
        parser_gen.set_defaults(func=gen)

        args = parser.parse_args(cmd_args)
        self.set_folder(args.folder)
        print(parser.description)
        print("")
        args.func()

Response: Command line interface of PyGreen.


Instruction:
Make a summary of the following Python 3 code
def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args):

        self.switch_configuration = switch_configuration
        self.terminal_controller = terminal_controller
        self.logger = logger
        self.piping_processor = piping_processor
        self.sub_processor = None
        self.continuing_to = None
        self.is_done = False
        self.replace_input = False
        self.awaiting_keystroke = False

Response: Initializes the object with the given switch configuration.


Instruction:
Given the following Python 3 function, write the documentation
def _gccalc(lon, lat, azimuth, maxdist=None):
    glat1 = lat * np.pi / 180.
    glon1 = lon * np.pi / 180.
    s = maxdist / 1.852243
    faz = azimuth * np.pi / 180.

    EPS = 0.00000000005
    if ((np.abs(np.cos(glat1)) < EPS) and not (np.abs(np.sin(faz)) < EPS)):
        raise CourseException("Only North-South courses are meaningful")

    a = 6378.137 / 1.852243
    f = 1 / 298.257223563
    r = 1 - f
    tu = r * np.tan(glat1)
    sf = np.sin(faz)
    cf = np.cos(faz)
    if (cf == 0):
        b = 0.
    else:
        b = 2. * np.arctan2 (tu, cf)

    cu = 1. / np.sqrt(1 + tu * tu)
    su = tu * cu
    sa = cu * sf
    c2a = 1 - sa * sa
    x = 1. + np.sqrt(1. + c2a * (1. / (r * r) - 1.))
    x = (x - 2.) / x
    c = 1. - x
    c = (x * x / 4. + 1.) / c
    d = (0.375 * x * x - 1.) * x
    tu = s / (r * a * c)
    y = tu
    c = y + 1
    while (np.abs (y - c) > EPS):
        sy = np.sin(y)
        cy = np.cos(y)
        cz = np.cos(b + y)
        e = 2. * cz * cz - 1.
        c = y
        x = e * cy
        y = e + e - 1.
        y = (((sy * sy * 4. - 3.) * y * cz * d / 6. + x) *
            d / 4. - cz) * sy * d + tu

    b = cu * cy * cf - su * sy
    c = r * np.sqrt(sa * sa + b * b)
    d = su * cy + cu * sy * cf
    glat2 = (np.arctan2(d, c) + np.pi) % (2*np.pi) - np.pi
    c = cu * cy - su * sy * cf
    x = np.arctan2(sy * sf, c)
    c = ((-3. * c2a + 4.) * f + 4.) * c2a * f / 16.
    d = ((e * cy * c + cz) * sy * c + y) * sa
    glon2 = ((glon1 + x - (1. - c) * d * f + np.pi) % (2*np.pi)) - np.pi

    baz = (np.arctan2(sa, b) + np.pi) % (2 * np.pi)

    glon2 *= 180./np.pi
    glat2 *= 180./np.pi
    baz *= 180./np.pi
    return (glon2, glat2, baz)

Response: This function calculates the base of the GC algorithm.


Instruction:
Can you create a Python 3 function that
returns lon lat tuples of a circle which matches the chosen Basemap projection

Response:
def circle(m, centerlon, centerlat, radius, *args, **kwargs):
    """
    Return lon, lat tuples of a "circle" which matches the chosen Basemap projection
    Takes the following arguments:
    m = basemap instance
    centerlon = originating lon
    centrelat = originating lat
    radius = radius

    """
    glon1 = centerlon
    glat1 = centerlat
    X = []
    Y = []
    for azimuth in range(0, 360):
        glon2, glat2, baz = _gccalc(glon1, glat1, azimuth, radius)
        X.append(glon2)
        Y.append(glat2)
    X.append(X[0])
    Y.append(Y[0])

    proj_x, proj_y = m(X,Y)
    return zip(proj_x, proj_y)


Instruction:
Write a Python 3 function that can
register a new mime type.

Response:
def register_mime(shortname, mime_types):
    """
    Register a new mime type.
    Usage example:
        mimerender.register_mime('svg', ('application/x-svg', 'application/svg+xml',))
    After this you can do:
        @mimerender.mimerender(svg=render_svg)
        def GET(...
            ...
    """
    if shortname in _MIME_TYPES:
        raise MimeRenderException('"%s" has already been registered'%shortname)
    _MIME_TYPES[shortname] = mime_types


Instruction:
Here you have a function in Python 3, explain what it does
def wsgi_wrap(app):
    '''
    Wraps a standard wsgi application e.g.:
        def app(environ, start_response)
    It intercepts the start_response callback and grabs the results from it
    so it can return the status, headers, and body as a tuple
    '''
    @wraps(app)
    def wrapped(environ, start_response):
        status_headers = [None, None]
        def _start_response(status, headers):
            status_headers[:] = [status, headers]
        body = app(environ, _start_response)
        ret = body, status_headers[0], status_headers[1]
        return ret
    return wrapped

Response: A decorator that wraps a wsgi application e. g. returns a status headers and body as a tuple


Instruction:
Given the following Python 3 function, write the documentation
def map_exceptions(self, mapping, *args, **kwargs):
        @self.__call__(*args, **kwargs)
        def helper(e, status):
            return dict(exception=e), status

        def wrap(target):
            @wraps(target)
            def wrapper(*args, **kwargs):
                try:
                    return target(*args, **kwargs)
                except BaseException as e:
                    for klass, status in mapping:
                        if isinstance(e, klass):
                            return helper(e, status)
                    raise
            return wrapper
        return wrap

Response: A decorator which maps exceptions to the internal state of the object.


Instruction:
How would you explain what the following Python 3 function does
def relative(self):

		scheme = self.scheme

		if not scheme:
			return True

		return scheme.is_relative(self)

Response: Identify if this URI is relative to some current context.


Instruction:
Implement a function in Python 3 to
attempt to resolve a new URI given an updated URI partial or complete.

Response:
def resolve(self, uri=None, **parts):
		"""Attempt to resolve a new URI given an updated URI, partial or complete."""

		if uri:
			result = self.__class__(urljoin(str(self), str(uri)))
		else:
			result = self.__class__(self)

		for part, value in parts.items():
			if part not in self.__all_parts__:
				raise TypeError("Unknown URI component: " + part)

			setattr(result, part, value)

		return result


Instruction:
Can you tell what is the following Python 3 function doing
def replace(self, year=None, month=None, day=None):

        return JalaliDate(
            year if year else self.year,
            month if month else self.month,
            day if day else self.day
        )

Response: Replaces the given arguments on this instance and returns a new instance.


Instruction:
Write a Python 3 script for
calculating the corresponding date in the gregorian calendar.

Response:
def todate(self):
        """
        Calculates the corresponding day in the gregorian calendar. this is the main use case of this library.

        :return: Corresponding date in gregorian calendar.
        :rtype: :py:class:`datetime.date`
        """
        arr = get_gregorian_date_from_julian_day(self.tojulianday())
        return datetime.date(int(arr[0]), int(arr[1]), int(arr[2]))


Instruction:
How would you explain what the following Python 3 function does
def timetuple(self):
        return time.struct_time((
            self.year,
            self.month,
            self.day,
            0,
            0,
            0,
            self.weekday(),
            self.dayofyear(),
            -1
        ))

Response: Returns a time. struct_time object for the current object.


Instruction:
Make a summary of the following Python 3 code
def weekofyear(self, first_day_of_week=SATURDAY):
        first_day_of_year = self.firstdayofyear()
        days = (self - first_day_of_year).days
        offset = first_day_of_week - first_day_of_year.weekday()
        if offset < 0:
            offset += 7

        if days < offset:
            return 0

        return int((days - offset) / 7 + 1)

Response: returns the week number of the year.


Instruction:
Write a Python 3 script to
create a new instance of the class cls from the given timestamp.

Response:
def fromtimestamp(cls, timestamp, tz=None):
        """
        Creates a new :py:class:`khayyam.JalaliDatetime` instance from the given posix timestamp.

        If optional argument tz is :py:obj:`None` or not specified, the timestamp is converted to
        the platform's local date and time, and the returned datetime object is naive.

        Else tz must be an instance of a class :py:class:`datetime.tzinfo` subclass,
        and the timestamp is converted to tz's time zone. In this case the result is
        equivalent to `tz.fromutc(JalaliDatetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))`.

        This method may raise `ValueError`, if the timestamp is out of the range of values
        supported by the platform C localtime() or gmtime() functions.
        It's common for this to be restricted to years in 1970 through 2038.

        Note that on non-POSIX systems that include leap seconds in their
        notion of a timestamp, leap seconds are ignored by fromtimestamp(), and then
        it's possible to have two timestamps differing by a second that yield
        identical datetime objects. See also :py:class:`khayyam.JalaliDatetime.utcfromtimestamp`.

        .. testsetup:: api-datetime-fromtimestamp

            import khayyam
            from khayyam import JalaliDatetime

        .. doctest:: api-datetime-fromtimestamp

            >>> JalaliDatetime.fromtimestamp(1313132131.21232)
            khayyam.JalaliDatetime(1390, 5, 21, 11, 25, 31, 212320, Jomeh)

        :param timestamp: float the posix timestamp, i.e 1014324234.23423423.
        :param tz: :py:class:`datetime.tzinfo` The optional timezone to get local date & time from the given timestamp.
        :return: The local date and time corresponding to the POSIX timestamp, such as is returned by :py:func:`time.time()`.
        :rtype: :py:class:`khayyam.JalaliDatetime`
        """
        return cls(datetime.fromtimestamp(timestamp, tz=tz))


Instruction:
Implement a function in Python 3 to
return a new jalali datetime object whose date members are equal to the given date object s and whose _time members are equal to the given time object s.

Response:
def combine(cls, date, _time):
        """
        Return a new jalali datetime object whose date members are equal to the given date object's, and whose _time
        and tzinfo members are equal to the given _time object's.
        For any datetime object d, d == datetime.combine(d.date(), d.timetz()). If date is a datetime object, its _time
        and tzinfo members are ignored.

        :param date: :py:class:`khayyam.JalaliDate` the date object to combine.
        :param _time: :py:class:`datetime.time` the time object to combine.
        :return: the combined jalali date & time object.
        :rtype: :py:class:`khayyam.JalaliDatetime`
        """
        if isinstance(date, (JalaliDatetime, khayyam.JalaliDate)):
            date = date.todate()
        return cls(datetime.combine(date, _time))


Instruction:
How would you explain what the following Python 3 function does
def todatetime(self):
        arr = get_gregorian_date_from_julian_day(self.tojulianday())
        return datetime(int(arr[0]), int(arr[1]), int(arr[2]), self.hour, self.minute, self.second, self.microsecond,
                        self.tzinfo)

Response: Converts the current instance to the python builtins datetime instance.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def date(self):
        return khayyam.JalaliDate(self.year, self.month, self.day)

Response: Return a new object with same year month and day.


Instruction:
Make a summary of the following Python 3 code
def replace(self, year=None, month=None, day=None, hour=None,
                minute=None, second=None, microsecond=None, tzinfo=None):
        """
        Return a :py:class:`khayyam.JalaliDatetime` instance with the same attributes, except for those attributes
        given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create
        a naive datetime from an aware datetime with no conversion of date and time data, without adjusting the date
        the and time based tzinfo.

        :param year: int
        :param month: int
        :param day: int
        :param hour: int
        :param minute: int
        :param second: int
        :param microsecond: int
        :param tzinfo: :py:class:`datetime.tzinfo`
        :rtype: :py:class:`khayyam.JalaliDatetime`
        """
        year, month, day = self._validate(
            year if year else self.year,
            month if month else self.month,
            day if day else self.day
        )

        result = JalaliDatetime(
            year,
            month,
            day,
            self.hour if hour is None else hour,
            self.minute if minute is None else minute,
            self.second if second is None else second,
            self.microsecond if microsecond is None else microsecond,
            tzinfo if tzinfo != self.tzinfo else self.tzinfo
        )
        return result

Response:
Returns a new instance of the same attributes except for those attributes
        given new values by whichever keyword arguments are specified.


Instruction:
Write a Python 3 function that can
return a new object with new time zone information set to tz.

Response:
def astimezone(self, tz):
        """
        Return a :py:class:`khayyam.JalaliDatetime` object with new :py:meth:`khayyam.JalaliDatetime.tzinfo` attribute
        tz, adjusting the date and time data so the result is the same UTC time as self, but in *tz*‘s local time.

        *tz* must be an instance of a :py:class:`datetime.tzinfo` subclass, and
        its :py:meth:`datetime.tzinfo.utcoffset()` and :py:meth:`datetime.tzinfo.dst()` methods must not
        return :py:obj:`None`. *self* must be aware (`self.tzinfo` must not be `None`, and `self.utcoffset()` must
        not return `None`).

        If `self.tzinfo` is `tz`, `self.astimezone(tz)` is equal to `self`: no adjustment of date or time data is
        performed. Else the result is local time in time zone `tz`, representing the same UTC time as `self`:
        after `astz = dt.astimezone(tz), astz - astz.utcoffset()` will usually have the same date and time data as
        `dt - dt.utcoffset()`. The discussion of class :py:class:`datetime.tzinfo` explains the cases at Daylight
        Saving Time transition boundaries where this cannot be achieved (an issue only if `tz` models both
        standard and daylight time).

        If you merely want to attach a time zone object `tz` to a datetime dt without adjustment of date and time data,
        use `dt.replace(tzinfo=tz)`. If you merely want to remove the time zone object from an aware datetime dt
        without conversion of date and time data, use `dt.replace(tzinfo=None)`.

        Note that the default :py:meth:`datetime.tzinfo.fromutc()` method can be overridden in a
        :py:class:`datetime.tzinfo` subclass to affect the result returned
        by :py:meth:`khayyam.JalaliDatetime.astimezone()`. Ignoring error
        cases, :py:meth:`khayyam.JalaliDatetime.astimezone()` acts like:

        .. code-block:: python
           :emphasize-lines: 3,5

           def astimezone(self, tz):  # doctest: +SKIP

               if self.tzinfo is tz:
                   return self
               if self.tzinfo:
                   utc = self - self.utcoffset()
               else:
                   utc = self
               return tz.fromutc(utc.replace(tzinfo=tz))

        :param tz: :py:class:`datetime.tzinfo`
        :rtype: :py:class:`khayyam.JalaliDatetime`
        """
        if self.tzinfo is tz:
            return self
        if self.tzinfo:
            utc = self - self.utcoffset()
        else:
            utc = self
        return tz.fromutc(utc.replace(tzinfo=tz))


Instruction:
Can you generate the documentation for the following Python 3 function
def hour12(self):
        res = self.hour
        if res > 12:
            res -= 12
        elif res == 0:
            res = 12
        return res

Response: Return The hour value between 1 - 12. use khayyam. JalaliDatetime. ampmascii to determineante meridiem and post meridiem. use khayyam. JalaliDatetime. ampmascii to determine post meridiem. use khayyam. jcjalaliDatetime. ampmascii to determineante meridiem and post meridiem.


Instruction:
Can you implement a function in Python 3 that
computes the Linear Prediction Coefficients for the input signal and the given order.

Response:
def lpc_ref(signal, order):
    """Compute the Linear Prediction Coefficients.

    Return the order + 1 LPC coefficients for the signal. c = lpc(x, k) will
    find the k+1 coefficients of a k order linear filter:

      xp[n] = -c[1] * x[n-2] - ... - c[k-1] * x[n-k-1]

    Such as the sum of the squared-error e[i] = xp[i] - x[i] is minimized.

    Parameters
    ----------
    signal: array_like
        input signal
    order : int
        LPC order (the output will have order + 1 items)

    Notes
    ----
    This is just for reference, as it is using the direct inversion of the
    toeplitz matrix, which is really slow"""
    if signal.ndim > 1:
        raise ValueError("Array of rank > 1 not supported yet")
    if order > signal.size:
        raise ValueError("Input signal must have a lenght >= lpc order")

    if order > 0:
        p = order + 1
        r = np.zeros(p, 'float32')
        # Number of non zero values in autocorrelation one needs for p LPC
        # coefficients
        nx = np.min([p, signal.size])
        x = np.correlate(signal, signal, 'full')
        r[:nx] = x[signal.size - 1:signal.size + order]
        phi = np.dot(sp.linalg.inv(sp.linalg.toeplitz(r[:-1])), -r[1:])
        return np.concatenate(([1.], phi))
    else:
        return np.ones(1, dtype='float32')


Instruction:
Implement a function in Python 3 to
compute the biased autocorrelation of x along the given axis.

Response:
def acorr_lpc(x, axis=-1):
    """Compute autocorrelation of x along the given axis.

    This compute the biased autocorrelation estimator (divided by the size of
    input signal)

    Notes
    -----
        The reason why we do not use acorr directly is for speed issue."""
    if not np.isrealobj(x):
        raise ValueError("Complex input not supported yet")

    maxlag = x.shape[axis]
    nfft = int(2 ** nextpow2(2 * maxlag - 1))

    if axis != -1:
        x = np.swapaxes(x, -1, axis)
    a = _acorr_last_axis(x, nfft, maxlag)
    if axis != -1:
        a = np.swapaxes(a, -1, axis)
    return a


Instruction:
Write a Python 3 script for
computing the Linear Prediction Coefficients.

Response:
def lpc(signal, order, axis=-1):
    """Compute the Linear Prediction Coefficients.

    Return the order + 1 LPC coefficients for the signal. c = lpc(x, k) will
    find the k+1 coefficients of a k order linear filter:

      xp[n] = -c[1] * x[n-2] - ... - c[k-1] * x[n-k-1]

    Such as the sum of the squared-error e[i] = xp[i] - x[i] is minimized.

    Parameters
    ----------
    signal: array_like
        input signal
    order : int
        LPC order (the output will have order + 1 items)

    Returns
    -------
    a : array-like
        the solution of the inversion.
    e : array-like
        the prediction error.
    k : array-like
        reflection coefficients.

    Notes
    -----
    This uses Levinson-Durbin recursion for the autocorrelation matrix
    inversion, and fft for the autocorrelation computation.

    For small order, particularly if order << signal size, direct computation
    of the autocorrelation is faster: use levinson and correlate in this case."""
    n = signal.shape[axis]
    if order > n:
        raise ValueError("Input signal must have length >= order")

    r = acorr_lpc(signal, axis)
    return levinson_1d(r, order)


Instruction:
Write a Python 3 function that can
take in an explicit mapping of full paths to. wav files to have acoustic similarity computed.

Response:
def acoustic_similarity_mapping(path_mapping, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True):
    """Takes in an explicit mapping of full paths to .wav files to have
    acoustic similarity computed.

    Parameters
    ----------
    path_mapping : iterable of iterables
        Explicit mapping of full paths of .wav files, in the form of a
        list of tuples to be compared.

    Returns
    -------
    dict
        Returns a list of tuples corresponding to the `path_mapping` input,
        with a new final element in the tuple being the similarity/distance
        score for that mapping.

    """

    num_cores = int((3 * cpu_count()) / 4)
    segments = set()
    for x in path_mapping:
        segments.update(x)
    if multiprocessing:
        cache = generate_cache_mp(segments, analysis_function, num_cores, call_back, stop_check)
        asim = calculate_distances_mp(path_mapping, cache, distance_function, num_cores, call_back, stop_check)
    else:
        cache = generate_cache_th(segments, analysis_function, num_cores, call_back, stop_check)
        asim = calculate_distances_th(path_mapping, cache, distance_function, num_cores, call_back, stop_check)
    return asim


Instruction:
Implement a Python 3 function for
taking in an explicit mapping of full paths to. wav files to have acoustic similarity computed.

Response:
def axb_mapping(path_mapping, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True):
    """Takes in an explicit mapping of full paths to .wav files to have
    acoustic similarity computed.

    Parameters
    ----------
    path_mapping : iterable of iterables
        Explicit mapping of full paths of .wav files, in the form of a
        list of tuples to be compared.

    Returns
    -------
    dict
        Returns a list of tuples corresponding to the `path_mapping` input,
        with a new final element in the tuple being the similarity/distance
        score for that mapping.

    """

    num_cores = int((3 * cpu_count()) / 4)
    segments = set()
    for x in path_mapping:
        segments.update(x)
    if multiprocessing:
        cache = generate_cache_mp(segments, analysis_function, num_cores, call_back, stop_check)
        asim = calculate_axb_ratio_mp(path_mapping, cache, distance_function, num_cores, call_back, stop_check)
    else:
        cache = generate_cache_th(segments, analysis_function, num_cores, call_back, stop_check)
        asim = calculate_axb_ratio_th(path_mapping, cache, distance_function, num_cores, call_back, stop_check)
    return asim


Instruction:
Can you generate a brief explanation for the following Python 3 code
def acoustic_similarity_directories(directories, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True):

    files = []

    if call_back is not None:
        call_back('Mapping directories...')
        call_back(0, len(directories))
        cur = 0
    for d in directories:
        if not os.path.isdir(d):
            continue
        if stop_check is not None and stop_check():
            return
        if call_back is not None:
            cur += 1
            if cur % 3 == 0:
                call_back(cur)

        files += [os.path.join(d, x) for x in os.listdir(d) if x.lower().endswith('.wav')]

    if len(files) == 0:
        raise (ConchError("The directories specified do not contain any wav files"))

    if call_back is not None:
        call_back('Mapping directories...')
        call_back(0, len(files) * len(files))
        cur = 0
    path_mapping = list()
    for x in files:
        for y in files:
            if stop_check is not None and stop_check():
                return
            if call_back is not None:
                cur += 1
                if cur % 20 == 0:
                    call_back(cur)
            if not x.lower().endswith('.wav'):
                continue
            if not y.lower().endswith('.wav'):
                continue
            if x == y:
                continue
            path_mapping.append((x, y))

    result = acoustic_similarity_mapping(path_mapping, analysis_function, distance_function, stop_check, call_back, multiprocessing)
    return result

Response: Analyze many directories and return a list of acoustic similarity files.


Instruction:
Write a Python 3 function that can
compute the distance between two representations using Dynamic Time Warping.

Response:
def dtw_distance(rep_one, rep_two, norm=True):
    """Computes the distance between two representations with the same
    number of filters using Dynamic Time Warping.

    Parameters
    ----------
    rep_one : 2D array
        First representation to compare. First dimension is time in frames
        or samples and second dimension is the features.
    rep_two : 2D array
        Second representation to compare. First dimension is time in frames
        or samples and second dimension is the features.

    Returns
    -------
    float
        Distance of dynamically time warping `rep_one` to `rep_two`.

    """
    if not isinstance(rep_one, np.ndarray):
        rep_one = rep_one.to_array()
    if not isinstance(rep_two, np.ndarray):
        rep_two = rep_two.to_array()
    assert (rep_one.shape[1] == rep_two.shape[1])
    distMat = generate_distance_matrix(rep_one, rep_two)
    return regularDTW(distMat, norm=norm)


Instruction:
How would you explain what the following Python 3 function does
def generate_distance_matrix(source, target, weights=None):
    if weights is None:
        weights = ones((source.shape[1], 1))
    sLen = source.shape[0]
    tLen = target.shape[0]
    distMat = zeros((sLen, tLen))
    for i in range(sLen):
        for j in range(tLen):
            distMat[i, j] = euclidean(source[i, :], target[j, :])
    return distMat

Response: Generates a local distance matrix for use in dynamic time warping.


Instruction:
Implement a Python 3 function for
using a local distance matrix to perform dynamic time warping.

Response:
def regularDTW(distMat, norm=True):
    """Use a local distance matrix to perform dynamic time warping.

    Parameters
    ----------
    distMat : 2D array
        Local distance matrix.

    Returns
    -------
    float
        Total unweighted distance of the optimal path through the
        local distance matrix.

    """
    sLen, tLen = distMat.shape
    totalDistance = zeros((sLen, tLen))
    totalDistance[0:sLen, 0:tLen] = distMat

    minDirection = zeros((sLen, tLen))

    for i in range(1, sLen):
        totalDistance[i, 0] = totalDistance[i, 0] + totalDistance[i - 1, 0]

    for j in range(1, tLen):
        totalDistance[0, j] = totalDistance[0, j] + totalDistance[0, j - 1]

    for i in range(1, sLen):
        for j in range(1, tLen):
            # direction,minPrevDistance = min(enumerate([totalDistance[i,j],totalDistance[i,j+1],totalDistance[i+1,j]]), key=operator.itemgetter(1))
            # totalDistance[i+1,j+1] = totalDistance[i+1,j+1] + minPrevDistance
            # minDirection[i,j] = direction
            minDirection[i, j], totalDistance[i, j] = min(
                enumerate([totalDistance[i - 1, j - 1] + 2 * totalDistance[i, j],
                           totalDistance[i - 1, j] + totalDistance[i, j],
                           totalDistance[i, j - 1] + totalDistance[i, j]]), key=operator.itemgetter(1))
    if norm:
        return totalDistance[sLen - 1, tLen - 1] / (sLen + tLen)
    return totalDistance[sLen - 1, tLen - 1]


Instruction:
Create a Python 3 function to
filter the signal x with the FIR filter described by the filter described by the overlap - add method.

Response:
def fftfilt(b, x, *n):
    """Filter the signal x with the FIR filter described by the
    coefficients in b using the overlap-add method. If the FFT
    length n is not specified, it and the overlap-add block length
    are selected so as to minimize the computational cost of
    the filtering operation."""

    N_x = len(x)
    N_b = len(b)

    # Determine the FFT length to use:
    if len(n):

        # Use the specified FFT length (rounded up to the nearest
        # power of 2), provided that it is no less than the filter
        # length:
        n = n[0]
        if n != int(n) or n <= 0:
            raise ValueError('n must be a nonnegative integer')
        if n < N_b:
            n = N_b
        N_fft = 2 ** nextpow2(n)
    else:

        if N_x > N_b:

            # When the filter length is smaller than the signal,
            # choose the FFT length and block size that minimize the
            # FLOPS cost. Since the cost for a length-N FFT is
            # (N/2)*log2(N) and the filtering operation of each block
            # involves 2 FFT operations and N multiplications, the
            # cost of the overlap-add method for 1 length-N block is
            # N*(1+log2(N)). For the sake of efficiency, only FFT
            # lengths that are powers of 2 are considered:
            N = 2 ** np.arange(np.ceil(np.log2(N_b)), np.floor(np.log2(N_x)))
            cost = np.ceil(N_x / (N - N_b + 1)) * N * (np.log2(N) + 1)
            if len(cost) > 0:
                N_fft = N[np.argmin(cost)]
            else:
                N_fft = 2 ** nextpow2(N_b + N_x - 1)

        else:

            # When the filter length is at least as long as the signal,
            # filter the signal using a single block:
            N_fft = 2 ** nextpow2(N_b + N_x - 1)

    N_fft = int(N_fft)

    # Compute the block length:
    L = int(N_fft - N_b + 1)

    # Compute the transform of the filter:
    H = fft(b, N_fft)

    y = np.zeros(N_x, np.float32)
    i = 0
    while i <= N_x:
        il = np.min([i + L, N_x])
        k = np.min([i + N_fft, N_x])
        yt = ifft(fft(x[i:il], N_fft) * H, N_fft)  # Overlap..
        y[i:k] = y[i:k] + yt[:k - i]  # and add
        i += L
    return y


Instruction:
Implement a function in Python 3 to
convert a spectrum into a cepstrum via type - III DCT.

Response:
def dct_spectrum(spec):
    """Convert a spectrum into a cepstrum via type-III DCT (following HTK).

    Parameters
    ----------
    spec : array
        Spectrum to perform a DCT on.

    Returns
    -------
    array
        Cepstrum of the input spectrum.

    """
    ncep = spec.shape[0]
    dctm = np.zeros((ncep, ncep))
    for i in range(ncep):
        dctm[i, :] = np.cos(i * np.arange(1, 2 * ncep, 2) / (2 * ncep) * np.pi) * np.sqrt(2 / ncep)
    dctm *= 0.230258509299405
    cep = np.dot(dctm, (10 * np.log10(spec + np.spacing(1))))
    return cep


Instruction:
Write a Python 3 script to
construct a filterbank for a set of mel - frequency filters.

Response:
def construct_filterbank(num_filters, nfft, sr, min_freq, max_freq):
    """Constructs a mel-frequency filter bank.

            Parameters
            ----------
            nfft : int
                Number of points in the FFT.

            Returns
            -------
            array
                Filter bank to multiply an FFT spectrum to create a mel-frequency
                spectrum.

            """

    min_mel = freq_to_mel(min_freq)
    max_mel = freq_to_mel(max_freq)
    mel_points = np.linspace(min_mel, max_mel, num_filters + 2)
    bin_freqs = mel_to_freq(mel_points)
    # bins = round((nfft - 1) * bin_freqs / sr)

    fftfreqs = np.arange(int(nfft / 2 + 1)) / nfft * sr

    fbank = np.zeros((num_filters, int(nfft / 2 + 1)))
    for i in range(num_filters):
        fs = bin_freqs[i + np.arange(3)]
        fs = fs[1] + (fs - fs[1])
        loslope = (fftfreqs - fs[0]) / (fs[1] - fs[0])
        highslope = (fs[2] - fftfreqs) / (fs[2] - fs[1])
        fbank[i, :] = np.maximum(np.zeros(loslope.shape), np.minimum(loslope, highslope))
    return fbank.transpose()


Instruction:
Given the following Python 3 function, write the documentation
def windowed_iterable(self):
        # Seek to offset
        effective_offset = max(0,self.item_view.iterable_index)
        for i,item in enumerate(self.iterable):
            if i<effective_offset:
                continue
            elif i>=(effective_offset+self.item_view.iterable_fetch_size):
                return
            yield item

Response: Yields the items in the iterable that are in the window.


Instruction:
How would you implement a function in Python 3 that
refreshes the items of the pattern. This method destroys the old items and creates and initializes the new items.

Response:
def refresh_items(self):
        """ Refresh the items of the pattern.

        This method destroys the old items and creates and initializes
        the new items.

        """
        old_items = self.items[:]# if self._dirty else []
        old_iter_data = self._iter_data# if self._dirty else {}
        iterable = self.windowed_iterable
        pattern_nodes = self.pattern_nodes
        new_iter_data = sortedmap()
        new_items = []

        if iterable is not None and len(pattern_nodes) > 0:
            for loop_index, loop_item in enumerate(iterable):
                iteration = old_iter_data.get(loop_item)
                if iteration is not None:
                    new_iter_data[loop_item] = iteration
                    new_items.append(iteration)
                    old_items.remove(iteration)
                    continue
                iteration = []
                new_iter_data[loop_item] = iteration
                new_items.append(iteration)
                for nodes, key, f_locals in pattern_nodes:
                    with new_scope(key, f_locals) as f_locals:
                        f_locals['loop_index'] = loop_index
                        f_locals['loop_item'] = loop_item
                        for node in nodes:
                            child = node(None)
                            if isinstance(child, list):
                                iteration.extend(child)
                            else:
                                iteration.append(child)

        # Add to old items list
        #self.old_items.extend(old_items)

        #if self._dirty:
        for iteration in old_items:
            for old in iteration:
                if not old.is_destroyed:
                    old.destroy()

        if len(new_items) > 0:
            expanded = []
            recursive_expand(sum(new_items, []), expanded)
            self.parent.insert_children(self, expanded)

        self.items = new_items# if self._dirty else new_items+old_items
        self._iter_data = new_iter_data


Instruction:
Explain what the following Python 3 code does
def create_widget(self):
        widget = QDoubleSpinBox(self.parent_widget())
        widget.setKeyboardTracking(False)
        self.widget = widget

Response: Create the underlying QDoubleSpinBox widget.


Instruction:
Make a summary of the following Python 3 code
def initialize(self):
        super(Block, self).initialize()
        if self.block:
            self.block.parent.insert_children(self.block, self.children)

Response:
A reimplemented initializer.

        This method will add the include objects to the parent of the
        include and ensure that they are initialized.


Instruction:
Create a Python 3 function to
update the index of the resource table.

Response:
def _update_index(self):
        """ Update the reference to the index within the table """
        d = self.declaration
        self.index = self.view.model.index(d.row, d.column)
        if self.delegate:
            self._refresh_count += 1
            timed_call(self._loading_interval, self._update_delegate)


Instruction:
Create a Python 3 function to
update the delegate cell widget.

Response:
def _update_delegate(self):
        """ Update the delegate cell widget. This is deferred so it
        does not get called until the user is done scrolling.
        """
        self._refresh_count -= 1
        if self._refresh_count != 0:
            return
        try:
            delegate = self.delegate
            if not self.is_visible():
                return
            # The table destroys when it goes out of view
            # so we always have to make a new one
            delegate.create_widget()
            delegate.init_widget()

            #  Set the index widget
            self.view.widget.setIndexWidget(self.index, delegate.widget)
        except RuntimeError:
            pass


Instruction:
Can you tell what is the following Python 3 function doing
def data_changed(self, change):
        index = self.index
        if index:
            self.view.model.dataChanged.emit(index, index)

Response: Notify the model that the data has changed in this cell!


Instruction:
Can you generate the documentation for the following Python 3 function
def GetHandle(self):
        ''' returns an the identifier of the GUI widget.
        It must be an integer
        '''
        win_id = self.winId()  # this returns either an int or voitptr

        if "%s"%type(win_id) == "<type 'PyCObject'>":  # PySide
            ### with PySide, self.winId() does not return an integer
            if sys.platform == "win32":
                ## Be careful, this hack is py27 specific
                ## does not work with python31 or higher
                ## since the PyCObject api was changed
                import ctypes
                ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p
                ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [
                    ctypes.py_object]
                win_id = ctypes.pythonapi.PyCObject_AsVoidPtr(win_id)
        elif type(win_id) is not int:  #PyQt4 or 5
            ## below integer cast may be required because self.winId() can
            ## returns a sip.voitptr according to the PyQt version used
            ## as well as the python version
            win_id = int(win_id)
        return win_id

Response: Returns the handle of the most recent available entry in the GUI.


Instruction:
Create a Python 3 function to
return a generator that yields the set of entities that are in the same topology.

Response:
def _map_shapes_and_ancestors(self, topoTypeA, topoTypeB, topologicalEntity):
        '''
        using the same method
        @param topoTypeA:
        @param topoTypeB:
        @param topologicalEntity:
        '''
        topo_set = set()
        _map = TopTools_IndexedDataMapOfShapeListOfShape()
        topexp_MapShapesAndAncestors(self.myShape, topoTypeA, topoTypeB, _map)
        results = _map.FindFromKey(topologicalEntity)
        if results.IsEmpty():
            yield None

        topology_iterator = TopTools_ListIteratorOfListOfShape(results)
        while topology_iterator.More():

            topo_entity = self.topoFactory[topoTypeB](topology_iterator.Value())

            # return the entity if not in set
            # to assure we're not returning entities several times
            if not topo_entity in topo_set:
                if self.ignore_orientation:
                    unique = True
                    for i in topo_set:
                        if i.IsSame(topo_entity):
                            unique = False
                            break
                    if unique:
                        yield topo_entity
                else:
                    yield topo_entity

            topo_set.add(topo_entity)
            topology_iterator.Next()


Instruction:
Can you generate the documentation for the following Python 3 function
def _number_shapes_ancestors(self, topoTypeA, topoTypeB, topologicalEntity):
        '''returns the number of shape ancestors
        If you want to know how many edges a faces has:
        _number_shapes_ancestors(self, TopAbs_EDGE, TopAbs_FACE, edg)
        will return the number of edges a faces has
        @param topoTypeA:
        @param topoTypeB:
        @param topologicalEntity:
        '''
        topo_set = set()
        _map = TopTools_IndexedDataMapOfShapeListOfShape()
        topexp_MapShapesAndAncestors(self.myShape, topoTypeA, topoTypeB, _map)
        results = _map.FindFromKey(topologicalEntity)
        if results.IsEmpty():
            return None
        topology_iterator = TopTools_ListIteratorOfListOfShape(results)
        while topology_iterator.More():
            topo_set.add(topology_iterator.Value())
            topology_iterator.Next()
        return len(topo_set)

Response: returns the number of shape ancestors


Instruction:
Given the following Python 3 function, write the documentation
def init_layout(self):
        for child in self.children():
            self.child_added(child)
        self.update_shape({})

Response: Initialize the layout of the toolkit shape.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def init_widget(self):
        super(QtKeyEvent, self).init_widget()
        d = self.declaration
        widget = self.widget
        self._keyPressEvent = widget.keyPressEvent
        self._keyReleaseEvent = widget.keyReleaseEvent
        self.set_enabled(d.enabled)
        self.set_keys(d.keys)

Response: The KeyEvent uses the parent_widget as it s widget


Instruction:
Make a summary of the following Python 3 code
def set_keys(self, keys):
        codes = {}
        for key in keys:
            parts = [k.strip().lower() for k in key.split("+")]
            code = KEYS.get(parts[-1])
            modifier = Qt.KeyboardModifiers()
            if code is None:
                raise KeyError("Invalid key code '{}'".format(key))
            if len(parts) > 1:
                for mod in parts[:-1]:
                    mod_code = MODIFIERS.get(mod)
                    if mod_code is None:
                        raise KeyError("Invalid key modifier '{}'"
                                       .format(mod_code))
                    modifier |= mod_code
            if code not in codes:
                codes[code] = []
            codes[code].append(modifier)
        self.codes = codes

Response: Parse all the key codes and save them in the codes attribute


Instruction:
Can you generate the documentation for the following Python 3 function
def _update_proxy(self, change):
        if change['name'] == 'items':
            self._update_visible_area()

        super(TableView, self)._update_proxy(change)

Response: An observer which sends state change to the proxy.


Instruction:
How would you explain what the following Python 3 function does
def _teardown_features(self):
        features = self._features
        if not features:
            return
        if features & Feature.FocusTraversal:
            self.unhook_focus_traversal()
        if features & Feature.FocusEvents:
            self.unhook_focus_events()
        if features & Feature.DragEnabled:
            self.unhook_drag()
        if features & Feature.DropEnabled:
            self.unhook_drop()

        features = self._extra_features
        if features & GraphicFeature.WheelEvent:
            self.unhook_wheel()
        if features & GraphicFeature.DrawEvent:
            self.unhook_draw()

Response: Teardowns the advanced widget feature handlers.


Instruction:
Can you implement a function in Python 3 that
handles a custom tab focus request. This method is called when focus is being set on the proxy as a result of a user-implemented focus traversal handler. This can be reimplemented by subclasses as needed. Parameters ---------- reason : Qt.FocusReason The reason value for the focus request. Returns ------- result : bool True if focus was set, False otherwise.

Response:
def tab_focus_request(self, reason):
        """ Handle a custom tab focus request.

        This method is called when focus is being set on the proxy
        as a result of a user-implemented focus traversal handler.
        This can be reimplemented by subclasses as needed.

        Parameters
        ----------
        reason : Qt.FocusReason
            The reason value for the focus request.

        Returns
        -------
        result : bool
            True if focus was set, False otherwise.

        """
        widget = self.focus_target()
        if not widget.focusPolicy & Qt.TabFocus:
            return False
        if not widget.isEnabled():
            return False
        if not widget.isVisibleTo(widget.window()):
            return False
        widget.setFocus(reason)
        return False


Instruction:
Write a Python 3 script to
install the hooks for focus events.

Response:
def hook_focus_events(self):
        """ Install the hooks for focus events.

        This method may be overridden by subclasses as needed.

        """
        widget = self.widget
        widget.focusInEvent = self.focusInEvent
        widget.focusOutEvent = self.focusOutEvent


Instruction:
Write a Python 3 function that can
install the hooks for drag operations.

Response:
def hook_drag(self):
        """ Install the hooks for drag operations.

        """
        widget = self.widget
        widget.mousePressEvent = self.mousePressEvent
        widget.mouseMoveEvent = self.mouseMoveEvent
        widget.mouseReleaseEvent = self.mouseReleaseEvent


Instruction:
Given the following Python 3 function, write the documentation
def unhook_drag(self):
        widget = self.widget
        del widget.mousePressEvent
        del widget.mouseMoveEvent
        del widget.mouseReleaseEvent

Response: Remove the hooks for drag operations.


Instruction:
How would you explain what the following Python 3 function does
def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._drag_origin = event.pos()
        widget = self.widget
        type(widget).mousePressEvent(widget, event)

Response: Handle the mouse press event for a drag operation.


Instruction:
Can you implement a function in Python 3 that
handles the mouse move event for a drag operation.

Response:
def mouseMoveEvent(self, event):
        """ Handle the mouse move event for a drag operation.

        """
        #if event.buttons() & Qt.LeftButton and self._drag_origin is not None:
            #dist = (event.pos() - self._drag_origin).manhattanLength()
            #if dist >= QApplication.startDragDistance():
                #self.do_drag(event.widget())
                #self._drag_origin = None
                #return # Don't returns
        widget = self.widget
        type(widget).mouseMoveEvent(widget, event)


Instruction:
Create a Python 3 function for
handling the mouse release event for the drag operation.

Response:
def mouseReleaseEvent(self, event):
        """ Handle the mouse release event for the drag operation.

        """
        if event.button() == Qt.LeftButton:
            self._drag_origin = None
        widget = self.widget
        type(widget).mouseReleaseEvent(widget, event)


Instruction:
Write a Python 3 script to
install hooks for drop operations.

Response:
def hook_drop(self):
        """ Install hooks for drop operations.

        """
        widget = self.widget
        widget.setAcceptDrops(True)
        widget.dragEnterEvent = self.dragEnterEvent
        widget.dragMoveEvent = self.dragMoveEvent
        widget.dragLeaveEvent = self.dragLeaveEvent
        widget.dropEvent = self.dropEvent


Instruction:
How would you explain what the following Python 3 function does
def unhook_drop(self):
        widget = self.widget
        widget.setAcceptDrops(False)
        del widget.dragEnterEvent
        del widget.dragMoveEvent
        del widget.dragLeaveEvent
        del widget.dropEvent

Response: Remove hooks for drop operations.


Instruction:
Create a Python 3 function for
performing the drag operation for the current window.

Response:
def do_drag(self, widget):
        """ Perform the drag operation for the widget.

        Parameters
        ----------
        widget: QWidget
            A reference to the viewport widget.

        """
        drag_data = self.declaration.drag_start()
        if drag_data is None:
            return
        #widget = self.widget
        qdrag = QDrag(widget)
        qdrag.setMimeData(drag_data.mime_data.q_data())
        if drag_data.image is not None:
            qimg = get_cached_qimage(drag_data.image)
            qdrag.setPixmap(QPixmap.fromImage(qimg))
        #else:
            #if __version_info__ < (5, ):
                #qdrag.setPixmap(QPixmap.grabWidget(self.widget))
            #else:
                #qdrag.setPixmap(widget.grab())
        if drag_data.hotspot:
            qdrag.setHotSpot(QPoint(*drag_data.hotspot))
        else:
            cursor_position = widget.mapFromGlobal(QCursor.pos())
            qdrag.setHotSpot(cursor_position)
        default = Qt.DropAction(drag_data.default_drop_action)
        supported = Qt.DropActions(drag_data.supported_actions)
        qresult = qdrag.exec_(supported, default)
        self.declaration.drag_end(drag_data, DropAction(int(qresult)))


Instruction:
Can you generate the documentation for the following Python 3 function
def draw(self, painter, options, widget):
        self.declaration.draw(painter, options, widget)

Response:
Handle the draw event for the
        widget.


Instruction:
Implement a function in Python 3 to
get the shared widget action for this widget.

Response:
def get_action(self, create=False):
        """ Get the shared widget action for this widget.

        This API is used to support widgets in tool bars and menus.

        Parameters
        ----------
        create : bool, optional
            Whether to create the action if it doesn't already exist.
            The default is False.

        Returns
        -------
        result : QWidgetAction or None
            The cached widget action or None, depending on arguments.

        """
        action = self._widget_action
        if action is None and create:
            action = self._widget_action = QWidgetAction(None)
            action.setDefaultWidget(self.widget)
        return action


Instruction:
Explain what the following Python 3 code does
def mousePressEvent(self, event):
        self.declaration.mouse_press_event(event)
        super(QtGraphicsView, self).mousePressEvent(event)

Response: Handle mouse press events for a drag operation.


Instruction:
Given the following Python 3 function, write the documentation
def mouseMoveEvent(self, event):
        self.declaration.mouse_move_event(event)
        super(QtGraphicsView, self).mouseMoveEvent(event)

Response: Handle the mouse move event for a drag operation.


Instruction:
Can you generate the documentation for the following Python 3 function
def mouseReleaseEvent(self, event):
        self.declaration.mouse_release_event(event)
        super(QtGraphicsView, self).mouseReleaseEvent(event)

Response: Handle the mouse release event for the drag operation.


Instruction:
Write a Python 3 function for
setting the viewport widget.

Response:
def set_renderer(self, renderer):
        """ Set the viewport widget.

        """
        viewport = None
        if renderer == 'opengl':
            from enaml.qt.QtWidgets import QOpenGLWidget
            viewport = QOpenGLWidget()
        elif renderer == 'default':
            try:
                from enaml.qt.QtWidgets import QOpenGLWidget
                viewport = QOpenGLWidget()
            except ImportError as e:
                warnings.warn(
                    "QOpenGLWidget could not be imported: {}".format(e))
        self.widget.setViewport(viewport)


Instruction:
Can you tell what is the following Python 3 function doing
def on_selection_changed(self):
        d = self.declaration
        selection = self.scene.selectedItems()
        self._guards |= 0x01
        try:
            d.selected_items = [item.ref().declaration for item in selection
                                if item.ref()]
        finally:
            self._guards &= ~0x01

Response: Callback invoked one the selection has changed.


Instruction:
Given the following Python 3 function, write the documentation
def set_background(self, background):
        scene = self.scene
        scene.setBackgroundBrush(QColor.fromRgba(background.argb))

Response: Set the background color of the current object.


Instruction:
Can you implement a function in Python 3 that
scales the zoom but keep in the min and max zoom bounds.

Response:
def scale_view(self, x, y):
        """ Scale the zoom but keep in in the min and max zoom bounds.

        """
        d = self.declaration
        factor = self.widget.transform().scale(x, y).mapRect(
            QRectF(0, 0, 1, 1)).width()
        if (d.min_zoom > factor > d.max_zoom):
            return
        self.widget.scale(x, y)
        return factor


Instruction:
How would you explain what the following Python 3 function does
def destroy(self):
        self._teardown_features()
        focus_registry.unregister(self.widget)
        widget = self.widget
        if widget is not None:
            del self.widget
        super(QtGraphicsItem, self).destroy()
        # If a QWidgetAction was created for this widget, then it has
        # taken ownership of the widget and the widget will be deleted
        # when the QWidgetAction is garbage collected. This means the
        # superclass destroy() method must run before the reference to
        # the QWidgetAction is dropped.
        del self._widget_action

Response: Destroys the underlying QWidget object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def parent_widget(self):
        parent = self.parent()
        if parent is not None and isinstance(parent, QtGraphicsItem):
            return parent.widget

Response: Reimplemented to only return GraphicsItems


Instruction:
How would you explain what the following Python 3 function does
def init_layout(self):
        self.widget = QGraphicsProxyWidget(self.parent_widget())
        widget = self.widget
        for item in self.child_widgets():
            widget.setWidget(item)
            break
        super(QtGraphicsWidget, self).init_widget()
        super(QtGraphicsWidget, self).init_layout()

Response: Create the widget in the layout pass after the child widget has been created and intialized.


Instruction:
Can you tell what is the following Python 3 function doing
def _dequeue_update(self,change):
        self._update_count -=1
        if self._update_count !=0:
            return
        self.update_shape(change)

Response: Dequeue an update for the specified duplicate.


Instruction:
How would you implement a function in Python 3 that
creates the toolkit shape for the object.

Response:
def create_shape(self):
        """ Create the toolkit shape for the proxy object.

        This method is called during the top-down pass, just before the
        'init_shape()' method is called. This method should create the
        toolkit widget and assign it to the 'widget' attribute.

        """
        d = self.declaration
        if d.shape1 and d.shape2:
            self.shape = self._do_operation(d.shape1, d.shape2)
        else:
            self.shape = None


Instruction:
Can you create a Python 3 function that
ensures the widget is shown.

Response:
def show(self):
        """ Ensure the widget is shown.
        Calling this method will also set the widget visibility to True.
        """
        self.visible = True
        if self.proxy_is_active:
            self.proxy.ensure_visible()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def hide(self):
        self.visible = False
        if self.proxy_is_active:
            self.proxy.ensure_hidden()

Response: Ensure the widget is hidden.


Instruction:
How would you code a function in Python 3 to
return the items at the given position

Response:
def get_item_at(self, *args, **kwargs):
        """ Return the items at the given position """
        return self.proxy.get_item_at(coerce_point(*args, **kwargs))


Instruction:
Can you write a function in Python 3 where it
centers on the given item or point.

Response:
def center_on(self, item):
        """ Center on the given item or point. """
        if not isinstance(item, GraphicsItem):
            item = coerce_point(item)
        self.proxy.center_on(item)


Instruction:
Explain what the following Python 3 code does
def _custom_token_stream(self):
    token_stream = default_make_token_stream(self)
    for processor in _token_stream_processors:
        token_stream = processor(token_stream)
    return token_stream

Response: A wrapper for the BaseEnamlLexer s make_token_stream which allows the token stream to be customized by adding the token_stream_processors list to the token_stream.


Instruction:
Can you generate the documentation for the following Python 3 function
def convert_enamldef_def_to_func(token_stream):
    in_enamldef = False
    depth = 0
    for tok in token_stream:
        if tok.type == 'ENAMLDEF':
            in_enamldef = True
        elif tok.type == 'INDENT':
            depth += 1
        elif in_enamldef and tok.type == 'DEF':
            # Since functions are not allowed on the RHS we can
            # transform the token type to a NAME so it's picked up by the
            # parser as a decl_funcdef instead of funcdef
            tok.type = 'NAME'
            tok.value = 'func'
        elif tok.type == 'DEDENT':
            depth -= 1
            if depth == 0:
                in_enamldef = False
        yield tok

Response:
A token stream processor which processes all enaml declarative functions
    to allow using def instead of func.


Instruction:
How would you explain what the following Python 3 function does
def child_added(self, child):
        super(AbstractItemView, self).child_added(child)
        self.get_member('_items').reset(self)

Response: Reset the item cache when a child is added


Instruction:
Implement a Python 3 function for
resetting the item cache when a child is removed

Response:
def child_removed(self, child):
        """ Reset the item cache when a child is removed """
        super(AbstractItemView, self).child_removed(child)
        self.get_member('_items').reset(self)


Instruction:
Given the following Python 3 function, write the documentation
def child_added(self, child):
        super(AbstractWidgetItemGroup, self).child_added(child)
        self.get_member('_items').reset(self)

Response: Reset the item cache when a child is added


Instruction:
Explain what the following Python 3 code does
def child_removed(self, child):
        super(AbstractWidgetItemGroup, self).child_removed(child)
        self.get_member('_items').reset(self)

Response: Reset the item cache when a child is removed


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _update_proxy(self, change):
        if change['name'] in ['row', 'column']:
            super(AbstractWidgetItem, self)._update_proxy(change)
        else:
            self.proxy.data_changed(change)

Response: An observer which sends state change to the proxy.


Instruction:
Explain what the following Python 3 code does
def init_signal(self):
        signal.signal(signal.SIGINT, lambda sig, frame: self.exit(-2))
        # need a timer, so that QApplication doesn't block until a real
        # Qt event fires (can require mouse movement)
        # timer trick from http://stackoverflow.com/q/4938723/938949
        timer = QtCore.QTimer()
        # Let the interpreter run each 200 ms:
        timer.timeout.connect(lambda: None)
        timer.start(200)
        # hold onto ref, so the timer doesn't get cleaned up
        self._sigint_timer = timer

Response: allow clean shutdown on sigint


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _update_position(self, change):
        if change['type']!='update':
            return
        pt = gp_Pnt(self.x,self.y,self.z)
        if not pt.IsEqual(self.position,self.tolerance):
            self.position = pt

Response: Update the position of the object based on the current values of the attributes.


Instruction:
Given the following Python 3 function, write the documentation
def _update_xyz(self, change):
        self.x,self.y,self.z = self.position.X(),self.position.Y(),self.position.Z()

Response: Update x y z values based on the current position


Instruction:
Can you generate the documentation for the following Python 3 function
def _update_state(self, change):
        self._block_updates = True
        try:
            self.position = self.axis.Location()
            self.direction = self.axis.Direction()
        finally:
            self._block_updates = False

Response: Update position and direction of the current object with the new values.


Instruction:
Can you implement a function in Python 3 that
refreshes the multi - axis of the plot.

Response:
def _refresh_multi_axis(self):
        """ If linked axis' are used, setup and link them """
        d = self.declaration

        #: Create a separate viewbox
        self.viewbox = pg.ViewBox()

        #: If this is the first nested plot, use the parent right axis
        _plots = [c for c in self.parent().children() if isinstance(c,AbstractQtPlotItem)]
        i = _plots.index(self)
        if i==0:
            self.axis = self.widget.getAxis('right')
            self.widget.showAxis('right')
        else:
            self.axis = pg.AxisItem('right')
            self.axis.setZValue(-10000)

            #: Add new axis to scene
            self.widget.layout.addItem(self.axis,2,i+2)

        #: Link x axis to the parent axis
        self.viewbox.setXLink(self.widget.vb)

        #: Link y axis to the view
        self.axis.linkToView(self.viewbox)

        #: Set axis label
        self.axis.setLabel(d.label_right)

        #: Add Viewbox to parent scene
        self.parent().parent_widget().scene().addItem(self.viewbox)