Instruction:
Can you write a function in Python 3 where it
checks that one or more elements matching the expression don t exist.

Response:
def element_should_not_exist(self, json_string, expr):
        """
        Check that one or more elements, matching [ http://jsonselect.org/ | JSONSelect] expression, don't exist.

        *DEPRECATED* JSON Select query language is outdated and not supported any more.
        Use other keywords of this library to query JSON.

        *Args:*\n
        _json_string_ - JSON string;\n
        _expr_ - JSONSelect expression;\n

        *Raises:*\n
        JsonValidatorError
        """
        value = self.select_elements(json_string, expr)
        if value is not None:
            raise JsonValidatorError('Elements %s exist but should not' % expr)


Instruction:
Make a summary of the following Python 3 code
def _json_path_search(self, json_dict, expr):
        path = parse(expr)
        results = path.find(json_dict)

        if len(results) is 0:
            raise JsonValidatorError("Nothing found in the dictionary {0} using the given path {1}".format(
                str(json_dict), str(expr)))

        return results

Response: Searches the given json - dictionary for items within the given path.


Instruction:
Make a summary of the following Python 3 code
def update_json(self, json_string, expr, value, index=0):
        load_input_json = self.string_to_json(json_string)
        matches = self._json_path_search(load_input_json, expr)

        datum_object = matches[int(index)]

        if not isinstance(datum_object, DatumInContext):
            raise JsonValidatorError("Nothing found by the given json-path")

        path = datum_object.path

        # Edit the directory using the received data
        # If the user specified a list
        if isinstance(path, Index):
            datum_object.context.value[datum_object.path.index] = value
        # If the user specified a value of type (string, bool, integer or complex)
        elif isinstance(path, Fields):
            datum_object.context.value[datum_object.path.fields[0]] = value

        return load_input_json

Response: Update the value in the JSON string with the value in the dictionary format.


Instruction:
Here you have a function in Python 3, explain what it does
def pretty_print_json(self, json_string):
        return json.dumps(self.string_to_json(json_string), indent=2, ensure_ascii=False)

Response: Return formatted JSON string _json_string_.


Instruction:
Can you tell what is the following Python 3 function doing
def output_interval_histogram(self,
                                  histogram,
                                  start_time_stamp_sec=0,
                                  end_time_stamp_sec=0,
                                  max_value_unit_ratio=1000000.0):
        '''Output an interval histogram, with the given timestamp and a
        configurable maxValueUnitRatio.
        (note that the specified timestamp will be used, and the timestamp in
        the actual histogram will be ignored).
        The max value reported with the interval line will be scaled by the
        given max_value_unit_ratio.
        The histogram start and end timestamps are assumed to be in msec units.
        Logging will be in seconds, realtive by a base time
        The default base time is 0.

        By covention, histogram start/end time are generally stamped with
        absolute times in msec since the epoch. For logging with absolute time
        stamps, the base time would remain zero. For
        logging with relative time stamps (time since a start point),
        Params:
            histogram The interval histogram to log.
            start_time_stamp_sec The start timestamp to log with the
                interval histogram, in seconds.
                default: using the start/end timestamp indicated in the histogram
            end_time_stamp_sec The end timestamp to log with the interval
                histogram, in seconds.
                default: using the start/end timestamp indicated in the histogram
            max_value_unit_ratio The ratio by which to divide the histogram's max
                value when reporting on it.
                default: 1,000,000 (which is the msec : nsec ratio
        '''
        if not start_time_stamp_sec:
            start_time_stamp_sec = \
                (histogram.get_start_time_stamp() - self.base_time) / 1000.0
        if not end_time_stamp_sec:
            end_time_stamp_sec = (histogram.get_end_time_stamp() - self.base_time) / 1000.0
        cpayload = histogram.encode()
        self.log.write("%f,%f,%f,%s\n" %
                       (start_time_stamp_sec,
                        end_time_stamp_sec - start_time_stamp_sec,
                        histogram.get_max_value() // max_value_unit_ratio,
                        cpayload.decode('utf-8')))

Response: Output an interval histogram with the given start and end timestamps.


Instruction:
Implement a Python 3 function for
logging a start time in the log.

Response:
def output_start_time(self, start_time_msec):
        '''Log a start time in the log.
        Params:
            start_time_msec time (in milliseconds) since the absolute start time (the epoch)
        '''
        self.log.write("#[StartTime: %f (seconds since epoch), %s]\n" %
                       (float(start_time_msec) / 1000.0,
                        datetime.fromtimestamp(start_time_msec).iso_format(' ')))


Instruction:
Given the following Python 3 function, write the documentation
def _decode_next_interval_histogram(self,
                                        dest_histogram,
                                        range_start_time_sec=0.0,
                                        range_end_time_sec=sys.maxsize,
                                        absolute=False):
        '''Read the next interval histogram from the log, if interval falls
        within an absolute or relative time range.

        Timestamps are assumed to appear in order in the log file, and as such
        this method will return a null upon encountering a timestamp larger than
        range_end_time_sec.

        Relative time range:
            the range is assumed to be in seconds relative to
            the actual timestamp value found in each interval line in the log
        Absolute time range:
            Absolute timestamps are calculated by adding the timestamp found
            with the recorded interval to the [latest, optional] start time
            found in the log. The start time is indicated in the log with
            a "#[StartTime: " followed by the start time in seconds.

        Params:
            dest_histogram if None, created a new histogram, else adds
                           the new interval histogram to it
            range_start_time_sec The absolute or relative start of the expected
                                 time range, in seconds.
            range_start_time_sec The absolute or relative end of the expected
                                  time range, in seconds.
            absolute Defines if the passed range is absolute or relative

        Return:
            Returns an histogram object if an interval line was found with an
            associated start timestamp value that falls between start_time_sec and
            end_time_sec,
            or null if no such interval line is found.
            Upon encountering any unexpected format errors in reading the next
            interval from the file, this method will return None.

            The histogram returned will have it's timestamp set to the absolute
            timestamp calculated from adding the interval's indicated timestamp
            value to the latest [optional] start time found in the log.

        Exceptions:
            ValueError if there is a syntax error in one of the float fields
        '''
        while 1:
            line = self.input_file.readline()
            if not line:
                return None
            if line[0] == '#':
                match_res = re_start_time.match(line)
                if match_res:
                    self.start_time_sec = float(match_res.group(1))
                    self.observed_start_time = True
                    continue
                match_res = re_base_time.match(line)
                if match_res:
                    self.base_time_sec = float(match_res.group(1))
                    self.observed_base_time = True
                    continue

            match_res = re_histogram_interval.match(line)
            if not match_res:
                # probably a legend line that starts with "\"StartTimestamp"
                continue
            # Decode: startTimestamp, intervalLength, maxTime, histogramPayload
            # Timestamp is expected to be in seconds
            log_time_stamp_in_sec = float(match_res.group(1))
            interval_length_sec = float(match_res.group(2))
            cpayload = match_res.group(4)

            if not self.observed_start_time:
                # No explicit start time noted. Use 1st observed time:
                self.start_time_sec = log_time_stamp_in_sec
                self.observed_start_time = True

            if not self.observed_base_time:
                # No explicit base time noted.
                # Deduce from 1st observed time (compared to start time):
                if log_time_stamp_in_sec < self.start_time_sec - (365 * 24 * 3600.0):
                    # Criteria Note: if log timestamp is more than a year in
                    # the past (compared to StartTime),
                    # we assume that timestamps in the log are not absolute
                    self.base_time_sec = self.start_time_sec
                else:
                    # Timestamps are absolute
                    self.base_time_sec = 0.0
                self.observed_base_time = True

            absolute_start_time_stamp_sec = \
                log_time_stamp_in_sec + self.base_time_sec
            offset_start_time_stamp_sec = \
                absolute_start_time_stamp_sec - self.start_time_sec

            # Timestamp length is expect to be in seconds
            absolute_end_time_stamp_sec = \
                absolute_start_time_stamp_sec + interval_length_sec

            if absolute:
                start_time_stamp_to_check_range_on = absolute_start_time_stamp_sec
            else:
                start_time_stamp_to_check_range_on = offset_start_time_stamp_sec

            if start_time_stamp_to_check_range_on < range_start_time_sec:
                continue

            if start_time_stamp_to_check_range_on > range_end_time_sec:
                return None
            if dest_histogram:
                # add the interval histogram to the destination histogram
                histogram = dest_histogram
                histogram.decode_and_add(cpayload)
            else:
                histogram = HdrHistogram.decode(cpayload)
                histogram.set_start_time_stamp(absolute_start_time_stamp_sec * 1000.0)
                histogram.set_end_time_stamp(absolute_end_time_stamp_sec * 1000.0)
            return histogram

Response: This method reads the next interval histogram from the log file and returns the corresponding histogram object.


Instruction:
How would you explain what the following Python 3 function does
def get_next_interval_histogram(self,
                                    range_start_time_sec=0.0,
                                    range_end_time_sec=sys.maxsize,
                                    absolute=False):
        '''Read the next interval histogram from the log, if interval falls
        within an absolute or relative time range.

        Timestamps are assumed to appear in order in the log file, and as such
        this method will return a null upon encountering a timestamp larger than
        range_end_time_sec.

        Relative time range:
            the range is assumed to be in seconds relative to
            the actual timestamp value found in each interval line in the log
        Absolute time range:
            Absolute timestamps are calculated by adding the timestamp found
            with the recorded interval to the [latest, optional] start time
            found in the log. The start time is indicated in the log with
            a "#[StartTime: " followed by the start time in seconds.

        Params:

            range_start_time_sec The absolute or relative start of the expected
                                 time range, in seconds.
            range_start_time_sec The absolute or relative end of the expected
                                  time range, in seconds.
            absolute Defines if the passed range is absolute or relative

        Return:
            Returns an histogram object if an interval line was found with an
            associated start timestamp value that falls between start_time_sec and
            end_time_sec,
            or null if no such interval line is found.
            Upon encountering any unexpected format errors in reading the next
            interval from the file, this method will return None.

            The histogram returned will have it's timestamp set to the absolute
            timestamp calculated from adding the interval's indicated timestamp
            value to the latest [optional] start time found in the log.

        Exceptions:
            ValueError if there is a syntax error in one of the float fields
        '''
        return self._decode_next_interval_histogram(None,
                                                    range_start_time_sec,
                                                    range_end_time_sec,
                                                    absolute)

Response: This method reads the next interval histogram from the log file.


Instruction:
Write a Python 3 script to
read the next interval histogram from the log, if interval falls within an absolute or relative time range, and add it to the destination histogram (or to the reference histogram if dest_histogram is None) Timestamps are assumed to appear in order in the log file, and as such this method will return a null upon encountering a timestamp larger than range_end_time_sec. Relative time range: the range is assumed to be in seconds relative to the actual timestamp value found in each interval line in the log Absolute time range: Absolute timestamps are calculated by adding the timestamp found with the recorded interval to the [latest, optional] start time found in the log. The start time is indicated in the log with a "#[StartTime: " followed by the start time in seconds. Params: dest_histogram where to add the next interval histogram, if None the interal histogram will be added to the reference histogram passed in the constructor range_start_time_sec The absolute or relative start of the expected time range, in seconds. range_start_time_sec The absolute or relative end of the expected time range, in seconds. absolute Defines if the passed range is absolute or relative Return: Returns the destination histogram if an interval line was found with an associated start timestamp value that falls between start_time_sec and end_time_sec, or None if no such interval line is found. Upon encountering any unexpected format errors in reading the next interval from the file, this method will return None. The histogram returned will have it's timestamp set to the absolute timestamp calculated from adding the interval's indicated timestamp value to the latest [optional] start time found in the log. Exceptions: ValueError if there is a syntax error in one of the float fields

Response:
def add_next_interval_histogram(self,
                                    dest_histogram=None,
                                    range_start_time_sec=0.0,
                                    range_end_time_sec=sys.maxsize,
                                    absolute=False):
        '''Read the next interval histogram from the log, if interval falls
        within an absolute or relative time range, and add it to the destination
        histogram (or to the reference histogram if dest_histogram is None)

        Timestamps are assumed to appear in order in the log file, and as such
        this method will return a null upon encountering a timestamp larger than
        range_end_time_sec.

        Relative time range:
            the range is assumed to be in seconds relative to
            the actual timestamp value found in each interval line in the log
        Absolute time range:
            Absolute timestamps are calculated by adding the timestamp found
            with the recorded interval to the [latest, optional] start time
            found in the log. The start time is indicated in the log with
            a "#[StartTime: " followed by the start time in seconds.

        Params:
            dest_histogram where to add the next interval histogram, if None
                           the interal histogram will be added to the reference
                           histogram passed in the constructor
            range_start_time_sec The absolute or relative start of the expected
                                 time range, in seconds.
            range_start_time_sec The absolute or relative end of the expected
                                  time range, in seconds.
            absolute Defines if the passed range is absolute or relative

        Return:
            Returns the destination histogram if an interval line was found with an
            associated start timestamp value that falls between start_time_sec and
            end_time_sec,
            or None if no such interval line is found.
            Upon encountering any unexpected format errors in reading the next
            interval from the file, this method will return None.

            The histogram returned will have it's timestamp set to the absolute
            timestamp calculated from adding the interval's indicated timestamp
            value to the latest [optional] start time found in the log.

        Exceptions:
            ValueError if there is a syntax error in one of the float fields
        '''
        if not dest_histogram:
            dest_histogram = self.reference_histogram
        return self._decode_next_interval_histogram(dest_histogram,
                                                    range_start_time_sec,
                                                    range_end_time_sec,
                                                    absolute)


Instruction:
Write a Python 3 script to
sanitize HTML tags other than provided tags and attributes.

Response:
def sanitize_allow(value, args=''):
    '''
    Strip HTML tags other than provided tags and attributes.
    Example usage:

    {% load sanitizer %}
    {{ post.body|sanitize_allow:'a, strong, img; href, src'}}
    '''
    if isinstance(value, basestring):
        allowed_tags = []
        allowed_attributes = []
        allowed_styles = []

        args = args.strip().split(';')
        if len(args) > 0:
            allowed_tags = [tag.strip() for tag in args[0].split(',')]
        if len(args) > 1:
            allowed_attributes = [attr.strip() for attr in args[1].split(',')]

        value = bleach.clean(value, tags=allowed_tags,
                             attributes=allowed_attributes, strip=True)
    return value


Instruction:
Write a Python 3 script to
escape HTML tags attributes and styles.

Response:
def escape_html(value, allowed_tags=[], allowed_attributes=[],
                allowed_styles=[]):
    """
    Template tag to sanitize string values. It accepts lists of
    allowed tags, attributes or styles in comma separated string or list format.

    For example:

    {% load sanitizer %}
    {% escape_html '<a href="">bar</a> <script>alert('baz')</script>' "a,img' 'href',src' %}

    Will output:

    <a href="">bar</a> &lt;cript&gt;alert('baz')&lt;/script&gt;

    On django 1.4 you could also use keyword arguments:

    {% escape_html '<a href="">bar</a>' allowed_tags="a,img' allowed_attributes='href',src' %}

    """
    if isinstance(value, basestring):
        value = bleach.clean(value, tags=allowed_tags,
                             attributes=allowed_attributes,
                             styles=allowed_styles, strip=False)
    return value


Instruction:
Can you write a function in Python 3 where it
templates tag to strip html from string values. It accepts lists of allowed tags, attributes or stylesin comma separated string or list format. For example: {% load sanitizer %} {% strip_html 'bar ' "a,img' 'href',src' %} Will output: bar alert('baz'); On django 1.4 you could also use keyword arguments: {% strip_html 'bar' allowed_tags="a,img' allowed_attributes='href',src' %}

Response:
def strip_html(value, allowed_tags=[], allowed_attributes=[],
               allowed_styles=[]):
    """
    Template tag to strip html from string values. It accepts lists of
    allowed tags, attributes or stylesin comma separated string or list format.

    For example:

    {% load sanitizer %}
    {% strip_html '<a href="">bar</a> <script>alert('baz')</script>' "a,img' 'href',src' %}

    Will output:

    <a href="">bar</a> alert('baz');

    On django 1.4 you could also use keyword arguments:

    {% strip_html '<a href="">bar</a>' allowed_tags="a,img' allowed_attributes='href',src' %}

    """
    if isinstance(value, basestring):
        value = bleach.clean(value, tags=allowed_tags,
                             attributes=allowed_attributes,
                             styles=allowed_styles, strip=True)
    return value


Instruction:
Given the following Python 3 function, write the documentation
def get_censor_char():
    global _censor_pool
    if not _censor_pool:
        # censor pool is empty. fill it back up.
        _censor_pool = list(_censor_chars)
    return _censor_pool.pop(random.randrange(len(_censor_pool)))

Response: Plucks a letter out of the censor_pool.


Instruction:
Write a Python 3 script to
return the input string with profanity replaced with a random string of characters plucked from the censor_characters pool.

Response:
def censor(input_text):
    """ Returns the input string with profanity replaced with a random string
    of characters plucked from the censor_characters pool.

    """
    ret = input_text
    words = get_words()
    for word in words:
        curse_word = re.compile(re.escape(word), re.IGNORECASE)
        cen = "".join(get_censor_char() for i in list(word))
        ret = curse_word.sub(cen, ret)
    return ret


Instruction:
Implement a Python 3 function for
loading and caches the profanity word list.

Response:
def load_words(wordlist=None):
    """ Loads and caches the profanity word list. Input file (if provided)
    should be a flat text file with one profanity entry per line.

    """
    global words
    if not wordlist:
        # no wordlist was provided, load the wordlist from the local store
        filename = get_data('wordlist.txt')
        f = open(filename)
        wordlist = f.readlines()
        wordlist = [w.strip() for w in wordlist if w]
    words = wordlist


Instruction:
Can you generate the documentation for the following Python 3 function
def convert(csv, json, **kwargs):
    '''Convert csv to json.

    csv:  filename or file-like object
    json: filename  or file-like object

    if csv is '-' or None:
        stdin is used for input
    if json is '-' or None:
        stdout is used for output
    '''

    csv_local, json_local = None, None
    try:
        if csv == '-' or csv is None:
            csv = sys.stdin
        elif isinstance(csv, str):
            csv = csv_local = open(csv, 'r')

        if json == '-' or json is None:
            json = sys.stdout
        elif isinstance(json, str):
            json = json_local = open(json, 'w')

        data = load_csv(csv, **kwargs)
        save_json(data, json, **kwargs)
    finally:
        if csv_local is not None:
            csv_local.close()
        if json_local is not None:
            json_local.close()

Response: Convert csv to json.


Instruction:
Can you write a function in Python 3 where it
adds new sentence to generate dictionarys.

Response:
def update_dicts(self, sentence):
        """Add new sentence to generate dictionaries.

        :param sentence: A list of strings representing the sentence.
        """
        self.dict_generator(sentence=sentence)
        self.word_dict, self.char_dict = None, None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_dicts(self, word_dict, char_dict):
        self.word_dict = word_dict
        self.char_dict = char_dict

Response: Set with custom dictionaries.


Instruction:
Create a Python 3 function for
getting word and character dictionaries.

Response:
def get_dicts(self):
        """Get word and character dictionaries.

        :return word_dict, char_dict:
        """
        if self.word_dict is None:
            self.word_dict, self.char_dict, self.max_word_len = self.dict_generator(return_dict=True)
        return self.word_dict, self.char_dict


Instruction:
Can you implement a function in Python 3 that
gets the merged embedding layer.

Response:
def get_embedding_layer(self,
                            word_embd_dim=300,
                            char_embd_dim=30,
                            char_hidden_dim=150,
                            char_hidden_layer_type='lstm',
                            word_embd_weights=None,
                            word_embd_file_path=None,
                            char_embd_weights=None,
                            char_embd_file_path=None,
                            word_embd_trainable=None,
                            char_embd_trainable=None,
                            word_mask_zero=True,
                            char_mask_zero=True,):
        """Get the merged embedding layer.

        :param word_embd_dim: The dimensions of the word embedding.
        :param char_embd_dim: The dimensions of the character embedding
        :param char_hidden_dim: The dimensions of the hidden states of RNN in one direction.
        :param word_embd_weights: A numpy array representing the pre-trained embeddings for words.
        :param word_embd_file_path: The file that contains the word embeddings.
        :param char_embd_weights: A numpy array representing the pre-trained embeddings for characters.
        :param char_embd_file_path: The file that contains the character embeddings.
        :param word_embd_trainable: Whether the word embedding layer is trainable.
        :param char_embd_trainable: Whether the character embedding layer is trainable.
        :param char_hidden_layer_type: The type of the recurrent layer, 'lstm' or 'gru'.
        :param word_mask_zero: Whether enable the mask for words.
        :param char_mask_zero: Whether enable the mask for characters.

        :return inputs, embd_layer: The keras layer.
        """
        if word_embd_file_path is not None:
            word_embd_weights = get_embedding_weights_from_file(word_dict=self.get_word_dict(),
                                                                file_path=word_embd_file_path,
                                                                ignore_case=self.word_ignore_case)
        if char_embd_file_path is not None:
            char_embd_weights = get_embedding_weights_from_file(word_dict=self.get_char_dict(),
                                                                file_path=char_embd_file_path,
                                                                ignore_case=self.char_ignore_case)
        return get_embedding_layer(word_dict_len=len(self.get_word_dict()),
                                   char_dict_len=len(self.get_char_dict()),
                                   max_word_len=self.max_word_len,
                                   word_embd_dim=word_embd_dim,
                                   char_embd_dim=char_embd_dim,
                                   char_hidden_dim=char_hidden_dim,
                                   char_hidden_layer_type=char_hidden_layer_type,
                                   word_embd_weights=word_embd_weights,
                                   char_embd_weights=char_embd_weights,
                                   word_embd_trainable=word_embd_trainable,
                                   char_embd_trainable=char_embd_trainable,
                                   word_mask_zero=word_mask_zero,
                                   char_mask_zero=char_mask_zero)


Instruction:
Can you implement a function in Python 3 that
converts sentences to desired input tensors.

Response:
def get_batch_input(self, sentences):
        """Convert sentences to desired input tensors.

        :param sentences: A list of lists representing the input sentences.

        :return word_embd_input, char_embd_input: The desired inputs.
        """
        return get_batch_input(sentences,
                               max_word_len=self.max_word_len,
                               word_dict=self.get_word_dict(),
                               char_dict=self.get_char_dict(),
                               word_ignore_case=self.word_ignore_case,
                               char_ignore_case=self.char_ignore_case)


Instruction:
Create a Python 3 function for
converting a list of sentences to a list of input tensors.

Response:
def get_batch_input(sentences,
                    max_word_len,
                    word_dict,
                    char_dict,
                    word_unknown=1,
                    char_unknown=1,
                    word_ignore_case=False,
                    char_ignore_case=False):
    """Convert sentences to desired input tensors.

    :param sentences: A list of lists representing the input sentences.
    :param max_word_len: The maximum allowed length of word.
    :param word_dict: Map a word to an integer. (0 and 1 should be preserved)
    :param char_dict: Map a character to an integer. (0 and 1 should be preserved)
    :param word_unknown: An integer representing the unknown word.
    :param char_unknown: An integer representing the unknown character.
    :param word_ignore_case: Word will be transformed to lower case before mapping.
    :param char_ignore_case: Character will be transformed to lower case before mapping.

    :return word_embd_input, char_embd_input: The desired inputs.
    """
    sentence_num = len(sentences)

    max_sentence_len = max(map(len, sentences))

    word_embd_input = [[0] * max_sentence_len for _ in range(sentence_num)]
    char_embd_input = [[[0] * max_word_len for _ in range(max_sentence_len)] for _ in range(sentence_num)]

    for sentence_index, sentence in enumerate(sentences):
        for word_index, word in enumerate(sentence):
            if word_ignore_case:
                word_key = word.lower()
            else:
                word_key = word
            word_embd_input[sentence_index][word_index] = word_dict.get(word_key, word_unknown)
            for char_index, char in enumerate(word):
                if char_index >= max_word_len:
                    break
                if char_ignore_case:
                    char = char.lower()
                char_embd_input[sentence_index][word_index][char_index] = char_dict.get(char, char_unknown)

    return [numpy.asarray(word_embd_input), numpy.asarray(char_embd_input)]


Instruction:
Can you implement a function in Python 3 that
gets the merged embedding layer.

Response:
def get_embedding_layer(word_dict_len,
                        char_dict_len,
                        max_word_len,
                        word_embd_dim=300,
                        char_embd_dim=30,
                        char_hidden_dim=150,
                        char_hidden_layer_type='lstm',
                        word_embd_weights=None,
                        char_embd_weights=None,
                        word_embd_trainable=None,
                        char_embd_trainable=None,
                        word_mask_zero=True,
                        char_mask_zero=True):
    """Get the merged embedding layer.

    :param word_dict_len: The number of words in the dictionary including the ones mapped to 0 or 1.
    :param char_dict_len: The number of characters in the dictionary including the ones mapped to 0 or 1.
    :param max_word_len: The maximum allowed length of word.
    :param word_embd_dim: The dimensions of the word embedding.
    :param char_embd_dim: The dimensions of the character embedding
    :param char_hidden_dim: The dimensions of the hidden states of RNN in one direction.
    :param word_embd_weights: A numpy array representing the pre-trained embeddings for words.
    :param char_embd_weights: A numpy array representing the pre-trained embeddings for characters.
    :param word_embd_trainable: Whether the word embedding layer is trainable.
    :param char_embd_trainable: Whether the character embedding layer is trainable.
    :param char_hidden_layer_type: The type of the recurrent layer, 'lstm' or 'gru'.
    :param word_mask_zero: Whether enable the mask for words.
    :param char_mask_zero: Whether enable the mask for characters.

    :return inputs, embd_layer: The keras layer.
    """
    if word_embd_weights is not None:
        word_embd_weights = [word_embd_weights]
    if word_embd_trainable is None:
        word_embd_trainable = word_embd_weights is None

    if char_embd_weights is not None:
        char_embd_weights = [char_embd_weights]
    if char_embd_trainable is None:
        char_embd_trainable = char_embd_weights is None

    word_input_layer = keras.layers.Input(
        shape=(None,),
        name='Input_Word',
    )
    char_input_layer = keras.layers.Input(
        shape=(None, max_word_len),
        name='Input_Char',
    )

    word_embd_layer = keras.layers.Embedding(
        input_dim=word_dict_len,
        output_dim=word_embd_dim,
        mask_zero=word_mask_zero,
        weights=word_embd_weights,
        trainable=word_embd_trainable,
        name='Embedding_Word',
    )(word_input_layer)
    char_embd_layer = keras.layers.Embedding(
        input_dim=char_dict_len,
        output_dim=char_embd_dim,
        mask_zero=char_mask_zero,
        weights=char_embd_weights,
        trainable=char_embd_trainable,
        name='Embedding_Char_Pre',
    )(char_input_layer)
    if char_hidden_layer_type == 'lstm':
        char_hidden_layer = keras.layers.Bidirectional(
            keras.layers.LSTM(
                units=char_hidden_dim,
                input_shape=(max_word_len, char_dict_len),
                return_sequences=False,
                return_state=False,
            ),
            name='Bi-LSTM_Char',
        )
    elif char_hidden_layer_type == 'gru':
        char_hidden_layer = keras.layers.Bidirectional(
            keras.layers.GRU(
                units=char_hidden_dim,
                input_shape=(max_word_len, char_dict_len),
                return_sequences=False,
                return_state=False,
            ),
            name='Bi-GRU_Char',
        )
    elif char_hidden_layer_type == 'cnn':
        char_hidden_layer = [
            MaskedConv1D(
                filters=max(1, char_hidden_dim // 5),
                kernel_size=3,
                activation='relu',
            ),
            MaskedFlatten(),
            keras.layers.Dense(
                units=char_hidden_dim,
                name='Dense_Char',
            ),
        ]
    elif isinstance(char_hidden_layer_type, list) or isinstance(char_hidden_layer_type, keras.layers.Layer):
        char_hidden_layer = char_hidden_layer_type
    else:
        raise NotImplementedError('Unknown character hidden layer type: %s' % char_hidden_layer_type)
    if not isinstance(char_hidden_layer, list):
        char_hidden_layer = [char_hidden_layer]
    for i, layer in enumerate(char_hidden_layer):
        if i == len(char_hidden_layer) - 1:
            name = 'Embedding_Char'
        else:
            name = 'Embedding_Char_Pre_%d' % (i + 1)
        char_embd_layer = keras.layers.TimeDistributed(layer=layer, name=name)(char_embd_layer)
    embd_layer = keras.layers.Concatenate(
        name='Embedding',
    )([word_embd_layer, char_embd_layer])
    return [word_input_layer, char_input_layer], embd_layer


Instruction:
Create a Python 3 function to
return a generator that returns the word and character dictionaries for a single word and a single character.

Response:
def get_dicts_generator(word_min_freq=4,
                        char_min_freq=2,
                        word_ignore_case=False,
                        char_ignore_case=False):
    """Get word and character dictionaries from sentences.

    :param word_min_freq: The minimum frequency of a word.
    :param char_min_freq: The minimum frequency of a character.
    :param word_ignore_case: Word will be transformed to lower case before saving to dictionary.
    :param char_ignore_case: Character will be transformed to lower case before saving to dictionary.
    :return gen: A closure that accepts sentences and returns the dictionaries.
    """
    word_count, char_count = {}, {}

    def get_dicts(sentence=None,
                  return_dict=False):
        """Update and return dictionaries for each sentence.

        :param sentence: A list of strings representing the sentence.
        :param return_dict: Returns the dictionaries if it is True.
        :return word_dict, char_dict, max_word_len:
        """
        if sentence is not None:
            for word in sentence:
                if not word:
                    continue
                if word_ignore_case:
                    word_key = word.lower()
                else:
                    word_key = word
                word_count[word_key] = word_count.get(word_key, 0) + 1
                for char in word:
                    if char_ignore_case:
                        char_key = char.lower()
                    else:
                        char_key = char
                    char_count[char_key] = char_count.get(char_key, 0) + 1
        if not return_dict:
            return None
        word_dict, char_dict = {'': 0, '<UNK>': 1}, {'': 0, '<UNK>': 1}
        max_word_len = 0
        for word, count in word_count.items():
            if count >= word_min_freq:
                word_dict[word] = len(word_dict)
                max_word_len = max(max_word_len, len(word))
        for char, count in char_count.items():
            if count >= char_min_freq:
                char_dict[char] = len(char_dict)
        return word_dict, char_dict, max_word_len

    return get_dicts


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_word_list_eng(text):
    words, index = [''], 0
    while index < len(text):
        while index < len(text) and ('a' <= text[index] <= 'z' or 'A' <= text[index] <= 'Z'):
            words[-1] += text[index]
            index += 1
        if words[-1]:
            words.append('')
        while index < len(text) and not ('a' <= text[index] <= 'z' or 'A' <= text[index] <= 'Z'):
            if text[index] != ' ':
                words[-1] += text[index]
            index += 1
        if words[-1]:
            words.append('')
    if not words[-1]:
        words.pop()
    return words

Response: A naive function that extracts English words from raw text.


Instruction:
How would you code a function in Python 3 to
load pre - trained embeddings from a text file.

Response:
def get_embedding_weights_from_file(word_dict, file_path, ignore_case=False):
    """Load pre-trained embeddings from a text file.

    Each line in the file should look like this:
        word feature_dim_1 feature_dim_2 ... feature_dim_n

    The `feature_dim_i` should be a floating point number.

    :param word_dict: A dict that maps words to indice.
    :param file_path: The location of the text file containing the pre-trained embeddings.
    :param ignore_case: Whether ignoring the case of the words.

    :return weights: A numpy array.
    """
    pre_trained = {}
    with codecs.open(file_path, 'r', 'utf8') as reader:
        for line in reader:
            line = line.strip()
            if not line:
                continue
            parts = line.split()
            if ignore_case:
                parts[0] = parts[0].lower()
            pre_trained[parts[0]] = list(map(float, parts[1:]))
    embd_dim = len(next(iter(pre_trained.values())))
    weights = [[0.0] * embd_dim for _ in range(max(word_dict.values()) + 1)]
    for word, index in word_dict.items():
        if not word:
            continue
        if ignore_case:
            word = word.lower()
        if word in pre_trained:
            weights[index] = pre_trained[word]
        else:
            weights[index] = numpy.random.random((embd_dim,)).tolist()
    return numpy.asarray(weights)


Instruction:
Can you write a function in Python 3 where it
returns the backend by name raises KeyError if no backend exists with the given name

Response:
def get_backend(name):
    """Returns the backend by name or raises KeyError"""

    for backend in _BACKENDS:
        if backend.NAME == name:
            return backend
    raise KeyError("Backend %r not available" % name)


Instruction:
Write a Python 3 script to
set a prefered ffi backend.

Response:
def set_backend(name=None):
    """Set a prefered ffi backend (cffi, ctypes).

    set_backend() -- default
    set_backend("cffi") -- cffi first, others as fallback
    set_backend("ctypes") -- ctypes first, others as fallback
    """

    possible = list(_BACKENDS)
    if name is None:
        names = []
    else:
        names = name.split(",")

    for name in reversed(names):
        for backend in list(possible):
            if backend.NAME == name:
                possible.remove(backend)
                possible.insert(0, backend)
                break
        else:
            raise LookupError("Unkown backend: %r" % name)

    # only add null as fallback it explicitly specified
    if "null" not in names:
        possible = [b for b in possible if b.NAME != "null"]

    _ACTIVE_BACKENDS[:] = possible


Instruction:
Write a Python 3 function that can
print debug information for various public objects like methods functions constructors etc.

Response:
def pprint(obj, file_=None):
    """Prints debug information for various public objects like methods,
    functions, constructors etc.
    """

    if file_ is None:
        file_ = sys.stdout

    # functions, methods
    if callable(obj) and hasattr(obj, "_code"):
        obj._code.pprint(file_)
        return

    # classes
    if isinstance(obj, type) and hasattr(obj, "_constructors"):
        constructors = obj._constructors
        for names, func in sorted(constructors.items()):
            func._code.pprint(file_)
        return

    raise TypeError("unkown type")


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

    type_ = info.get_type()

    cls = get_field_class(type_)

    field = cls(info, type_, None)
    field.setup()
    return field.py_type

Response: A field python type


Instruction:
Can you create a Python 3 function that
returns a new Color object from red green and blue values from 0. 0 to 1. 0.

Response:
def from_floats(red, green, blue):
        """Return a new Color object from red/green/blue values from 0.0 to 1.0."""

        return Color(int(red * Color.MAX_VALUE),
                     int(green * Color.MAX_VALUE),
                     int(blue * Color.MAX_VALUE))


Instruction:
Make a summary of the following Python 3 code
def _construct_target_list(targets):
    target_entries = []
    for entry in targets:
        if not isinstance(entry, Gtk.TargetEntry):
            entry = Gtk.TargetEntry.new(*entry)
        target_entries.append(entry)
    return target_entries

Response: Construct a list of TargetEntry items from a list of tuples.


Instruction:
Given the following Python 3 function, write the documentation
def child_get_property(self, child, property_name, value=None):

        if value is None:
            prop = self.find_child_property(property_name)
            if prop is None:
                raise ValueError('Class "%s" does not contain child property "%s"' %
                                 (self, property_name))
            value = GObject.Value(prop.value_type)

        Gtk.Container.child_get_property(self, child, property_name, value)
        return value.get_value()

Response: get_property - Gets the value of a child property


Instruction:
Write a Python 3 script to
return a list of child property values for the given names.

Response:
def child_get(self, child, *prop_names):
        """Returns a list of child property values for the given names."""

        return [self.child_get_property(child, name) for name in prop_names]


Instruction:
Can you generate the documentation for the following Python 3 function
def child_set(self, child, **kwargs):

        for name, value in kwargs.items():
            name = name.replace('_', '-')
            self.child_set_property(child, name, value)

Response: Set a child property on the given child to key - value pairs.


Instruction:
Implement a function in Python 3 to
insert text into the contents of the the widget at the specified position.

Response:
def insert_text(self, text, position):
        """insert_text(self, text, position)

        :param new_text:
            the text to append
        :type new_text: :obj:`str`

        :param position:
            location of the position text will be inserted at
        :type position: :obj:`int`

        :returns:
            location of the position text will be inserted at
        :rtype: :obj:`int`

        Inserts `new_text` into the contents of the
        widget, at position `position`.

        Note that the position is in characters, not in bytes.
        """

        return super(Editable, self).insert_text(text, -1, position)


Instruction:
Explain what the following Python 3 code does
def add_actions(self, entries, user_data=None):
        try:
            iter(entries)
        except (TypeError):
            raise TypeError('entries must be iterable')

        def _process_action(name, stock_id=None, label=None, accelerator=None, tooltip=None, callback=None):
            action = Action(name=name, label=label, tooltip=tooltip, stock_id=stock_id)
            if callback is not None:
                if user_data is None:
                    action.connect('activate', callback)
                else:
                    action.connect('activate', callback, user_data)

            self.add_action_with_accel(action, accelerator)

        for e in entries:
            # using inner function above since entries can leave out optional arguments
            _process_action(*e)

Response: This method creates a list of gtk. Action objects based on the information in entries and adds them to the action group.


Instruction:
How would you explain what the following Python 3 function does
def add_ui_from_string(self, buffer, length=-1):

        return Gtk.UIManager.add_ui_from_string(self, buffer, length)

Response: Add a UI from a string.


Instruction:
How would you explain what the following Python 3 function does
def add_objects_from_string(self, buffer, object_ids):

        length = -1
        return Gtk.Builder.add_objects_from_string(self, buffer, length, object_ids)

Response: add_objects_from_string - Adds objects from a string to the tree


Instruction:
Explain what the following Python 3 code does
def create_tag(self, tag_name=None, **properties):

        tag = Gtk.TextTag(name=tag_name, **properties)
        self._get_or_create_tag_table().add(tag)
        return tag

Response: Creates a new tag and adds it to the tag table of the TextBuffer.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_text(self, text, length=-1):

        Gtk.TextBuffer.set_text(self, text, length)

Response: set text to be displayed in the log


Instruction:
Write a Python 3 script to
insert text into the buffer

Response:
def insert(self, iter, text, length=-1):
        """insert(iter, text, length=-1)

        {{ all }}
        """

        Gtk.TextBuffer.insert(self, iter, text, length)


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

        path = self._coerce_path(path)
        success, aiter = super(TreeModel, self).get_iter(path)
        if not success:
            raise ValueError("invalid tree path '%s'" % path)
        return aiter

Response: Returns an iterator pointing to the given path.


Instruction:
Create a Python 3 function to
return an iterator pointing to the next node following iter.

Response:
def iter_next(self, iter):
        """
        :param iter: the :obj:`Gtk.TreeIter`-struct
        :type iter: :obj:`Gtk.TreeIter`

        :returns: a :obj:`Gtk.TreeIter` or :obj:`None`
        :rtype: :obj:`Gtk.TreeIter` or :obj:`None`

        Returns an iterator pointing to the node following `iter` at the
        current level.

        If there is no next `iter`, :obj:`None` is returned.
        """

        next_iter = iter.copy()
        success = super(TreeModel, self).iter_next(next_iter)
        if success:
            return next_iter


Instruction:
Write a Python 3 script to
return an iterator pointing to the previous node at the current level.

Response:
def iter_previous(self, iter):
        """
        :param iter: the :obj:`Gtk.TreeIter`-struct
        :type iter: :obj:`Gtk.TreeIter`

        :returns: a :obj:`Gtk.TreeIter` or :obj:`None`
        :rtype: :obj:`Gtk.TreeIter` or :obj:`None`

        Returns an iterator pointing to the previous node at the current level.

        If there is no previous `iter`, :obj:`None` is returned.
        """

        prev_iter = iter.copy()
        success = super(TreeModel, self).iter_previous(prev_iter)
        if success:
            return prev_iter


Instruction:
Here you have a function in Python 3, explain what it does
def set_row(self, treeiter, row):

        converted_row, columns = self._convert_row(row)
        for column in columns:
            value = row[column]
            if value is None:
                continue  # None means skip this row

            self.set_value(treeiter, column, value)

Response: Sets the value of the item in the treestore from a list of values.


Instruction:
Can you implement a function in Python 3 that
converts value to a GObject. Value of the expected type

Response:
def _convert_value(self, column, value):
        '''Convert value to a GObject.Value of the expected type'''

        if isinstance(value, GObject.Value):
            return value
        return GObject.Value(self.get_column_type(column), value)


Instruction:
Write a Python 3 script for
returning a tuple of all values in the tree store for the given treeiter and the given columns.

Response:
def get(self, treeiter, *columns):
        """
        :param treeiter: the :obj:`Gtk.TreeIter`
        :type treeiter: :obj:`Gtk.TreeIter`

        :param \\*columns: a list of column indices to fetch
        :type columns: (:obj:`int`)

        Returns a tuple of all values specified by their indices in `columns`
        in the order the indices are contained in `columns`

        Also see :obj:`Gtk.TreeStore.get_value`\\()
        """

        n_columns = self.get_n_columns()

        values = []
        for col in columns:
            if not isinstance(col, int):
                raise TypeError("column numbers must be ints")

            if col < 0 or col >= n_columns:
                raise ValueError("column number is out of range")

            values.append(self.get_value(treeiter, col))

        return tuple(values)


Instruction:
Write a Python 3 function for
appending - Appends a new entry to the list store

Response:
def append(self, row=None):
        """append(row=None)

        :param row: a list of values to apply to the newly append row or :obj:`None`
        :type row: [:obj:`object`] or :obj:`None`

        :returns: :obj:`Gtk.TreeIter` of the appended row
        :rtype: :obj:`Gtk.TreeIter`

        If `row` is :obj:`None` the appended row will be empty and to fill in
        values you need to call :obj:`Gtk.ListStore.set`\\() or
        :obj:`Gtk.ListStore.set_value`\\().

        If `row` isn't :obj:`None` it has to be a list of values which will be
        used to fill the row .
        """

        if row:
            return self._do_insert(-1, row)
        # gtk_list_store_insert() does not know about the "position == -1"
        # case, so use append() here
        else:
            return Gtk.ListStore.append(self)


Instruction:
Write a Python 3 script to
insert a new row before a sibling.

Response:
def insert_before(self, sibling, row=None):
        """insert_before(sibling, row=None)

        :param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
        :type sibling: :obj:`Gtk.TreeIter` or :obj:`None`

        :param row: a list of values to apply to the newly inserted row or :obj:`None`
        :type row: [:obj:`object`] or :obj:`None`

        :returns: :obj:`Gtk.TreeIter` pointing to the new row
        :rtype: :obj:`Gtk.TreeIter`

        Inserts a new row before `sibling`. If `sibling` is :obj:`None`, then
        the row will be appended to the end of the list.

        The row will be empty if `row` is :obj:`None. To fill in values, you
        need to call :obj:`Gtk.ListStore.set`\\() or
        :obj:`Gtk.ListStore.set_value`\\().

        If `row` isn't :obj:`None` it has to be a list of values which will be
        used to fill the row.
        """

        treeiter = Gtk.ListStore.insert_before(self, sibling)

        if row is not None:
            self.set_row(treeiter, row)

        return treeiter


Instruction:
How would you implement a function in Python 3 that
inserts a new row after a sibling.

Response:
def insert_after(self, sibling, row=None):
        """insert_after(sibling, row=None)

        :param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None`
        :type sibling: :obj:`Gtk.TreeIter` or :obj:`None`

        :param row: a list of values to apply to the newly inserted row or :obj:`None`
        :type row: [:obj:`object`] or :obj:`None`

        :returns: :obj:`Gtk.TreeIter` pointing to the new row
        :rtype: :obj:`Gtk.TreeIter`

        Inserts a new row after `sibling`. If `sibling` is :obj:`None`, then
        the row will be prepended to the beginning of the list.

        The row will be empty if `row` is :obj:`None. To fill in values, you
        need to call :obj:`Gtk.ListStore.set`\\() or
        :obj:`Gtk.ListStore.set_value`\\().

        If `row` isn't :obj:`None` it has to be a list of values which will be
        used to fill the row.
        """

        treeiter = Gtk.ListStore.insert_after(self, sibling)

        if row is not None:
            self.set_row(treeiter, row)

        return treeiter


Instruction:
Create a Python 3 function to
set the value of the a column in the treeiter.

Response:
def set_value(self, treeiter, column, value):
        """
        {{ all }}

        `value` can also be a Python value and will be converted to a
        :obj:`GObject.Value` using the corresponding column type (See
        :obj:`Gtk.ListStore.set_column_types`\\()).
        """

        value = self._convert_value(column, value)
        Gtk.ListStore.set_value(self, treeiter, column, value)


Instruction:
Create a Python 3 function to
return the next TreeModelRow

Response:
def get_next(self):
        """Returns the next :obj:`Gtk.TreeModelRow` or None"""

        next_iter = self.model.iter_next(self.iter)
        if next_iter:
            return TreeModelRow(self.model, next_iter)


Instruction:
Create a Python 3 function for
returning the previous TreeModelRow

Response:
def get_previous(self):
        """Returns the previous :obj:`Gtk.TreeModelRow` or None"""

        prev_iter = self.model.iter_previous(self.iter)
        if prev_iter:
            return TreeModelRow(self.model, prev_iter)


Instruction:
Create a Python 3 function for
returning the parent TreeModelRow or None

Response:
def get_parent(self):
        """Returns the parent :obj:`Gtk.TreeModelRow` or htis row or None"""

        parent_iter = self.model.iter_parent(self.iter)
        if parent_iter:
            return TreeModelRow(self.model, parent_iter)


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

        child_iter = self.model.iter_children(self.iter)
        return TreeModelRowIter(self.model, child_iter)

Response: Returns a : obj : Gtk. TreeModelRowIter for the row s children


Instruction:
Can you generate a brief explanation for the following Python 3 code
def insert(self, parent, position, row=None):

        return self._do_insert(parent, position, row)

Response: Insert a new entry into the tree.


Instruction:
Given the following Python 3 function, write the documentation
def insert_before(self, parent, sibling, row=None):

        treeiter = Gtk.TreeStore.insert_before(self, parent, sibling)

        if row is not None:
            self.set_row(treeiter, row)

        return treeiter

Response: Insert a new row before a sibling.


Instruction:
How would you explain what the following Python 3 function does
def set_value(self, treeiter, column, value):

        value = self._convert_value(column, value)
        Gtk.TreeStore.set_value(self, treeiter, column, value)

Response: Set the value of the key - value pair in the treestore.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def insert_column_with_attributes(self, position, title, cell, **kwargs):

        column = TreeViewColumn()
        column.set_title(title)
        column.pack_start(cell, False)
        self.insert_column(column, position)
        column.set_attributes(cell, **kwargs)

Response: Insert a new column with the given title and cell attributes.


Instruction:
Can you implement a function in Python 3 that
sets the attributes of the cell layout.

Response:
def set_attributes(self, cell_renderer, **attributes):
        """
        :param cell_renderer: the :obj:`Gtk.CellRenderer` we're setting the attributes of
        :type cell_renderer: :obj:`Gtk.CellRenderer`

        {{ docs }}
        """

        Gtk.CellLayout.clear_attributes(self, cell_renderer)

        for (name, value) in attributes.items():
            Gtk.CellLayout.add_attribute(self, cell_renderer, name, value)


Instruction:
Write a Python 3 function for
returning the selected entry in the tree.

Response:
def get_selected(self):
        """
        :returns:
            :model: the :obj:`Gtk.TreeModel`
            :iter: The :obj:`Gtk.TreeIter` or :obj:`None`

        :rtype: (**model**: :obj:`Gtk.TreeModel`, **iter**: :obj:`Gtk.TreeIter` or :obj:`None`)

        {{ docs }}
        """

        success, model, aiter = super(TreeSelection, self).get_selected()
        if success:
            return (model, aiter)
        else:
            return (model, None)


Instruction:
Implement a Python 3 function for
setting the value of the child model

Response:
def set_value(self, iter, column, value):
        """Set the value of the child model"""

        # Delegate to child model
        iter = self.convert_iter_to_child_iter(iter)
        self.get_model().set_value(iter, column, value)


Instruction:
Here you have a function in Python 3, explain what it does
def get_foreign_module(namespace):

    if namespace not in _MODULES:
        try:
            module = importlib.import_module("." + namespace, __package__)
        except ImportError:
            module = None
        _MODULES[namespace] = module

    module = _MODULES.get(namespace)
    if module is None:
        raise ForeignError("Foreign %r structs not supported" % namespace)
    return module

Response: Returns the module or raises ForeignError


Instruction:
Make a summary of the following Python 3 code
def get_foreign_struct(namespace, name):

    get_foreign_module(namespace)

    try:
        return ForeignStruct.get(namespace, name)
    except KeyError:
        raise ForeignError("Foreign %s.%s not supported" % (namespace, name))

Response: Returns a ForeignStruct implementation or raises ForeignError


Instruction:
Make a summary of the following Python 3 code
def require_foreign(namespace, symbol=None):

    try:
        if symbol is None:
            get_foreign_module(namespace)
        else:
            get_foreign_struct(namespace, symbol)
    except ForeignError as e:
        raise ImportError(e)

Response: Raises ImportError if the specified foreign module isn t supported or the required dependencies aren t installed.


Instruction:
Make a summary of the following Python 3 code
def io_add_watch(*args, **kwargs):
    channel, priority, condition, func, user_data = _io_add_watch_get_args(*args, **kwargs)
    return GLib.io_add_watch(channel, priority, condition, func, *user_data)

Response: Wrapper for GLib. io_add_watch.


Instruction:
Create a Python 3 function to
wrap for GLib. child_watch_add.

Response:
def child_watch_add(*args, **kwargs):
    """child_watch_add(priority, pid, function, *data)"""
    priority, pid, function, data = _child_watch_add_get_args(*args, **kwargs)
    return GLib.child_watch_add(priority, pid, function, *data)


Instruction:
Create a Python 3 function to
create a GVariant object from given format and argument list.

Response:
def _create(self, format, args):
        """Create a GVariant object from given format and argument list.

        This method recursively calls itself for complex structures (arrays,
        dictionaries, boxed).

        Return a tuple (variant, rest_format, rest_args) with the generated
        GVariant, the remainder of the format string, and the remainder of the
        arguments.

        If args is None, then this won't actually consume any arguments, and
        just parse the format string and generate empty GVariant structures.
        This is required for creating empty dictionaries or arrays.
        """
        # leaves (simple types)
        constructor = self._LEAF_CONSTRUCTORS.get(format[0])
        if constructor:
            if args is not None:
                if not args:
                    raise TypeError('not enough arguments for GVariant format string')
                v = constructor(args[0])
                return (v, format[1:], args[1:])
            else:
                return (None, format[1:], None)

        if format[0] == '(':
            return self._create_tuple(format, args)

        if format.startswith('a{'):
            return self._create_dict(format, args)

        if format[0] == 'a':
            return self._create_array(format, args)

        raise NotImplementedError('cannot handle GVariant type ' + format)


Instruction:
Create a Python 3 function for
handling the case where the outermost type of format is a tuple.

Response:
def _create_tuple(self, format, args):
        """Handle the case where the outermost type of format is a tuple."""

        format = format[1:]  # eat the '('
        if args is None:
            # empty value: we need to call _create() to parse the subtype
            rest_format = format
            while rest_format:
                if rest_format.startswith(')'):
                    break
                rest_format = self._create(rest_format, None)[1]
            else:
                raise TypeError('tuple type string not closed with )')

            rest_format = rest_format[1:]  # eat the )
            return (None, rest_format, None)
        else:
            if not args or not isinstance(args[0], tuple):
                raise TypeError('expected tuple argument')

            builder = GLib.VariantBuilder.new(variant_type_from_string('r'))
            for i in range(len(args[0])):
                if format.startswith(')'):
                    raise TypeError('too many arguments for tuple signature')

                (v, format, _) = self._create(format, args[0][i:])
                builder.add_value(v)
            args = args[1:]
            if not format.startswith(')'):
                raise TypeError('tuple type string not closed with )')

            rest_format = format[1:]  # eat the )
            return (builder.end(), rest_format, args)


Instruction:
Create a Python 3 function to
handle the case where the outermost type of format is a dict.

Response:
def _create_dict(self, format, args):
        """Handle the case where the outermost type of format is a dict."""

        builder = None
        if args is None or not args[0]:
            # empty value: we need to call _create() to parse the subtype,
            # and specify the element type precisely
            rest_format = self._create(format[2:], None)[1]
            rest_format = self._create(rest_format, None)[1]
            if not rest_format.startswith('}'):
                raise TypeError('dictionary type string not closed with }')
            rest_format = rest_format[1:]  # eat the }
            element_type = format[:len(format) - len(rest_format)]
            builder = GLib.VariantBuilder.new(variant_type_from_string(element_type))
        else:
            builder = GLib.VariantBuilder.new(variant_type_from_string('a{?*}'))
            for k, v in args[0].items():
                (key_v, rest_format, _) = self._create(format[2:], [k])
                (val_v, rest_format, _) = self._create(rest_format, [v])

                if not rest_format.startswith('}'):
                    raise TypeError('dictionary type string not closed with }')
                rest_format = rest_format[1:]  # eat the }

                entry = GLib.VariantBuilder.new(variant_type_from_string('{?*}'))
                entry.add_value(key_v)
                entry.add_value(val_v)
                builder.add_value(entry.end())

        if args is not None:
            args = args[1:]
        return (builder.end(), rest_format, args)


Instruction:
Can you generate the documentation for the following Python 3 function
def _create_array(self, format, args):

        builder = None
        if args is None or not args[0]:
            # empty value: we need to call _create() to parse the subtype,
            # and specify the element type precisely
            rest_format = self._create(format[1:], None)[1]
            element_type = format[:len(format) - len(rest_format)]
            builder = GLib.VariantBuilder.new(variant_type_from_string(element_type))
        else:
            builder = GLib.VariantBuilder.new(variant_type_from_string('a*'))
            for i in range(len(args[0])):
                (v, rest_format, _) = self._create(format[1:], args[0][i:])
                builder.add_value(v)
        if args is not None:
            args = args[1:]
        return (builder.end(), rest_format, args)

Response: Handle the case where the outermost type of format is an array.


Instruction:
Write a Python 3 script for
decomposing a GVariant into a native Python object.

Response:
def unpack(self):
        """Decompose a GVariant into a native Python object."""

        LEAF_ACCESSORS = {
            'b': self.get_boolean,
            'y': self.get_byte,
            'n': self.get_int16,
            'q': self.get_uint16,
            'i': self.get_int32,
            'u': self.get_uint32,
            'x': self.get_int64,
            't': self.get_uint64,
            'h': self.get_handle,
            'd': self.get_double,
            's': self.get_string,
            'o': self.get_string,  # object path
            'g': self.get_string,  # signature
        }

        # simple values
        la = LEAF_ACCESSORS.get(self.get_type_string())
        if la:
            return la()

        # tuple
        if self.get_type_string().startswith('('):
            res = [self.get_child_value(i).unpack()
                   for i in range(self.n_children())]
            return tuple(res)

        # dictionary
        if self.get_type_string().startswith('a{'):
            res = {}
            for i in range(self.n_children()):
                v = self.get_child_value(i)
                res[v.get_child_value(0).unpack()] = v.get_child_value(1).unpack()
            return res

        # array
        if self.get_type_string().startswith('a'):
            return [self.get_child_value(i).unpack()
                    for i in range(self.n_children())]

        # variant (just unbox transparently)
        if self.get_type_string().startswith('v'):
            return self.get_variant().unpack()

        # maybe
        if self.get_type_string().startswith('m'):
            m = self.get_maybe()
            return m.unpack() if m else None

        raise NotImplementedError('unsupported GVariant type ' + self.get_type_string())


Instruction:
How would you implement a function in Python 3 that
splits a signature into a list of elements.

Response:
def split_signature(klass, signature):
        """Return a list of the element signatures of the topmost signature tuple.

        If the signature is not a tuple, it returns one element with the entire
        signature. If the signature is an empty tuple, the result is [].

        This is useful for e. g. iterating over method parameters which are
        passed as a single Variant.
        """
        if signature == '()':
            return []

        if not signature.startswith('('):
            return [signature]

        result = []
        head = ''
        tail = signature[1:-1]  # eat the surrounding ()
        while tail:
            c = tail[0]
            head += c
            tail = tail[1:]

            if c in ('m', 'a'):
                # prefixes, keep collecting
                continue
            if c in ('(', '{'):
                # consume until corresponding )/}
                level = 1
                up = c
                if up == '(':
                    down = ')'
                else:
                    down = '}'
                while level > 0:
                    c = tail[0]
                    head += c
                    tail = tail[1:]
                    if c == up:
                        level += 1
                    elif c == down:
                        level -= 1

            # otherwise we have a simple type
            result.append(head)
            head = ''

        return result


Instruction:
Can you generate a brief explanation for the following Python 3 code
def typeinfo_to_ctypes(info, return_value=False):

    tag = info.tag.value
    ptr = info.is_pointer

    mapping = {
        GITypeTag.BOOLEAN: gboolean,
        GITypeTag.INT8: gint8,
        GITypeTag.UINT8: guint8,
        GITypeTag.INT16: gint16,
        GITypeTag.UINT16: guint16,
        GITypeTag.INT32: gint32,
        GITypeTag.UINT32: guint32,
        GITypeTag.INT64: gint64,
        GITypeTag.UINT64: guint64,
        GITypeTag.FLOAT: gfloat,
        GITypeTag.DOUBLE: gdouble,
        GITypeTag.VOID: None,
        GITypeTag.GTYPE: GType,
        GITypeTag.UNICHAR: gunichar,
    }

    if ptr:
        if tag == GITypeTag.INTERFACE:
            return gpointer
        elif tag in (GITypeTag.UTF8, GITypeTag.FILENAME):
            if return_value:
                # ctypes does auto conversion to str and gives us no chance
                # to free the pointer if transfer=everything
                return gpointer
            else:
                return gchar_p
        elif tag == GITypeTag.ARRAY:
            return gpointer
        elif tag == GITypeTag.ERROR:
            return GErrorPtr
        elif tag == GITypeTag.GLIST:
            return GListPtr
        elif tag == GITypeTag.GSLIST:
            return GSListPtr
        else:
            if tag in mapping:
                return ctypes.POINTER(mapping[tag])
    else:
        if tag == GITypeTag.INTERFACE:
            iface = info.get_interface()
            iface_type = iface.type.value
            if iface_type == GIInfoType.ENUM:
                return guint32
            elif iface_type == GIInfoType.OBJECT:
                return gpointer
            elif iface_type == GIInfoType.STRUCT:
                return gpointer
            elif iface_type == GIInfoType.UNION:
                return gpointer
            elif iface_type == GIInfoType.FLAGS:
                return guint
            elif iface_type == GIInfoType.CALLBACK:
                return GCallback

            raise NotImplementedError(
                "Could not convert interface: %r to ctypes type" % iface.type)
        else:
            if tag in mapping:
                return mapping[tag]

    raise NotImplementedError("Could not convert %r to ctypes type" % info.tag)

Response: Maps a GITypeInfo object to a ctypes type.


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

        return self.parse("""
raise $_.TypeError('Can\\'t convert %(type_name)s to pointer: %%r' %% $in_)
""" % {"type_name": type(self).__name__}, in_=name)["in_"]

Response: Returns a pointer containing the value.


Instruction:
How would you code a function in Python 3 to
take bytes and returns a GITypelib or raises GIError

Response:
def new_from_memory(cls, data):
        """Takes bytes and returns a GITypelib, or raises GIError"""

        size = len(data)
        copy = g_memdup(data, size)
        ptr = cast(copy, POINTER(guint8))
        try:
            with gerror(GIError) as error:
                return GITypelib._new_from_memory(ptr, size, error)
        except GIError:
            free(copy)
            raise


Instruction:
Here you have a function in Python 3, explain what it does
def _get_type(cls, ptr):

        # fall back to the base class if unknown
        return cls.__types.get(lib.g_base_info_get_type(ptr), cls)

Response: Get the subtype class for a pointer


Instruction:
How would you explain what the following Python 3 function does
def add_method(info, target_cls, virtual=False, dont_replace=False):

    # escape before prefixing, like pygobject
    name = escape_identifier(info.name)
    if virtual:
        name = "do_" + name
        attr = VirtualMethodAttribute(info, target_cls, name)
    else:
        attr = MethodAttribute(info, target_cls, name)

    if dont_replace and hasattr(target_cls, name):
        return

    setattr(target_cls, name, attr)

Response: Add a method to the target class.


Instruction:
Given the following Python 3 function, write the documentation
def InterfaceAttribute(iface_info):

    # Create a new class
    cls = type(iface_info.name, (InterfaceBase,), dict(_Interface.__dict__))
    cls.__module__ = iface_info.namespace

    # GType
    cls.__gtype__ = PGType(iface_info.g_type)

    # Properties
    cls.props = PropertyAttribute(iface_info)

    # Signals
    cls.signals = SignalsAttribute(iface_info)

    # Add constants
    for constant in iface_info.get_constants():
        constant_name = constant.name
        attr = ConstantAttribute(constant)
        setattr(cls, constant_name, attr)

    # Add methods
    for method_info in iface_info.get_methods():
        add_method(method_info, cls)

    # VFuncs
    for vfunc_info in iface_info.get_vfuncs():
        add_method(vfunc_info, cls, virtual=True)

    cls._sigs = {}

    is_info = iface_info.get_iface_struct()
    if is_info:
        iface_struct = import_attribute(is_info.namespace, is_info.name)
    else:
        iface_struct = None

    def get_iface_struct(cls):
        if not iface_struct:
            return None

        ptr = cls.__gtype__._type.default_interface_ref()
        if not ptr:
            return None
        return iface_struct._from_pointer(addressof(ptr.contents))

    setattr(cls, "_get_iface_struct", classmethod(get_iface_struct))

    return cls

Response: Creates a new GInterface class based on the given InterfaceInfo.


Instruction:
Here you have a function in Python 3, explain what it does
def new_class_from_gtype(gtype):

    if gtype.is_a(PGType.from_name("GObject")):
        parent = gtype.parent.pytype
        if parent is None or parent == PGType.from_name("void"):
            return
        interfaces = [i.pytype for i in gtype.interfaces]
        bases = tuple([parent] + interfaces)

        cls = type(gtype.name, bases, dict())
        cls.__gtype__ = gtype

        return cls
    elif gtype.is_a(PGType.from_name("GEnum")):
        from pgi.enum import GEnumBase
        return GEnumBase

Response: Create a new class from a gtype.


Instruction:
Can you create a Python 3 function that
creates a new object class.

Response:
def ObjectAttribute(obj_info):
    """Creates a GObject class.

    It inherits from the base class and all interfaces it implements.
    """

    if obj_info.name == "Object" and obj_info.namespace == "GObject":
        cls = Object
    else:
        # Get the parent class
        parent_obj = obj_info.get_parent()
        if parent_obj:
            attr = import_attribute(parent_obj.namespace, parent_obj.name)
            bases = (attr,)
        else:
            bases = (object,)

        # Get all object interfaces
        ifaces = []
        for interface in obj_info.get_interfaces():
            attr = import_attribute(interface.namespace, interface.name)
            # only add interfaces if the base classes don't have it
            for base in bases:
                if attr in base.__mro__:
                    break
            else:
                ifaces.append(attr)

        # Combine them to a base class list
        if ifaces:
            bases = tuple(list(bases) + ifaces)

        # Create a new class
        cls = type(obj_info.name, bases, dict())

    cls.__module__ = obj_info.namespace

    # Set root to unowned= False and InitiallyUnowned=True
    if obj_info.namespace == "GObject":
        if obj_info.name == "InitiallyUnowned":
            cls._unowned = True
        elif obj_info.name == "Object":
            cls._unowned = False

    # GType
    cls.__gtype__ = PGType(obj_info.g_type)

    if not obj_info.fundamental:
        # Constructor cache
        cls._constructors = {}

        # Properties
        setattr(cls, PROPS_NAME, PropertyAttribute(obj_info))

        # Signals
        cls.signals = SignalsAttribute(obj_info)

        # Signals
        cls.__sigs__ = {}
        for sig_info in obj_info.get_signals():
            signal_name = sig_info.name
            cls.__sigs__[signal_name] = sig_info

    # Add constants
    for constant in obj_info.get_constants():
        constant_name = constant.name
        attr = ConstantAttribute(constant)
        setattr(cls, constant_name, attr)

    # Fields
    for field in obj_info.get_fields():
        field_name = escape_identifier(field.name)
        attr = FieldAttribute(field_name, field)
        setattr(cls, field_name, attr)

    # Add methods
    for method_info in obj_info.get_methods():
        # we implement most of the base object ourself
        add_method(method_info, cls, dont_replace=cls is Object)

    # VFuncs
    for vfunc_info in obj_info.get_vfuncs():
        add_method(vfunc_info, cls, virtual=True)

    cs_info = obj_info.get_class_struct()
    if cs_info:
        class_struct = import_attribute(cs_info.namespace, cs_info.name)
    else:
        class_struct = None

    # XXX ^ 2
    def get_class_struct(cls, type_=None):
        """Returns the class struct casted to the passed type"""

        if type_ is None:
            type_ = class_struct

        if type_ is None:
            return None

        ptr = cls.__gtype__._type.class_ref()
        return type_._from_pointer(ptr)

    setattr(cls, "_get_class_struct", classmethod(get_class_struct))

    return cls


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _generate_constructor(cls, names):

        cache = cls._constructors
        if names in cache:
            return cache[names]
        elif len(cache) > 3:
            cache.clear()

        func = generate_constructor(cls, names)
        cache[names] = func
        return func

Response: Generate a hopefully cache constructor


Instruction:
Here you have a function in Python 3, explain what it does
def set_property(self, name, value):

        if not hasattr(self.props, name):
            raise TypeError("Unknown property: %r" % name)
        setattr(self.props, name, value)

Response: Set a property of the current object.


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

        if not hasattr(self.props, name):
            raise TypeError("Unknown property: %r" % name)
        return getattr(self.props, name)

Response: Returns a property value.


Instruction:
Here you have a function in Python 3, explain what it does
def connect(self, detailed_signal, handler, *args):

        return self.__connect(0, detailed_signal, handler, *args)

Response: Connect a signal to a specific class.


Instruction:
Can you generate the documentation for the following Python 3 function
def connect_after(self, detailed_signal, handler, *args):

        flags = GConnectFlags.CONNECT_AFTER
        return self.__connect(flags, detailed_signal, handler, *args)

Response: Connect to the specified handler after the specified time period.


Instruction:
Create a Python 3 function to
make the Python instance take ownership of the GIBaseInfo. i. e. the Python instance unref the GIBaseInfo. i. e. the Python instance gets gced.

Response:
def _take_ownership(self):
        """Make the Python instance take ownership of the GIBaseInfo. i.e.
        unref if the python instance gets gc'ed.
        """

        if self:
            ptr = cast(self.value, GIBaseInfo)
            _UnrefFinalizer.track(self, ptr)
            self.__owns = True


Instruction:
How would you code a function in Python 3 to
cast a GIBaseInfo instance to the right sub type.

Response:
def _cast(cls, base_info, take_ownership=True):
        """Casts a GIBaseInfo instance to the right sub type.

        The original GIBaseInfo can't have ownership.
        Will take ownership.
        """

        type_value = base_info.type.value
        try:
            new_obj = cast(base_info, cls.__types[type_value])
        except KeyError:
            new_obj = base_info

        if take_ownership:
            assert not base_info.__owns
            new_obj._take_ownership()

        return new_obj


Instruction:
Given the following Python 3 function, write the documentation
def decode_return(codec="ascii"):

    def outer(f):
        def wrap(*args, **kwargs):
            res = f(*args, **kwargs)
            if res is not None:
                return res.decode(codec)
            return res
        return wrap
    return outer

Response: Decodes the return value of it isn t None


Instruction:
Can you implement a function in Python 3 that
takes a library name and calls find_library in case loading fails

Response:
def load_ctypes_library(name):
    """Takes a library name and calls find_library in case loading fails,
    since some girs don't include the real .so name.

    Raises OSError like LoadLibrary if loading fails.

    e.g. javascriptcoregtk-3.0 should be libjavascriptcoregtk-3.0.so on unix
    """

    try:
        return cdll.LoadLibrary(name)
    except OSError:
        name = find_library(name)
        if name is None:
            raise
        return cdll.LoadLibrary(name)


Instruction:
Create a Python 3 function to
escape partial C identifiers so they can be used as attributes and arguments

Response:
def escape_identifier(text, reg=KWD_RE):
    """Escape partial C identifiers so they can be used as
    attributes/arguments"""

    # see http://docs.python.org/reference/lexical_analysis.html#identifiers
    if not text:
        return "_"
    if text[0].isdigit():
        text = "_" + text
    return reg.sub(r"\1_", text)


Instruction:
Write a Python 3 function that can
cache the return value of a function without arguments

Response:
def cache_return(func):
    """Cache the return value of a function without arguments"""

    _cache = []

    def wrap():
        if not _cache:
            _cache.append(func())
        return _cache[0]
    return wrap


Instruction:
Write a Python 3 script to
return a struct or a list of names for a given name.

Response:
def lookup_name_fast(self, name):
        """Might return a struct"""

        if name in self.__names:
            return self.__names[name]

        count = self.__get_count_cached()
        lo = 0
        hi = count
        while lo < hi:
            mid = (lo + hi) // 2
            if self.__get_name_cached(mid) < name:
                lo = mid + 1
            else:
                hi = mid

        if lo != count and self.__get_name_cached(lo) == name:
            return self.__get_info_cached(lo)


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

        for index in xrange(self.__get_count_cached()):
            if self.__get_name_cached(index) == name:
                return self.__get_info_cached(index)

Response: Returns a struct if one exists


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

        try:
            info = self._get_by_name(self._source, name)
        except NotImplementedError:
            pass
        else:
            if info:
                return info
            return

        info = self.lookup_name_fast(name)
        if info:
            return info
        return self.lookup_name_slow(name)

Response: Returns a struct if one exists with the given name.


Instruction:
Explain what the following Python 3 code does
def _new_type(cls, args):

        fformat = ["%r" if f is None else "%s=%%r" % f for f in args]
        fformat = "(%s)" % ", ".join(fformat)

        class _ResultTuple(cls):
            __slots__ = ()
            _fformat = fformat
            if args:
                for i, a in enumerate(args):
                    if a is not None:
                        vars()[a] = property(itemgetter(i))
                del i, a

        return _ResultTuple

Response:
Creates a new class similar to namedtuple.

        Pass a list of field names or None for no field name.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def signal_list_names(type_):

    ids = signal_list_ids(type_)
    return tuple(GObjectModule.signal_name(i) for i in ids)

Response:
Returns a list of signal names for the given type
   .


Instruction:
Write a Python 3 script for
blocking the signal handler from being invoked until handler_unblock is called.

Response:
def signal_handler_block(obj, handler_id):
    """Blocks the signal handler from being invoked until
    handler_unblock() is called.

    :param GObject.Object obj:
        Object instance to block handlers for.
    :param int handler_id:
        Id of signal to block.
    :returns:
        A context manager which optionally can be used to
        automatically unblock the handler:

    .. code-block:: python

        with GObject.signal_handler_block(obj, id):
            pass
    """
    GObjectModule.signal_handler_block(obj, handler_id)
    return _HandlerBlockManager(obj, handler_id)


Instruction:
Can you tell what is the following Python 3 function doing
def signal_parse_name(detailed_signal, itype, force_detail_quark):
    res, signal_id, detail = GObjectModule.signal_parse_name(detailed_signal, itype,
                                                             force_detail_quark)
    if res:
        return signal_id, detail
    else:
        raise ValueError('%s: unknown signal name: %s' % (itype, detailed_signal))

Response: Parse a detailed signal name into a tuple of signal_id and detail.


Instruction:
Write a Python 3 script for
finding a library by name.

Response:
def find_library(name, cached=True, internal=True):
    """
        cached: Return a new instance
        internal: return a shared instance that's not the ctypes cached one
    """

    # a new one
    if not cached:
        return cdll.LoadLibrary(_so_mapping[name])

    # from the shared internal set or a new one
    if internal:
        if name not in _internal:
            _internal[name] = cdll.LoadLibrary(_so_mapping[name])
        return _internal[name]

    # a shared one
    return getattr(cdll, _so_mapping[name])


Instruction:
Write a Python 3 script for
tracking an object which needs destruction when it is garbage collected.

Response:
def track(cls, obj, ptr):
        """
        Track an object which needs destruction when it is garbage collected.
        """
        cls._objects.add(cls(obj, ptr))


Instruction:
Write a Python 3 script to
convert a D - BUS return variant into an appropriate return value

Response:
def _unpack_result(klass, result):
        '''Convert a D-BUS return variant into an appropriate return value'''

        result = result.unpack()

        # to be compatible with standard Python behaviour, unbox
        # single-element tuples and return None for empty result tuples
        if len(result) == 1:
            result = result[0]
        elif len(result) == 0:
            result = None

        return result


Instruction:
Explain what the following Python 3 code does
def list_properties(type):

    if isinstance(type, PGType):
        type = type.pytype

    from pgi.obj import Object, InterfaceBase

    if not issubclass(type, (Object, InterfaceBase)):
        raise TypeError("Must be a subclass of %s or %s" %
                        (Object.__name__, InterfaceBase.__name__))

    gparams = []
    for key in dir(type.props):
        if not key.startswith("_"):
            gparams.append(getattr(type.props, key))
    return gparams

Response: Returns a list of GParamSpecs for all properties of a given type.


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

    namespace = introspection_module.__name__.rsplit(".", 1)[-1]
    module_keys = [prefix + "." + namespace for prefix in const.PREFIX]

    # We use sys.modules so overrides can import from gi.repository
    # but restore everything at the end so this doesn't have any side effects
    for module_key in module_keys:
        has_old = module_key in sys.modules
        old_module = sys.modules.get(module_key)

    # Create a new sub type, so we can separate descriptors like
    # _DeprecatedAttribute for each namespace.
    proxy_type = type(namespace + "ProxyModule", (OverridesProxyModule, ), {})

    proxy = proxy_type(introspection_module)
    for module_key in module_keys:
        sys.modules[module_key] = proxy

    try:
        override_package_name = 'pgi.overrides.' + namespace

        # http://bugs.python.org/issue14710
        try:
            override_loader = get_loader(override_package_name)

        except AttributeError:
            override_loader = None

        # Avoid checking for an ImportError, an override might
        # depend on a missing module thus causing an ImportError
        if override_loader is None:
            return introspection_module

        override_mod = importlib.import_module(override_package_name)

    finally:
        for module_key in module_keys:
            del sys.modules[module_key]
            if has_old:
                sys.modules[module_key] = old_module

    override_all = []
    if hasattr(override_mod, "__all__"):
        override_all = override_mod.__all__

    for var in override_all:
        try:
            item = getattr(override_mod, var)
        except (AttributeError, TypeError):
            # Gedit puts a non-string in __all__, so catch TypeError here
            continue
        # make sure new classes have a proper __module__
        try:
            if item.__module__.split(".")[-1] == namespace:
                item.__module__ = namespace
        except AttributeError:
            pass
        setattr(proxy, var, item)

    # Replace deprecated module level attributes with a descriptor
    # which emits a warning when accessed.
    for attr, replacement in _deprecated_attrs.pop(namespace, []):
        try:
            value = getattr(proxy, attr)
        except AttributeError:
            raise AssertionError(
                "%s was set deprecated but wasn't added to __all__" % attr)
        delattr(proxy, attr)
        deprecated_attr = _DeprecatedAttribute(
            namespace, attr, value, replacement)
        setattr(proxy_type, attr, deprecated_attr)

    return proxy

Response: Loads the overrides for the given introspection module.


Instruction:
Write a Python 3 script to
take a override class or function and assigns it dunder arguments form the overidden one.

Response:
def override(klass):
    """Takes a override class or function and assigns it dunder arguments
    form the overidden one.
    """

    namespace = klass.__module__.rsplit(".", 1)[-1]
    mod_name = const.PREFIX[-1] + "." + namespace
    module = sys.modules[mod_name]

    if isinstance(klass, types.FunctionType):
        def wrap(wrapped):
            setattr(module, klass.__name__, wrapped)
            return wrapped
        return wrap

    old_klass = klass.__mro__[1]
    name = old_klass.__name__
    klass.__name__ = name
    klass.__module__ = old_klass.__module__

    setattr(module, name, klass)

    return klass


Instruction:
How would you explain what the following Python 3 function does
def deprecated(function, instead):

    # skip for classes, breaks doc generation
    if not isinstance(function, types.FunctionType):
        return function

    @wraps(function)
    def wrap(*args, **kwargs):
        warnings.warn("Deprecated, use %s instead" % instead,
                      PyGIDeprecationWarning)
        return function(*args, **kwargs)

    return wrap

Response: Mark a function deprecated so calling it issues a warning


Instruction:
Implement a Python 3 function for
marking a module level attribute as deprecated.

Response:
def deprecated_attr(namespace, attr, replacement):
    """Marks a module level attribute as deprecated. Accessing it will emit
    a PyGIDeprecationWarning warning.

    e.g. for ``deprecated_attr("GObject", "STATUS_FOO", "GLib.Status.FOO")``
    accessing GObject.STATUS_FOO will emit:

        "GObject.STATUS_FOO is deprecated; use GLib.Status.FOO instead"

    :param str namespace:
        The namespace of the override this is called in.
    :param str namespace:
        The attribute name (which gets added to __all__).
    :param str replacement:
        The replacement text which will be included in the warning.
    """

    _deprecated_attrs.setdefault(namespace, []).append((attr, replacement))


Instruction:
Here you have a function in Python 3, explain what it does
def deprecated_init(super_init_func, arg_names, ignore=tuple(),
                    deprecated_aliases={}, deprecated_defaults={},
                    category=PyGIDeprecationWarning,
                    stacklevel=2):
    """Wrapper for deprecating GObject based __init__ methods which specify
    defaults already available or non-standard defaults.

    :param callable super_init_func:
        Initializer to wrap.
    :param list arg_names:
        Ordered argument name list.
    :param list ignore:
        List of argument names to ignore when calling the wrapped function.
        This is useful for function which take a non-standard keyword that is munged elsewhere.
    :param dict deprecated_aliases:
        Dictionary mapping a keyword alias to the actual g_object_newv keyword.
    :param dict deprecated_defaults:
        Dictionary of non-standard defaults that will be used when the
        keyword is not explicitly passed.
    :param Exception category:
        Exception category of the error.
    :param int stacklevel:
        Stack level for the deprecation passed on to warnings.warn
    :returns: Wrapped version of ``super_init_func`` which gives a deprecation
        warning when non-keyword args or aliases are used.
    :rtype: callable
    """
    # We use a list of argument names to maintain order of the arguments
    # being deprecated. This allows calls with positional arguments to
    # continue working but with a deprecation message.
    def new_init(self, *args, **kwargs):
        """Initializer for a GObject based classes with support for property
        sets through the use of explicit keyword arguments.
        """
        # Print warnings for calls with positional arguments.
        if args:
            warnings.warn('Using positional arguments with the GObject constructor has been deprecated. '
                          'Please specify keyword(s) for "%s" or use a class specific constructor. '
                          'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' %
                          ', '.join(arg_names[:len(args)]),
                          category, stacklevel=stacklevel)
            new_kwargs = dict(zip(arg_names, args))
        else:
            new_kwargs = {}
        new_kwargs.update(kwargs)

        # Print warnings for alias usage and transfer them into the new key.
        aliases_used = []
        for key, alias in deprecated_aliases.items():
            if alias in new_kwargs:
                new_kwargs[key] = new_kwargs.pop(alias)
                aliases_used.append(key)

        if aliases_used:
            warnings.warn('The keyword(s) "%s" have been deprecated in favor of "%s" respectively. '
                          'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' %
                          (', '.join(deprecated_aliases[k] for k in sorted(aliases_used)),
                           ', '.join(sorted(aliases_used))),
                          category, stacklevel=stacklevel)

        # Print warnings for defaults different than what is already provided by the property
        defaults_used = []
        for key, value in deprecated_defaults.items():
            if key not in new_kwargs:
                new_kwargs[key] = deprecated_defaults[key]
                defaults_used.append(key)

        if defaults_used:
            warnings.warn('Initializer is relying on deprecated non-standard '
                          'defaults. Please update to explicitly use: %s '
                          'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations' %
                          ', '.join('%s=%s' % (k, deprecated_defaults[k]) for k in sorted(defaults_used)),
                          category, stacklevel=stacklevel)

        # Remove keywords that should be ignored.
        for key in ignore:
            if key in new_kwargs:
                new_kwargs.pop(key)

        return super_init_func(self, **new_kwargs)

    return new_init

Response: Wrapper for deprecating GObject based __init__ methods which specify deprecated defaults already available or non - standard defaults.


Instruction:
Here you have a function in Python 3, explain what it does
def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None):
    @wraps(method)
    def wrapped(*args, **kwargs):
        ret = method(*args, **kwargs)
        if ret[0]:
            if len(ret) == 2:
                return ret[1]
            else:
                return ret[1:]
        else:
            if exc_type:
                raise exc_type(exc_str or 'call failed')
            return fail_ret
    return wrapped

Response: Translate method s return value for stripping off success flag.