Instruction:
Given the following Python 3 function, write the documentation
def set_torrent_download_limit(self, infohash_list, limit):
        data = self._process_infohash_list(infohash_list)
        data.update({'limit': limit})
        return self._post('command/setTorrentsDlLimit', data=data)

Response: Set download speed limit of the supplied torrents.


Instruction:
Here you have a function in Python 3, explain what it does
def get_torrent_upload_limit(self, infohash_list):
        data = self._process_infohash_list(infohash_list)
        return self._post('command/getTorrentsUpLimit', data=data)

Response: Get upoload speed limit of the supplied torrents.


Instruction:
Write a Python 3 script to
set upload speed limit of the supplied torrents.

Response:
def set_torrent_upload_limit(self, infohash_list, limit):
        """
        Set upload speed limit of the supplied torrents.

        :param infohash_list: Single or list() of infohashes.
        :param limit: Speed limit in bytes.
        """
        data = self._process_infohash_list(infohash_list)
        data.update({'limit': limit})
        return self._post('command/setTorrentsUpLimit', data=data)


Instruction:
Can you generate the documentation for the following Python 3 function
def set_preferences(self, **kwargs):
        json_data = "json={}".format(json.dumps(kwargs))
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        return self._post('command/setPreferences', data=json_data,
                          headers=headers)

Response: Set all possible preferences of qBittorrent.


Instruction:
Implement a Python 3 function for
toggling sequential download in supplied torrents.

Response:
def toggle_sequential_download(self, infohash_list):
        """
        Toggle sequential download in supplied torrents.

        :param infohash_list: Single or list() of infohashes.
        """
        data = self._process_infohash_list(infohash_list)
        return self._post('command/toggleSequentialDownload', data=data)


Instruction:
Here you have a function in Python 3, explain what it does
def toggle_first_last_piece_priority(self, infohash_list):
        data = self._process_infohash_list(infohash_list)
        return self._post('command/toggleFirstLastPiecePrio', data=data)

Response: Toggle first or last piece priority of supplied torrents.


Instruction:
How would you code a function in Python 3 to
force start selected torrents.

Response:
def force_start(self, infohash_list, value=True):
        """
        Force start selected torrents.

        :param infohash_list: Single or list() of infohashes.
        :param value: Force start value (bool)
        """
        data = self._process_infohash_list(infohash_list)
        data.update({'value': json.dumps(value)})
        return self._post('command/setForceStart', data=data)


Instruction:
Can you generate the documentation for the following Python 3 function
def vue_find_resource(name, use_minified=None):
    target = list(filter(lambda x: x['name'] == name, current_app.config['VUE_CONFIGURATION']))
    if not target:
        raise ValueError('Can not find resource from configuration.')
    target = target[0]
    use_minified = (isinstance(use_minified, bool) and use_minified) or current_app.config['VUE_USE_MINIFIED']
    CdnClass = LocalCDN if target['use_local'] else getattr(cdn, target['cdn'], CDN)
    resource_url = CdnClass(name=name, version=target.get('version', ''),
                            use_minified=use_minified).get_resource_url()
    if resource_url.startswith('//') and current_app.config['VUE_CDN_FORCE_SSL']:
        resource_url = 'https:%s' % resource_url
    return resource_url

Response: Resource finding function also available in templates.


Instruction:
Can you create a Python 3 function that
converts a time in seconds to a reasonable human readable time.

Response:
def humantime(time):
    """Converts a time in seconds to a reasonable human readable time

    Parameters
    ----------
    t : float
        The number of seconds

    Returns
    -------
    time : string
        The human readable formatted value of the given time
    """
    try:
        time = float(time)
    except (ValueError, TypeError):
        raise ValueError("Input must be numeric")

    # weeks
    if time >= 7 * 60 * 60 * 24:
        weeks = math.floor(time / (7 * 60 * 60 * 24))
        timestr = "{:g} weeks, ".format(weeks) + humantime(time % (7 * 60 * 60 * 24))

    # days
    elif time >= 60 * 60 * 24:
        days = math.floor(time / (60 * 60 * 24))
        timestr = "{:g} days, ".format(days) + humantime(time % (60 * 60 * 24))

    # hours
    elif time >= 60 * 60:
        hours = math.floor(time / (60 * 60))
        timestr = "{:g} hours, ".format(hours) + humantime(time % (60 * 60))

    # minutes
    elif time >= 60:
        minutes = math.floor(time / 60.)
        timestr = "{:g} min., ".format(minutes) + humantime(time % 60)

    # seconds
    elif (time >= 1) | (time == 0):
        timestr = "{:g} s".format(time)

    # milliseconds
    elif time >= 1e-3:
        timestr = "{:g} ms".format(time * 1e3)

    # microseconds
    elif time >= 1e-6:
        timestr = "{:g} \u03BCs".format(time * 1e6)

    # nanoseconds or smaller
    else:
        timestr = "{:g} ns".format(time * 1e9)

    return timestr


Instruction:
Can you tell what is the following Python 3 function doing
def ansi_len(string):
    return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string))

Response: Extra length due to any ANSI sequences in the string.


Instruction:
Write a Python 3 function that can
format a list of elements using the given line style

Response:
def format_line(data, linestyle):
    """Formats a list of elements using the given line style"""
    return linestyle.begin + linestyle.sep.join(data) + linestyle.end


Instruction:
Make a summary of the following Python 3 code
def parse_width(width, n):
    if isinstance(width, int):
        widths = [width] * n

    else:
        assert len(width) == n, "Widths and data do not match"
        widths = width

    return widths

Response: Parses an int or array of widths returning a list of widths


Instruction:
Can you implement a function in Python 3 that
prints a table with the given data

Response:
def table(data, headers=None, format_spec=FMT, width=WIDTH, align=ALIGN, style=STYLE, out=sys.stdout):
    """Print a table with the given data

    Parameters
    ----------
    data : array_like
        An (m x n) array containing the data to print (m rows of n columns)

    headers : list, optional
        A list of n strings consisting of the header of each of the n columns (Default: None)

    format_spec : string, optional
        Format specification for formatting numbers (Default: '5g')

    width : int or array_like, optional
        The width of each column in the table (Default: 11)

    align : string
        The alignment to use ('left', 'center', or 'right'). (Default: 'right')

    style : string or tuple, optional
        A formatting style. (Default: 'fancy_grid')

    out : writer, optional
        A file handle or object that has write() and flush() methods (Default: sys.stdout)
    """
    # Number of columns in the table.
    ncols = len(data[0]) if headers is None else len(headers)
    tablestyle = STYLES[style]
    widths = parse_width(width, ncols)

    # Initialize with a hr or the header
    tablestr = [hrule(ncols, widths, tablestyle.top)] \
        if headers is None else [header(headers, width=widths, align=align, style=style)]

    # parse each row
    tablestr += [row(d, widths, format_spec, align, style) for d in data]

    # only add the final border if there was data in the table
    if len(data) > 0:
        tablestr += [hrule(ncols, widths, tablestyle.bottom)]

    # print the table
    out.write('\n'.join(tablestr) + '\n')
    out.flush()


Instruction:
Given the following Python 3 function, write the documentation
def header(headers, width=WIDTH, align=ALIGN, style=STYLE, add_hr=True):
    tablestyle = STYLES[style]
    widths = parse_width(width, len(headers))
    alignment = ALIGNMENTS[align]

    # string formatter
    data = map(lambda x: ('{:%s%d}' % (alignment, x[0] + ansi_len(x[1]))).format(x[1]), zip(widths, headers))

    # build the formatted str
    headerstr = format_line(data, tablestyle.row)

    if add_hr:
        upper = hrule(len(headers), widths, tablestyle.top)
        lower = hrule(len(headers), widths, tablestyle.below_header)
        headerstr = '\n'.join([upper, headerstr, lower])

    return headerstr

Response: Returns a formatted row of column header strings


Instruction:
Can you generate a brief explanation for the following Python 3 code
def row(values, width=WIDTH, format_spec=FMT, align=ALIGN, style=STYLE):
    tablestyle = STYLES[style]
    widths = parse_width(width, len(values))

    assert isinstance(format_spec, string_types) | isinstance(format_spec, list), \
        "format_spec must be a string or list of strings"

    if isinstance(format_spec, string_types):
        format_spec = [format_spec] * len(list(values))

    # mapping function for string formatting
    def mapdata(val):

        # unpack
        width, datum, prec = val

        if isinstance(datum, string_types):
            return ('{:%s%i}' % (ALIGNMENTS[align], width + ansi_len(datum))).format(datum)

        elif isinstance(datum, Number):
            return ('{:%s%i.%s}' % (ALIGNMENTS[align], width, prec)).format(datum)

        else:
            raise ValueError('Elements in the values array must be strings, ints, or floats')

    # string formatter
    data = map(mapdata, zip(widths, values, format_spec))

    # build the row string
    return format_line(data, tablestyle.row)

Response: Returns a formatted row of data in a new column of the log file.


Instruction:
Here you have a function in Python 3, explain what it does
def hrule(n=1, width=WIDTH, linestyle=LineStyle('', '─', '─', '')):
    widths = parse_width(width, n)
    hrstr = linestyle.sep.join([('{:%s^%i}' % (linestyle.hline, width)).format('')
                                for width in widths])
    return linestyle.begin + hrstr + linestyle.end

Response: Returns a formatted string used as a border between table rows.


Instruction:
Explain what the following Python 3 code does
def top(n, width=WIDTH, style=STYLE):
    return hrule(n, width, linestyle=STYLES[style].top)

Response: Prints the top row of a table


Instruction:
Can you generate the documentation for the following Python 3 function
def banner(message, width=30, style='banner', out=sys.stdout):
    out.write(header([message], width=max(width, len(message)), style=style) + '\n')
    out.flush()

Response: Prints a banner message in the alphabetical order


Instruction:
Create a Python 3 function for
printing a table with data from the given pandas DataFrame

Response:
def dataframe(df, **kwargs):
    """Print table with data from the given pandas DataFrame

    Parameters
    ----------
    df : DataFrame
        A pandas DataFrame with the table to print
    """
    table(df.values, list(df.columns), **kwargs)


Instruction:
Create a Python 3 function to
set the address of the resource.

Response:
def set_address(self, address):
        """
        Set the address.
        :param address:
        """
        self._query_params += str(QueryParam.ADVANCED) + str(QueryParam.ADDRESS) + address.replace(" ", "+").lower()


Instruction:
Write a Python 3 function that can
set the minimum lease period in months.

Response:
def set_min_lease(self, min_lease):
        """
        Set the minimum lease period in months.
        :param min_lease: int
        """
        self._query_params += str(QueryParam.MIN_LEASE) + str(min_lease)


Instruction:
Given the following Python 3 function, write the documentation
def set_added_since(self, added):
        self._query_params += str(QueryParam.DAYS_OLD) + str(added)

Response: Sets the added since parameter for the resource.


Instruction:
Write a Python 3 script for
setting the maximum lease period in months.

Response:
def set_max_lease(self, max_lease):
        """
        Set the maximum lease period in months.
        :param max_lease: int
        """
        self._query_params += str(QueryParam.MAX_LEASE) + str(max_lease)


Instruction:
Create a Python 3 function to
set the availability of the resource.

Response:
def set_availability(self, availability):
        """
        Set the maximum lease period in months.
        :param availability:
        """
        if availability >= 5:
            availability = '5%2B'
        self._query_params += str(QueryParam.AVALIABILITY) + str(availability)


Instruction:
Can you implement a function in Python 3 that
sets the room type.

Response:
def set_room_type(self, room_type):
        """
        Set the room type.
        :param room_type:
        """
        if not isinstance(room_type, RoomType):
            raise DaftException("room_type should be an instance of RoomType.")
        self._query_params += str(QueryParam.ROOM_TYPE) + str(room_type)


Instruction:
Explain what the following Python 3 code does
def set_keywords(self, keywords):
        self._query_params += str(QueryParam.KEYWORDS) + '+'.join(keywords)

Response: Sets the keywords for the query


Instruction:
Can you write a function in Python 3 where it
sets the area to retrieve listings from. Use an array to search multiple areas.

Response:
def set_area(self, area):
        """
        The area to retrieve listings from. Use an array to search multiple areas.
        :param area:
        :return:
        """
        self._area = area.replace(" ", "-").lower() if isinstance(area, str) else ','.join(
            map(lambda x: x.lower().replace(' ', '-'), area))


Instruction:
Can you write a function in Python 3 where it
sets the _open_viewing property to True to only search for properties that have upcoming open for viewing dates.

Response:
def set_open_viewing(self, open_viewing):
        """
        Set to True to only search for properties that have upcoming 'open for viewing' dates.
        :param open_viewing:
        :return:
        """
        if open_viewing:
            self._open_viewing = open_viewing
            self._query_params += str(QueryParam.OPEN_VIEWING)


Instruction:
Can you implement a function in Python 3 that
sets the offset of the record set.

Response:
def set_offset(self, offset):
        """
        The page number which is in increments of 10. The default page number is 0.
        :param offset:
        :return:
        """

        if not isinstance(offset, int) or offset < 0:
            raise DaftException("Offset should be a positive integer.")

        self._offset = str(offset)


Instruction:
Can you implement a function in Python 3 that
sets the minimum price of the resource.

Response:
def set_min_price(self, min_price):
        """
        The minimum price.
        :param min_price:
        :return:
        """

        if not isinstance(min_price, int):
            raise DaftException("Min price should be an integer.")

        self._min_price = str(min_price)
        self._price += str(QueryParam.MIN_PRICE) + self._min_price


Instruction:
Can you generate the documentation for the following Python 3 function
def set_max_price(self, max_price):

        if not isinstance(max_price, int):
            raise DaftException("Max price should be an integer.")

        self._max_price = str(max_price)
        self._price += str(QueryParam.MAX_PRICE) + self._max_price

Response: Sets the max price of the resource.


Instruction:
Can you tell what is the following Python 3 function doing
def set_listing_type(self, listing_type):

        if not isinstance(listing_type, SaleType) and not isinstance(listing_type, RentType):
            raise DaftException("listing_type should be an instance of SaleType or RentType.")

        self._listing_type = listing_type

Response: Sets the listing type of the resource.


Instruction:
Can you create a Python 3 function that
sets the minimum number of beds for the resource.

Response:
def set_min_beds(self, min_beds):
        """
        The minimum number of beds.
        :param min_beds:
        :return:
        """

        if not isinstance(min_beds, int):
            raise DaftException("Minimum number of beds should be an integer.")

        self._min_beds = str(min_beds)
        self._query_params += str(QueryParam.MIN_BEDS) + self._min_beds


Instruction:
Write a Python 3 script to
set the maximum number of beds for a resource.

Response:
def set_max_beds(self, max_beds):
        """
        The maximum number of beds.
        :param max_beds:
        :return:
        """
        if not isinstance(max_beds, int):
            raise DaftException("Maximum number of beds should be an integer.")

        self._max_beds = str(max_beds)
        self._query_params += str(QueryParam.MAX_BEDS) + self._max_beds


Instruction:
Explain what the following Python 3 code does
def set_sort_by(self, sort_by):
        if not isinstance(sort_by, SortType):
            raise DaftException("sort_by should be an instance of SortType.")

        self._sort_by = str(sort_by)

Response: Set the sort_by property of the object.


Instruction:
Can you implement a function in Python 3 that
sets the sort order of the listings.

Response:
def set_sort_order(self, sort_order):
        """
        Use the SortOrder object to sort the listings descending or ascending.
        :param sort_order:
        :return:
        """

        if not isinstance(sort_order, SortOrder):
            raise DaftException("sort_order should be an instance of SortOrder.")

        self._sort_order = str(sort_order)


Instruction:
Can you implement a function in Python 3 that
sets the commercial property type.

Response:
def set_commercial_property_type(self, commercial_property_type):
        """
        Use the CommercialType object to set the commercial property type.
        :param commercial_property_type:
        :return:
        """

        if not isinstance(commercial_property_type, CommercialType):
            raise DaftException("commercial_property_type should be an instance of CommercialType.")

        self._commercial_property_type = str(commercial_property_type)


Instruction:
Create a Python 3 function for
setting the commercial minimum size in sq ft.

Response:
def set_commercial_min_size(self, commercial_min_size):
        """
        The minimum size in sq ft.
        :param commercial_min_size:
        :return:
        """
        if not isinstance(commercial_min_size, int):
            raise DaftException("commercial_min_size should be an integer.")

        self._commercial_min_size = str(commercial_min_size)
        self._query_params += str(QueryParam.COMMERCIAL_MIN) + self._commercial_min_size


Instruction:
Implement a function in Python 3 to
set the commercial max size in sq ft.

Response:
def set_commercial_max_size(self, commercial_max_size):
        """
        The maximum size in sq ft.
        :param commercial_max_size:
        :return:
        """
        if not isinstance(commercial_max_size, int):
            raise DaftException("commercial_max_size should be an integer.")

        self._commercial_max_size = str(commercial_max_size)
        self._query_params += str(QueryParam.COMMERCIAL_MAX) + self._commercial_max_size


Instruction:
Implement a function in Python 3 to
set the student accomodation type.

Response:
def set_student_accommodation_type(self, student_accommodation_type):
        """
        Set the student accomodation type.
        :param student_accommodation_type: StudentAccomodationType
        """
        if not isinstance(student_accommodation_type, StudentAccommodationType):
            raise DaftException("student_accommodation_type should be an instance of StudentAccommodationType.")

        self._student_accommodation_type = str(student_accommodation_type)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_num_occupants(self, num_occupants):
        self._query_params += str(QueryParam.NUM_OCCUPANTS) + str(num_occupants)

Response: Sets the number of occupants living in the property for rent.


Instruction:
Make a summary of the following Python 3 code
def set_public_transport_route(self, public_transport_route):
        self._query_params += str(QueryParam.ROUTE_ID) + str(public_transport_route)

Response: Sets the public transport route for the current node.


Instruction:
Create a Python 3 function for
setting the property type for rents.

Response:
def set_property_type(self, property_types):
        """
        Set the property type for rents.
        :param property_types: Array of Enum PropertyType
        """
        query_add = ''
        for property_type in property_types:
            if not isinstance(property_type, PropertyType):
                raise DaftException("property_types should be an instance of PropertyType.")
            query_add += str(property_type)

        self._query_params += query_add


Instruction:
How would you explain what the following Python 3 function does
def search(self):
        self.set_url()
        listings = []
        request = Request(debug=self._debug)
        url = self.get_url()
        soup = request.get(url)
        divs = soup.find_all("div", {"class": "box"})
        [listings.append(Listing(div, debug=self._debug)) for div in divs]
        return listings

Response: The search function returns an array of Listing objects.


Instruction:
Here you have a function in Python 3, explain what it does
def price_change(self):
        try:
            if self._data_from_search:
                return self._data_from_search.find('div', {'class': 'price-changes-sr'}).text
            else:
                return self._ad_page_content.find('div', {'class': 'price-changes-sr'}).text
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting price_change. Error message: " + e.args[0])
            return

Response: This method returns any price change.


Instruction:
Can you implement a function in Python 3 that
returns an array of upcoming viewings for a property.

Response:
def upcoming_viewings(self):
        """
        Returns an array of upcoming viewings for a property.
        :return:
        """
        upcoming_viewings = []
        try:
            if self._data_from_search:
                viewings = self._data_from_search.find_all(
                    'div', {'class': 'smi-onview-text'})
            else:
                viewings = []
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting upcoming_viewings. Error message: " + e.args[0])
            return
        for viewing in viewings:
            upcoming_viewings.append(viewing.text.strip())
        return upcoming_viewings


Instruction:
Explain what the following Python 3 code does
def facilities(self):
        facilities = []
        try:
            list_items = self._ad_page_content.select("#facilities li")
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting facilities. Error message: " + e.args[0])
            return

        for li in list_items:
            facilities.append(li.text)
        return facilities

Response: This method returns the properties facilities.


Instruction:
Make a summary of the following Python 3 code
def overviews(self):
        overviews = []
        try:
            list_items = self._ad_page_content.select("#overview li")
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting overviews. Error message: " + e.args[0])
            return

        for li in list_items:
            overviews.append(li.text)
        return overviews

Response: This method returns the properties overviews.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def features(self):
        features = []
        try:
            list_items = self._ad_page_content.select("#features li")
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting features. Error message: " + e.args[0])
            return

        for li in list_items:
            features.append(li.text)
        return features

Response: This method returns the properties features.


Instruction:
Here you have a function in Python 3, explain what it does
def images(self):
        try:
            uls = self._ad_page_content.find(
                "ul", {"class": "smi-gallery-list"})
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting images. Error message: " + e.args[0])
            return
        images = []
        if uls is None:
            return
        for li in uls.find_all('li'):
            if li.find('img')['src']:
                images.append(li.find('img')['src'])

        return images

Response: This method returns the listing image.


Instruction:
Given the following Python 3 function, write the documentation
def agent_url(self):
        try:
            if self._data_from_search:
                agent = self._data_from_search.find('ul', {'class': 'links'})
                links = agent.find_all('a')
                return links[1]['href']
            else:
                return self._ad_page_content.find('a', {'id': 'smi-link-branded'})['href']
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting agent_url. Error message: " + e.args[0])
            return

Response: This method returns the agent s url.


Instruction:
Given the following Python 3 function, write the documentation
def contact_number(self):
        try:
            number = self._ad_page_content.find(
                'button', {'class': 'phone-number'})
            return (base64.b64decode(number.attrs['data-p'])).decode('ascii')
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting contact_number. Error message: " + e.args[0])
            return 'N/A'

Response: This method returns the contact phone number.


Instruction:
Make a summary of the following Python 3 code
def daft_link(self):
        try:
            if self._data_from_search:
                link = self._data_from_search.find('a', href=True)
                return 'http://www.daft.ie' + link['href']
            else:
                return self._ad_page_content.find('link', {'rel': 'canonical'})['href']
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting daft_link. Error message: " + e.args[0])
            return

Response: This method returns the url of the daft. ie.


Instruction:
How would you explain what the following Python 3 function does
def shortcode(self):
        try:
            div = self._ad_page_content.find(
                'div', {'class': 'description_extras'})
            index = [i for i, s in enumerate(
                div.contents) if 'Shortcode' in str(s)][0] + 1
            return div.contents[index]['href']
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting shortcode. Error message: " + e.args[0])
            return 'N/A'

Response: This method returns the shortcode url of the listing.


Instruction:
Here you have a function in Python 3, explain what it does
def views(self):
        try:
            div = self._ad_page_content.find(
                'div', {'class': 'description_extras'})
            index = [i for i, s in enumerate(
                div.contents) if 'Property Views' in str(s)][0] + 1
            return int(''.join(list(filter(str.isdigit, div.contents[index]))))
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting views. Error message: " + e.args[0])
            return 'N/A'

Response: This method returns the Property Views from listing.


Instruction:
Can you tell what is the following Python 3 function doing
def dwelling_type(self):
        try:
            if self._data_from_search:
                info = self._data_from_search.find(
                    'ul', {"class": "info"}).text
                s = info.split('|')
                return s[0].strip()
            else:
                return self._ad_page_content.find(
                    'div', {'id': 'smi-summary-items'}
                ).find('span', {'class': 'header_text'}).text

        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting dwelling_type. Error message: " + e.args[0])
            return

Response: This method returns the dwelling type of the current page.


Instruction:
Make a summary of the following Python 3 code
def transport_routes(self):
        routes = {}
        try:
            big_div = self._ad_page_content.find(
                'div', {"class": "half_area_box_right"})
            uls = big_div.find("ul")
            if uls is None:
                return None
            for li in uls.find_all('li'):
                route_li = li.text.split(':')
                routes[route_li[0]] = [x.strip()
                                       for x in route_li[1].split(',')]
            return routes
        except Exception as e:
            if self._debug:
                logging.error(e.args[0])
            return 'N/A'

Response: This method gets a dict of routes listed in Daft.


Instruction:
Explain what the following Python 3 code does
def longitude(self):
        try:
            scripts = self._ad_page_content.find_all('script')
            for script in scripts:
                if 'longitude' in script.text:
                    find_list = re.findall(
                        r'"longitude":"([\-]?[0-9.]*[0-9]+)"', script.text)
                    if len(find_list) >= 1:
                        return find_list[0]
            return None
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting longitude. Error message: " + e.args[0])
            return None

Response: This method gets a dict of routes listed in Daft.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ber_code(self):
        try:
            alt_text = self._ad_page_content.find(
                'span', {'class': 'ber-hover'}
            ).find('img')['alt']

            if ('exempt' in alt_text):
                return 'exempt'
            else:
                alt_arr = alt_text.split()
                if 'ber' in alt_arr[0].lower():
                    return alt_arr[1].lower()
                else:
                    return None
        except Exception as e:
            if self._debug:
                logging.error(
                    "Error getting the Ber Code. Error message: " + e.args[0])
            return None

Response: This method gets the Ber Code from the Daft.


Instruction:
Can you tell what is the following Python 3 function doing
def as_dict(self):
        return {
            'search_type': self.search_type,
            'agent_id': self.agent_id,
            'id': self.id,
            'price': self.price,
            'price_change': self.price_change,
            'viewings': self.upcoming_viewings,
            'facilities': self.facilities,
            'overviews': self.overviews,
            'formalised_address': self.formalised_address,
            'address_line_1': self.address_line_1,
            'county': self.county,
            'listing_image': self.images,
            'listing_hires_image': self.hires_images,
            'agent': self.agent,
            'agent_url': self.agent_url,
            'contact_number': self.contact_number,
            'daft_link': self.daft_link,
            'shortcode': self.shortcode,
            'date_insert_update': self.date_insert_update,
            'views': self.views,
            'description': self.description,
            'dwelling_type': self.dwelling_type,
            'posted_since': self.posted_since,
            'num_bedrooms': self.bedrooms,
            'num_bathrooms': self.bathrooms,
            'city_center_distance': self.city_center_distance,
            'transport_routes': self.transport_routes,
            'latitude': self.latitude,
            'longitude': self.longitude,
            'ber_code': self.ber_code,
            'commercial_area_size': self.commercial_area_size
        }

Response: Return a Listing object as a dictionary.


Instruction:
Can you implement a function in Python 3 that
fetches the variables and functions

Response:
def on_config(self, config):
        "Fetch the variables and functions"
        #print("Here is the config:", config)

        # fetch variables from YAML file:
        self._variables = config.get(YAML_SUBSET)

        # add variables and functions from the module:
        module_reader.load_variables(self._variables, config)

        print("Variables:", self.variables)


Instruction:
Given the following Python 3 function, write the documentation
def on_page_markdown(self, markdown, page, config,
                          site_navigation=None, **kwargs):
        "Provide a hook for defining functions from an external module"

        # the site_navigation argument has been made optional
        # (deleted in post 1.0 mkdocs, but maintained here
        # for backward compatibility)

        if not self.variables:
            return markdown

        else:

            # Create templae and get the variables
            md_template = Template(markdown)

            # Execute the jinja2 template and return
            return md_template.render(**self.variables)

Response: Provide a hook for defining functions from an external module


Instruction:
Write a Python 3 function that can
load the variables from the yaml file and add them to the internal list of variables.

Response:
def load_variables(variables, config):
    """
    Add the template functions, via the python module
    located in the same directory as the Yaml config file.

    The python module must contain the following hook:

    declare_variables(variables, macro):

        variables['a'] = 5

        @macro
        def bar(x):
            ....

        @macro
        def baz(x):
            ....

    """

    def macro(v, name=''):
        """
        Registers a variable as a macro in the template,
        i.e. in the variables dictionary:

            macro(myfunc)

        Optionally, you can assign a different name:

            macro(myfunc, 'funcname')

        You can also use it as a decorator:

        @macro
        def foo(a):
            return a ** 2

        More info:
        https://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
        """

        name = name or v.__name__
        variables[name] = v
        return v

    # determine the package name, from the filename:
    python_module = config.get('python_module') or DEFAULT_MODULE_NAME
    # get the directory of the yaml file:
    config_file = config['config_file_path']
    yaml_dir = os.path.dirname(config_file)
    # print("Found yaml directory: %s" % yaml_dir)

    # that's the directory of the package:
    repackage.add(yaml_dir)
    try:
        module = importlib.import_module(python_module)
        print("Found module '%s'" % python_module)
        # execute the hook, passing the template decorator function
        module.declare_variables(variables, macro)
    except ModuleNotFoundError:
        print("No module found.")


Instruction:
Write a Python 3 script for
decoding bytes encoded with the standard Base64 alphabet.

Response:
def b64decode(s, altchars=None, validate=False):
    """Decode bytes encoded with the standard Base64 alphabet.

    Argument ``s`` is a :term:`bytes-like object` or ASCII string to
    decode.

    Optional ``altchars`` must be a :term:`bytes-like object` or ASCII
    string of length 2 which specifies the alternative alphabet used instead
    of the '+' and '/' characters.

    If ``validate`` is ``False`` (the default), characters that are neither in
    the normal base-64 alphabet nor the alternative alphabet are discarded
    prior to the padding check.
    If ``validate`` is ``True``, these non-alphabet characters in the input
    result in a :exc:`binascii.Error`.

    The result is returned as a :class:`bytes` object.

    A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded.
    """
    if version_info < (3, 0) or validate:
        if validate and len(s) % 4 != 0:
            raise BinAsciiError('Incorrect padding')
        s = _get_bytes(s)
        if altchars is not None:
            altchars = _get_bytes(altchars)
            assert len(altchars) == 2, repr(altchars)
            if version_info < (3, 0):
                map = maketrans(altchars, b'+/')
            else:
                map = bytes.maketrans(altchars, b'+/')
            s = s.translate(map)
        try:
            result = builtin_decode(s, altchars)
        except TypeError as e:
            raise BinAsciiError(str(e))
        if validate:
            # check length of result vs length of input
            padding = 0
            if len(s) > 1 and s[-2] in (b'=', 61):
                padding = padding + 1
            if len(s) > 0 and s[-1] in (b'=', 61):
                padding = padding + 1
            if 3 * (len(s) / 4) - padding != len(result):
                raise BinAsciiError('Non-base64 digit found')
        return result
    return builtin_decode(s, altchars)


Instruction:
Implement a Python 3 function for
encoding bytes using the standard Base64 alphabet.

Response:
def b64encode(s, altchars=None):
    """Encode bytes using the standard Base64 alphabet.

    Argument ``s`` is a :term:`bytes-like object` to encode.

    Optional ``altchars`` must be a byte string of length 2 which specifies
    an alternative alphabet for the '+' and '/' characters.  This allows an
    application to e.g. generate url or filesystem safe Base64 strings.

    The result is returned as a :class:`bytes` object.
    """
    if altchars is not None:
        altchars = _get_bytes(altchars)
        assert len(altchars) == 2, repr(altchars)
    if version_info < (3, 0):
        if isinstance(s, text_type):
            raise TypeError('a bytes-like object is required, not \''
                            + type(s).__name__ + '\'')
    return builtin_encode(s, altchars)


Instruction:
Implement a Python 3 function for
improving file name by removing words such as HD Official etc.

Response:
def improve_name(song_name):
    """
    Improves file name by removing words such as HD, Official,etc
    eg : Hey Jude (Official HD) lyrics -> Hey Jude
    This helps in better searching of metadata since a spotify search of
    'Hey Jude (Official HD) lyrics' fetches 0 results
    """

    try:
        song_name = os.path.splitext(song_name)[0]
    except IndexError:
        pass

    song_name = song_name.partition('ft')[0]

    # Replace characters to filter with spaces
    song_name = ''.join(
        map(lambda c: " " if c in chars_filter else c, song_name))

    # Remove crap words
    song_name = re.sub('|'.join(re.escape(key) for key in words_filter),
                       "", song_name, flags=re.IGNORECASE)

    # Remove duplicate spaces
    song_name = re.sub(' +', ' ', song_name)

    return song_name.strip()


Instruction:
Can you implement a function in Python 3 that
gathers all urls titles for a search query from youtube

Response:
def get_song_urls(song_input):
    """
    Gather all urls, titles for a search query
    from youtube
    """
    YOUTUBECLASS = 'spf-prefetch'

    html = requests.get("https://www.youtube.com/results",
                        params={'search_query': song_input})
    soup = BeautifulSoup(html.text, 'html.parser')

    soup_section = soup.findAll('a', {'rel': YOUTUBECLASS})

    # Use generator over list, since storage isn't important
    song_urls = ('https://www.youtube.com' + i.get('href')
                 for i in soup_section)
    song_titles = (i.get('title') for i in soup_section)

    youtube_list = list(zip(song_urls, song_titles))

    del song_urls
    del song_titles

    return youtube_list


Instruction:
Write a Python 3 script to
download a song using youtube url and song title

Response:
def download_song(song_url, song_title):
    """
    Download a song using youtube url and song title
    """

    outtmpl = song_title + '.%(ext)s'
    ydl_opts = {
        'format': 'bestaudio/best',
        'outtmpl': outtmpl,
        'postprocessors': [
            {'key': 'FFmpegExtractAudio','preferredcodec': 'mp3',
             'preferredquality': '192',
            },
            {'key': 'FFmpegMetadata'},
        ],
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(song_url, download=True)


Instruction:
Write a Python 3 function that can
try finding metadata through Spotify

Response:
def get_metadata(file_name, client_id, client_secret):
    """
    Tries finding metadata through Spotify
    """

    song_name = improve_name(file_name)  # Remove useless words from title
    client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)

    spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    results = spotify.search(song_name, limit=1)

    results = results['tracks']['items'][0]  # Find top result
    album = results['album']['name']  # Parse json dictionary
    artist = results['album']['artists'][0]['name']
    song_title = results['name']
    album_art = results['album']['images'][0]['url']

    return artist, album, song_title, album_art


Instruction:
Can you tell what is the following Python 3 function doing
def add_album_art(file_name, album_art):

    img = requests.get(album_art, stream=True)  # Gets album art from url
    img = img.raw

    audio = EasyMP3(file_name, ID3=ID3)

    try:
        audio.add_tags()
    except _util.error:
        pass

    audio.tags.add(
        APIC(
            encoding=3,  # UTF-8
            mime='image/png',
            type=3,  # 3 is for album art
            desc='Cover',
            data=img.read()  # Reads and adds album art
        )
    )
    audio.save()

    return album_art

Response: Add album_art in. mp3 s tags


Instruction:
Create a Python 3 function for
adding metadata to the neccessary object.

Response:
def add_metadata(file_name, title, artist, album):
    """
    As the method name suggests
    """

    tags = EasyMP3(file_name)
    if title:
        tags["title"] = title
    if artist:
        tags["artist"] = artist
    if album:
        tags["album"] = album
    tags.save()

    return file_name


Instruction:
Can you generate a brief explanation for the following Python 3 code
def revert_metadata(files):
    for file_path in files:
        tags = EasyMP3(file_path)
        tags.delete()
        tags.save()

Response: Revert all tags from a mp3 file to a new mp3 file


Instruction:
Can you create a Python 3 function that
returns a vault_id string or None

Response:
def get_user_vault_instance_or_none(self, user):
        """Returns a vault_id string or None"""
        qset = self.filter(user=user)
        if not qset:
            return None

        if qset.count() > 1:
            raise Exception('This app does not currently support multiple vault ids')

        return qset.get()


Instruction:
Write a Python 3 function for
charging a user in a vault.

Response:
def charge(self, user, vault_id=None):
        """If vault_id is not passed this will assume that there is only one instane of user and vault_id in the db."""
        assert self.is_in_vault(user)
        if vault_id:
            user_vault = self.get(user=user, vault_id=vault_id)
        else:
            user_vault = self.get(user=user)


Instruction:
Can you generate the documentation for the following Python 3 function
def charge(self, amount):
        try:
            result = Transaction.sale(
                {
                    'amount': amount.quantize(Decimal('.01')),
                    'customer_id': self.vault_id,
                    "options": {
                        "submit_for_settlement": True
                    }
                }
            )

            if result.is_success:
                # create a payment log
                payment_log = PaymentLog.objects.create(user=self.user, amount=amount, transaction_id=result.transaction.id)
                return payment_log
            else:
                raise Exception('Logical error in CC transaction')
        except Exception:
            logging.error('Failed to charge $%s to user: %s with vault_id: %s' % (amount, self.user, self.vault_id))
            return None

Response: Charge the users credit card with he passed amount. Returns the payment log instance if successful.


Instruction:
Write a Python 3 function for
saving the current user to the vault.

Response:
def save(self, prepend_vault_id=''):
        """
        Adds or updates a users CC to the vault.

        @prepend_vault_id: any string to prepend all vault id's with in case the same braintree account is used by
        multiple projects/apps.
        """
        assert self.is_valid()

        cc_details_map = {    # cc details
            'number': self.cleaned_data['cc_number'],
            'cardholder_name': self.cleaned_data['name'],
            'expiration_date': '%s/%s' %\
                (self.cleaned_data['expiration_month'], self.cleaned_data['expiration_year']),
            'cvv': self.cleaned_data['cvv'],
            'billing_address': {
                'postal_code': self.cleaned_data['zip_code'],
            }
        }

        if self.__user_vault:
            try:
                # get customer info, its credit card and then update that credit card
                response = Customer.find(self.__user_vault.vault_id)
                cc_info = response.credit_cards[0]
                return CreditCard.update(cc_info.token, params=cc_details_map)
            except Exception, e:
                logging.error('Was not able to get customer from vault. %s' % e)
                self.__user_vault.delete()  # delete the stale instance from our db

        # in case the above updating fails or user was never in the vault
        new_customer_vault_id = '%s%s' % (prepend_vault_id, md5_hash()[:24])
        respone = Customer.create({    # creating a customer, but we really just want to store their CC details
            'id': new_customer_vault_id,   # vault id, uniquely identifies customer. We're not caring about tokens (used for storing multiple CC's per user)
            'credit_card': cc_details_map
        })

        if respone.is_success:  # save a new UserVault instance
            UserVault.objects.create(user=self.__user, vault_id=new_customer_vault_id)

        return respone


Instruction:
How would you explain what the following Python 3 function does
def payments_billing(request, template='django_braintree/payments_billing.html'):
    d = {}

    if request.method == 'POST':
        # Credit Card is being changed/updated by the user
        form = UserCCDetailsForm(request.user, True, request.POST)
        if form.is_valid():
            response = form.save()
            if response.is_success:
                messages.add_message(request, messages.SUCCESS, 'Your credit card information has been securely saved.')
                return JsonResponse()
            else:
                return JsonResponse(success=False, errors=[BAD_CC_ERROR_MSG])

        return JsonResponse(success=False, data={'form': form_errors_serialize(form)})
    else:
        if UserVault.objects.is_in_vault(request.user):
            try:
                response = Customer.find(UserVault.objects.get_user_vault_instance_or_none(request.user).vault_id)
                d['current_cc_info'] = response.credit_cards[0]
            except Exception, e:
                logging.error('Unable to get vault information for user from braintree. %s' % e)
        d['cc_form'] = UserCCDetailsForm(request.user)

    return render(request, template, d)

Response: Renders both the past payments that have occurred on the users credit card and their CC information on file


Instruction:
Write a Python 3 script to
snooze incident. :param requester: The email address of the individual requesting snooze.

Response:
def snooze(self, requester, duration):
        """Snooze incident.
        :param requester: The email address of the individual requesting snooze.
        """
        path = '{0}/{1}/{2}'.format(self.collection.name, self.id, 'snooze')
        data = {"duration": duration}
        extra_headers = {"From": requester}
        return self.pagerduty.request('POST', path, data=_json_dumper(data), extra_headers=extra_headers)


Instruction:
Write a Python 3 script for
reassigning this incident to a user or list of users

Response:
def reassign(self, user_ids, requester):
        """Reassign this incident to a user or list of users

        :param user_ids: A non-empty list of user ids
        :param requester: The email address of individual requesting reassign
        """
        path = '{0}'.format(self.collection.name)
        assignments = []
        if not user_ids:
            raise Error('Must pass at least one user id')
        for user_id in user_ids:
            ref = {
                "assignee": {
                    "id": user_id,
                    "type": "user_reference"
                }
            }
            assignments.append(ref)
        data = {
            "incidents": [
                {
                    "id": self.id,
                    "type": "incident_reference",
                    "assignments": assignments
                }
            ]
        }
        extra_headers = {"From": requester}
        return self.pagerduty.request('PUT', path, data=_json_dumper(data), extra_headers=extra_headers)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def resolve_incident(self, incident_key,
                         description=None, details=None):
        """ Causes the referenced incident to enter resolved state.
        Send a resolve event when the problem that caused the initial
        trigger has been fixed.
        """

        return self.create_event(description, "resolve",
                                 details, incident_key)

Response: Send a resolve event when the problem that caused the referenced incident to enter resolved state.


Instruction:
Make a summary of the following Python 3 code
def _lower(string):
    if not string:
        return ""

    new_string = [string[0].lower()]
    for char in string[1:]:
        if char.isupper():
            new_string.append("_")
        new_string.append(char.lower())

    return "".join(new_string)

Response: Custom lower string function.


Instruction:
Explain what the following Python 3 code does
def reassign(self, user_ids, requester_id):
        if not user_ids:
            raise Error('Must pass at least one user id')
        self._do_action('reassign', requester_id=requester_id, assigned_to_user=','.join(user_ids))

Response: Reassign this incident to a user or list of users


Instruction:
Can you generate a brief explanation for the following Python 3 code
def acknowledge_incident(self, service_key, incident_key,
                             description=None, details=None):
        """ Causes the referenced incident to enter the acknowledged state.
        Send an acknowledge event when someone is presently working on the
        incident.
        """

        return self.create_event(service_key, description, "acknowledge",
                                 details, incident_key)

Response: Send an acknowledge event to the user who has entered the acknowledged state.


Instruction:
How would you implement a function in Python 3 that
reports a new or ongoing problem.

Response:
def trigger_incident(self, service_key, description,
                         incident_key=None, details=None,
                         client=None, client_url=None, contexts=None):
        """ Report a new or ongoing problem. When PagerDuty receives a trigger,
        it will either open a new incident, or add a new log entry to an
        existing incident.
        """

        return self.create_event(service_key, description, "trigger",
                                 details, incident_key,
                                 client=client, client_url=client_url, contexts=contexts)


Instruction:
Can you create a Python 3 function that
confirms shape of dataset and range of array

Response:
def check_dataset(dataset):
    """Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK."""
    if isinstance(dataset, numpy.ndarray) and not len(dataset.shape) == 4:
        check_dataset_shape(dataset)
        check_dataset_range(dataset)
    else:  # must be a list of arrays or a 4D NumPy array
        for i, d in enumerate(dataset):
            if not isinstance(d, numpy.ndarray):
                raise ValueError(
                    'Requires a NumPy array (rgb x rows x cols) '
                    'with integer values in the range [0, 255].'
                )
            try:
                check_dataset_shape(d)
                check_dataset_range(d)
            except ValueError as err:
                raise ValueError(
                    '{}\nAt position {} in the list of arrays.'
                    .format(err, i)
                )


Instruction:
Given the following Python 3 function, write the documentation
def try_fix_dataset(dataset):
    if isinstance(dataset, numpy.ndarray):
        if len(dataset.shape) == 3:  # NumPy 3D
            if dataset.shape[-1] == 3:
                return dataset.transpose((2, 0, 1))
        elif len(dataset.shape) == 4:  # NumPy 4D
            if dataset.shape[-1] == 3:
                return dataset.transpose((0, 3, 1, 2))
        # Otherwise couldn't fix it.
        return dataset
    # List of Numpy 3D arrays.
    for i, d in enumerate(dataset):
        if not isinstance(d, numpy.ndarray):
            return dataset
        if not (len(d.shape) == 3 and d.shape[-1] == 3):
            return dataset
        dataset[i] = d.transpose()
    return dataset

Response: Transpose the image data if it s in PIL format.


Instruction:
Can you write a function in Python 3 where it
converts the NumPy array to two nested lists with r g b tuples.

Response:
def get_image(dataset):
    """Convert the NumPy array to two nested lists with r,g,b tuples."""
    dim, nrow, ncol = dataset.shape
    uint8_dataset = dataset.astype('uint8')
    if not (uint8_dataset == dataset).all():
        message = (
            "\nYour image was cast to a `uint8` (`<img>.astype(uint8)`), "
            "but some information was lost.\nPlease check your gif and "
            "convert to uint8 beforehand if the gif looks wrong."
        )
        warnings.warn(message)
    image = [[
            struct.pack(
                'BBB',
                uint8_dataset[0, i, j],
                uint8_dataset[1, i, j],
                uint8_dataset[2, i, j]
            )
            for j in range(ncol)]
        for i in range(nrow)]
    return image


Instruction:
How would you explain what the following Python 3 function does
def get_color_table_size(num_colors):
    nbits = max(math.ceil(math.log(num_colors, 2)), 2)
    return '{:03b}'.format(int(nbits - 1))

Response: Returns the size of the color table.


Instruction:
Write a Python 3 script to
return a Counter containing each color and how often it appears.

Response:
def get_colors(image):
    """Return a Counter containing each color and how often it appears.
    """
    colors = Counter(pixel for row in image for pixel in row)
    if len(colors) > 256:
        msg = (
            "The maximum number of distinct colors in a GIF is 256 but "
            "this image has {} colors and can't be encoded properly."
        )
        raise RuntimeError(msg.format(len(colors)))
    return colors


Instruction:
Write a Python 3 script for
returning a color table sorted in descending order of count.

Response:
def _get_global_color_table(colors):
    """Return a color table sorted in descending order of count.
    """
    global_color_table = b''.join(c[0] for c in colors.most_common())
    full_table_size = 2**(1+int(get_color_table_size(len(colors)), 2))
    repeats = 3 * (full_table_size - len(colors))
    zeros = struct.pack('<{}x'.format(repeats))
    return global_color_table + zeros


Instruction:
How would you code a function in Python 3 to
perform the LZW compression as described by Matthew Flickinger.

Response:
def _get_image_data(image, colors):
    """Performs the LZW compression as described by Matthew Flickinger.

    This isn't fast, but it works.
    http://www.matthewflickinger.com/lab/whatsinagif/lzw_image_data.asp
    """
    lzw_code_size, coded_bits = _lzw_encode(image, colors)
    coded_bytes = ''.join(
        '{{:0{}b}}'.format(nbits).format(val) for val, nbits in coded_bits)
    coded_bytes = '0' * ((8 - len(coded_bytes)) % 8) + coded_bytes
    coded_data = list(
        reversed([
            int(coded_bytes[8*i:8*(i+1)], 2)
            for i in range(len(coded_bytes) // 8)
        ])
    )
    output = [struct.pack('<B', lzw_code_size)]
    # Must output the data in blocks of length 255
    block_length = min(255, len(coded_data))
    while block_length > 0:
        block = struct.pack(
            '<{}B'.format(block_length + 1),
            block_length,
            *coded_data[:block_length]
        )
        output.append(block)
        coded_data = coded_data[block_length:]
        block_length = min(255, len(coded_data))
    return b''.join(output)


Instruction:
Can you tell what is the following Python 3 function doing
def write_gif(dataset, filename, fps=10):
    try:
        check_dataset(dataset)
    except ValueError as e:
        dataset = try_fix_dataset(dataset)
        check_dataset(dataset)
    delay_time = 100 // int(fps)

    def encode(d):
        four_d = isinstance(dataset, numpy.ndarray) and len(dataset.shape) == 4
        if four_d or not isinstance(dataset, numpy.ndarray):
            return _make_animated_gif(d, delay_time=delay_time)
        else:
            return _make_gif(d)

    with open(filename, 'wb') as outfile:
        outfile.write(HEADER)
        for block in encode(dataset):
            outfile.write(block)
        outfile.write(TRAILER)

Response: Write a NumPy array to GIF 89a format.


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

    # Smart import of the rc file
    f = QtCore.QFile(':qdarkgraystyle/style.qss')
    if not f.exists():
        _logger().error('Unable to load stylesheet, file not found in '
                        'resources')
        return ''
    else:
        f.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text)
        ts = QtCore.QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet

Response: Loads the stylesheet for use in a pyqt5 application.


Instruction:
Write a Python 3 script for
getting time offset that aligns image timestamps with gyro timestamps. Given an image sequence, and gyroscope data, with their respective timestamps, calculate the offset that aligns the image data with the gyro data. The timestamps must only differ by an offset, not a scale factor. This function finds an approximation of the offset *d* that makes this transformation t_gyro = t_camera + d i.e. your new image timestamps should be image_timestamps_aligned = image_timestamps + d The offset is calculated using zero-mean cross correlation of the gyroscope data magnitude and the optical flow magnitude, calculated from the image sequence. ZNCC is performed using pyramids to make it quick. The offset is accurate up to about +/- 2 frames, so you should run *refine_time_offset* if you need better accuracy. Parameters --------------- image_sequence_or_flow : sequence of image data, or ndarray This must be either a list or generator that provides a stream of images that are used for optical flow calculations. image_timestamps : ndarray Timestamps of the images in image_sequence gyro_data : (3, N) ndarray Gyroscope measurements (angular velocity) gyro_timestamps : ndarray Timestamps of data in gyro_data levels : int Number of pyramid levels full_output : bool If False, only return the offset, otherwise return extra data Returns -------------- time_offset : float The time offset to add to image_timestamps to align the image data with the gyroscope data flow : ndarray (Only if full_output=True) The calculated optical flow magnitude

Response:
def sync_camera_gyro(image_sequence_or_flow, image_timestamps, gyro_data, gyro_timestamps, levels=6, full_output=False):
    """Get time offset that aligns image timestamps with gyro timestamps.

    Given an image sequence, and gyroscope data, with their respective timestamps,
    calculate the offset that aligns the image data with the gyro data.
    The timestamps must only differ by an offset, not a scale factor.

    This function finds an approximation of the offset *d* that makes this transformation

        t_gyro = t_camera + d

    i.e. your new image timestamps should be

        image_timestamps_aligned = image_timestamps + d

    The offset is calculated using zero-mean cross correlation of the gyroscope data magnitude
    and the optical flow magnitude, calculated from the image sequence.
    ZNCC is performed using pyramids to make it quick.

    The offset is accurate up to about +/- 2 frames, so you should run
    *refine_time_offset* if you need better accuracy.

    Parameters
    ---------------
    image_sequence_or_flow : sequence of image data, or ndarray
            This must be either a list or generator that provides a stream of
            images that are used for optical flow calculations.
    image_timestamps : ndarray
            Timestamps of the images in image_sequence
    gyro_data : (3, N) ndarray
            Gyroscope measurements (angular velocity)
    gyro_timestamps : ndarray
            Timestamps of data in gyro_data
    levels : int
            Number of pyramid levels
    full_output : bool
            If False, only return the offset, otherwise return extra data

    Returns
    --------------
    time_offset  :  float
            The time offset to add to image_timestamps to align the image data
            with the gyroscope data
    flow : ndarray
            (Only if full_output=True)
            The calculated optical flow magnitude
    """

    # If input is not flow, then create from iamge sequence
    try:
        assert image_sequence_or_flow.ndim == 1
        flow_org = image_sequence_or_flow
    except AssertionError:
        flow_org = tracking.optical_flow_magnitude(image_sequence_or_flow)

    # Gyro from gyro data
    gyro_mag = np.sum(gyro_data**2, axis=0)
    flow_timestamps = image_timestamps[:-2]

    # Resample to match highest
    rate = lambda ts: len(ts) / (ts[-1] - ts[0])
    freq_gyro = rate(gyro_timestamps)
    freq_image = rate(flow_timestamps)

    if freq_gyro > freq_image:
        rel_rate = freq_gyro / freq_image
        flow_mag = znccpyr.upsample(flow_org, rel_rate)
    else:
        flow_mag = flow_org
        rel_rate = freq_image / freq_gyro
        gyro_mag = znccpyr.upsample(gyro_mag, rel_rate)

    ishift = znccpyr.find_shift_pyr(flow_mag, gyro_mag, levels)

    if freq_gyro > freq_image:
        flow_shift = int(-ishift / rel_rate)
    else:
        flow_shift = int(-ishift)

    time_offset = flow_timestamps[flow_shift]

    if full_output:
        return time_offset, flow_org # Return the orginal flow, not the upsampled version
    else:
        return time_offset


Instruction:
Implement a Python 3 function for
getting time offset that aligns image timestamps with gyro timestamps. Given an image sequence, and gyroscope data, with their respective timestamps, calculate the offset that aligns the image data with the gyro data. The timestamps must only differ by an offset, not a scale factor. This function finds an approximation of the offset *d* that makes this transformation t_gyro = t_camera + d i.e. your new image timestamps should be image_timestamps_aligned = image_timestamps + d The offset is calculated using correlation. The parts of the signals to use are chosen by the user by picking points in a plot window. The offset is accurate up to about +/- 2 frames, so you should run *refine_time_offset* if you need better accuracy. Parameters --------------- image_sequence : sequence of image data This must be either a list or generator that provides a stream of images that are used for optical flow calculations. image_timestamps : ndarray Timestamps of the images in image_sequence gyro_data : (3, N) ndarray Gyroscope measurements (angular velocity) gyro_timestamps : ndarray Timestamps of data in gyro_data full_output : bool If False, only return the offset, otherwise return extra data Returns -------------- time_offset : float The time offset to add to image_timestamps to align the image data with the gyroscope data flow : ndarray (Only if full_output=True) The calculated optical flow magnitude frame_pair : (int, int) The frame pair that was picked for synchronization

Response:
def sync_camera_gyro_manual(image_sequence, image_timestamps, gyro_data, gyro_timestamps, full_output=False):
    """Get time offset that aligns image timestamps with gyro timestamps.

    Given an image sequence, and gyroscope data, with their respective timestamps,
    calculate the offset that aligns the image data with the gyro data.
    The timestamps must only differ by an offset, not a scale factor.

    This function finds an approximation of the offset *d* that makes this transformation

        t_gyro = t_camera + d

    i.e. your new image timestamps should be

        image_timestamps_aligned = image_timestamps + d

    The offset is calculated using correlation. The parts of the signals to use are
    chosen by the user by picking points in a plot window.

    The offset is accurate up to about +/- 2 frames, so you should run
    *refine_time_offset* if you need better accuracy.

    Parameters
    ---------------
    image_sequence : sequence of image data
            This must be either a list or generator that provides a stream of
            images that are used for optical flow calculations.
    image_timestamps : ndarray
            Timestamps of the images in image_sequence
    gyro_data : (3, N) ndarray
            Gyroscope measurements (angular velocity)
    gyro_timestamps : ndarray
            Timestamps of data in gyro_data
    full_output : bool
            If False, only return the offset, otherwise return extra data

    Returns
    --------------
    time_offset  :  float
            The time offset to add to image_timestamps to align the image data
            with the gyroscope data
    flow : ndarray
            (Only if full_output=True)
            The calculated optical flow magnitude
    frame_pair : (int, int)
            The frame pair that was picked for synchronization
    """

    flow = tracking.optical_flow_magnitude(image_sequence)
    flow_timestamps = image_timestamps[:-2]

    # Let user select points in both pieces of data
    (frame_pair, gyro_idx) = manual_sync_pick(flow, gyro_timestamps, gyro_data)

    # Normalize data
    gyro_abs_max = np.max(np.abs(gyro_data), axis=0)
    gyro_normalized = (gyro_abs_max / np.max(gyro_abs_max)).flatten()
    flow_normalized = (flow / np.max(flow)).flatten()

    rate = lambda ts: len(ts) / (ts[-1] - ts[0])

    # Resample to match highest
    freq_gyro = rate(gyro_timestamps)
    freq_image = rate(flow_timestamps)
    logger.debug("Gyro sampling frequency: %.2f Hz, Image sampling frequency: %.2f Hz", freq_gyro, freq_image)

    gyro_part = gyro_normalized[gyro_idx[0]:gyro_idx[1]+1] # only largest
    flow_part = flow_normalized[frame_pair[0]:frame_pair[1]+1]

    N = flow_part.size * freq_gyro / freq_image
    flow_part_resampled = ssig.resample(flow_part, N).flatten()

    # ) Cross correlate the two signals and find time diff
    corr = ssig.correlate(gyro_part, flow_part_resampled, 'full') # Find the flow in gyro data

    i = np.argmax(corr)

    t_0_f = flow_timestamps[frame_pair[0]]
    t_1_f = flow_timestamps[frame_pair[1]]

    t_off_g = gyro_timestamps[gyro_idx[0] + i]
    t_off_f = t_1_f
    time_offset = t_off_g - t_off_f

    if full_output:
        return time_offset, flow, frame_pair
    else:
        return time_offset


Instruction:
Can you write a function in Python 3 where it
refines a time offset between camera and IMU using rolling shutter aware optimization. To refine the time offset using this function, you must meet the following constraints 1) The data must already be roughly aligned. Only a few image frames of error is allowed. 2) The images *must* have been captured by a *rolling shutter* camera. This function finds a refined offset using optimization. Points are first tracked from the start to the end of the provided images. Then an optimization function looks at the reprojection error of the tracked points given the IMU-data and the refined offset. The found offset *d* is such that you want to perform the following time update new_frame_timestamps = frame_timestamps + d Parameters ------------ image_list : list of ndarray A list of images to perform tracking on. High quality tracks are required, so make sure the sequence you choose is easy to track in. frame_timestamps : ndarray Timestamps of image_list rotation_sequence : (4, N) ndarray Absolute rotations as a sequence of unit quaternions (first element is scalar). rotation_timestamps : ndarray Timestamps of rotation_sequence camera_matrix : (3,3) ndarray The internal camera calibration matrix of the camera. readout_time : float The readout time of the camera. Returns ------------ offset : float A refined offset that aligns the image data with the rotation data.

Response:
def refine_time_offset(image_list, frame_timestamps, rotation_sequence, rotation_timestamps, camera_matrix, readout_time):
    """Refine a time offset between camera and IMU using rolling shutter aware optimization.

    To refine the time offset using this function, you must meet the following constraints

    1) The data must already be roughly aligned. Only a few image frames of error
        is allowed.
    2) The images *must* have been captured by a *rolling shutter* camera.

    This function finds a refined offset using optimization.
    Points are first tracked from the start to the end of the provided images.
    Then an optimization function looks at the reprojection error of the tracked points
    given the IMU-data and the refined offset.

    The found offset *d* is such that you want to perform the following time update

        new_frame_timestamps = frame_timestamps + d

    Parameters
    ------------
    image_list : list of ndarray
            A list of images to perform tracking on. High quality tracks are required,
            so make sure the sequence you choose is easy to track in.
    frame_timestamps : ndarray
            Timestamps of image_list
    rotation_sequence : (4, N) ndarray
            Absolute rotations as a sequence of unit quaternions (first element is scalar).
    rotation_timestamps : ndarray
            Timestamps of rotation_sequence
    camera_matrix : (3,3) ndarray
            The internal camera calibration matrix of the camera.
    readout_time : float
            The readout time of the camera.

    Returns
    ------------
    offset : float
            A refined offset that aligns the image data with the rotation data.
    """
    # ) Track points
    max_corners = 200
    quality_level = 0.07
    min_distance = 5
    max_tracks = 20
    initial_points = cv2.goodFeaturesToTrack(image_list[0], max_corners, quality_level, min_distance)
    (points, status) = tracking.track_retrack(image_list, initial_points)

    # Prune to at most max_tracks number of tracks, choose randomly
    track_id_list = np.random.permutation(points.shape[0])[:max_tracks]

    rows, cols = image_list[0].shape[:2]
    row_delta_time = readout_time / rows
    num_tracks, num_frames, _ = points.shape
    K = np.matrix(camera_matrix)

    def func_to_optimize(td, *args):
        res = 0.0
        N = 0
        for frame_idx in range(num_frames-1):
            for track_id in track_id_list:
                p1 = points[track_id, frame_idx, :].reshape((-1,1))
                p2 = points[track_id, frame_idx + 1, :].reshape((-1,1))
                t1 = frame_timestamps[frame_idx] + (p1[1] - 1) * row_delta_time + td
                t2 = frame_timestamps[frame_idx + 1] + (p2[1] - 1) * row_delta_time +td
                t1 = float(t1)
                t2 = float(t2)
                q1 = IMU.rotation_at_time(t1, rotation_timestamps, rotation_sequence)
                q2 = IMU.rotation_at_time(t2, rotation_timestamps, rotation_sequence)
                R1 = rotations.quat_to_rotation_matrix(q1)
                R2 = rotations.quat_to_rotation_matrix(q2)
                p1_rec = K.dot(R1.T).dot(R2).dot(K.I).dot(np.vstack((p2, 1)))
                if p1_rec[2] == 0:
                    continue
                else:
                    p1_rec /= p1_rec[2]
                res += np.sum((p1 - np.array(p1_rec[0:2]))**2)
                N += 1
        return res / N

    # Bounded Brent optimizer
    t0 = time.time()
    tolerance = 1e-4 # one tenth millisecond
    (refined_offset, fval, ierr, numfunc) = scipy.optimize.fminbound(func_to_optimize, -0.12, 0.12, xtol=tolerance, full_output=True)
    t1 = time.time()
    if ierr == 0:
        logger.info("Time offset found by brent optimizer: %.4f. Elapsed: %.2f seconds (%d function calls)", refined_offset, t1-t0, numfunc)
    else:
        logger.error("Brent optimizer did not converge. Aborting!")
        raise Exception("Brent optimizer did not converge, when trying to refine offset.")

    return refined_offset


Instruction:
Implement a Python 3 function for
returning a list of good frames to track in the given optical flow.

Response:
def good_sequences_to_track(flow, motion_threshold=1.0):
    """Get list of good frames to do tracking in.

    Looking at the optical flow, this function chooses a span of frames
    that fulfill certain criteria.
    These include
        * not being too short or too long
        * not too low or too high mean flow magnitude
        * a low max value (avoids motion blur)
    Currently, the cost function for a sequence is hard coded. Sorry about that.

    Parameters
    -------------
    flow : ndarray
            The optical flow magnitude
    motion_threshold : float
            The maximum amount of motion to consider for sequence endpoints.

    Returns
    ------------
    sequences : list
            Sorted list of (a, b, score) elements (highest scpre first) of sequences
            where a sequence is frames with frame indices in the span [a, b].
    """
    endpoints = []
    in_low = False
    for i, val in enumerate(flow):
        if val < motion_threshold:
            if not in_low:
                endpoints.append(i)
                in_low = True
        else:
            if in_low:
                endpoints.append(i-1) # Previous was last in a low spot
            in_low = False

    def mean_score_func(m):
        mu = 15
        sigma = 8
        top_val = normpdf(mu, mu, sigma)
        return normpdf(m, mu, sigma) / top_val

    def max_score_func(m):
        mu = 40
        sigma = 8
        if m <= mu:
            return 1.
        else:
            top_val = normpdf(mu, mu, sigma)
            return normpdf(m, mu, sigma) / top_val

    def length_score_func(l):
        mu = 30
        sigma = 10
        top_val = normpdf(mu, mu, sigma)
        return normpdf(l, mu, sigma) / top_val

    min_length = 5 # frames
    sequences = []
    for k, i in enumerate(endpoints[:-1]):
        for j in endpoints[k+1:]:
            length = j - i
            if length < min_length:
                continue
            seq = flow[i:j+1]
            m_score = mean_score_func(np.mean(seq))
            mx_score = max_score_func(np.max(seq))
            l_score = length_score_func(length)
            logger.debug("%d, %d scores: (mean=%.5f, max=%.5f, length=%.5f)" % (i,j,m_score, mx_score, l_score))
            if min(m_score, mx_score, l_score) < 0.2:
                continue

            score = m_score + mx_score + l_score
            sequences.append((i, j, score))

    return sorted(sequences, key=lambda x: x[2], reverse=True)


Instruction:
Can you create a Python 3 function that
initializes the calendar with the provided gyroscope sample rate and optionally a list of slices.

Response:
def initialize(self, gyro_rate, slices=None, skip_estimation=False):
        """Prepare calibrator for calibration

        This method does three things:
        1. Create slices from the video stream, if not already provided
        2. Estimate time offset
        3. Estimate rotation between camera and gyroscope

        Parameters
        ------------------
        gyro_rate : float
            Estimated gyroscope sample rate
        slices : list of Slice, optional
            Slices to use for optimization
        skip_estimation : bool
            Do not estimate initial time offset and rotation.

        Raises
        --------------------
        InitializationError
            If the initialization fails
        """
        self.params['user']['gyro_rate'] = gyro_rate

        for p in ('gbias_x', 'gbias_y', 'gbias_z'):
            self.params['initialized'][p] = 0.0

        if slices is not None:
            self.slices = slices

        if self.slices is None:
            self.slices = videoslice.Slice.from_stream_randomly(self.video)
            logger.debug("Number of slices: {:d}".format(len(self.slices)))

        if len(self.slices) < 2:
            logger.error("Calibration requires at least 2 video slices to proceed, got %d", len(self.slices))
            raise InitializationError("Calibration requires at least 2 video slices to proceed, got {:d}".format(len(self.slices)))

        if not skip_estimation:
            time_offset = self.find_initial_offset()
            # TODO: Detect when time offset initialization fails, and raise InitializationError

            R = self.find_initial_rotation()
            if R is None:
                raise InitializationError("Failed to calculate initial rotation")


Instruction:
Can you tell what is the following Python 3 function doing
def video_time_to_gyro_sample(self, t):
        f_g = self.parameter['gyro_rate']
        d_c = self.parameter['time_offset']
        n = f_g * (t + d_c)
        n0 = int(np.floor(n))
        tau = n - n0
        return n0, tau

Response: Convert video time to gyroscope sample index and interpolation factor


Instruction:
Make a summary of the following Python 3 code
def parameter(self):
        D = {}
        for source in PARAM_SOURCE_ORDER:
            D.update(self.params[source])
        return D

Response: Return the current best value of a parameter


Instruction:
Can you tell what is the following Python 3 function doing
def calibrate(self, max_tracks=MAX_OPTIMIZATION_TRACKS, max_eval=MAX_OPTIMIZATION_FEV, norm_c=DEFAULT_NORM_C):
        x0 = np.array([self.parameter[param] for param in PARAM_ORDER])
        available_tracks = np.sum([len(s.inliers) for s in self.slices])
        if available_tracks < max_tracks:
            warnings.warn("Could not use the requested {} tracks, since only {} were available in the slice data.".format(max_tracks, available_tracks))
            max_tracks = available_tracks

        # Get subset of available tracks such that all slices are still used
        slice_sample_idxs = videoslice.fill_sampling(self.slices, max_tracks)

        func_args = (self.slices, slice_sample_idxs, self.video.camera_model, self.gyro, norm_c)
        self.slice_sample_idxs = slice_sample_idxs
        logger.debug("Starting optimization on {:d} slices and {:d} tracks".format(len(self.slices), max_tracks))
        start_time = time.time()
        # TODO: Check what values of ftol and xtol are required for good results. The current setting is probably pessimistic.
        leastsq_result = scipy.optimize.leastsq(optimization_func, x0, args=func_args, full_output=True, ftol=1e-10, xtol=1e-10, maxfev=max_eval)
        elapsed = time.time() - start_time
        x, covx, infodict, mesg, ier = leastsq_result
        self.__debug_leastsq = leastsq_result
        logger.debug("Optimization completed in {:.1f} seconds and {:d} function evaluations. ier={}, mesg='{}'".format(elapsed, infodict['nfev'], ier, mesg))
        if ier in (1,2,3,4):
            for pname, val in zip(PARAM_ORDER, x):
                self.params['calibrated'][pname] = val
            return self.parameter
        else:
            raise CalibrationError(mesg)

Response: Perform calibration on the available inliers and return a dictionary of the results.


Instruction:
Can you tell what is the following Python 3 function doing
def find_initial_offset(self, pyramids=6):
        flow = self.video.flow
        gyro_rate = self.parameter['gyro_rate']
        frame_times = np.arange(len(flow)) / self.video.frame_rate
        gyro_times = np.arange(self.gyro.num_samples) / gyro_rate
        time_offset = timesync.sync_camera_gyro(flow, frame_times, self.gyro.data.T, gyro_times, levels=pyramids)

        logger.debug("Initial time offset: {:.4f}".format(time_offset))
        self.params['initialized']['time_offset'] = time_offset

        return time_offset

Response: This sets and returns the initial time offset estimation.


Instruction:
Implement a Python 3 function for
estimating the initial rotation between camera and gyroscope. This function returns the initial rotation estimate.

Response:
def find_initial_rotation(self):
        """Estimate rotation between camera and gyroscope

        This sets and returns the initial rotation estimate.
        Note that the initial time offset must have been estimated before calling this function!

        Returns
        --------------------
        (3,3) ndarray
            Estimated rotation between camera and gyroscope
        """
        if 'time_offset' not in self.parameter:
            raise InitializationError("Can not estimate rotation without an estimate of time offset. Please estimate the offset and try again.")

        dt = float(1.0 / self.parameter['gyro_rate']) # Must be python float for fastintegrate
        q = self.gyro.integrate(dt)

        video_axes = []
        gyro_axes = []

        for _slice in self.slices:
            # Estimate rotation here
            _slice.estimate_rotation(self.video.camera_model, ransac_threshold=7.0) # sets .axis and .angle memebers
            if _slice.axis is None:
                continue
            assert _slice.angle > 0

            t1 = _slice.start / self.video.frame_rate
            n1, _ = self.video_time_to_gyro_sample(t1)
            t2 = _slice.end / self.video.frame_rate
            n2, _ = self.video_time_to_gyro_sample(t2)

            try:
                qx = q[n1]
                qy = q[n2]
            except IndexError:
                continue # No gyro data -> nothing to do with this slice

            Rx = rotations.quat_to_rotation_matrix(qx)
            Ry = rotations.quat_to_rotation_matrix(qy)
            R = np.dot(Rx.T, Ry)
            v, theta = rotations.rotation_matrix_to_axis_angle(R)
            if theta < 0:
                v = -v

            gyro_axes.append(v)
            video_axes.append(_slice.axis)

        if len(gyro_axes) < 2:
            logger.warning("Rotation estimation requires at least 2 rotation axes, got {}".format(len(gyro_axes)))
            return None

        logger.debug("Using {:d} slices (from initial {:d} for rotation estimation".format(len(gyro_axes), len(self.slices)))

        model_func = lambda data: rotations.procrustes(data[:3], data[3:6], remove_mean=False)[0]

        def eval_func(model, data):
            X = data[:3].reshape(3,-1)
            Y = data[3:6].reshape(3,-1)
            R = model
            Xhat = np.dot(R, Y)

            costheta = np.sum(Xhat*X, axis=0)
            theta = np.arccos(costheta)

            return theta

        inlier_selection_prob = 0.99999
        model_points = 2 # Set to 3 to use non-minimal case
        inlier_ratio = 0.5
        threshold = np.deg2rad(10.0)
        ransac_iterations = int(np.log(1 - inlier_selection_prob) / np.log(1-inlier_ratio**model_points))
        data = np.vstack((np.array(video_axes).T, np.array(gyro_axes).T))
        assert data.shape == (6, len(gyro_axes))

        R, ransac_conseus_idx = ransac.RANSAC(model_func, eval_func, data,
                                              model_points, ransac_iterations,
                                              threshold, recalculate=True)

        n, theta = rotations.rotation_matrix_to_axis_angle(R)
        logger.debug("Found rotation: n={} theta={};  r={}".format(n, theta, n*theta))
        logger.debug(R)
        rx, ry, rz = theta * n
        self.params['initialized']['rot_x'] = rx
        self.params['initialized']['rot_y'] = ry
        self.params['initialized']['rot_z'] = rz

        return R


Instruction:
Can you generate a brief explanation for the following Python 3 code
def print_params(self):
        print("Parameters")
        print("--------------------")
        for param in PARAM_ORDER:
            print('  {:>11s} = {}'.format(param, self.parameter[param]))

Response: Print the current best set of parameters


Instruction:
Given the following Python 3 function, write the documentation
def remove_slp(img, gstd1=GSTD1, gstd2=GSTD2, gstd3=GSTD3, ksize=KSIZE, w=W):
    gf1 = cv2.getGaussianKernel(ksize, gstd1)
    gf2 = cv2.getGaussianKernel(ksize, gstd2)
    gf3 = cv2.getGaussianKernel(ksize, gstd3)
    sqrtimg = cv2.sqrt(img)
    p1 = cv2.sepFilter2D(sqrtimg, -1, gf1, gf1)
    p2 = cv2.sepFilter2D(sqrtimg, -1, gf2, gf2)
    maxarr = np.maximum(0, (p1 - p2) / p2)
    minarr = np.minimum(w * maxarr, 1)
    p = 1 - minarr
    nc = cv2.sepFilter2D(p, -1, gf3, gf3) + EPS
    output = cv2.sepFilter2D(p*sqrtimg, -1, gf3, gf3)
    output = (output / nc) ** 2 # Since input is sqrted

    return output

Response: Remove the SLP from kinect IR image


Instruction:
Write a Python 3 script to
load camera model parameters from a HDF5 file.

Response:
def from_hdf(cls, filename):
        """Load camera model params from a HDF5 file

        The HDF5 file should contain the following datasets:
            wc : (2,) float with distortion center
            lgamma : float distortion parameter
            readout : float readout value
            size : (2,) int image size
            fps : float frame rate
            K : (3, 3) float camera matrix

        Parameters
        --------------------
        filename : str
            Path to file with parameters

        Returns
        ---------------------
        AtanCameraModel
            Camera model instance
        """
        import h5py
        with h5py.File(filename, 'r') as f:
            wc = f["wc"].value
            lgamma = f["lgamma"].value
            K = f["K"].value
            readout = f["readout"].value
            image_size = f["size"].value
            fps = f["fps"].value
            instance = cls(image_size, fps, readout, K, wc, lgamma)
            return instance


Instruction:
Can you generate a brief explanation for the following Python 3 code
def invert(self, points):
        X = points if not points.ndim == 1 else points.reshape((points.size, 1))

        wx, wy = self.wc

        # Switch to polar coordinates
        rn = np.sqrt((X[0,:] - wx)**2 + (X[1,:] - wy)**2)
        phi = np.arctan2(X[1,:] - wy, X[0,:]-wx)
        # 'atan' method
        r = np.tan(rn * self.lgamma) / self.lgamma;

        # Switch back to rectangular coordinates
        Y = np.ones(X.shape)
        Y[0,:] = wx + r * np.cos(phi)
        Y[1,:]= wy + r * np.sin(phi)
        return Y

Response: Invert the distortion of the distortion of the current image.


Instruction:
Make a summary of the following Python 3 code
def project(self, points):
        K = self.camera_matrix
        XU = points
        XU = XU / np.tile(XU[2], (3,1))
        X = self.apply(XU)
        x2d = np.dot(K, X)
        return from_homogeneous(x2d)

Response: Project 3D points to image coordinates.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unproject(self, image_points):
        Ki = self.inv_camera_matrix
        X = np.dot(Ki, to_homogeneous(image_points))
        X = X / X[2]
        XU = self.invert(X)
        return XU

Response: Unproject an image point into a 3D coordinate.


Instruction:
Explain what the following Python 3 code does
def project(self, points):
        rvec = tvec = np.zeros(3)
        image_points, jac = cv2.projectPoints(points.T.reshape(-1,1,3), rvec, tvec, self.camera_matrix, self.dist_coefs)
        return image_points.reshape(-1,2).T

Response: Project 3D points to image coordinates.


Instruction:
Can you write a function in Python 3 where it
finds (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray Image points Returns ---------------------- points : (3, N) ndarray 3D coordinates (valid up to scale)

Response:
def unproject(self, image_points):
        """Find (up to scale) 3D coordinate of an image point

        This is the inverse of the `project` function.
        The resulting 3D points are only valid up to an unknown scale.

        Parameters
        ----------------------
        image_points : (2, N) ndarray
            Image points

        Returns
        ----------------------
        points : (3, N) ndarray
            3D coordinates (valid up to scale)
        """
        undist_image_points = cv2.undistortPoints(image_points.T.reshape(1,-1,2), self.camera_matrix, self.dist_coefs, P=self.camera_matrix)
        world_points = np.dot(self.inv_camera_matrix, to_homogeneous(undist_image_points.reshape(-1,2).T))
        return world_points


Instruction:
Create a Python 3 function for
taking list of Kinect filenames without path and extracts timestamps while accounting for timestamp overflow ( returns linear timestamps.

Response:
def timestamps_from_file_list(file_list):
        "Take list of Kinect filenames (without path) and extracts timestamps while accounting for timestamp overflow (returns linear timestamps)."
        timestamps = np.array([Kinect.timestamp_from_filename(fname) for fname in file_list])

        # Handle overflow
        diff = np.diff(timestamps)
        idxs = np.flatnonzero(diff < 0)
        ITEM_SIZE = 2**32
        for i in idxs:
            timestamps[i+1:] += ITEM_SIZE

        return timestamps.flatten()


Instruction:
How would you implement a function in Python 3 that
gives a list of image files find bad frames remove them and modify file_list

Response:
def purge_bad_timestamp_files(file_list):
        "Given a list of image files, find bad frames, remove them and modify file_list"
        MAX_INITIAL_BAD_FRAMES = 15
        bad_ts = Kinect.detect_bad_timestamps(Kinect.timestamps_from_file_list(file_list))

        # Trivial case
        if not bad_ts:
            return file_list

        # No bad frames after the initial allowed
        last_bad = max(bad_ts)
        if last_bad >= MAX_INITIAL_BAD_FRAMES:
            raise Exception('Only 15 initial bad frames are allowed, but last bad frame is %d' % last_bad)

        # Remove all frames up to the last bad frame
        for i in range(last_bad + 1):
            os.remove(file_list[i])

        # Purge from the list
        file_list = file_list[last_bad+1:]

        return file_list


Instruction:
Here you have a function in Python 3, explain what it does
def depth_file_for_nir_file(video_filename, depth_file_list):
        (root, filename) = os.path.split(video_filename)
        needle_ts = int(filename.split('-')[2].split('.')[0])
        haystack_ts_list = np.array(Kinect.timestamps_from_file_list(depth_file_list))
        haystack_idx = np.flatnonzero(haystack_ts_list == needle_ts)[0]
        depth_filename = depth_file_list[haystack_idx]
        return depth_filename

Response: Returns the corresponding depth filename given a NIR filename


Instruction:
Create a Python 3 function for
returning the closest depth file from an RGB filename

Response:
def depth_file_for_rgb_file(rgb_filename, rgb_file_list, depth_file_list):
        """Returns the *closest* depth file from an RGB filename"""
        (root, filename) = os.path.split(rgb_filename)
        rgb_timestamps = np.array(Kinect.timestamps_from_file_list(rgb_file_list))
        depth_timestamps = np.array(Kinect.timestamps_from_file_list(depth_file_list))
        needle_ts = rgb_timestamps[rgb_file_list.index(rgb_filename)]
        haystack_idx = np.argmin(np.abs(depth_timestamps - needle_ts))
        depth_filename = depth_file_list[haystack_idx]
        return depth_filename


Instruction:
How would you code a function in Python 3 to
remove all files without its own counterpart. Returns new lists of files

Response:
def find_nir_file_with_missing_depth(video_file_list, depth_file_list):
        "Remove all files without its own counterpart. Returns new lists of files"
        new_video_list = []
        new_depth_list = []
        for fname in video_file_list:
            try:
                depth_file = Kinect.depth_file_for_nir_file(fname, depth_file_list)
                new_video_list.append(fname)
                new_depth_list.append(depth_file)
            except IndexError: # Missing file
                pass

        # Purge bad files
        bad_nir = [f for f in video_file_list if f not in new_video_list]
        bad_depth = [f for f in depth_file_list if f not in new_depth_list]

        return (new_video_list, new_depth_list, bad_nir, bad_depth)


Instruction:
Write a Python 3 function for
converting image of Kinect disparity values to distance ( linear method )

Response:
def disparity_image_to_distance(self, dval_img):
        "Convert image of Kinect disparity values to distance (linear method)"
        dist_img = dval_img / 2048.0
        dist_img = 1 / (self.opars[0]*dist_img + self.opars[1])
        return dist_img


Instruction:
Can you generate the documentation for the following Python 3 function
def fill_sampling(slice_list, N):
    A = [len(s.inliers) for s in slice_list]
    N_max = np.sum(A)
    if N > N_max:
        raise ValueError("Tried to draw {:d} samples from a pool of only {:d} items".format(N, N_max))

    samples_from = np.zeros((len(A),), dtype='int') # Number of samples to draw from each group

    remaining = N
    while remaining > 0:
        remaining_groups = np.flatnonzero(samples_from - np.array(A))

        if remaining < len(remaining_groups):
            np.random.shuffle(remaining_groups)
            for g in remaining_groups[:remaining]:
                samples_from[g] += 1
        else:
            # Give each group the allowed number of samples. Constrain to their max size.
            to_each = max(1, int(remaining / len(remaining_groups)))
            samples_from = np.min(np.vstack((samples_from + to_each, A)), axis=0)

        # Update remaining count
        remaining = int(N - np.sum(samples_from))
    if not remaining == 0:
        raise ValueError("Still {:d} samples left! This is an error in the selection.")

    # Construct index list of selected samples
    samples = []
    for s, a, n in zip(slice_list, A, samples_from):
        if a == n:
            samples.append(np.array(s.inliers)) # all
        elif a == 0:
            samples.append(np.arange([]))
        else:
            chosen = np.random.choice(s.inliers, n, replace=False)
            samples.append(np.array(chosen))
    return samples

Response: Given a list of slices draw N samples such that each slice contributes as much as possible


Instruction:
Write a Python 3 function for
estimating the rotation between the first and last frame of the current object.

Response:
def estimate_rotation(self, camera, ransac_threshold=7.0):
        """Estimate the rotation between first and last frame

        It uses RANSAC where the error metric is the reprojection error of the points
        from the last frame to the first frame.

        Parameters
        -----------------
        camera : CameraModel
            Camera model
        ransac_threshold : float
            Distance threshold (in pixels) for a reprojected point to count as an inlier
        """
        if self.axis is None:
            x = self.points[:, 0, :].T
            y = self.points[:, -1, :].T
            inlier_ratio = 0.5
            R, t, dist, idx = rotations.estimate_rotation_procrustes_ransac(x, y,
                                                                     camera,
                                                                     ransac_threshold,
                                                                     inlier_ratio=inlier_ratio,
                                                                     do_translation=False)

            if R is not None:
                self.axis, self.angle = rotations.rotation_matrix_to_axis_angle(R)
                if self.angle < 0: # Constrain to positive angles
                    self.angle = -self.angle
                    self.axis = -self.axis
                self.inliers = idx

        return self.axis is not None