Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_xid_device(device_number):
    scanner = XidScanner()
    com = scanner.device_at_index(device_number)
    com.open()
    return XidDevice(com)

Response: Returns the XidDevice object for the device at the passed in index.


Instruction:
Can you tell what is the following Python 3 function doing
def connect(self, receiver):
        if not callable(receiver):
            raise ValueError('Invalid receiver: %s' % receiver)
        self.receivers.append(receiver)

Response: Append receiver to the list of receivers.


Instruction:
Create a Python 3 function for
disconnecting receiver from the list of receivers.

Response:
def disconnect(self, receiver):
        """Remove receiver."""
        try:
            self.receivers.remove(receiver)
        except ValueError:
            raise ValueError('Unknown receiver: %s' % receiver)


Instruction:
Can you tell what is the following Python 3 function doing
def send(self, instance, *args, **kwargs):
        for receiver in self.receivers:
            receiver(instance, *args, **kwargs)

Response: Send an instance to all the receivers.


Instruction:
Write a Python 3 function for
getting database from given URI or object.

Response:
def get_database(obj, **params):
    """Get database from given URI/Object."""
    if isinstance(obj, string_types):
        return connect(obj, **params)
    return obj


Instruction:
Can you tell what is the following Python 3 function doing
def close(self, response):
        LOGGER.info('Closing [%s]', os.getpid())
        if not self.database.is_closed():
            self.database.close()
        return response

Response: Close connection to database.


Instruction:
Write a Python 3 function that can
bind model to self database.

Response:
def Model(self):
        """Bind model to self database."""
        Model_ = self.app.config['PEEWEE_MODELS_CLASS']
        meta_params = {'database': self.database}
        if self.slaves and self.app.config['PEEWEE_USE_READ_SLAVES']:
            meta_params['read_slaves'] = self.slaves

        Meta = type('Meta', (), meta_params)
        return type('Model', (Model_,), {'Meta': Meta})


Instruction:
Implement a Python 3 function for
returning self. application models.

Response:
def models(self):
        """Return self.application models."""
        Model_ = self.app.config['PEEWEE_MODELS_CLASS']
        ignore = self.app.config['PEEWEE_MODELS_IGNORE']

        models = []
        if Model_ is not Model:
            try:
                mod = import_module(self.app.config['PEEWEE_MODELS_MODULE'])
                for model in dir(mod):
                    models = getattr(mod, model)
                    if not isinstance(model, pw.Model):
                        continue
                    models.append(models)
            except ImportError:
                return models
        elif isinstance(Model_, BaseSignalModel):
            models = BaseSignalModel.models

        return [m for m in models if m._meta.name not in ignore]


Instruction:
Implement a function in Python 3 to
create a new migration.

Response:
def cmd_create(self, name, auto=False):
        """Create a new migration."""

        LOGGER.setLevel('INFO')
        LOGGER.propagate = 0

        router = Router(self.database,
                        migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'],
                        migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE'])

        if auto:
            auto = self.models

        router.create(name, auto=auto)


Instruction:
Implement a function in Python 3 to
integrate a Flask - Script.

Response:
def manager(self):
        """Integrate a Flask-Script."""
        from flask_script import Manager, Command

        manager = Manager(usage="Migrate database.")
        manager.add_command('create', Command(self.cmd_create))
        manager.add_command('migrate', Command(self.cmd_migrate))
        manager.add_command('rollback', Command(self.cmd_rollback))
        manager.add_command('list', Command(self.cmd_list))
        manager.add_command('merge', Command(self.cmd_merge))

        return manager


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

    python = sys.executable
    os.execl(python, python, * sys.argv)

Response: Restarts the current program with the current sequence of python modules.


Instruction:
Here you have a function in Python 3, explain what it does
def __load(arff):
    attrs = arff['attributes']
    attrs_t = []
    for attr in attrs:
        if isinstance(attr[1], list):
            attrs_t.append("%s@{%s}" % (attr[0], ','.join(attr[1])))
        else:
            attrs_t.append("%s@%s" % (attr[0], attr[1]))

    df = pd.DataFrame(data=arff['data'], columns=attrs_t)
    return df

Response: loads liac - arff to pandas DataFrame


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __dump(df,relation='data',description=''):
    attrs = []
    for col in df.columns:
        attr = col.split('@')
        if attr[1].count('{')>0 and attr[1].count('}')>0:
            vals = attr[1].replace('{','').replace('}','').split(',')
            attrs.append((attr[0],vals))
        else:
            attrs.append((attr[0],attr[1]))

    data = list(df.values)
    result = {
        'attributes':attrs,
        'data':data,
        'description':description,
        'relation':relation
    }
    return result

Response: Dump a DataFrame to liac - arff dict


Instruction:
Here you have a function in Python 3, explain what it does
def dump(df,fp):
    arff = __dump(df)
    liacarff.dump(arff,fp)

Response: Dump a DataFrame to a file in a Sequential fashion.


Instruction:
How would you implement a function in Python 3 that
inserts marker at offset into text and return the marked line.

Response:
def markup_line(text, offset, marker='>>!<<'):
    """Insert `marker` at `offset` into `text`, and return the marked
    line.

    .. code-block:: python

       >>> markup_line('0\\n1234\\n56', 3)
       1>>!<<234

    """

    begin = text.rfind('\n', 0, offset)
    begin += 1

    end = text.find('\n', offset)

    if end == -1:
        end = len(text)

    return text[begin:offset] + marker + text[offset:end]


Instruction:
Implement a Python 3 function for
initializing a tokenizer. Should only be called by the :func:`~textparser.Parser.tokenize` method in the parser.

Response:
def tokenize_init(spec):
    """Initialize a tokenizer. Should only be called by the
    :func:`~textparser.Parser.tokenize` method in the parser.

    """

    tokens = [Token('__SOF__', '__SOF__', 0)]
    re_token = '|'.join([
        '(?P<{}>{})'.format(name, regex) for name, regex in spec
    ])

    return tokens, re_token


Instruction:
Make a summary of the following Python 3 code
def tokenize(self, text):

        names, specs = self._unpack_token_specs()
        keywords = self.keywords()
        tokens, re_token = tokenize_init(specs)

        for mo in re.finditer(re_token, text, re.DOTALL):
            kind = mo.lastgroup

            if kind == 'SKIP':
                pass
            elif kind != 'MISMATCH':
                value = mo.group(kind)

                if value in keywords:
                    kind = value

                if kind in names:
                    kind = names[kind]

                tokens.append(Token(kind, value, mo.start()))
            else:
                raise TokenizeError(text, mo.start())

        return tokens

Response: Tokenize given string text and return a list of tokens. Raises TokenizeError on failure.


Instruction:
Implement a function in Python 3 to
parse given string text and return the parse tree.

Response:
def parse(self, text, token_tree=False, match_sof=False):
        """Parse given string `text` and return the parse tree. Raises
        :class:`~textparser.ParseError` on failure.

        Returns a parse tree of tokens if `token_tree` is ``True``.

        .. code-block:: python

           >>> MyParser().parse('Hello, World!')
           ['Hello', ',', 'World', '!']
           >>> tree = MyParser().parse('Hello, World!', token_tree=True)
           >>> from pprint import pprint
           >>> pprint(tree)
           [Token(kind='WORD', value='Hello', offset=0),
            Token(kind=',', value=',', offset=5),
            Token(kind='WORD', value='World', offset=7),
            Token(kind='!', value='!', offset=12)]

        """

        try:
            tokens = self.tokenize(text)

            if len(tokens) == 0 or tokens[-1].kind != '__EOF__':
                tokens.append(Token('__EOF__', '__EOF__', len(text)))

            if not match_sof:
                if len(tokens) > 0 and tokens[0].kind == '__SOF__':
                    del tokens[0]

            return Grammar(self.grammar()).parse(tokens, token_tree)
        except (TokenizeError, GrammarError) as e:
            raise ParseError(text, e.offset)


Instruction:
Given the following Python 3 function, write the documentation
def x_at_y(self, y, reverse=False):
        logger.info('Running %(name)s.y_at_x(y=%(y)s, reverse=%(rev)s)',
                    {"name": self.__class__, "y": y, "rev": reverse})
        # positive or negative direction handles
        x_handle, y_handle = self.x, self.y
        if reverse:
            x_handle, y_handle = self.x[::-1], self.y[::-1]

        # find the index of first value in self.y greater or equal than y
        cond = y_handle >= y
        ind = np.argmax(cond)

        # two boundary conditions where x cannot be found:
        # A) y > max(self.y)
        # B) y < min(self.y)

        # A) if y > max(self.y) then condition self.y >= y
        #   will never be satisfied
        #   np.argmax( cond ) will be equal 0  and  cond[ind] will be False
        if not cond[ind]:
            return np.nan

        # B) if y < min(self.y) then condition self.y >= y
        #   will be satisfied on first item
        #   np.argmax(cond) will be equal 0,
        #   to exclude situation that y_handle[0] = y
        #   we also check if y < y_handle[0]
        if ind == 0 and y < y_handle[0]:
            return np.nan

        # use lookup if y in self.y:
        if cond[ind] and y_handle[ind] == y:
            return x_handle[ind]

        # alternatively - pure python implementation
        # return x_handle[ind] - \
        #        ((x_handle[ind] - x_handle[ind - 1]) / \
        #        (y_handle[ind] - y_handle[ind - 1])) * \
        #        (y_handle[ind] - y)

        # use interpolation
        sl = slice(ind - 1, ind + 1)
        return np.interp(y, y_handle[sl], x_handle[sl])

Response: Calculates inverse profile of x at given y


Instruction:
Make a summary of the following Python 3 code
def width(self, level):
        return self.x_at_y(level, reverse=True) - self.x_at_y(level)

Response: Returns the width of the log entry at a given level.


Instruction:
Implement a function in Python 3 to
normalize to 1 over - dt area.

Response:
def normalize(self, dt, allow_cast=True):
        """
        Normalize to 1 over [-dt, +dt] area, if allow_cast is set
        to True, division not in place and casting may occur.
        If division in place is not possible and allow_cast is False
        an exception is raised.

        >>> a = Profile([[0, 0], [1, 5], [2, 10], [3, 5], [4, 0]])
        >>> a.normalize(1, allow_cast=True)
        >>> print(a.y)
        [0. 2. 4. 2. 0.]

        :param dt:
        :param allow_cast:
        """
        if dt <= 0:
            raise ValueError("Expected positive input")
        logger.info('Running %(name)s.normalize(dt=%(dt)s)', {"name": self.__class__, "dt": dt})
        try:
            ave = np.average(self.y[np.fabs(self.x) <= dt])
        except RuntimeWarning as e:
            logger.error('in normalize(). self class is %(name)s, dt=%(dt)s', {"name": self.__class__, "dt": dt})
            raise Exception("Scaling factor error: {0}".format(e))
        try:
            self.y /= ave
        except TypeError as e:
            logger.warning("Division in place is impossible: %s", e)
            if allow_cast:
                self.y = self.y / ave
            else:
                logger.error("Division in place impossible - allow_cast flag set to True should help")
                raise


Instruction:
Given the following Python 3 function, write the documentation
def rescale(self, factor=1.0, allow_cast=True):
        try:
            self.y /= factor
        except TypeError as e:
            logger.warning("Division in place is impossible: %s", e)
            if allow_cast:
                self.y = self.y / factor
            else:
                logger.error("allow_cast flag set to True should help")
                raise

Response: Rescales self. y by given factor.


Instruction:
Here you have a function in Python 3, explain what it does
def change_domain(self, domain):
        logger.info('Running %(name)s.change_domain() with new domain range:[%(ymin)s, %(ymax)s]',
                    {"name": self.__class__, "ymin": np.min(domain), "ymax": np.max(domain)})

        # check if new domain includes in the original domain
        if np.max(domain) > np.max(self.x) or np.min(domain) < np.min(self.x):
            logger.error('Old domain range: [%(xmin)s, %(xmax)s] does not include new domain range:'
                         '[%(ymin)s, %(ymax)s]', {"xmin": np.min(self.x), "xmax": np.max(self.x),
                                                  "ymin": np.min(domain), "ymax": np.max(domain)})
            raise ValueError('in change_domain():' 'the old domain does not include the new one')

        y = np.interp(domain, self.x, self.y)
        # We need to join together domain and values (y) because we are recreating Curve object
        # (we pass it as argument to self.__class__)
        # np.dstack((arrays), axis=1) joins given arrays like np.dstack() but it also nests the result
        # in additional list and this is the reason why we use [0] to remove this extra layer of list like this:
        # np.dstack([[0, 5, 10], [0, 0, 0]]) gives [[[ 0,  0], [ 5,  0], [10,  0]]] so use dtack()[0]
        # to get this: [[0,0], [5, 5], [10, 0]]
        # which is a 2 dimensional array and can be used to create a new Curve object
        obj = self.__class__(np.dstack((domain, y))[0], **self.__dict__['metadata'])
        return obj

Response: Creates a new Curve object with new domain and returns it.


Instruction:
Can you generate the documentation for the following Python 3 function
def rebinned(self, step=0.1, fixp=0):
        logger.info('Running %(name)s.rebinned(step=%(st)s, fixp=%(fx)s)',
                    {"name": self.__class__, "st": step, "fx": fixp})
        a, b = (np.min(self.x), np.max(self.x))
        count_start = abs(fixp - a) / step
        count_stop = abs(fixp - b) / step

        # depending on position of fixp with respect to the original domain
        # 3 cases may occur:
        if fixp < a:
            count_start = math.ceil(count_start)
            count_stop = math.floor(count_stop)
        elif fixp > b:
            count_start = -math.floor(count_start)
            count_stop = -math.ceil(count_stop)
        else:
            count_start = -count_start
            count_stop = count_stop

        domain = [fixp + n * step for n in range(int(count_start), int(count_stop) + 1)]
        return self.change_domain(domain)

Response: Returns a new curve object with the domain of the new domain.


Instruction:
Implement a Python 3 function for
evaluating at x - value

Response:
def evaluate_at_x(self, arg, def_val=0):
        """
        Returns Y value at arg of self. Arg can be a scalar,
        but also might be np.array or other iterable
        (like list). If domain of self is not wide enough to
        interpolate the value of Y, method will return
        def_val for those arguments instead.

        Check the interpolation when arg in domain of self:
        >>> Curve([[0, 0], [2, 2], [4, 4]]).evaluate_at_x([1, 2 ,3])
        array([1., 2., 3.])

        Check if behavior of the method is correct when arg
        id partly outside the domain:
        >>> Curve([[0, 0], [2, 2], [4, 4]]).evaluate_at_x(\
            [-1, 1, 2 ,3, 5], 100)
        array([100.,   1.,   2.,   3., 100.])

        :param arg: x-value to calculate Y (may be an array or list as well)
        :param def_val: default value to return if can't interpolate at arg
        :return: np.array of Y-values at arg. If arg is a scalar,
            will return scalar as well
        """
        y = np.interp(arg, self.x, self.y, left=def_val, right=def_val)
        return y


Instruction:
Can you tell what is the following Python 3 function doing
def alert(text='', title='', button='OK'):
    messageBoxFunc(0, text, title, MB_OK | MB_SETFOREGROUND | MB_TOPMOST)
    return button

Response: Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.


Instruction:
How would you explain what the following Python 3 function does
def confirm(text='', title='', buttons=['OK', 'Cancel']):
    retVal = messageBoxFunc(0, text, title, MB_OKCANCEL | MB_ICONQUESTION | MB_SETFOREGROUND | MB_TOPMOST)
    if retVal == 1 or len(buttons) == 1:
        return buttons[0]
    elif retVal == 2:
        return buttons[1]
    else:
        assert False, 'Unexpected return value from MessageBox: %s' % (retVal)

Response: Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.


Instruction:
How would you code a function in Python 3 to
function calculates difference between two curves and returns new object which domain is an union of curve1 and curve2 domains

Response:
def subtract(curve1, curve2, def_val=0):
    """
    Function calculates difference between curve1 and curve2
    and returns new object which domain is an union
    of curve1 and curve2 domains
    Returned object is of type type(curve1)
    and has same metadata as curve1 object

    :param curve1: first curve to calculate the difference
    :param curve2: second curve to calculate the difference
    :param def_val: default value for points that cannot be interpolated
    :return: new object of type type(curve1) with element-wise difference
    (using interpolation if necessary)
    """
    coord1 = np.union1d(curve1.x, curve2.x)
    y1 = curve1.evaluate_at_x(coord1, def_val)
    y2 = curve2.evaluate_at_x(coord1, def_val)
    coord2 = y1 - y2
    # the below is explained at the end of curve.Curve.change_domain()
    obj = curve1.__class__(np.dstack((coord1, coord2))[0], **curve1.__dict__['metadata'])
    return obj


Instruction:
Implement a Python 3 function for
applying a window - length median filter to a 1D array vector.

Response:
def medfilt(vector, window):
    """
    Apply a window-length median filter to a 1D array vector.

    Should get rid of 'spike' value 15.
    >>> print(medfilt(np.array([1., 15., 1., 1., 1.]), 3))
    [1. 1. 1. 1. 1.]

    The 'edge' case is a bit tricky...
    >>> print(medfilt(np.array([15., 1., 1., 1., 1.]), 3))
    [15.  1.  1.  1.  1.]

    Inspired by: https://gist.github.com/bhawkins/3535131
    """
    if not window % 2 == 1:
        raise ValueError("Median filter length must be odd.")
    if not vector.ndim == 1:
        raise ValueError("Input must be one-dimensional.")

    k = (window - 1) // 2  # window movement
    result = np.zeros((len(vector), window), dtype=vector.dtype)
    result[:, k] = vector
    for i in range(k):
        j = k - i
        result[j:, i] = vector[:-j]
        result[:j, i] = vector[0]
        result[:-j, -(i + 1)] = vector[j:]
        result[-j:, -(i + 1)] = vector[-1]

    return np.median(result, axis=1)


Instruction:
Explain what the following Python 3 code does
def interpn(*args, **kw):
	method = kw.pop('method', 'cubic')
	if kw:
		raise ValueError("Unknown arguments: " % kw.keys())
	nd = (len(args)-1)//2
	if len(args) != 2*nd+1:
		raise ValueError("Wrong number of arguments")
	q = args[:nd]
	qi = args[nd+1:]
	a = args[nd]
	for j in range(nd):
		#print q[j].shape, a.shape
		a = interp1d(q[j], a, axis=j, kind=method)(qi[j])
	return a

Response: Interpolate on N - D.


Instruction:
Can you create a Python 3 function that
interpolates on N - D.

Response:
def npinterpn(*args, **kw):
	"""Interpolation on N-D.

	ai = interpn(x, y, z, ..., a, xi, yi, zi, ...)
	where the arrays x, y, z, ... define a rectangular grid
	and a.shape == (len(x), len(y), len(z), ...) are the values
	interpolate at xi, yi, zi, ...
	"""
	method = kw.pop('method', 'cubic')
	if kw:
		raise ValueError("Unknown arguments: " % kw.keys())
	nd = (len(args)-1)//2
	if len(args) != 2*nd+1:
		raise ValueError("Wrong number of arguments")
	q = args[:nd]
	qi = args[nd+1:]
	a = args[nd]
	for j in range(nd):
		#print q[j].shape, a.shape
		a = interp(q[j], a, axis=j, kind=method)(qi[j])
	return a


Instruction:
Write a Python 3 function that can
generate a dictionary of fields for a given Peewee model.

Response:
def model_fields(model, allow_pk=False, only=None, exclude=None,
                 field_args=None, converter=None):
    """
    Generate a dictionary of fields for a given Peewee model.

    See `model_form` docstring for description of parameters.
    """
    converter = converter or ModelConverter()
    field_args = field_args or {}

    model_fields = list(model._meta.sorted_fields)
    if not allow_pk:
        model_fields.pop(0)

    if only:
        model_fields = [x for x in model_fields if x.name in only]
    elif exclude:
        model_fields = [x for x in model_fields if x.name not in exclude]

    field_dict = {}
    for model_field in model_fields:
        name, field = converter.convert(
            model,
            model_field,
            field_args.get(model_field.name))
        field_dict[name] = field

    return field_dict


Instruction:
Given the following Python 3 function, write the documentation
def model_form(model, base_class=Form, allow_pk=False, only=None, exclude=None,
               field_args=None, converter=None):
    """
    Create a wtforms Form for a given Peewee model class::

        from wtfpeewee.orm import model_form
        from myproject.myapp.models import User
        UserForm = model_form(User)

    :param model:
        A Peewee model class
    :param base_class:
        Base form class to extend from. Must be a ``wtforms.Form`` subclass.
    :param only:
        An optional iterable with the property names that should be included in
        the form. Only these properties will have fields.
    :param exclude:
        An optional iterable with the property names that should be excluded
        from the form. All other properties will have fields.
    :param field_args:
        An optional dictionary of field names mapping to keyword arguments used
        to construct each field object.
    :param converter:
        A converter to generate the fields based on the model properties. If
        not set, ``ModelConverter`` is used.
    """
    field_dict = model_fields(model, allow_pk, only, exclude, field_args, converter)
    return type(model.__name__ + 'Form', (base_class, ), field_dict)

Response: Returns a new form class for a given Peewee model class.


Instruction:
Make a summary of the following Python 3 code
def alert(text='', title='', button=OK_TEXT, root=None, timeout=None):
    assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox'
    return _buttonbox(msg=text, title=title, choices=[str(button)], root=root, timeout=timeout)

Response: Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.


Instruction:
How would you explain what the following Python 3 function does
def confirm(text='', title='', buttons=[OK_TEXT, CANCEL_TEXT], root=None, timeout=None):
    assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox'
    return _buttonbox(msg=text, title=title, choices=[str(b) for b in buttons], root=root, timeout=timeout)

Response: Displays a message box with OK and CANCEL buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.


Instruction:
Make a summary of the following Python 3 code
def prompt(text='', title='' , default='', root=None, timeout=None):
    assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox'
    return __fillablebox(text, title, default=default, mask=None,root=root, timeout=timeout)

Response: Displays a message box with text input and OK & Cancel buttons. Returns the text entered or None.


Instruction:
Implement a function in Python 3 to
display a message a title and a set of buttons.

Response:
def _buttonbox(msg, title, choices, root=None, timeout=None):
    """
    Display a msg, a title, and a set of buttons.
    The buttons are defined by the members of the choices list.
    Return the text of the button that the user selected.

    @arg msg: the msg to be displayed.
    @arg title: the window title
    @arg choices: a list or tuple of the choices to be displayed
    """
    global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame

    # Initialize __replyButtonText to the first choice.
    # This is what will be used if the window is closed by the close button.
    __replyButtonText = choices[0]

    if root:
        root.withdraw()
        boxRoot = tk.Toplevel(master=root)
        boxRoot.withdraw()
    else:
        boxRoot = tk.Tk()
        boxRoot.withdraw()

    boxRoot.title(title)
    boxRoot.iconname('Dialog')
    boxRoot.geometry(rootWindowPosition)
    boxRoot.minsize(400, 100)

    # ------------- define the messageFrame ---------------------------------
    messageFrame = tk.Frame(master=boxRoot)
    messageFrame.pack(side=tk.TOP, fill=tk.BOTH)

    # ------------- define the buttonsFrame ---------------------------------
    buttonsFrame = tk.Frame(master=boxRoot)
    buttonsFrame.pack(side=tk.TOP, fill=tk.BOTH)

    # -------------------- place the widgets in the frames -----------------------
    messageWidget = tk.Message(messageFrame, text=msg, width=400)
    messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY, PROPORTIONAL_FONT_SIZE))
    messageWidget.pack(side=tk.TOP, expand=tk.YES, fill=tk.X, padx='3m', pady='3m')

    __put_buttons_in_buttonframe(choices)

    # -------------- the action begins -----------
    # put the focus on the first button
    __firstWidget.focus_force()

    boxRoot.deiconify()
    if timeout is not None:
        boxRoot.after(timeout, timeoutBoxRoot)
    boxRoot.mainloop()
    try:
        boxRoot.destroy()
    except tk.TclError:
        if __replyButtonText != TIMEOUT_TEXT:
            __replyButtonText = None

    if root: root.deiconify()
    return __replyButtonText


Instruction:
Explain what the following Python 3 code does
def __put_buttons_in_buttonframe(choices):
    global __widgetTexts, __firstWidget, buttonsFrame

    __firstWidget = None
    __widgetTexts = {}

    i = 0

    for buttonText in choices:
        tempButton = tk.Button(buttonsFrame, takefocus=1, text=buttonText)
        _bindArrows(tempButton)
        tempButton.pack(expand=tk.YES, side=tk.LEFT, padx='1m', pady='1m', ipadx='2m', ipady='1m')

        # remember the text associated with this widget
        __widgetTexts[tempButton] = buttonText

        # remember the first widget, so we can put the focus there
        if i == 0:
            __firstWidget = tempButton
            i = 1

        # for the commandButton, bind activation events to the activation event handler
        commandButton  = tempButton
        handler = __buttonEvent
        for selectionEvent in STANDARD_SELECTION_EVENTS:
            commandButton.bind('<%s>' % selectionEvent, handler)

        if CANCEL_TEXT in choices:
            commandButton.bind('<Escape>', __cancelButtonEvent)

Response: Put the buttons in the buttons frame


Instruction:
Create a Python 3 function for
filling a box with a message.

Response:
def __fillablebox(msg, title='', default='', mask=None, root=None, timeout=None):
    """
    Show a box in which a user can enter some text.
    You may optionally specify some default text, which will appear in the
    enterbox when it is displayed.
    Returns the text that the user entered, or None if he cancels the operation.
    """

    global boxRoot, __enterboxText, __enterboxDefaultText
    global cancelButton, entryWidget, okButton

    if title == None:
        title == ''
    if default == None:
        default = ''
    __enterboxDefaultText = default
    __enterboxText        = __enterboxDefaultText

    if root:
        root.withdraw()
        boxRoot = tk.Toplevel(master=root)
        boxRoot.withdraw()
    else:
        boxRoot = tk.Tk()
        boxRoot.withdraw()

    boxRoot.title(title)
    boxRoot.iconname('Dialog')
    boxRoot.geometry(rootWindowPosition)
    boxRoot.bind('<Escape>', __enterboxCancel)

    # ------------- define the messageFrame ---------------------------------
    messageFrame = tk.Frame(master=boxRoot)
    messageFrame.pack(side=tk.TOP, fill=tk.BOTH)

    # ------------- define the buttonsFrame ---------------------------------
    buttonsFrame = tk.Frame(master=boxRoot)
    buttonsFrame.pack(side=tk.TOP, fill=tk.BOTH)

    # ------------- define the entryFrame ---------------------------------
    entryFrame = tk.Frame(master=boxRoot)
    entryFrame.pack(side=tk.TOP, fill=tk.BOTH)

    # ------------- define the buttonsFrame ---------------------------------
    buttonsFrame = tk.Frame(master=boxRoot)
    buttonsFrame.pack(side=tk.TOP, fill=tk.BOTH)

    #-------------------- the msg widget ----------------------------
    messageWidget = tk.Message(messageFrame, width='4.5i', text=msg)
    messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY, PROPORTIONAL_FONT_SIZE))
    messageWidget.pack(side=tk.RIGHT, expand=1, fill=tk.BOTH, padx='3m', pady='3m')

    # --------- entryWidget ----------------------------------------------
    entryWidget = tk.Entry(entryFrame, width=40)
    _bindArrows(entryWidget, skipArrowKeys=True)
    entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY, TEXT_ENTRY_FONT_SIZE))
    if mask:
        entryWidget.configure(show=mask)
    entryWidget.pack(side=tk.LEFT, padx='3m')
    entryWidget.bind('<Return>', __enterboxGetText)
    entryWidget.bind('<Escape>', __enterboxCancel)

    # put text into the entryWidget and have it pre-highlighted
    if __enterboxDefaultText != '':
        entryWidget.insert(0,__enterboxDefaultText)
        entryWidget.select_range(0, tk.END)

    # ------------------ ok button -------------------------------
    okButton = tk.Button(buttonsFrame, takefocus=1, text=OK_TEXT)
    _bindArrows(okButton)
    okButton.pack(expand=1, side=tk.LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m')

    # for the commandButton, bind activation events to the activation event handler
    commandButton  = okButton
    handler = __enterboxGetText
    for selectionEvent in STANDARD_SELECTION_EVENTS:
        commandButton.bind('<%s>' % selectionEvent, handler)

    # ------------------ cancel button -------------------------------
    cancelButton = tk.Button(buttonsFrame, takefocus=1, text=CANCEL_TEXT)
    _bindArrows(cancelButton)
    cancelButton.pack(expand=1, side=tk.RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m')

    # for the commandButton, bind activation events to the activation event handler
    commandButton  = cancelButton
    handler = __enterboxCancel
    for selectionEvent in STANDARD_SELECTION_EVENTS:
        commandButton.bind('<%s>' % selectionEvent, handler)

    # ------------------- time for action! -----------------
    entryWidget.focus_force()    # put the focus on the entryWidget
    boxRoot.deiconify()
    if timeout is not None:
        boxRoot.after(timeout, timeoutBoxRoot)
    boxRoot.mainloop()  # run it!

    # -------- after the run has completed ----------------------------------
    if root: root.deiconify()
    try:
        boxRoot.destroy()  # button_click didn't destroy boxRoot, so we do it now
    except tk.TclError:
        if __enterboxText != TIMEOUT_TEXT:
            return None

    return __enterboxText


Instruction:
Implement a function in Python 3 to
parse the login xml response and populate the internal attributes.

Response:
def parse(self, response):
        """
        Parse the login xml response
        :param response: the login response from the RETS server
        :return: None
        """
        self.headers = response.headers

        if 'xml' in self.headers.get('Content-Type'):
            # Got an XML response, likely an error code.
            xml = xmltodict.parse(response.text)
            self.analyze_reply_code(xml_response_dict=xml)

        lines = response.text.split('\r\n')
        if len(lines) < 3:
            lines = response.text.split('\n')

        for line in lines:
            line = line.strip()

            name, value = self.read_line(line)
            if name:
                if name in self.valid_transactions or re.match(pattern='/^X\-/', string=name):
                    self.capabilities[name] = value
                else:
                    self.details[name] = value


Instruction:
How would you implement a function in Python 3 that
reads lines of XML and delimits strips and returns.

Response:
def read_line(line):
        """Reads lines of XML and delimits, strips, and returns."""
        name, value = '', ''

        if '=' in line:
            name, value = line.split('=', 1)

        return [name.strip(), value.strip()]


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

        delim = '\t'  # Default to tab delimited
        columns = []
        response.raw.decode_content = True
        events = ET.iterparse(BytesIO(response.content))

        results = []
        for event, elem in events:
            # Analyze search record data
            if "DATA" == elem.tag:
                data_dict = {column: data for column, data in zip(columns, elem.text.split(delim)) if column != ''}
                self.parsed_rows += 1  # Rows parsed with all requests
                results.append(data_dict)

            # Handle reply code
            elif "RETS" == elem.tag:
                reply_code = elem.get('ReplyCode')
                reply_text = elem.get('ReplyText')

                if reply_code == '20201':
                    # RETS Response 20201 - No Records Found
                    # Generator should continue and return nothing
                    continue
                elif reply_code != '0':
                    msg = "RETS Error {0!s}: {1!s}".format(reply_code, reply_text)
                    raise RETSException(msg)

            # Analyze delimiter
            elif "DELIMITER" == elem.tag:
                val = elem.get("value")
                delim = chr(int(val))

            # Analyze columns
            elif "COLUMNS" == elem.tag:
                columns = elem.text.split(delim)

            # handle max rows
            elif "MAXROWS" == elem.tag:
                logger.debug("MAXROWS Tag reached in XML")
                logger.debug("Received {0!s} results from this search".format(self.parsed_rows))
                raise MaxrowException(results)

            else:
                # This is a tag we don't process (like COUNT)
                continue

            elem.clear()

        return results

Response: Takes a Requests response socket connection and iteratively parses and yields the results as python dictionaries.


Instruction:
Implement a Python 3 function for
taking a urlinfo object and returns a flat dictionary.

Response:
def flatten_urlinfo(urlinfo, shorter_keys=True):
    """ Takes a urlinfo object and returns a flat dictionary."""
    def flatten(value, prefix=""):
        if is_string(value):
            _result[prefix[1:]] = value
            return
        try:
            len(value)
        except (AttributeError, TypeError):  # a leaf
            _result[prefix[1:]] = value
            return

        try:
            items = value.items()
        except AttributeError:  # an iterable, but not a dict
            last_prefix = prefix.split(".")[-1]
            if shorter_keys:
                prefix = "." + last_prefix

            if last_prefix == "Country":
                for v in value:
                    country = v.pop("@Code")
                    flatten(v, ".".join([prefix, country]))
            elif last_prefix in ["RelatedLink", "CategoryData"]:
                for i, v in enumerate(value):
                    flatten(v, ".".join([prefix, str(i)]))
            elif value[0].get("TimeRange"):
                for v in value:
                    time_range = ".".join(tuple(v.pop("TimeRange").items())[0])
                    # python 3 odict_items don't support indexing
                    if v.get("DataUrl"):
                        time_range = ".".join([v.pop("DataUrl"), time_range])
                    flatten(v, ".".join([prefix, time_range]))
            else:
                msg = prefix + " contains a list we don't know how to flatten."
                raise NotImplementedError(msg)
        else:  # a dict, go one level deeper
            for k, v in items:
                flatten(v, ".".join([prefix, k]))

    _result = {}
    info = xmltodict.parse(str(urlinfo))
    flatten(info["aws:UrlInfoResponse"]["Response"]["UrlInfoResult"]["Alexa"])
    _result["OutputTimestamp"] = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
    return _result


Instruction:
How would you implement a function in Python 3 that
creates a V4 signature for the given request parameters.

Response:
def create_v4_signature(self, request_params):
        '''
        Create URI and signature headers based on AWS V4 signing process.
        Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params.
        :param request_params: dictionary of request parameters
        :return: URL and header to be passed to requests.get
        '''

        method = 'GET'
        service = 'awis'
        host = 'awis.us-west-1.amazonaws.com'
        region = 'us-west-1'
        endpoint = 'https://awis.amazonaws.com/api'
        request_parameters = urlencode([(key, request_params[key]) for key in sorted(request_params.keys())])

        # Key derivation functions. See:
        # http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
        def sign(key, msg):
            return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

        def getSignatureKey(key, dateStamp, regionName, serviceName):
            kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
            kRegion = sign(kDate, regionName)
            kService = sign(kRegion, serviceName)
            kSigning = sign(kService, 'aws4_request')
            return kSigning

        # Create a date for headers and the credential string
        t = datetime.datetime.utcnow()
        amzdate = t.strftime('%Y%m%dT%H%M%SZ')
        datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope

        # Create canonical request
        canonical_uri = '/api'
        canonical_querystring = request_parameters
        canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
        signed_headers = 'host;x-amz-date'
        payload_hash = hashlib.sha256(''.encode('utf8')).hexdigest()
        canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

        # Create string to sign
        algorithm = 'AWS4-HMAC-SHA256'
        credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
        string_to_sign = algorithm + '\n' +  amzdate + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode('utf8')).hexdigest()

        # Calculate signature
        signing_key = getSignatureKey(self.secret_access_key, datestamp, region, service)

        # Sign the string_to_sign using the signing_key
        signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()

        # Add signing information to the request
        authorization_header = algorithm + ' ' + 'Credential=' + self.access_id + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
        headers = {'X-Amz-Date':amzdate, 'Authorization':authorization_header, 'Content-Type': 'application/xml', 'Accept': 'application/xml'}

        # Create request url
        request_url = endpoint + '?' + canonical_querystring

        return request_url, headers


Instruction:
Make a summary of the following Python 3 code
def urlinfo(self, domain, response_group = URLINFO_RESPONSE_GROUPS):
        '''
        Provide information about supplied domain as specified by the response group
        :param domain: Any valid URL
        :param response_group: Any valid urlinfo response group
        :return: Traffic and/or content data of the domain in XML format
        '''
        params = {
            'Action': "UrlInfo",
            'Url': domain,
            'ResponseGroup': response_group
        }

        url, headers = self.create_v4_signature(params)
        return self.return_output(url, headers)

Response: This method provides information about the supplied domain in XML format.


Instruction:
Can you tell what is the following Python 3 function doing
def traffichistory(self, domain, response_group=TRAFFICINFO_RESPONSE_GROUPS, myrange=31, start=20070801):
        '''
        Provide traffic history of supplied domain
        :param domain: Any valid URL
        :param response_group: Any valid traffic history response group
        :return: Traffic and/or content data of the domain in XML format
        '''
        params = {
            'Action': "TrafficHistory",
            'Url': domain,
            'ResponseGroup': response_group,
            'Range': myrange,
            'Start': start,
        }

        url, headers = self.create_v4_signature(params)
        return self.return_output(url, headers)

Response: This method provides a traffichistory of the supplied domain.


Instruction:
Implement a Python 3 function for
providing category browse information of specified domain :param domain: Any valid URL :param path: Valid category path :param response_group: Any valid traffic history response group :return: Traffic and/or content data of the domain in XML format

Response:
def cat_browse(self, domain, path, response_group=CATEGORYBROWSE_RESPONSE_GROUPS, descriptions='True'):
        '''
        Provide category browse information of specified domain
        :param domain: Any valid URL
        :param path: Valid category path
        :param response_group: Any valid traffic history response group
        :return: Traffic and/or content data of the domain in XML format
        '''
        params = {
            'Action': "CategoryListings",
            'ResponseGroup': 'Listings',
            'Path': quote(path),
            'Descriptions': descriptions
        }

        url, headers = self.create_v4_signature(params)
        return self.return_output(url, headers)


Instruction:
Write a Python 3 function for
adding a capability to the capabilities dictionary.

Response:
def add_capability(self, name, uri):
        """
        Add a capability of the RETS board
        :param name: The name of the capability
        :param uri: The capability URI given by the RETS board
        :return: None
        """

        parse_results = urlparse(uri)
        if parse_results.hostname is None:
            # relative URL given, so build this into an absolute URL
            login_url = self.capabilities.get('Login')
            if not login_url:
                logger.error("There is no login URL stored, so additional capabilities cannot be added.")
                raise ValueError("Cannot automatically determine absolute path for {0!s} given.".format(uri))

            parts = urlparse(login_url)
            port = ':{}'.format(parts.port) if parts.port else ''
            uri = parts.scheme + '://' + parts.hostname + port + '/' + uri.lstrip('/')

        self.capabilities[name] = uri


Instruction:
Can you generate a brief explanation for the following Python 3 code
def login(self):
        response = self._request('Login')
        parser = OneXLogin()
        parser.parse(response)

        self.session_id = response.cookies.get(self.session_id_cookie_name, '')

        if parser.headers.get('RETS-Version') is not None:
            self.version = str(parser.headers.get('RETS-Version'))
            self.client.headers['RETS-Version'] = self.version

        for k, v in parser.capabilities.items():
            self.add_capability(k, v)

        if self.capabilities.get('Action'):
            self._request('Action')
        return True

Response: Login to the RETS board and return an instance of Bulletin


Instruction:
Create a Python 3 function for
getting resource metadata for a resource

Response:
def get_resource_metadata(self, resource=None):
        """
        Get resource metadata
        :param resource: The name of the resource to get metadata for
        :return: list
        """
        result = self._make_metadata_request(meta_id=0, metadata_type='METADATA-RESOURCE')
        if resource:
            result = next((item for item in result if item['ResourceID'] == resource), None)
        return result


Instruction:
Can you generate the documentation for the following Python 3 function
def get_table_metadata(self, resource, resource_class):
        return self._make_metadata_request(meta_id=resource + ':' + resource_class, metadata_type='METADATA-TABLE')

Response: Get the metadata for a given resource and class


Instruction:
Given the following Python 3 function, write the documentation
def get_lookup_values(self, resource, lookup_name):
        return self._make_metadata_request(meta_id=resource + ':' + lookup_name, metadata_type='METADATA-LOOKUP_TYPE')

Response: Get possible lookup values for a given resource and lookup name


Instruction:
Given the following Python 3 function, write the documentation
def _make_metadata_request(self, meta_id, metadata_type=None):
        # If this metadata _request has already happened, returned the saved result.
        key = '{0!s}:{1!s}'.format(metadata_type, meta_id)
        if key in self.metadata_responses and self.cache_metadata:
            response = self.metadata_responses[key]
        else:
            response = self._request(
                capability='GetMetadata',
                options={
                    'query': {
                        'Type': metadata_type,
                        'ID': meta_id,
                        'Format': self.metadata_format
                    }
                }
            )
            self.metadata_responses[key] = response

        if self.metadata_format == 'COMPACT-DECODED':
            parser = CompactMetadata()
        else:
            parser = StandardXMLetadata()

        try:
            return parser.parse(response=response, metadata_type=metadata_type)
        except RETSException as e:
            # Remove response from cache
            self.metadata_responses.pop(key, None)

            # If the server responds with an invalid parameter for COMPACT-DECODED, try STANDARD-XML
            if self.metadata_format != 'STANDARD-XML' and e.reply_code in ['20513', '20514']:
                self.metadata_responses.pop(key, None)
                self.metadata_format = 'STANDARD-XML'
                return self._make_metadata_request(meta_id=meta_id, metadata_type=metadata_type)
            raise RETSException(e.reply_text, e.reply_code)

Response: Make the metadata request.


Instruction:
Given the following Python 3 function, write the documentation
def get_preferred_object(self, resource, object_type, content_id, location=0):
        collection = self.get_object(resource=resource, object_type=object_type,
                                     content_ids=content_id, object_ids='0', location=location)
        return collection[0]

Response: Get the first object from a Resource


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_object(self, resource, object_type, content_ids, object_ids='*', location=0):
        object_helper = GetObject()
        request_ids = object_helper.ids(content_ids=content_ids, object_ids=object_ids)

        response = self._request(
            capability='GetObject',
            options={
                'query':
                    {
                        "Resource": resource,
                        "Type": object_type,
                        "ID": ','.join(request_ids),
                        "Location": location
                    }
            }
        )

        if 'multipart' in response.headers.get('Content-Type'):
            parser = MultipleObjectParser()
            collection = parser.parse_image_response(response)
        else:
            parser = SingleObjectParser()
            collection = [parser.parse_image_response(response)]

        return collection

Response: Get a list of objects from a resource


Instruction:
Make a summary of the following Python 3 code
def search(self, resource, resource_class, search_filter=None, dmql_query=None, limit=9999999, offset=0,
               optional_parameters=None, auto_offset=True, query_type='DMQL2', standard_names=0,
               response_format='COMPACT-DECODED'):
        """
        Preform a search on the RETS board
        :param resource: The resource that contains the class to search
        :param resource_class: The class to search
        :param search_filter: The query as a dict
        :param dmql_query: The query in dmql format
        :param limit: Limit search values count
        :param offset: Offset for RETS request. Useful when RETS limits number of results or transactions
        :param optional_parameters: Values for option paramters
        :param auto_offset: Should the search be allowed to trigger subsequent searches.
        :param query_type: DMQL or DMQL2 depending on the rets server.
        :param standard_names: 1 to use standard names, 0 to use system names
        :param response_format: COMPACT-DECODED, COMPACT, or STANDARD-XML
        :return: dict
        """

        if (search_filter and dmql_query) or (not search_filter and not dmql_query):
            raise ValueError("You may specify either a search_filter or dmql_query")

        search_helper = DMQLHelper()

        if dmql_query:
            dmql_query = search_helper.dmql(query=dmql_query)
        else:
            dmql_query = search_helper.filter_to_dmql(filter_dict=search_filter)

        parameters = {
            'SearchType': resource,
            'Class': resource_class,
            'Query': dmql_query,
            'QueryType': query_type,
            'Count': 1,
            'Format': response_format,
            'StandardNames': standard_names,
        }

        if not optional_parameters:
            optional_parameters = {}
        parameters.update(optional_parameters)

        # if the Select parameter given is an array, format it as it needs to be
        if 'Select' in parameters and isinstance(parameters.get('Select'), list):
            parameters['Select'] = ','.join(parameters['Select'])

        if limit:
            parameters['Limit'] = limit

        if offset:
            parameters['Offset'] = offset

        search_cursor = OneXSearchCursor()
        response = self._request(
            capability='Search',
            options={
                'query': parameters,
            },
            stream=True
        )
        try:
            return search_cursor.generator(response=response)

        except MaxrowException as max_exception:
            # Recursive searching if automatically performing offsets for the  client
            if auto_offset and limit > len(max_exception.rows_returned):
                new_limit = limit - len(max_exception.rows_returned)  # have not returned results to the desired limit
                new_offset = offset + len(max_exception.rows_returned)  # adjust offset
                results = self.search(resource=resource, resource_class=resource_class, search_filter=None,
                                      dmql_query=dmql_query, offset=new_offset, limit=new_limit,
                                      optional_parameters=optional_parameters, auto_offset=auto_offset)

                previous_results = max_exception.rows_returned
                return previous_results + results
            return max_exception.rows_returned

Response: Perform a dmql search on the RETS board and return a dictionary of the results.


Instruction:
How would you implement a function in Python 3 that
makes a request to the RETS server.

Response:
def _request(self, capability, options=None, stream=False):
        """
        Make a _request to the RETS server
        :param capability: The name of the capability to use to get the URI
        :param options: Options to put into the _request
        :return: Response
        """
        if options is None:
            options = {}

        options.update({
            'headers': self.client.headers.copy()
        })

        url = self.capabilities.get(capability)

        if not url:
            msg = "{0!s} tried but no valid endpoints was found. Did you forget to Login?".format(capability)
            raise NotLoggedIn(msg)

        if self.user_agent_password:
            ua_digest = self._user_agent_digest_hash()
            options['headers']['RETS-UA-Authorization'] = 'Digest {0!s}'.format(ua_digest)

        if self.use_post_method and capability != 'Action':  # Action Requests should always be GET
            query = options.get('query')
            response = self.client.post(url, data=query, headers=options['headers'], stream=stream)
        else:
            if 'query' in options:
                url += '?' + '&'.join('{0!s}={1!s}'.format(k, quote(str(v))) for k, v in options['query'].items())

            response = self.client.get(url, headers=options['headers'], stream=stream)

        if response.status_code in [400, 401]:
            if capability == 'Login':
                m = "Could not log into the RETS server with the provided credentials."
            else:
                m = "The RETS server returned a 401 status code. You must be logged in to make this request."
            raise NotLoggedIn(m)

        elif response.status_code == 404 and self.use_post_method:
            raise HTTPException("Got a 404 when making a POST request. Try setting use_post_method=False when "
                                "initializing the Session.")

        return response


Instruction:
Can you create a Python 3 function that
hashes the user agent and password and return the md5 hash

Response:
def _user_agent_digest_hash(self):
        """
        Hash the user agent and user agent password
        Section 3.10 of https://www.nar.realtor/retsorg.nsf/retsproto1.7d6.pdf
        :return: md5
        """
        if not self.version:
            raise MissingVersion("A version is required for user agent auth. The RETS server should set this"
                                 "automatically but it has not. Please instantiate the session with a version argument"
                                 "to provide the version.")
        version_number = self.version.strip('RETS/')
        user_str = '{0!s}:{1!s}'.format(self.user_agent, self.user_agent_password).encode('utf-8')
        a1 = hashlib.md5(user_str).hexdigest()
        session_id = self.session_id if self.session_id is not None else ''
        digest_str = '{0!s}::{1!s}:{2!s}'.format(a1, session_id, version_number).encode('utf-8')
        digest = hashlib.md5(digest_str).hexdigest()
        return digest


Instruction:
Given the following Python 3 function, write the documentation
def exempt(self, obj):
        name = '%s.%s' % (obj.__module__, obj.__name__)

        @wraps(obj)
        def __inner(*a, **k):
            return obj(*a, **k)

        self._exempt_routes.add(name)
        return __inner

Response: Decorator to mark a view as exempt from htmlmin.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dmql(query):
        if isinstance(query, dict):
            raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required."
                                " Did you mean to pass this to the search_filter parameter? ")

        # automatically surround the given query with parentheses if it doesn't have them already
        if len(query) > 0 and query != "*" and query[0] != '(' and query[-1] != ')':
            query = '({})'.format(query)
        return query

Response: Client supplied raw DMQL ensure quote wrap.


Instruction:
Create a Python 3 function for
converting a dictionary of filter values into a DMQL query string.

Response:
def filter_to_dmql(filter_dict):
        """Converts the filter dictionary into DMQL"""

        if not isinstance(filter_dict, (dict, collections.OrderedDict)):
            raise TypeError('Expected a dictionary type buy got {} instead.'.format(type(filter_dict)))

        def is_date_time_type(val):
            """Returns True if the value is a datetime"""
            return isinstance(val, (datetime.datetime, datetime.date, datetime.time))

        def evaluate_datetime(val):
            """Converts the datetime object into the RETS expected format"""
            date_format = '%Y-%m-%d'
            time_format = '%H:%M:%S'
            datetime_format = '{}T{}'.format(date_format, time_format)

            if isinstance(val, datetime.datetime):
                evaluated = val.strftime(datetime_format)
            elif isinstance(val, datetime.date):
                evaluated = val.strftime(date_format)
            elif isinstance(val, datetime.time):
                evaluated = val.strftime(time_format)
            else:
                evaluated = val

            return evaluated

        def evaluate_operators(key_dict):
            """Turns the custom filter operators into the expected RETS query"""
            allowed_operators = ['$gte', '$lte', '$contains', '$begins', '$ends', '$in', '$nin', '$neq']

            # If key not in allowed_operators, assume it is a field name with the and operation.
            if not all(op in allowed_operators for op in key_dict.keys()):
                raise ValueError("You have supplied an invalid operator. "
                                 "Please provide one of the following {}".format(allowed_operators))

            # We can have a single operator key, or the combination of gte/lte
            keys = key_dict.keys()
            string = ''

            # Search between two numbers or two dates
            if len(keys) == 2 and all(k in ['$gte', '$lte'] for k in keys):
                if all(is_date_time_type(key_dict[v]) for v in keys):
                    # comparing dates
                    string = '{}-{}'.format(evaluate_datetime(key_dict['$gte']), evaluate_datetime(key_dict['$lte']))
                else:
                    # comparing numbers
                    try:
                        float(key_dict['$gte'])
                        float(key_dict['$lte'])
                    except ValueError:
                        raise ValueError("$gte and $lte expect numeric or datetime values")
                    string = '{:.2f}-{:.2f}'.format(key_dict['$gte'], key_dict['$lte'])

            # Using a single operator key
            elif len(keys) == 1:
                if '$gte' in key_dict:
                    if is_date_time_type(key_dict['$gte']):
                        string = '{}+'.format(evaluate_datetime(key_dict['$gte']))
                    else:
                        try:
                            float(key_dict['$gte'])
                        except ValueError:
                            raise ValueError("$gte expects a numeric value or a datetime object")
                        string = '{:.2f}+'.format(key_dict['$gte'])

                elif '$lte' in key_dict:
                    if is_date_time_type(key_dict['$lte']):
                        string = '{}-'.format(evaluate_datetime(key_dict['$lte']))
                    else:
                        try:
                            float(key_dict['$lte'])
                        except ValueError:
                            raise ValueError("$lte expects a numeric value or a datetime object")
                        string = '{:.2f}-'.format(key_dict['$lte'])

                elif '$in' in key_dict:
                    if not isinstance(key_dict['$in'], list):
                        raise ValueError("$in expects a list of strings")
                    key_dict['$in'] = [evaluate_datetime(v) for v in key_dict['$in']]
                    if not all(isinstance(v, string_types) for v in key_dict['$in']):
                        raise ValueError("$in expects a list of strings")
                    options = ','.join(key_dict['$in'])
                    string = '{}'.format(options)

                elif '$nin' in key_dict:
                    if not isinstance(key_dict['$nin'], list):
                        raise ValueError("$nin expects a list of strings")
                    key_dict['$nin'] = [evaluate_datetime(v) for v in key_dict['$nin']]
                    if not all(isinstance(v, string_types) for v in key_dict['$nin']):
                        raise ValueError("$nin expects a list of strings")
                    options = ','.join(key_dict['$nin'])
                    string = '~{}'.format(options)

                elif '$contains' in key_dict:
                    if not isinstance(key_dict['$contains'], string_types):
                        raise ValueError("$contains expects a string.")
                    string = '*{}*'.format(key_dict['$contains'])

                elif '$begins' in key_dict:
                    if not isinstance(key_dict['$begins'], string_types):
                        raise ValueError("$begins expects a string.")
                    string = '{}*'.format(key_dict['$begins'])

                elif '$ends' in key_dict:
                    if not isinstance(key_dict['$ends'], string_types):
                        raise ValueError("$ends expects a string.")
                    string = '*{}'.format(key_dict['$ends'])

                elif '$neq' in key_dict:
                    string = '~{}'.format(key_dict['$neq'])

            else:
                # Provided too many or too few operators
                raise ValueError("Please supply $gte and $lte for getting values between numbers or 1 of {}".format(
                    allowed_operators))

            return string

        dmql_search_filters = []

        for filt, value in filter_dict.items():
            dmql_string = '({}='.format(filt)
            if isinstance(value, dict):
                # Applying an operator. This will need to be recursive because of the or possibility
                dmql_string += evaluate_operators(key_dict=value)
            else:
                # Simle equals statement
                dmql_string += '{}'.format(evaluate_datetime(value))
            dmql_string += ')'
            dmql_search_filters.append(dmql_string)

        search_string = ','.join(dmql_search_filters)
        # Converts the filter dictionary to dmqp string
        logger.debug("Filter returned the following DMQL: {}".format(search_string))
        return search_string


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_attributes(input_dict):
        return {k.lstrip("@"): v for k, v in input_dict.items() if k[0] == "@"}

Response: Get attributes of xml tags in input_dict and creates a dictionary with the key and the value as the key and the value as the value


Instruction:
How would you explain what the following Python 3 function does
def data_columns_to_dict(columns_string, dict_string, delimiter=None):
        if delimiter:
            return {k: v for k, v in zip(columns_string.split(delimiter), dict_string.split(delimiter))}
        else:
            return {k: v for k, v in zip(columns_string.split(), dict_string.split())}

Response: Turn column names in a single string into a dictionary with the key being the column name and the value being the value in that column for each row.


Instruction:
Given the following Python 3 function, write the documentation
def analyze_reply_code(self, xml_response_dict):
        if 'RETS-STATUS' in xml_response_dict:
            attributes = self.get_attributes(xml_response_dict['RETS-STATUS'])
            reply_code = attributes['ReplyCode']
            reply_text = attributes.get('ReplyText', 'RETS did not supply a Reply Text.')

            logger.debug("Received ReplyCode of {0!s} from the RETS Server: {0!s}".format(reply_code, reply_text))
            if reply_code != '0':
                raise RETSException(reply_text, reply_code)

        elif 'RETS' not in xml_response_dict:  # pragma: no cover
            raise RETSException("The <RETS> tag was expected in the response XML but it was not found.")

        attributes = self.get_attributes(input_dict=xml_response_dict['RETS'])
        if 'ReplyCode' not in attributes:  # pragma: no cover
            # The RETS server did not return a response code.
            return True

        reply_code = attributes['ReplyCode']
        reply_text = attributes.get('ReplyText', 'RETS did not supply a Reply Text.')

        logger.debug("Received ReplyCode of {0!s} from the RETS Server: {0!s}".format(reply_code, reply_text))
        if reply_code != '0':
            raise RETSException(reply_text, reply_code)

Response: Checks the RETS Response Code and handles non - zero answers.


Instruction:
How would you code a function in Python 3 to
append the content and object ids how RETS expects them

Response:
def ids(self, content_ids, object_ids):
        """Appends the content and object ids how RETS expects them"""
        result = []

        content_ids = self.split(content_ids, False)
        object_ids = self.split(object_ids)

        for cid in content_ids:
            result.append('{}:{}'.format(cid, ':'.join(object_ids)))

        return result


Instruction:
Create a Python 3 function to
split value into list of strings.

Response:
def split(value, dash_ranges=True):
        """Splits """
        if isinstance(value, list):
            value = [str(v) for v in value]
        else:
            str_value = str(value)
            dash_matches = re.match(pattern='(\d+)\-(\d+)', string=str_value)

            if ':' in str_value or ',' in str_value:
                value = [v.strip() for v in str_value.replace(',', ':').split(':')]
            elif dash_ranges and dash_matches:
                start_range = int(dash_matches.group(1))
                end_range = int(dash_matches.group(2)) + 1
                rng = range(start_range, end_range)
                value = [str(r) for r in rng]
            else:
                value = [str_value]

        return value


Instruction:
Can you tell what is the following Python 3 function doing
def set_value(self, key, value):
        file_cache = self.read_file()
        if file_cache:
            file_cache[key] = value
        else:
            file_cache = {}
        file_cache[key] = value
        self.update_file(file_cache)

Response: Set the value of the key to the file.


Instruction:
Here you have a function in Python 3, explain what it does
def delete_value(self, key):
        response = {}
        response['status'] = False
        response['msg'] = "key does not exist"

        file_cache = self.read_file()
        if key in file_cache:
            del file_cache[key]
            self.update_file(file_cache)
            response['status'] = True
            response['msg'] = "success"
        return response

Response: Delete the value in the cache.


Instruction:
Can you generate the documentation for the following Python 3 function
def read_file(self):
        file_obj = open(self.file, 'r')
        content = file_obj.read()
        file_obj.close()
        if content:
            content = json.loads(content)
            return content
        else:
            return {}

Response: Reads the file and returns the content in json formate.


Instruction:
Can you tell what is the following Python 3 function doing
def parse(self, response, metadata_type):
        xml = xmltodict.parse(response.text)
        self.analyze_reply_code(xml_response_dict=xml)
        base = xml.get('RETS', {}).get(metadata_type, {})
        attributes = self.get_attributes(base)

        parsed = []
        if base.get('System') or base.get('SYSTEM'):
            system_obj = {}

            if base.get('SYSTEM', {}).get('@SystemDescription'):
                system_obj['system_id'] = str(base['SYSTEM']['@SystemID'])

            if base.get('SYSTEM', {}).get('@SystemDescription'):
                system_obj['system_description'] = str(base['SYSTEM']['@SystemDescription'])

            if base.get('SYSTEM', {}).get('@TimeZoneOffset'):
                system_obj['timezone_offset'] = str(base['SYSTEM']['@TimeZoneOffset'])

            if base.get('SYSTEM', {}).get('Comments'):
                system_obj['comments'] = base['SYSTEM']['Comments']

            if base.get('@Version'):
                system_obj['version'] = base['@Version']

            parsed.append(system_obj)

        elif 'DATA' in base:
            if not isinstance(base['DATA'], list):  # xmltodict could take single entry XML lists and turn them into str
                base['DATA'] = [base['DATA']]

            for data in base['DATA']:
                data_dict = self.data_columns_to_dict(columns_string=base.get('COLUMNS', ''), dict_string=data)
                data_dict.update(attributes)
                parsed.append(data_dict)

        return parsed

Response: Parses RETS metadata using the COMPACT - DECODED format.


Instruction:
How would you explain what the following Python 3 function does
def parse(self, response, metadata_type):
        xml = xmltodict.parse(response.text)
        self.analyze_reply_code(xml_response_dict=xml)
        base = xml.get('RETS', {}).get('METADATA', {}).get(metadata_type, {})

        if metadata_type == 'METADATA-SYSTEM':
            syst = base.get('System', base.get('SYSTEM'))
            if not syst:
                raise ParseError("Could not get the System key from a METADATA-SYSTEM request.")

            system_obj = {}
            if syst.get('SystemID'):
                system_obj['system_id'] = str(syst['SystemID'])
            if syst.get('SystemDescription'):
                system_obj['system_description'] = str(syst['SystemDescription'])
            if syst.get('Comments'):
                system_obj['comments'] = syst['Comments']
            if base.get('@Version'):
                system_obj['version'] = base['@Version']
            return [system_obj]

        elif metadata_type == 'METADATA-CLASS':
            key = 'class'
        elif metadata_type == 'METADATA-RESOURCE':
            key = 'resource'
        elif metadata_type == 'METADATA-LOOKUP_TYPE':
            key = 'lookuptype'
        elif metadata_type == 'METADATA-OBJECT':
            key = 'object'
        elif metadata_type == 'METADATA-TABLE':
            key = 'field'
        else:
            msg = "Got an unknown metadata type of {0!s}".format(metadata_type)
            raise ParseError(msg)

        # Get the version with the right capitalization from the dictionary
        key_cap = None
        for k in base.keys():
            if k.lower() == key:
                key_cap = k

        if not key_cap:
            msg = 'Could not find {0!s} in the response XML'.format(key)
            raise ParseError(msg)

        if isinstance(base[key_cap], list):
            return base[key_cap]
        else:
            return [base[key_cap]]

Response: Parses the RETS metadata using the STANDARD - XML format.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_multiparts(response):
        boundary = None
        for part in response.headers.get('Content-Type', '').split(';'):
            if 'boundary=' in part:
                boundary = '--{}'.format(part.split('=', 1)[1].strip('\"'))
                break

        if not boundary:
            raise ParseError("Was not able to find the boundary between objects in a multipart response")

        if response.content is None:
            return []

        response_string = response.content

        if six.PY3:
            # Python3 returns bytes, decode for string operations
            response_string = response_string.decode('latin-1')

        #  help bad responses be more multipart compliant
        whole_body = response_string.strip('\r\n')
        no_front_boundary = whole_body.strip(boundary)
        # The boundary comes with some characters

        multi_parts = []
        for part in no_front_boundary.split(boundary):
            multi_parts.append(part.strip('\r\n'))

        return multi_parts

Response: Get the list of objects in a multipart response.


Instruction:
Can you tell what is the following Python 3 function doing
def parse_image_response(self, response):
        if 'xml' in response.headers.get('Content-Type'):
            # Got an XML response, likely an error code.
            xml = xmltodict.parse(response.text)
            self.analyze_reply_code(xml_response_dict=xml)

        multi_parts = self._get_multiparts(response)
        parsed = []
        # go through each part of the multipart message
        for part in multi_parts:
            clean_part = part.strip('\r\n\r\n')
            if '\r\n\r\n' in clean_part:
                header, body = clean_part.split('\r\n\r\n', 1)
            else:
                header = clean_part
                body = None
            part_header_dict = {k.strip(): v.strip() for k, v in (h.split(':', 1) for h in header.split('\r\n'))}

            # Some multipart requests respond with a text/XML part stating an error
            if 'xml' in part_header_dict.get('Content-Type'):
                # Got an XML response, likely an error code.
                # Some rets servers give characters after the closing brace.
                body = body[:body.index('/>') + 2]  if '/>' in body else body
                xml = xmltodict.parse(body)
                try:
                    self.analyze_reply_code(xml_response_dict=xml)
                except RETSException as e:
                    if e.reply_code == '20403':
                        # The requested object_id was not found.
                        continue
                    raise e

            if body:
                obj = self._response_object_from_header(
                    obj_head_dict=part_header_dict,
                    content=body.encode('latin-1') if six.PY3 else body)
            else:
                obj = self._response_object_from_header(obj_head_dict=part_header_dict)
            parsed.append(obj)
        return parsed

Response: Parses the response from the RETS feed and returns a list of SingleObjectParser objects.


Instruction:
Can you tell what is the following Python 3 function doing
def parse_image_response(self, response):
        if 'xml' in response.headers.get('Content-Type'):
            # Got an XML response, likely an error code.
            xml = xmltodict.parse(response.text)
            self.analyze_reply_code(xml_response_dict=xml)

        obj = self._response_object_from_header(
            obj_head_dict=response.headers,
            content=response.content)
        return obj

Response: Parse a single object from the RETS feed and return it.


Instruction:
How would you explain what the following Python 3 function does
def auth(self):
        if not self.store_handler.has_value('access_token'):
            params = {}
            params["access_key"] = self.access_key
            params["secret_key"] = self.secret_key
            params["app_id"] = self.app_id
            params["device_id"] = self.device_id
            auth_url = self.api_path + "auth/"
            response = self.get_response(auth_url, params, "post")

            if 'auth' in response:
                self.store_handler.set_value("access_token", response['auth']['access_token'])
                self.store_handler.set_value("expires", response['auth']['expires'])
                logger.info('Getting new access token')
            else:
                msg = "Error getting access_token, " + \
                      "please verify your access_key, secret_key and app_id"
                logger.error(msg)
                raise Exception("Auth Failed, please check your access details")

Response: Auth function is used to get the access token for every request to the server.


Instruction:
Implement a Python 3 function for
getting the active access token.

Response:
def get_active_token(self):
        """
        Getting the valid access token.

           Access token expires every 24 hours, It will expires then it will
           generate a new token.
        Return:
           active access token
        """

        expire_time = self.store_handler.has_value("expires")
        access_token = self.store_handler.has_value("access_token")
        if expire_time and access_token:
            expire_time = self.store_handler.get_value("expires")
            if not datetime.now() < datetime.fromtimestamp(float(expire_time)):
                self.store_handler.delete_value("access_token")
                self.store_handler.delete_value("expires")
                logger.info('Access token expired, going to get new token')
                self.auth()
            else:
                logger.info('Access token noy expired yet')
        else:
            self.auth()
        return self.store_handler.get_value("access_token")


Instruction:
Create a Python 3 function to
call the Match API. Arg: match_key: key of the match card_type: optional, default to full_card. Accepted values are micro_card, summary_card & full_card. Return: json data

Response:
def get_match(self, match_key, card_type="full_card"):
        """
        Calling the Match API.

        Arg:
           match_key: key of the match
           card_type: optional, default to full_card. Accepted values are
           micro_card, summary_card & full_card.
        Return:
           json data
        """

        match_url = self.api_path + "match/" + match_key + "/"
        params = {}
        params["card_type"] = card_type
        response = self.get_response(match_url, params)
        return response


Instruction:
Can you write a function in Python 3 where it
calls the Recent Matches API.

Response:
def get_recent_matches(self, card_type="micro_card"):
        """
        Calling the Recent Matches API.

        Arg:
           card_type: optional, default to micro_card. Accepted values are
           micro_card & summary_card.
        Return:
           json data
        """

        recent_matches_url = self.api_path + "recent_matches/"
        params = {}
        params["card_type"] = card_type
        response = self.get_response(recent_matches_url, params)
        return response


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_player_stats(self, player_key, board_key):
        player_stats_url = self.api_path + 'player/' + player_key + '/league/' + board_key + '/stats/'
        response = self.get_response(player_stats_url)
        return response

Response: Calling the Player Stats API


Instruction:
Can you generate the documentation for the following Python 3 function
def get_ball_by_ball(self, match_key, over_key=None):

        if over_key:
            ball_by_ball_url = "{base_path}match/{match_key}/balls/{over_key}/".format(base_path=self.api_path, match_key=match_key, over_key=over_key)
        else:
            ball_by_ball_url = "{base_path}match/{match_key}/balls/".format(base_path=self.api_path, match_key=match_key)
        response = self.get_response(ball_by_ball_url)
        return response

Response: Get the balls by ball


Instruction:
Create a Python 3 function for
calling specific season recent matches. Arg: season_key: key of the season. Return: json date

Response:
def get_recent_season_matches(self, season_key):
        """
        Calling specific season recent matches.

        Arg:
           season_key: key of the season.
        Return:
           json date
        """

        season_recent_matches_url = self.api_path + "season/" + season_key + "/recent_matches/"
        response = self.get_response(season_recent_matches_url)
        return response


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

        recent_seasons_url = self.api_path + "recent_seasons/"
        response = self.get_response(recent_seasons_url)
        return response

Response: This method returns the recent seasons for the current user


Instruction:
Implement a Python 3 function for
calling the Schedule API.

Response:
def get_schedule(self, date=None):
        """
        Calling the Schedule API.

        Return:
           json data
        """

        schedule_url = self.api_path + "schedule/"
        params = {}
        if date:
            params['date'] = date
        response = self.get_response(schedule_url, params)
        return response


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

        schedule_url = self.api_path + "season/" + season_key + "/schedule/"
        response = self.get_response(schedule_url)
        return response

Response: Calling specific season schedule


Instruction:
Can you tell what is the following Python 3 function doing
def get_season(self, season_key, card_type="micro_card"):

        season_url = self.api_path + "season/" + season_key + "/"
        params = {}
        params["card_type"] = card_type
        response = self.get_response(season_url, params)
        return response

Response: This function returns the neccesary data for a given season.


Instruction:
Implement a Python 3 function for
calling Season Stats API.

Response:
def get_season_stats(self, season_key):
        """
        Calling Season Stats API.

        Arg:
           season_key: key of the season
        Return:
           json data
        """

        season_stats_url = self.api_path + "season/" + season_key + "/stats/"
        response = self.get_response(season_stats_url)
        return response


Instruction:
Make a summary of the following Python 3 code
def get_season_team(self, season_key, season_team_key,stats_type=None):
        params = {"stats_type": stats_type}
        season_team_url = self.api_path + 'season/' +  season_key + '/team/' + season_team_key + '/'
        response = self.get_response(season_team_url, params=params)
        return response

Response: Calling Season teams API


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

        season_points_url = self.api_path + "season/" + season_key + "/points/"
        response = self.get_response(season_points_url)
        return response

Response: This method returns the Season Points API.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_season_player_stats(self, season_key, player_key):

        season_player_stats_url = self.api_path + "season/" + season_key + "/player/" + player_key + "/stats/"
        response = self.get_response(season_player_stats_url)
        return response

Response: Calling Season Player Stats API.


Instruction:
Write a Python 3 script for
calling Overs Summary API

Response:
def get_overs_summary(self, match_key):
        """
        Calling Overs Summary API

        Arg:
           match_key: key of the match
        Return:
           json data
        """
        overs_summary_url = self.api_path + "match/" + match_key + "/overs_summary/"
        response = self.get_response(overs_summary_url)
        return response


Instruction:
Write a Python 3 script to
call News Aggregation API Return: json data

Response:
def get_news_aggregation(self):
        """
        Calling News Aggregation API

        Return:
           json data
        """

        news_aggregation_url = self.api_path + "news_aggregation" + "/"
        response = self.get_response(news_aggregation_url)
        return response


Instruction:
Create a Python 3 function to
call Fantasy Credit API Arg: match_key: key of the match Return: json data

Response:
def get_fantasy_credits(self, match_key):
        """
        Calling Fantasy Credit API

        Arg:
            match_key: key of the match
        Return:
            json data
        """

        fantasy_credit_url = self.api_path_v3 + "fantasy-match-credits/" + match_key + "/"
        response = self.get_response(fantasy_credit_url)
        return response


Instruction:
Implement a Python 3 function for
calling Fantasy Points API Arg: match_key: key of the match Return: json data

Response:
def get_fantasy_points(self, match_key):
        """
        Calling Fantasy Points API

        Arg:
            match_key: key of the match
        Return:
            json data
        """

        fantasy_points_url = self.api_path_v3 + "fantasy-match-points/" + match_key + "/"
        response = self.get_response(fantasy_points_url)
        return response


Instruction:
Can you implement a function in Python 3 that
generates an output string by replacing the keywords in the format string with the corresponding values from a submission dictionary.

Response:
def main(self):
        """
        Generates an output string by replacing the keywords in the format
        string with the corresponding values from a submission dictionary.
        """
        self.manage_submissions()
        out_string = self.options['format']

        # Pop until we get something which len(title) <= max-chars
        length = float('inf')
        while length > self.options['max_chars']:
            self.selected_submission = self.submissions.pop()
            length = len(self.selected_submission['title'])

        for k, v in self.selected_submission.items():
            out_string = out_string.replace(k, self.h.unescape(str(v)))
        return self.output(out_string, out_string)


Instruction:
Can you implement a function in Python 3 that
logs into Reddit in order to display a personalised front page.

Response:
def login(self):
        """
        Logs into Reddit in order to display a personalised front page.
        """
        data = {'user': self.options['username'], 'passwd':
                self.options['password'], 'api_type': 'json'}
        response = self.client.post('http://www.reddit.com/api/login', data=data)
        self.client.modhash = response.json()['json']['data']['modhash']


Instruction:
Can you create a Python 3 function that
manages URL creation and the specifics for front page and subreddit.

Response:
def manage_submissions(self):
        """
        If there are no or only one submissions left, get new submissions.
        This function manages URL creation and the specifics for front page
        or subreddit mode.
        """
        if not hasattr(self, 'submissions') or len(self.submissions) == 1:
            self.submissions = []
            if self.options['mode'] == 'front':
                # If there are no login details, the standard front
                # page will be displayed.
                if self.options['password'] and self.options['username']:
                    self.login()
                url = 'http://reddit.com/.json?sort={0}'.format(self.options['sort'])
                self.submissions = self.get_submissions(url)
            elif self.options['mode'] == 'subreddit':
                for subreddit in self.options['subreddits']:
                    url = 'http://reddit.com/r/{0}/.json?sort={1}'.format(
                        subreddit, self.options['limit'])
                    self.submissions += self.get_submissions(url)
        else:
            return


Instruction:
Can you create a Python 3 function that
connects to Reddit and gets a JSON representation of submissions.

Response:
def get_submissions(self, url):
        """
        Connects to Reddit and gets a JSON representation of submissions.
        This JSON data is then processed and returned.

        url: A url that requests for submissions should be sent to.
        """
        response = self.client.get(url, params={'limit': self.options['limit']})
        submissions = [x['data'] for x in response.json()['data']['children']]
        return submissions


Instruction:
How would you explain what the following Python 3 function does
def main(self):
        try:
            # Setting stderr to subprocess.STDOUT seems to stop the error
            # message returned by the process from being output to STDOUT.
            cmus_output = subprocess.check_output(['cmus-remote', '-Q'],
                                    stderr=subprocess.STDOUT).decode('utf-8')
        except subprocess.CalledProcessError:
            return self.output(None, None)
        if 'duration' in cmus_output:
            status = self.convert_cmus_output(cmus_output)
            out_string = self.options['format']
            for k, v in status.items():
                out_string = out_string.replace(k, v)
        else:
            out_string = None
        return self.output(out_string, out_string)

Response: A compulsary function that gets the output of the cmus - remote - Q command and converts it to unicode and then outputs the result.


Instruction:
Write a Python 3 script to
change the newline separated string of output data into a dictionary which can then be used to replace the strings in the config format.

Response:
def convert_cmus_output(self, cmus_output):
        """
        Change the newline separated string of output data into
        a dictionary which can then be used to replace the strings in the config
        format.

        cmus_output: A string with information about cmus that is newline
        seperated. Running cmus-remote -Q in a terminal will show you what
        you're dealing with.
        """
        cmus_output = cmus_output.split('\n')
        cmus_output = [x.replace('tag ', '') for x in cmus_output if not x in '']
        cmus_output = [x.replace('set ', '') for x in cmus_output]
        status = {}
        partitioned = (item.partition(' ') for item in cmus_output)
        status = {item[0]: item[2] for item in partitioned}
        status['duration'] = self.convert_time(status['duration'])
        status['position'] = self.convert_time(status['position'])
        return status


Instruction:
Create a Python 3 function to
output all of the options and data for a segment.

Response:
def output(self, full_text, short_text):
        """
        Output all of the options and data for a segment.

        full_text: A string representing the data that should be output to i3bar.
        short_text: A more concise version of full_text, in case there is minimal
        room on the i3bar.
        """
        full_text = full_text.replace('\n', '')
        short_text = short_text.replace('\n', '')
        self.output_options.update({'full_text': full_text, 'short_text': short_text})
        self.output_options = {k: v for k, v in self.output_options.items() if v}
        return self.output_options


Instruction:
Can you generate the documentation for the following Python 3 function
def on_click(self, event):
        if event['button'] == 1 and 'button1' in self.options:
            subprocess.call(self.options['button1'].split())
        elif event['button'] == 2 and 'button2' in self.options:
            subprocess.call(self.options['button2'].split())
        elif event['button'] == 3 and 'button3' in self.options:
            subprocess.call(self.options['button3'].split())

Response:
A function that should be overwritten by a plugin that wishes to react to events other than running the react
        command related to a button.


Instruction:
How would you explain what the following Python 3 function does
def url_reverse(request):
    if request.method in ('GET', 'POST'):
        data = getattr(request, request.method)
        url_name = data.get('url_name')
        try:
            path = urls.reverse(url_name, args=data.getlist('args'))
            (view_func, args, kwargs) = urls.resolve(path)
            return http.HttpResponse(path, content_type='text/plain')
        except urls.NoReverseMatch:
            return http.HttpResponse('Error', content_type='text/plain')
    return http.HttpResponseNotAllowed(('GET', 'POST'))

Response: Reverse the requested URL.


Instruction:
Write a Python 3 function that can
return a JSON representation of the image in a complete path.

Response:
def url_image(request, image_id, thumb_options=None, width=None, height=None):
    """
    Converts a filer image ID in a complete path

    :param request: Request object
    :param image_id: Filer image ID
    :param thumb_options: ThumbnailOption ID
    :param width: user-provided width
    :param height: user-provided height
    :return: JSON serialized URL components ('url', 'width', 'height')
    """
    image = File.objects.get(pk=image_id)
    if getattr(image, 'canonical_url', None):
        url = image.canonical_url
    else:
        url = image.url
    thumb = _return_thumbnail(image, thumb_options, width, height)
    if thumb:
        image = thumb
        url = image.url
    data = {
        'url': url,
        'width': image.width,
        'height': image.height,
    }
    return http.HttpResponse(json.dumps(data), content_type='application/json')


Instruction:
Create a Python 3 function for
returning the requested ThumbnailOption as JSON

Response:
def thumbnail_options(request):
    """
    Returns the requested ThumbnailOption as JSON

    :param request: Request object
    :return: JSON serialized ThumbnailOption
    """
    response_data = [{'id': opt.pk, 'name': opt.name} for opt in ThumbnailOption.objects.all()]
    return http.HttpResponse(json.dumps(response_data), content_type="application/json")


Instruction:
Implement a Python 3 function for
returning the content of an image in a Filer object.

Response:
def serve_image(request, image_id, thumb_options=None, width=None, height=None):
    """
    returns the content of an image sized according to the parameters

    :param request: Request object
    :param image_id: Filer image ID
    :param thumb_options: ThumbnailOption ID
    :param width: user-provided width
    :param height: user-provided height
    :return: JSON serialized URL components ('url', 'width', 'height')
    """
    image = File.objects.get(pk=image_id)
    if getattr(image, 'canonical_url', None):
        url = image.canonical_url
    else:
        url = image.url
    thumb = _return_thumbnail(image, thumb_options, width, height)
    if thumb:
        return server.serve(request, file_obj=thumb, save_as=False)
    else:
        return HttpResponseRedirect(url)


Instruction:
Here you have a function in Python 3, explain what it does
def _touch_dir(self, path):
        try:
            os.makedirs(path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

Response: A helper function to create a directory if it doesn t exist.


Instruction:
Given the following Python 3 function, write the documentation
def reload(self):
        self._conf = configparser.ConfigParser()
        # Preserve the case of sections and keys.
        self._conf.optionxform = str
        self._conf.read(self.config_file_path)
        if 'general' not in self._conf.keys():
            raise IncompleteConfigurationFile('Missing the general section')
        general = self._replace_data_types(dict(self._conf.items('general')))
        self._conf.remove_section('general')
        plugin = []
        for section in self._conf.sections():
            plugin.append(dict(self._conf.items(section)))
            plugin[-1].update({'name': section})
            plugin[-1] = self._replace_data_types(plugin[-1])
        return (plugin, general)

Response: Reload the configuration from the file.


Instruction:
How would you code a function in Python 3 to
replace strings with appropriate data types.

Response:
def _replace_data_types(dictionary):
        """
        Replaces strings with appropriate data types (int, boolean).
        Also replaces the human readable logging levels with the integer form.

        dictionary: A dictionary returned from the config file.
        """
        logging_levels = {'NONE': 0, 'NULL': 0, 'DEBUG': 10, 'INFO': 20,
                'WARNING': 30, 'ERROR': 40, 'CRITICAL': 50}
        for k, v in dictionary.items():
            if v in ['true', 'True', 'on']:
                dictionary[k] = True
            elif v in ['false', 'False', 'off']:
                dictionary[k] = False
            elif k == 'log_file' and '~' in v:
                dictionary[k] = v.replace('~', os.path.expanduser('~'))
            elif v in logging_levels:
                dictionary[k] = logging_levels[v]
            elif isinstance(v, str) and v.isnumeric():
                dictionary[k] = int(v)
            elif ',' in v:
                dictionary[k] = [x.strip() for x in v.split(',')]
        return dictionary