Instruction:
How would you explain what the following Python 3 function does
def use_refresh_token(self, refresh_token, scope=None):
        # type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]]
        """
        Creates a new access token, and refresh token, based on the supplied refresh token.
        :return: new access token and new refresh token if the old one had an expiration time
        """

        if refresh_token not in self.refresh_tokens:
            raise InvalidRefreshToken('{} unknown'.format(refresh_token))

        refresh_token_info = self.refresh_tokens[refresh_token]
        if 'exp' in refresh_token_info and refresh_token_info['exp'] < int(time.time()):
            raise InvalidRefreshToken('{} has expired'.format(refresh_token))

        authz_info = self.access_tokens[refresh_token_info['access_token']]

        if scope:
            if not requested_scope_is_allowed(scope, authz_info['granted_scope']):
                logger.debug('trying to refresh token with superset scope, requested_scope=%s, granted_scope=%s',
                             scope, authz_info['granted_scope'])
                raise InvalidScope('Requested scope includes non-granted value')
            scope = ' '.join(scope)
            logger.debug('refreshing token with new scope, old_scope=%s -> new_scope=%s', authz_info['scope'], scope)
        else:
            # OAuth 2.0: scope: "[...] if omitted is treated as equal to the scope originally granted by the resource owner"
            scope = authz_info['granted_scope']

        new_access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],
                                                     authz_info['granted_scope'], scope)

        new_refresh_token = None
        if self.refresh_token_threshold \
                and 'exp' in refresh_token_info \
                and refresh_token_info['exp'] - int(time.time()) < self.refresh_token_threshold:
            # refresh token is close to expiry, issue a new one
            new_refresh_token = self.create_refresh_token(new_access_token.value)
        else:
            self.refresh_tokens[refresh_token]['access_token'] = new_access_token.value

        logger.debug('refreshed tokens, new_access_token=%s new_refresh_token=%s old_refresh_token=%s',
                     new_access_token, new_refresh_token, refresh_token)
        return new_access_token, new_refresh_token

Response: Creates a new access token and a new refresh token based on the supplied refresh token.


Instruction:
How would you code a function in Python 3 to
return the subject identifier for the given user identifier.

Response:
def get_subject_identifier(self, subject_type, user_id, sector_identifier=None):
        # type: (str, str, str) -> str
        """
        Returns a subject identifier for the local user identifier.
        :param subject_type: 'pairwise' or 'public', see

            "OpenID Connect Core 1.0", Section 8.
        :param user_id: local user identifier
        :param sector_identifier: the client's sector identifier,
            see
            "OpenID Connect Core 1.0", Section 1.2
        """

        if user_id not in self.subject_identifiers:
            self.subject_identifiers[user_id] = {}

        if subject_type == 'public':
            if 'public' not in self.subject_identifiers[user_id]:
                new_sub = self._subject_identifier_factory.create_public_identifier(user_id)
                self.subject_identifiers[user_id] = {'public': new_sub}

                logger.debug('created new public sub=% for user_id=%s',
                             self.subject_identifiers[user_id]['public'], user_id)
            sub = self.subject_identifiers[user_id]['public']
            logger.debug('returning public sub=%s', sub)
            return sub
        elif subject_type == 'pairwise':
            if not sector_identifier:
                raise ValueError('sector_identifier cannot be None or empty')

            subject_id = self._subject_identifier_factory.create_pairwise_identifier(user_id, sector_identifier)
            logger.debug('returning pairwise sub=%s for user_id=%s and sector_identifier=%s',
                         subject_id, user_id, sector_identifier)
            sub = self.subject_identifiers[user_id]
            pairwise_set = set(sub.get('pairwise', []))
            pairwise_set.add(subject_id)
            sub['pairwise'] = list(pairwise_set)
            self.subject_identifiers[user_id] = sub
            return subject_id

        raise ValueError('Unknown subject_type={}'.format(subject_type))


Instruction:
Explain what the following Python 3 code does
def authorization_request_verify(authentication_request):
    try:
        authentication_request.verify()
    except MessageException as e:
        raise InvalidAuthenticationRequest(str(e), authentication_request, oauth_error='invalid_request') from e

Response: Verifies that all required parameters and correct values are included in the authentication request.


Instruction:
Can you generate the documentation for the following Python 3 function
def client_id_is_known(provider, authentication_request):
    if authentication_request['client_id'] not in provider.clients:
        logger.error('Unknown client_id \'{}\''.format(authentication_request['client_id']))
        raise InvalidAuthenticationRequest('Unknown client_id',
                                           authentication_request,
                                           oauth_error='unauthorized_client')

Response: Verifies the client identifier is known.


Instruction:
Make a summary of the following Python 3 code
def redirect_uri_is_in_registered_redirect_uris(provider, authentication_request):
    error = InvalidAuthenticationRequest('Redirect uri is not registered',
                                         authentication_request,
                                         oauth_error="invalid_request")
    try:
        allowed_redirect_uris = provider.clients[authentication_request['client_id']]['redirect_uris']
    except KeyError as e:
        logger.error('client metadata is missing redirect_uris')
        raise error

    if authentication_request['redirect_uri'] not in allowed_redirect_uris:
        logger.error("Redirect uri \'{0}\' is not registered for this client".format(authentication_request['redirect_uri']))
        raise error

Response: Verifies that the redirect uri is registered for the client making the request.


Instruction:
Can you write a function in Python 3 where it
verifies that the requested response type is allowed for the client making the request.

Response:
def response_type_is_in_registered_response_types(provider, authentication_request):
    """
    Verifies that the requested response type is allowed for the client making the request.
    :param provider: provider instance
    :param authentication_request: authentication request to verify
    :raise InvalidAuthenticationRequest: if the response type is not allowed
    """
    error = InvalidAuthenticationRequest('Response type is not registered',
                                         authentication_request,
                                         oauth_error='invalid_request')
    try:
        allowed_response_types = provider.clients[authentication_request['client_id']]['response_types']
    except KeyError as e:
        logger.error('client metadata is missing response_types')
        raise error

    if not is_allowed_response_type(authentication_request['response_type'], allowed_response_types):
        logger.error('Response type \'{}\' is not registered'.format(' '.join(authentication_request['response_type'])))
        raise error


Instruction:
Write a Python 3 function for
according to  "OpenID Connect Core 1.0", Section 5.5: "When the userinfo member is used, the request MUST also use a response_type value that results in an Access Token being issued to the Client for use at the UserInfo Endpoint." :param authentication_request: the authentication request to verify :raise InvalidAuthenticationRequest: if the requested claims can not be returned according to the request

Response:
def userinfo_claims_only_specified_when_access_token_is_issued(authentication_request):
    """
    According to
    "OpenID Connect Core 1.0", Section 5.5: "When the userinfo member is used, the request MUST
    also use a response_type value that results in an Access Token being issued to the Client for
    use at the UserInfo Endpoint."
    :param authentication_request: the authentication request to verify
    :raise InvalidAuthenticationRequest: if the requested claims can not be returned according to the request
    """
    will_issue_access_token = authentication_request['response_type'] != ['id_token']
    contains_userinfo_claims_request = 'claims' in authentication_request and 'userinfo' in authentication_request[
        'claims']
    if not will_issue_access_token and contains_userinfo_claims_request:
        raise InvalidAuthenticationRequest('Userinfo claims cannot be requested, when response_type=\'id_token\'',
                                           authentication_request,
                                           oauth_error='invalid_request')


Instruction:
Implement a function in Python 3 to
verify that all required parameters and correct values are included in the client registration request.

Response:
def registration_request_verify(registration_request):
    """
    Verifies that all required parameters and correct values are included in the client registration request.
    :param registration_request: the authentication request to verify
    :raise InvalidClientRegistrationRequest: if the registration is incorrect
    """
    try:
        registration_request.verify()
    except MessageException as e:
        raise InvalidClientRegistrationRequest(str(e), registration_request, oauth_error='invalid_request') from e


Instruction:
Implement a function in Python 3 to
verify that all requested preferences in the client metadata can be fulfilled by this provider.

Response:
def client_preferences_match_provider_capabilities(provider, registration_request):
    """
    Verifies that all requested preferences in the client metadata can be fulfilled by this provider.
    :param registration_request: the authentication request to verify
    :raise InvalidClientRegistrationRequest: if the registration is incorrect
    """

    def match(client_preference, provider_capability):
        if isinstance(client_preference, list):
            # deal with comparing space separated values, e.g. 'response_types', without considering the order
            # at least one requested preference must be matched
            return len(find_common_values(client_preference, provider_capability)) > 0

        return client_preference in provider_capability

    for client_preference in registration_request.keys():
        if client_preference not in PREFERENCE2PROVIDER:
            # metadata parameter that shouldn't be matched
            continue

        provider_capability = PREFERENCE2PROVIDER[client_preference]
        if not match(registration_request[client_preference], provider.configuration_information[provider_capability]):
            raise InvalidClientRegistrationRequest(
                'Could not match client preference {}={} with provider capability {}={}'.format(
                    client_preference, registration_request[client_preference], provider_capability,
                    provider.configuration_information[provider_capability]),
                registration_request,
                oauth_error='invalid_request')


Instruction:
Create a Python 3 function to
compute the n - th term in the infinite sum of the Jacobi density.

Response:
def _psi_n(x, n, b):
    """
    Compute the n-th term in the infinite sum of
    the Jacobi density.
    """
    return 2**(b-1) / gamma(b) * (-1)**n * \
    np.exp(gammaln(n+b) -
           gammaln(n+1) +
           np.log(2*n+b) -
           0.5 * np.log(2*np.pi*x**3) -
           (2*n+b)**2 / (8.*x))


Instruction:
Can you generate the documentation for the following Python 3 function
def _tilt(omega, b, psi):
    return np.cosh(psi/2.0)**b * np.exp(-psi**2/2.0 * omega)

Response:
Compute the tilt of the PG density for value omega
    and tilt psi.


Instruction:
Write a Python 3 script for
computing the density log PG of omega | b psi

Response:
def pgpdf(omega, b, psi, trunc=200):
    """
    Approximate the density log PG(omega | b, psi) using a
    truncation of the density written as an infinite sum.

    :param omega: point at which to evaluate density
    :param b:   first parameter of PG
    :param psi: tilting of PG
    :param trunc: number of terms in sum
    """
    ns = np.arange(trunc)
    psi_ns = np.array([_psi_n(omega, n, b) for n in ns])
    pdf = np.sum(psi_ns, axis=0)

    # Account for tilting
    pdf *= _tilt(omega, b, psi)

    return pdf


Instruction:
Can you write a function in Python 3 where it
converts a psi array to a probability vector pi.

Response:
def psi_to_pi(psi, axis=None):
    """
    Convert psi to a probability vector pi
    :param psi:     Length K-1 vector
    :return:        Length K normalized probability vector
    """
    if axis is None:
        if psi.ndim == 1:
            K = psi.size + 1
            pi = np.zeros(K)

            # Set pi[1..K-1]
            stick = 1.0
            for k in range(K-1):
                pi[k] = logistic(psi[k]) * stick
                stick -= pi[k]

            # Set the last output
            pi[-1] = stick
            # DEBUG
            assert np.allclose(pi.sum(), 1.0)

        elif psi.ndim == 2:
            M, Km1 = psi.shape
            K = Km1 + 1
            pi = np.zeros((M,K))

            # Set pi[1..K-1]
            stick = np.ones(M)
            for k in range(K-1):
                pi[:,k] = logistic(psi[:,k]) * stick
                stick -= pi[:,k]

            # Set the last output
            pi[:,-1] = stick

            # DEBUG
            assert np.allclose(pi.sum(axis=1), 1.0)

        else:
            raise ValueError("psi must be 1 or 2D")
    else:
        K = psi.shape[axis] + 1
        pi = np.zeros([psi.shape[dim] if dim != axis else K for dim in range(psi.ndim)])
        stick = np.ones(psi.shape[:axis] + psi.shape[axis+1:])
        for k in range(K-1):
            inds = [slice(None) if dim != axis else k for dim in range(psi.ndim)]
            pi[inds] = logistic(psi[inds]) * stick
            stick -= pi[inds]
        pi[[slice(None) if dim != axis else -1 for dim in range(psi.ndim)]] = stick
        assert np.allclose(pi.sum(axis=axis), 1.)

    return pi


Instruction:
Explain what the following Python 3 code does
def verify_client_authentication(clients, parsed_request, authz_header=None):
    # type: (Mapping[str, str], Mapping[str, Mapping[str, Any]], Optional[str]) -> bool
    """
    Verifies client authentication at the token endpoint, see
    "The OAuth 2.0 Authorization Framework",
    Section 2.3.1
    :param parsed_request: key-value pairs from parsed urlencoded request
    :param clients: clients db
    :param authz_header: the HTTP Authorization header value
    :return: the unmodified parsed request
    :raise InvalidClientAuthentication: if the client authentication was incorrect
    """
    client_id = None
    client_secret = None
    authn_method = None
    if authz_header:
        logger.debug('client authentication in Authorization header %s', authz_header)

        authz_scheme = authz_header.split(maxsplit=1)[0]
        if authz_scheme == 'Basic':
            authn_method = 'client_secret_basic'
            credentials = authz_header[len('Basic '):]
            missing_padding = 4 - len(credentials) % 4
            if missing_padding:
                credentials += '=' * missing_padding
            try:
                auth = base64.urlsafe_b64decode(credentials.encode('utf-8')).decode('utf-8')
            except UnicodeDecodeError as e:
                raise InvalidClientAuthentication('Could not userid/password from authorization header'.format(authz_scheme))
            client_id, client_secret = auth.split(':')
        else:
            raise InvalidClientAuthentication('Unknown scheme in authorization header, {} != Basic'.format(authz_scheme))
    elif 'client_id' in parsed_request:
        logger.debug('client authentication in request body %s', parsed_request)

        client_id = parsed_request['client_id']
        if 'client_secret' in parsed_request:
            authn_method = 'client_secret_post'
            client_secret = parsed_request['client_secret']
        else:
            authn_method = 'none'
            client_secret = None

    if client_id not in clients:
        raise InvalidClientAuthentication('client_id \'{}\' unknown'.format(client_id))

    client_info = clients[client_id]
    if client_secret != client_info.get('client_secret', None):
        raise InvalidClientAuthentication('Incorrect client_secret')

    expected_authn_method = client_info.get('token_endpoint_auth_method', 'client_secret_basic')
    if authn_method != expected_authn_method:
        raise InvalidClientAuthentication(
            'Wrong authentication method used, MUST use \'{}\''.format(expected_authn_method))

    return client_id

Response: Verifies the client authentication at the token endpoint.


Instruction:
Make a summary of the following Python 3 code
def add_visualization(self, visualization, size_x=6, size_y=3, col=0, row=0):
        new_panel_index = self.get_max_index()+1
        if col and row:
            new_panel = {
                'col': col, 'row': row,
                'size_x': size_x, 'size_y': size_y,
                'panelIndex': new_panel_index,
                'type': 'visualization',
                'id': visualization.id
            }
            self.panels.append(new_panel)
            return new_panel
        else:
            new_panel = append_panel(self.panels, size_x, size_y)
            if new_panel:
                new_panel['id'] = visualization.id
                new_panel['panelIndex'] = new_panel_index
                new_panel['type'] = 'visualization'
                return new_panel

Response: Adds a visualization to the dashboard.


Instruction:
Write a Python 3 script to
remove all visualizations with the specified id from the dashboard.

Response:
def remove_visualization(self, visualization_id):
        """
        Removes all visualizations with the specified id from the dashboard
        :param visualization_id:
        :return:
        """
        for i, panel in enumerate(self.panels):
            if panel['id'] == visualization_id:
                del self.panels[i]


Instruction:
Implement a Python 3 function for
returning a list of all visualizations

Response:
def get_all(self):
        """
        Returns a list of all visualizations
        :return: list of the Visualization instances
        """
        res = self.es.search(index=self.index, doc_type=self.doc_type, body={'query': {'match_all': {}}})
        if not res['hits']['total']:
            return []
        return [Visualization.from_kibana(hit) for hit in res['hits']['hits']]


Instruction:
Write a Python 3 script for
adding a new visualization to the index

Response:
def add(self, visualization):
        """
        Creates a new visualization
        :param visualization: instance of Visualization
        :return:
        """
        res = self.es.create(index=self.index,
                             id=visualization.id or str(uuid.uuid1()),
                             doc_type=self.doc_type,
                             body=visualization.to_kibana(), refresh=True)
        return res


Instruction:
Given the following Python 3 function, write the documentation
def update(self, visualization):
        res = self.es.update(index=self.index, id=visualization.id, doc_type=self.doc_type,
                             body={'doc': visualization.to_kibana()},
                             refresh=True)
        return res

Response: Updates existing visualization with new data


Instruction:
Can you implement a function in Python 3 that
deletes the visualization s related items from the index

Response:
def remove(self, visualization):
        """
        Deletes the visualization
        :param visualization: instance of Visualization that was previously loaded
        :return:
        """
        res = self.es.delete(index=self.index, id=visualization.id, doc_type=self.doc_type, refresh=True)
        return res


Instruction:
Write a Python 3 script for
finding bottom lines of all panels in a

Response:
def bottoms(panels):
    """
    Finds bottom lines of all panels
    :param panels:
    :return: sorted by row list of tuples representing lines (col, row , col + len, row)
    """
    bottom_lines = [(p['col'], p['row'] + p['size_y'], p['col'] + p['size_x'], p['row'] + p['size_y']) for p in panels]
    return sorted(bottom_lines, key=lambda l: l[1], reverse=True)


Instruction:
Make a summary of the following Python 3 code
def find_shape(bottom_lines, max_len):
    shape = [1] * max_len
    for i in range(max_len):
        for line in bottom_lines:
            if line[0] <= i + 1 < line[2]:
                shape[i] = line[1]
                break
    return shape

Response: Find a shape of lowest horizontal lines with step = 1


Instruction:
Explain what the following Python 3 code does
def longest_lines(shape):
    lines = []
    for level in set(shape):
        count = 0
        for i in range(len(shape)):
            if shape[i] <= level:
                count += 1
            elif count:
                lines.append({'row': level, 'col': i - count + 1, 'len': count})
                count = 0
        if count:
            lines.append({'row': level, 'col': i - count + 2, 'len': count})

    return sorted(lines, key=lambda l: l['row'])

Response: Creates lines from shape containing longest available data.


Instruction:
Implement a function in Python 3 to
append a panel to the list of panels.

Response:
def append_panel(panels, size_x, size_y, max_col=12):
    """
    Appends a panel to the list of panels. Finds the highest palce at the left for the new panel.
    :param panels:
    :param size_x:
    :param size_y:
    :param max_col:
    :return: a new panel or None if it is not possible to place a panel with such size_x
    """
    bottom_lines = bottoms(panels)
    shape = find_shape(bottom_lines, max_col)
    lines = longest_lines(shape)
    line = find_place(lines, size_x)
    if not line:
        return
    panel = {
        'col': line['col'],
        'row': line['row'],
        'size_x': size_x,
        'size_y': size_y,
    }
    panels.append(panel)
    return panel


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

        self.test_runner = test_runner_class
        super(Command, self).run_from_argv(argv)

Response: Set the default test runner for the command.


Instruction:
Given the following Python 3 function, write the documentation
def handle(self, *test_labels, **options):
        if not options.get('testrunner', None):
            options['testrunner'] = test_runner_class

        return super(Command, self).handle(*test_labels, **options)

Response: Set the default Gherkin test runner.


Instruction:
How would you explain what the following Python 3 function does
def django_url(step, url=None):

    base_url = step.test.live_server_url

    if url:
        return urljoin(base_url, url)
    else:
        return base_url

Response: Returns the URL for a page from the test server.


Instruction:
Write a Python 3 function for
filtering by namespace. Try to guess which field to use in lookup. Accept 'to' argument if you need to specify.

Response:
def namespace(self, namespace, to=None):
        """
        Filter by namespace. Try to guess which field to use in lookup.
        Accept 'to' argument if you need to specify.
        """
        fields = get_apphook_field_names(self.model)
        if not fields:
            raise ValueError(
                ugettext(
                    'Can\'t find any relation to an ApphookConfig model in {0}'
                ).format(self.model.__name__)
            )
        if to and to not in fields:
            raise ValueError(
                ugettext(
                    'Can\'t find relation to ApphookConfig model named '
                    '"{0}" in "{1}"'
                ).format(to, self.model.__name__)
            )
        if len(fields) > 1 and to not in fields:
            raise ValueError(
                ugettext(
                    '"{0}" has {1} relations to an ApphookConfig model.'
                    ' Please, specify which one to use in argument "to".'
                    ' Choices are: {2}'
                ).format(
                    self.model.__name__, len(fields), ', '.join(fields)
                )
            )
        else:
            if not to:
                to = fields[0]

        lookup = '{0}__namespace'.format(to)
        kwargs = {lookup: namespace}
        return self.filter(**kwargs)


Instruction:
How would you code a function in Python 3 to
return the select value for apphook configs clf_id

Response:
def _app_config_select(self, request, obj):
        """
        Return the select value for apphook configs

        :param request: request object
        :param obj: current object
        :return: False if no preselected value is available (more than one or no apphook
                 config is present), apphook config instance if exactly one apphook
                 config is defined or apphook config defined in the request or in the current
                 object, False otherwise
        """
        if not obj and not request.GET.get(self.app_config_attribute, False):
            config_model = get_apphook_model(self.model, self.app_config_attribute)
            if config_model.objects.count() == 1:
                return config_model.objects.first()
            return None
        elif obj and getattr(obj, self.app_config_attribute, False):
            return getattr(obj, self.app_config_attribute)
        elif request.GET.get(self.app_config_attribute, False):
            config_model = get_apphook_model(self.model, self.app_config_attribute)
            return config_model.objects.get(
                pk=int(request.GET.get(self.app_config_attribute, False))
            )
        return False


Instruction:
Write a Python 3 script for
setting the form value according to the apphook config values.

Response:
def _set_config_defaults(self, request, form, obj=None):
        """
        Cycle through app_config_values and sets the form value according to the
        options in the current apphook config.

        self.app_config_values is a dictionary containing config options as keys, form fields as
        values::

            app_config_values = {
                'apphook_config': 'form_field',
                ...
            }

        :param request: request object
        :param form: model form for the current model
        :param obj: current object
        :return: form with defaults set
        """
        for config_option, field in self.app_config_values.items():
            if field in form.base_fields:
                form.base_fields[field].initial = self.get_config_data(request, obj, config_option)
        return form


Instruction:
How would you implement a function in Python 3 that
returns a list of fieldset objects for the apphook config.

Response:
def get_fieldsets(self, request, obj=None):
        """
        If the apphook config must be selected first, returns a fieldset with just the
         app config field and help text
        :param request:
        :param obj:
        :return:
        """
        app_config_default = self._app_config_select(request, obj)
        if app_config_default is None and request.method == 'GET':
            return (_(self.app_config_selection_title),
                    {'fields': (self.app_config_attribute, ),
                     'description': _(self.app_config_selection_desc)}),
        else:
            return super(ModelAppHookConfig, self).get_fieldsets(request, obj)


Instruction:
Can you tell what is the following Python 3 function doing
def get_form(self, request, obj=None, **kwargs):
        form = super(ModelAppHookConfig, self).get_form(request, obj, **kwargs)
        if self.app_config_attribute not in form.base_fields:
            return form
        app_config_default = self._app_config_select(request, obj)
        if app_config_default:
            form.base_fields[self.app_config_attribute].initial = app_config_default
            get = copy.copy(request.GET)
            get[self.app_config_attribute] = app_config_default.pk
            request.GET = get
        elif app_config_default is None and request.method == 'GET':
            class InitialForm(form):
                class Meta(form.Meta):
                    fields = (self.app_config_attribute,)
            form = InitialForm
        form = self._set_config_defaults(request, form, obj)
        return form

Response: Returns the right form according to the context.


Instruction:
How would you implement a function in Python 3 that
generates a hash of verbose names to models

Response:
def _models_generator():
    """
    Build a hash of model verbose names to models
    """

    for app in apps.get_app_configs():
        for model in app.get_models():
            yield (str(model._meta.verbose_name).lower(), model)
            yield (str(model._meta.verbose_name_plural).lower(), model)


Instruction:
How would you implement a function in Python 3 that
returns a model class by its verbose name.

Response:
def get_model(name):
    """
    Convert a model's verbose name to the model class. This allows us to
    use the models verbose name in steps.
    """

    model = MODELS.get(name.lower(), None)

    assert model, "Could not locate model by name '%s'" % name

    return model


Instruction:
How would you implement a function in Python 3 that
resets the ID sequence for a given model.

Response:
def reset_sequence(model):
    """
    Reset the ID sequence for a model.
    """
    sql = connection.ops.sequence_reset_sql(no_style(), [model])
    for cmd in sql:
        connection.cursor().execute(cmd)


Instruction:
Explain what the following Python 3 code does
def _dump_model(model, attrs=None):

    fields = []

    for field in model._meta.fields:
        fields.append((field.name, str(getattr(model, field.name))))

    if attrs is not None:
        for attr in attrs:
            fields.append((attr, str(getattr(model, attr))))

    for field in model._meta.many_to_many:
        vals = getattr(model, field.name)
        fields.append((field.name, '{val} ({count})'.format(
            val=', '.join(map(str, vals.all())),
            count=vals.count(),
        )))

    print(', '.join(
        '{0}={1}'.format(field, value)
        for field, value in fields
    ))

Response: Dump the model fields for debugging.


Instruction:
Given the following Python 3 function, write the documentation
def _model_exists_step(self, model, should_exist):

    model = get_model(model)
    data = guess_types(self.hashes)

    queryset = model.objects

    try:
        existence_check = _TEST_MODEL[model]
    except KeyError:
        existence_check = test_existence

    failed = 0
    try:
        for hash_ in data:
            match = existence_check(queryset, hash_)

            if should_exist:
                assert match, \
                    "%s does not exist: %s" % (model.__name__, hash_)
            else:
                assert not match, \
                    "%s exists: %s" % (model.__name__, hash_)

    except AssertionError as exc:
        print(exc)
        failed += 1

    if failed:
        print("Rows in DB are:")
        for existing_model in queryset.all():
            _dump_model(existing_model,
                        attrs=[k[1:]
                               for k in data[0].keys()
                               if k.startswith('@')])

        if should_exist:
            raise AssertionError("%i rows missing" % failed)
        else:
            raise AssertionError("%i rows found" % failed)

Response: Test for existence of a model matching the given data.


Instruction:
Here you have a function in Python 3, explain what it does
def write_models(model, data, field):
    written = []

    for hash_ in data:
        if field:
            if field not in hash_:
                raise KeyError(("The \"%s\" field is required for all update "
                                "operations") % field)

            model_kwargs = {field: hash_[field]}
            model_obj = model.objects.get(**model_kwargs)

            for to_set, val in hash_.items():
                setattr(model_obj, to_set, val)

            model_obj.save()

        else:
            model_obj = model.objects.create(**hash_)

        written.append(model_obj)

    reset_sequence(model)
    return written

Response: Writes models for each data hash to the database.


Instruction:
Make a summary of the following Python 3 code
def _write_models_step(self, model, field=None):

    model = get_model(model)
    data = guess_types(self.hashes)

    try:
        func = _WRITE_MODEL[model]
    except KeyError:
        func = partial(write_models, model)

    func(data, field)

Response: Write or update a model.


Instruction:
Write a Python 3 script to
create a new model linked to the given model.

Response:
def _create_models_for_relation_step(self, rel_model_name,
                                     rel_key, rel_value, model):
    """
    Create a new model linked to the given model.

    Syntax:

        And `model` with `field` "`value`" has `new model` in the database:

    Example:

    .. code-block:: gherkin

        And project with name "Ball Project" has goals in the database:
            | description                             |
            | To have fun playing with balls of twine |
    """

    model = get_model(model)
    lookup = {rel_key: rel_value}
    rel_model = get_model(rel_model_name).objects.get(**lookup)

    data = guess_types(self.hashes)

    for hash_ in data:
        hash_['%s' % rel_model_name] = rel_model

    try:
        func = _WRITE_MODEL[model]
    except KeyError:
        func = partial(write_models, model)

    func(data, None)


Instruction:
Explain what the following Python 3 code does
def _create_m2m_links_step(self, rel_model_name,
                           rel_key, rel_value, relation_name):
    """
    Link many-to-many models together.

    Syntax:

        And `model` with `field` "`value`" is linked to `other model` in the
        database:

    Example:

    .. code-block:: gherkin

        And article with name "Guidelines" is linked to tags in the database:
            | name   |
            | coding |
            | style  |
    """

    lookup = {rel_key: rel_value}
    rel_model = get_model(rel_model_name).objects.get(**lookup)
    relation = None
    for m2m in rel_model._meta.many_to_many:
        if relation_name in (m2m.name, m2m.verbose_name):
            relation = getattr(rel_model, m2m.name)
            break
    if not relation:
        try:
            relation = getattr(rel_model, relation_name)
        except AttributeError:
            pass
    assert relation, \
        "%s does not have a many-to-many relation named '%s'" % (
            rel_model._meta.verbose_name.capitalize(),
            relation_name,
        )
    m2m_model = relation.model

    for hash_ in self.hashes:
        relation.add(m2m_model.objects.get(**hash_))

Response: Create many - to - many links for a given model.


Instruction:
Given the following Python 3 function, write the documentation
def _model_count_step(self, count, model):

    model = get_model(model)

    expected = int(count)
    found = model.objects.count()
    assert found == expected, "Expected %d %s, found %d." % \
        (expected, model._meta.verbose_name_plural, found)

Response: Count the number of models in the database.


Instruction:
Implement a Python 3 function for
testing that count mails have been sent.

Response:
def mail_sent_count(self, count):
    """
    Test that `count` mails have been sent.

    Syntax:

        I have sent `count` emails

    Example:

    .. code-block:: gherkin

        Then I have sent 2 emails
    """
    expected = int(count)
    actual = len(mail.outbox)
    assert expected == actual, \
        "Expected to send {0} email(s), got {1}.".format(expected, actual)


Instruction:
Implement a Python 3 function for
testing an email contains the given text in the relevant

Response:
def mail_sent_content(self, text, part):
    """
    Test an email contains (assert text in) the given text in the relevant
    message part (accessible as an attribute on the email object).

    This step strictly applies whitespace.

    Syntax:

        I have sent an email with "`text`" in the `part`

    Example:

    .. code-block:: gherkin

        Then I have sent an email with "pandas" in the body
    """
    if not any(text in getattr(email, part) for email in mail.outbox):
        dump_emails(part)
        raise AssertionError(
            "No email contained expected text in the {0}.".format(part))


Instruction:
Create a Python 3 function for
testing that an email has the HTML in the multiline as

Response:
def mail_sent_contains_html(self):
    """
    Test that an email contains the HTML (assert HTML in) in the multiline as
    one of its MIME alternatives.

    The HTML is normalised by passing through Django's
    :func:`django.test.html.parse_html`.

    Example:

    .. code-block:: gherkin

        And I have sent an email with the following HTML alternative:
        \"\"\"

Name: Sir Panda

Phone: 0400000000

Email: sir.panda@pand.as

        \"\"\"
    """

    for email in mail.outbox:
        try:
            html = next(content for content, mime in email.alternatives
                        if mime == 'text/html')
            dom1 = parse_html(html)
            dom2 = parse_html(self.multiline)

            assert_in(dom1, dom2)

        except AssertionError as exc:
            print("Email did not match", exc)
            # we intentionally eat the exception
            continue

        return True

    raise AssertionError("No email contained the HTML")


Instruction:
Write a Python 3 script for
showing the sent emails to aid in debugging.

Response:
def dump_emails(part):
    """Show the sent emails' tested parts, to aid in debugging."""

    print("Sent emails:")
    for email in mail.outbox:
        print(getattr(email, part))


Instruction:
Write a Python 3 script for
returning an absolute URL matching named view with its parameters and the application instance namespace.

Response:
def namespace_url(context, view_name, *args, **kwargs):
    """
    Returns an absolute URL matching named view with its parameters and the
    provided application instance namespace.

    If no namespace is passed as a kwarg (or it is "" or None), this templatetag
    will look into the request object for the app_config's namespace. If there
    is still no namespace found, this tag will act like the normal {% url ... %}
    template tag.

    Normally, this tag will return whatever is returned by the ultimate call to
    reverse, which also means it will raise NoReverseMatch if reverse() cannot
    find a match. This behaviour can be override by suppling a 'default' kwarg
    with the value of what should be returned when no match is found.
    """

    namespace = kwargs.pop('namespace', None)

    if not namespace:
        namespace, __ = get_app_instance(context['request'])

    if namespace:
        namespace += ':'

    reverse = partial(
        urls.reverse, '{0:s}{1:s}'.format(namespace, view_name))

    # We're explicitly NOT happy to just re-raise the exception, as that may
    # adversely affect stack traces.
    if 'default' not in kwargs:
        if kwargs:
            return reverse(kwargs=kwargs)
        elif args:
            return reverse(args=args)
        else:
            return reverse()

    default = kwargs.pop('default', None)
    try:
        if kwargs:
            return reverse(kwargs=kwargs)
        elif args:
            return reverse(args=args)
        else:
            return reverse()
    except urls.NoReverseMatch:
        return default


Instruction:
How would you explain what the following Python 3 function does
def get_app_instance(request):
    app = None
    if getattr(request, 'current_page', None) and request.current_page.application_urls:
        app = apphook_pool.get_apphook(request.current_page.application_urls)
    if app and app.app_config:
        try:
            config = None
            with override(get_language_from_request(request, check_path=True)):
                namespace = resolve(request.path_info).namespace
                config = app.get_config(namespace)
            return namespace, config
        except Resolver404:
            pass
    return '', None

Response: Returns the current namespace and AppHookConfig instance of the current AppHook


Instruction:
Write a Python 3 function for
registering the provided form as config form for the provided config model

Response:
def setup_config(form_class, config_model=None):
    """
    Register the provided form as config form for the provided config model

    This can be used as a decorator by adding a `model` attribute to the config form::

        @setup_config
        class ExampleConfigForm(AppDataForm):
            model = ExampleConfig

    :param form_class: Form class derived from AppDataForm
    :param config_model: Model class derived from AppHookConfig
    :return:
    """
    # allow use as a decorator
    if config_model is None:
        return setup_config(form_class, form_class.model)

    app_registry.register('config', AppDataContainer.from_form(form_class), config_model)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_apphook_field_names(model):
    from .models import AppHookConfig  # avoid circular dependencies
    fields = []
    for field in model._meta.fields:
        if isinstance(field, ForeignKey) and issubclass(field.remote_field.model, AppHookConfig):
            fields.append(field)
    return [field.name for field in fields]

Response: Return all foreign key field names for a AppHookConfig based model


Instruction:
Make a summary of the following Python 3 code
def get_apphook_field_names(model):
    key = APP_CONFIG_FIELDS_KEY.format(
        app_label=model._meta.app_label,
        model_name=model._meta.object_name
    ).lower()
    if not hasattr(model, key):
        field_names = _get_apphook_field_names(model)
        setattr(model, key, field_names)
    return getattr(model, key)

Response: Cache app - hook field names on model


Instruction:
Explain what the following Python 3 code does
def get_apphook_configs(obj):
    keys = get_apphook_field_names(obj)
    return [getattr(obj, key) for key in keys] if keys else []

Response: Get apphook configs for a given object


Instruction:
Write a Python 3 script for
receiving data from the protocol.

Response:
def data_received(self, data):
        """Receive data from the protocol.

        Called when asyncio.Protocol detects received data from network.
        """
        _LOGGER.debug("Starting: data_received")
        _LOGGER.debug('Received %d bytes from PLM: %s',
                      len(data), binascii.hexlify(data))
        self._buffer.put_nowait(data)
        asyncio.ensure_future(self._peel_messages_from_buffer(),
                              loop=self._loop)

        _LOGGER.debug("Finishing: data_received")


Instruction:
Can you write a function in Python 3 where it
calls when the connection to the transport is lost.

Response:
def connection_lost(self, exc):
        """Reestablish the connection to the transport.

        Called when asyncio.Protocol loses the network connection.
        """
        if exc is None:
            _LOGGER.warning('End of file received from Insteon Modem')
        else:
            _LOGGER.warning('Lost connection to Insteon Modem: %s', exc)

        self.transport = None
        asyncio.ensure_future(self.pause_writing(), loop=self.loop)

        if self._connection_lost_callback:
            self._connection_lost_callback()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_all_link_done_callback(self, callback):
        _LOGGER.debug('Added new callback %s ', callback)
        self._cb_load_all_link_db_done.append(callback)

Response: Register a callback to be invoked when the ALDB is loaded.


Instruction:
Write a Python 3 script to
register callback to be invoked when a device is not responding.

Response:
def add_device_not_active_callback(self, callback):
        """Register callback to be invoked when a device is not responding."""
        _LOGGER.debug('Added new callback %s ', callback)
        self._cb_device_not_active.append(callback)


Instruction:
How would you explain what the following Python 3 function does
def poll_devices(self):
        for addr in self.devices:
            device = self.devices[addr]
            if not device.address.is_x10:
                device.async_refresh_state()

Response: Request status updates from each device.


Instruction:
Explain what the following Python 3 code does
def send_msg(self, msg, wait_nak=True, wait_timeout=WAIT_TIMEOUT):
        msg_info = MessageInfo(msg=msg, wait_nak=wait_nak,
                               wait_timeout=wait_timeout)
        _LOGGER.debug("Queueing msg: %s", msg)
        self._send_queue.put_nowait(msg_info)

Response: Send a message to the send queue.


Instruction:
Implement a Python 3 function for
starting All - Linking mode.

Response:
def start_all_linking(self, mode, group):
        """Put the IM into All-Linking mode.

        Puts the IM into All-Linking mode for 4 minutes.

        Parameters:
            mode: 0 | 1 | 3 | 255
                  0 - PLM is responder
                  1 - PLM is controller
                  3 - Device that initiated All-Linking is Controller
                255 = Delete All-Link
            group: All-Link group number (0 - 255)

        """
        msg = StartAllLinking(mode, group)
        self.send_msg(msg)


Instruction:
Explain what the following Python 3 code does
def add_x10_device(self, housecode, unitcode, feature='OnOff'):
        device = insteonplm.devices.create_x10(self, housecode,
                                               unitcode, feature)
        if device:
            self.devices[device.address.id] = device
        return device

Response: Add an X10 device based on a feature description.


Instruction:
Create a Python 3 function for
removing device from ALDB device list.

Response:
def aldb_device_handled(self, addr):
        """Remove device from ALDB device list."""
        if isinstance(addr, Address):
            remove_addr = addr.id
        else:
            remove_addr = addr
        try:
            self._aldb_devices.pop(remove_addr)
            _LOGGER.debug('Removed ALDB device %s', remove_addr)
        except KeyError:
            _LOGGER.debug('Device %s not in ALDB device list', remove_addr)
        _LOGGER.debug('ALDB device count: %d', len(self._aldb_devices))


Instruction:
Can you generate the documentation for the following Python 3 function
def manage_aldb_record(self, control_code, control_flags, group, address,
                           data1, data2, data3):
        """Update an IM All-Link record.

        Control Code values:
        - 0x00 Find First Starting at the top of the ALDB, search for the
        first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes
        5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will
        receive an ACK at the end of the returned message if such an ALL-Link
        Record exists, or else a NAK if it doesn’t.  If the record exists, the
        IM will return it in an ALL-Link Record Response (0x51) message.

        - 0x01 Find Next Search for the next ALL-Link Record following the one
        found using <Control Code> 0x00 above.  This allows you to find both
        Controller and Responder records for a given <ALL-Link Group> and
        <ID>. Be sure to use the same <ALL-Link Group> and <ID> (bytes 5 – 8)
        as you used for <Control Code> 0x00. You will receive an ACK at the
        end of the returned message if another matching ALL-Link Record
        exists, or else a NAK if it doesn’t.  If the record exists, the IM
        will return it in an ALL-Link Record Response (0x51) message.

        - 0x20 Modify First Found or Add Modify an existing or else add a new
        ALL-Link Record for either a Controller or Responder. Starting at the
        top of the ALDB, search for the first ALL-Link Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  The search ignores byte 4,
        <ALL-Link Record Flags>. If such an ALL-Link Record exists, overwrite
        it with the data in bytes 4 – 11; otherwise, create a new ALL-Link
        Record using bytes 4 – 11. Note that the IM will copy
        <ALL-Link Record Flags> you supplied in byte 4 below directly into the
        <ALL-Link Record Flags> byte of the ALL-Link Record in an ALDB-L
        (linear) database.  Use caution, because you can damage an ALDB-L if
        you misuse this Command.  For instance, if you zero the
        <ALL-Link Record Flags> byte in the first ALL-Link Record, the IM’s
        ALDB-L database will then appear empty.

        - 0x40 Modify First Controller Found or Add Modify an existing or else
        add a new Controller (master) ALL-Link Record. Starting at the top of
        the ALDB, search for the first ALL-Link Controller Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  An ALL-Link Controller
        Record has bit 6 of its <ALL-Link Record Flags> byte set to 1. If such
        a Controller ALL-Link Record exists, overwrite it with the data in
        bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes
        5 – 11.  In either case, the IM will set bit 6 of the
        <ALL-Link Record Flags> byte in the ALL-Link Record to 1 to indicate
        that the record is for a Controller.

        - 0x41 Modify First Responder Found or Add Modify an existing or else
        add a new Responder (slave) ALLLink Record. Starting at the top of the
        ALDB, search for the first ALL-Link Responder Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  An ALL-Link Responder
        Record has bit 6 of its <ALL-Link Record Flags> byte cleared to 0. If
        such a Responder ALL-Link Record exists, overwrite it with the data in
        bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes
        5 – 11.  In either case, The IM will clear bit 6 of the
        <ALL-Link Record Flags> byte in the ALL-Link Record to 0 to indicate
        that the record is for a Responder.

        - 0x80 Delete First Found Delete an ALL-Link Record. Starting at the
        top of the ALDB, search for the first ALL-Link Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  The search ignores byte 4,
        <ALL-Link Record Flags>. You will receive an ACK at the end of the
        returned message if such an ALL-Link Record existed and was deleted,
        or else a NAK no such record exists.
        """
        msg = ManageAllLinkRecord(control_code, control_flags, group, address,
                                  data1, data2, data3)
        self.send_msg(msg)

Response: This function is called by the IM when it is about to update the ALL - Link record. It is called by the IM when it is about to update the ALL - Link record.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _load_all_link_database(self):
        _LOGGER.debug("Starting: _load_all_link_database")
        self.devices.state = 'loading'
        self._get_first_all_link_record()
        _LOGGER.debug("Ending: _load_all_link_database")

Response: Load the ALL - Link Database into object.


Instruction:
How would you implement a function in Python 3 that
requests first ALL - Link record.

Response:
def _get_first_all_link_record(self):
        """Request first ALL-Link record."""
        _LOGGER.debug("Starting: _get_first_all_link_record")
        _LOGGER.info('Requesting ALL-Link Records')
        if self.aldb.status == ALDBStatus.LOADED:
            self._next_all_link_rec_nak_retries = 3
            self._handle_get_next_all_link_record_nak(None)
            return
        self.aldb.clear()
        self._next_all_link_rec_nak_retries = 0
        msg = GetFirstAllLinkRecord()
        self.send_msg(msg, wait_nak=True, wait_timeout=.5)
        _LOGGER.debug("Ending: _get_first_all_link_record")


Instruction:
Here you have a function in Python 3, explain what it does
def _get_next_all_link_record(self):
        _LOGGER.debug("Starting: _get_next_all_link_record")
        _LOGGER.debug("Requesting Next All-Link Record")
        msg = GetNextAllLinkRecord()
        self.send_msg(msg, wait_nak=True, wait_timeout=.5)
        _LOGGER.debug("Ending: _get_next_all_link_record")

Response: Request next ALL - Link record.


Instruction:
Implement a Python 3 function for
sending the X10 All Units Off command.

Response:
def x10_all_units_off(self, housecode):
        """Send the X10 All Units Off command."""
        if isinstance(housecode, str):
            housecode = housecode.upper()
        else:
            raise TypeError('Housecode must be a string')
        msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_UNITS_OFF)
        self.send_msg(msg)
        self._x10_command_to_device(housecode, X10_COMMAND_ALL_UNITS_OFF, msg)


Instruction:
Can you create a Python 3 function that
sends the X10 All Lights Off command to the specified resource.

Response:
def x10_all_lights_off(self, housecode):
        """Send the X10 All Lights Off command."""
        msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_LIGHTS_OFF)
        self.send_msg(msg)
        self._x10_command_to_device(housecode, X10_COMMAND_ALL_LIGHTS_OFF, msg)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def x10_all_lights_on(self, housecode):
        msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_LIGHTS_ON)
        self.send_msg(msg)
        self._x10_command_to_device(housecode, X10_COMMAND_ALL_LIGHTS_ON, msg)

Response: Send the X10 All Lights Off command.


Instruction:
Can you create a Python 3 function that
calls when asyncio. Protocol establishes the network connection.

Response:
def connection_made(self, transport):
        """Start the PLM connection process.

        Called when asyncio.Protocol establishes the network connection.
        """
        _LOGGER.info('Connection established to PLM')
        self.transport = transport

        self._restart_writer = True
        self.restart_writing()

        # Testing to see if this fixes the 2413S issue
        self.transport.serial.timeout = 1
        self.transport.serial.write_timeout = 1
        self.transport.set_write_buffer_limits(128)
        # limit = self.transport.get_write_buffer_size()
        # _LOGGER.debug('Write buffer size is %d', limit)
        if self._aldb.status != ALDBStatus.LOADED:
            asyncio.ensure_future(self._setup_devices(), loop=self._loop)


Instruction:
How would you code a function in Python 3 to
call when asyncio. Protocol establishes the network connection.

Response:
def connection_made(self, transport):
        """Start the Hub connection process.

        Called when asyncio.Protocol establishes the network connection.
        """
        _LOGGER.info('Connection established to Hub')
        _LOGGER.debug('Transport: %s', transport)
        self.transport = transport

        self._restart_writer = True
        self.restart_writing()

        if self._aldb.status != ALDBStatus.LOADED:
            asyncio.ensure_future(self._setup_devices(), loop=self._loop)


Instruction:
Write a Python 3 script to
create a device from device info data.

Response:
def create(plm, address, cat, subcat, firmware=None):
    """Create a device from device info data."""
    from insteonplm.devices.ipdb import IPDB
    ipdb = IPDB()
    product = ipdb[[cat, subcat]]
    deviceclass = product.deviceclass
    device = None
    if deviceclass is not None:
        device = deviceclass(plm, address, cat, subcat,
                             product.product_key,
                             product.description,
                             product.model)
    return device


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_x10(plm, housecode, unitcode, feature):
    from insteonplm.devices.ipdb import IPDB
    ipdb = IPDB()
    product = ipdb.x10(feature)
    deviceclass = product.deviceclass
    device = None
    if deviceclass:
        device = deviceclass(plm, housecode, unitcode)
    return device

Response: Create an X10 device from a feature definition.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def id_request(self):
        import inspect
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 2)
        _LOGGER.debug('caller name: %s', calframe[1][3])
        msg = StandardSend(self.address, COMMAND_ID_REQUEST_0X10_0X00)
        self._plm.send_msg(msg)

Response: Request a device ID from a device.


Instruction:
Given the following Python 3 function, write the documentation
def product_data_request(self):
        msg = StandardSend(self._address,
                           COMMAND_PRODUCT_DATA_REQUEST_0X03_0X00)
        self._send_msg(msg)

Response: Request product data from a device.


Instruction:
Create a Python 3 function to
assign a device to an All - Link Group.

Response:
def assign_to_all_link_group(self, group=0x01):
        """Assign a device to an All-Link Group.

        The default is group 0x01.
        """
        msg = StandardSend(self._address,
                           COMMAND_ASSIGN_TO_ALL_LINK_GROUP_0X01_NONE,
                           cmd2=group)
        self._send_msg(msg)


Instruction:
Explain what the following Python 3 code does
def delete_from_all_link_group(self, group):
        msg = StandardSend(self._address,
                           COMMAND_DELETE_FROM_ALL_LINK_GROUP_0X02_NONE,
                           cmd2=group)
        self._send_msg(msg)

Response: Delete a device from an All - Link Group.


Instruction:
Explain what the following Python 3 code does
def fx_username(self):
        msg = StandardSend(self._address, COMMAND_FX_USERNAME_0X03_0X01)
        self._send_msg(msg)

Response:
Get FX Username.

        Only required for devices that support FX Commands.
        FX Addressee responds with an ED 0x0301 FX Username Response message


Instruction:
How would you implement a function in Python 3 that
sends a FX Username Response message to the device.

Response:
def device_text_string_request(self):
        """Get FX Username.

        Only required for devices that support FX Commands.
        FX Addressee responds with an ED 0x0301 FX Username Response message.
        """
        msg = StandardSend(self._address, COMMAND_FX_USERNAME_0X03_0X01)
        self._send_msg(msg)


Instruction:
Write a Python 3 function for
telling a device to enter All - Linking Mode.

Response:
def enter_linking_mode(self, group=0x01):
        """Tell a device to enter All-Linking Mode.

        Same as holding down the Set button for 10 sec.
        Default group is 0x01.

        Not supported by i1 devices.
        """
        msg = ExtendedSend(self._address,
                           COMMAND_ENTER_LINKING_MODE_0X09_NONE,
                           cmd2=group,
                           userdata=Userdata())
        msg.set_checksum()
        self._send_msg(msg)


Instruction:
Can you tell what is the following Python 3 function doing
def enter_unlinking_mode(self, group):
        msg = StandardSend(self._address,
                           COMMAND_ENTER_UNLINKING_MODE_0X0A_NONE,
                           cmd2=group)
        self._send_msg(msg)

Response: Unlink a device from an All - Link group.


Instruction:
Write a Python 3 script for
getting the device engine version.

Response:
def get_engine_version(self):
        """Get the device engine version."""
        msg = StandardSend(self._address,
                           COMMAND_GET_INSTEON_ENGINE_VERSION_0X0D_0X00)
        self._send_msg(msg)


Instruction:
Can you tell what is the following Python 3 function doing
def create_default_links(self):
        self._plm.manage_aldb_record(0x40, 0xe2, 0x00, self.address,
                                     self.cat, self.subcat, self.product_key)
        self.manage_aldb_record(0x41, 0xa2, 0x00, self._plm.address,
                                self._plm.cat, self._plm.subcat,
                                self._plm.product_key)
        for link in self._stateList:
            state = self._stateList[link]
            if state.is_responder:
                # IM is controller
                self._plm.manage_aldb_record(0x40, 0xe2, link, self._address,
                                             0x00, 0x00, 0x00)
                # Device is responder
                self.manage_aldb_record(0x41, 0xa2, link, self._plm.address,
                                        state.linkdata1, state.linkdata2,
                                        state.linkdata3)
            if state.is_controller:
                # IM is responder
                self._plm.manage_aldb_record(0x41, 0xa2, link, self._address,
                                             0x00, 0x00, 0x00)
                # Device is controller
                self.manage_aldb_record(0x40, 0xe2, link, self._plm.address,
                                        0x00, 0x00, 0x00)
        self.read_aldb()

Response: Create the default links between the IM and the device.


Instruction:
Can you generate the documentation for the following Python 3 function
def read_aldb(self, mem_addr=0x0000, num_recs=0):
        if self._aldb.version == ALDBVersion.Null:
            _LOGGER.info('Device %s does not contain an All-Link Database',
                         self._address.human)
        else:
            _LOGGER.info('Reading All-Link Database for device %s',
                         self._address.human)
            asyncio.ensure_future(self._aldb.load(mem_addr, num_recs),
                                  loop=self._plm.loop)
            self._aldb.add_loaded_callback(self._aldb_loaded_callback)

Response: Read the device All - Link Database.


Instruction:
Can you generate the documentation for the following Python 3 function
def manage_aldb_record(self, control_code, control_flags, group, address,
                           data1, data2, data3):
        """Update an IM All-Link record.

        Control Code values:
        - 0x00 Find First Starting at the top of the ALDB, search for the
        first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes
        5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will
        receive an ACK at the end of the returned message if such an ALL-Link
        Record exists, or else a NAK if it doesn’t.  If the record exists, the
        IM will return it in an ALL-Link Record Response (0x51) message.

        - 0x01 Find Next Search for the next ALL-Link Record following the one
        found using <Control Code> 0x00 above.  This allows you to find both
        Controller and Responder records for a given <ALL-Link Group> and
        <ID>. Be sure to use the same <ALL-Link Group> and <ID> (bytes 5 – 8)
        as you used for <Control Code> 0x00. You will receive an ACK at the
        end of the returned message if another matching ALL-Link Record
        exists, or else a NAK if it doesn’t.  If the record exists, the IM
        will return it in an ALL-Link Record Response (0x51) message.

        - 0x20 Modify First Found or Add Modify an existing or else add a new
        ALL-Link Record for either a Controller or Responder. Starting at the
        top of the ALDB, search for the first ALL-Link Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  The search ignores byte 4,
        <ALL-Link Record Flags>. If such an ALL-Link Record exists, overwrite
        it with the data in bytes 4 – 11; otherwise, create a new ALL-Link
        Record using bytes 4 – 11. Note that the IM will copy
        <ALL-Link Record Flags> you supplied in byte 4 below directly into the
        <ALL-Link Record Flags> byte of the ALL-Link Record in an ALDB-L
        (linear) database.  Use caution, because you can damage an ALDB-L if
        you misuse this Command.  For instance, if you zero the
        <ALL-Link Record Flags> byte in the first ALL-Link Record, the IM’s
        ALDB-L database will then appear empty.

        - 0x40 Modify First Controller Found or Add Modify an existing or else
        add a new Controller (master) ALL-Link Record. Starting at the top of
        the ALDB, search for the first ALL-Link Controller Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  An ALL-Link Controller
        Record has bit 6 of its <ALL-Link Record Flags> byte set to 1. If such
        a Controller ALL-Link Record exists, overwrite it with the data in
        bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes
        5 – 11.  In either case, the IM will set bit 6 of the
        <ALL-Link Record Flags> byte in the ALL-Link Record to 1 to indicate
        that the record is for a Controller.

        - 0x41 Modify First Responder Found or Add Modify an existing or else
        add a new Responder (slave) ALLLink Record. Starting at the top of the
        ALDB, search for the first ALL-Link Responder Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  An ALL-Link Responder
        Record has bit 6 of its <ALL-Link Record Flags> byte cleared to 0. If
        such a Responder ALL-Link Record exists, overwrite it with the data in
        bytes 5 – 11; otherwise, create a new ALL-Link Record using bytes
        5 – 11.  In either case, The IM will clear bit 6 of the
        <ALL-Link Record Flags> byte in the ALL-Link Record to 0 to indicate
        that the record is for a Responder.

        - 0x80 Delete First Found Delete an ALL-Link Record. Starting at the
        top of the ALDB, search for the first ALL-Link Record matching the
        <ALL-Link Group> and <ID> in bytes 5 – 8.  The search ignores byte 4,
        <ALL-Link Record Flags>. You will receive an ACK at the end of the
        returned message if such an ALL-Link Record existed and was deleted,
        or else a NAK no such record exists.
        """
        found_first = False
        for memaddr in self.aldb:
            found = False
            rec = self.aldb[memaddr]
            found = Address(address) == rec.address
            found = found & int(group) == rec.group
            if control_code == 0x00:
                if found:
                    return (True, rec)
                if rec.control_flags.is_high_water_mark:
                    return (False, None)
            if control_code == 0x01:
                if found & found_first:
                    return (True, rec)
                if rec.control_flags.is_high_water_mark:
                    return (False, None)
                if found:
                    found_first = True
            elif control_code == 0x20:
                if found or rec.control_flags.is_high_water_mark:
                    new_rec = self._write_new_aldb_rec(
                        rec.mem_addr, control_flags, group, address,
                        data1, data2, data3)
                    return (found, new_rec)
            elif control_code == 0x40:
                found = found & rec.control_flags.is_controller
                if found or rec.control_flags.is_high_water_mark:
                    new_rec = self._write_new_aldb_rec(
                        rec.mem_addr, control_flags, group, address,
                        data1, data2, data3)
                    return (found, new_rec)
            elif control_code == 0x41:
                found = found & rec.control_flags.is_responder
                if found or rec.control_flags.is_high_water_mark:
                    new_rec = self._write_new_aldb_rec(
                        rec.mem_addr, control_flags, group, address,
                        data1, data2, data3)
                    return (found, new_rec)
            elif control_code == 0x80:
                if found:
                    cf = rec.control_flags
                    new_control_flags = ControlFlags(False, cf.is_controller,
                                                     cf.is_high_water_mark,
                                                     False, False)
                    new_rec = self._write_new_aldb_rec(
                        rec.mem_addr, new_control_flags, rec.group,
                        rec.address, rec.data1, rec.data2, rec.data3)
                    return (found, new_rec)
            return (False, rec)

Response: This function is called by the IM when it is about to update the ALL - Link record. It is called by the IM when it is about to update the ALL - Link record.


Instruction:
Write a Python 3 script to
write the record to the All - Link Database.

Response:
def write_aldb(self, mem_addr: int, mode: str, group: int, target,
                   data1=0x00, data2=0x00, data3=0x00):
        """Write to the device All-Link Database.

        Parameters:
            Required:
            mode:   r - device is a responder of target
                    c - device is a controller of target
            group:  Link group
            target: Address of the other device

            Optional:
            data1:  Device dependant
            data2:  Device dependant
            data3:  Device dependant

        """
        if isinstance(mode, str) and mode.lower() in ['c', 'r']:
            pass
        else:
            _LOGGER.error('Insteon link mode: %s', mode)
            raise ValueError("Mode must be 'c' or 'r'")
        if isinstance(group, int):
            pass
        else:
            raise ValueError("Group must be an integer")

        target_addr = Address(target)

        _LOGGER.debug('calling aldb write_record')
        self._aldb.write_record(mem_addr, mode, group, target_addr,
                                data1, data2, data3)
        self._aldb.add_loaded_callback(self._aldb_loaded_callback)


Instruction:
How would you code a function in Python 3 to
delete an All - Link Database record.

Response:
def del_aldb(self, mem_addr: int):
        """Delete an All-Link Database record."""
        self._aldb.del_record(mem_addr)
        self._aldb.add_loaded_callback(self._aldb_loaded_callback)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _refresh_aldb_records(self, linkcode, address, group):
        if self.aldb.status in [ALDBStatus.LOADED, ALDBStatus.PARTIAL]:
            for mem_addr in self.aldb:
                rec = self.aldb[mem_addr]
                if linkcode in [0, 1, 3]:
                    if rec.control_flags.is_high_water_mark:
                        _LOGGER.debug('Removing HWM record %04x', mem_addr)
                        self.aldb.pop(mem_addr)
                    elif not rec.control_flags.is_in_use:
                        _LOGGER.debug('Removing not in use record %04x',
                                      mem_addr)
                        self.aldb.pop(mem_addr)
                else:
                    if rec.address == self.address and rec.group == group:
                        _LOGGER.debug('Removing record %04x with addr %s and '
                                      'group %d', mem_addr, rec.address,
                                      rec.group)
                        self.aldb.pop(mem_addr)
            self.read_aldb()

Response: Refresh the IM and device ALDB records.


Instruction:
Write a Python 3 function that can
receive a message from the device.

Response:
def receive_message(self, msg):
        """Receive a messages sent to this device."""
        _LOGGER.debug('Starting Device.receive_message')
        if hasattr(msg, 'isack') and msg.isack:
            _LOGGER.debug('Got Message ACK')
            if self._sent_msg_wait_for_directACK.get('callback') is not None:
                _LOGGER.debug('Look for direct ACK')
                asyncio.ensure_future(self._wait_for_direct_ACK(),
                                      loop=self._plm.loop)
            else:
                _LOGGER.debug('DA queue: %s',
                              self._sent_msg_wait_for_directACK)
                _LOGGER.debug('Message ACK with no callback')
        if (hasattr(msg, 'flags') and
                hasattr(msg.flags, 'isDirectACK') and
                msg.flags.isDirectACK):
            _LOGGER.debug('Got Direct ACK message')
            if self._send_msg_lock.locked():
                self._directACK_received_queue.put_nowait(msg)
            else:
                _LOGGER.debug('But Direct ACK not expected')
        if not self._is_duplicate(msg):
            callbacks = self._message_callbacks.get_callbacks_from_message(msg)
            for callback in callbacks:
                _LOGGER.debug('Scheduling msg callback: %s', callback)
                self._plm.loop.call_soon(callback, msg)
        else:
            _LOGGER.debug('msg is duplicate')
            _LOGGER.debug(msg)
        self._last_communication_received = datetime.datetime.now()
        _LOGGER.debug('Ending Device.receive_message')


Instruction:
Can you generate the documentation for the following Python 3 function
def receive_message(self, msg):
        _LOGGER.debug('Starting X10Device.receive_message')
        if hasattr(msg, 'isack') and msg.isack:
            _LOGGER.debug('Got Message ACK')
            if self._send_msg_lock.locked():
                self._send_msg_lock.release()
        callbacks = self._message_callbacks.get_callbacks_from_message(msg)
        _LOGGER.debug('Found %d callbacks for msg %s', len(callbacks), msg)
        for callback in callbacks:
            _LOGGER.debug('Scheduling msg callback: %s', callback)
            self._plm.loop.call_soon(callback, msg)
        self._last_communication_received = datetime.datetime.now()
        _LOGGER.debug('Ending Device.receive_message')

Response: Receive a message from the device.


Instruction:
Explain what the following Python 3 code does
def add(self, plm, device, stateType, stateName, group, defaultValue=None):
        self._stateList[group] = stateType(plm, device, stateName, group,
                                           defaultValue=defaultValue)

Response: Add a state to the StateList.


Instruction:
Make a summary of the following Python 3 code
def create_from_userdata(userdata):
        memhi = userdata.get('d3')
        memlo = userdata.get('d4')
        memory = memhi << 8 | memlo
        control_flags = userdata.get('d6')
        group = userdata.get('d7')
        addrhi = userdata.get('d8')
        addrmed = userdata.get('d9')
        addrlo = userdata.get('d10')
        addr = Address(bytearray([addrhi, addrmed, addrlo]))
        data1 = userdata.get('d11')
        data2 = userdata.get('d12')
        data3 = userdata.get('d13')
        return ALDBRecord(memory, control_flags, group, addr,
                          data1, data2, data3)

Response: Create ALDB Record from the userdata dictionary.


Instruction:
Implement a Python 3 function for
returning a Userdata dictionary.

Response:
def to_userdata(self):
        """Return a Userdata dictionary."""
        userdata = Userdata({'d3': self.memhi,
                             'd4': self.memlo,
                             'd6': self.control_flags,
                             'd7': self.group,
                             'd8': self.address.bytes[2],
                             'd9': self.address.bytes[1],
                             'd10': self.address.bytes[0],
                             'd11': self.data1,
                             'd12': self.data2,
                             'd13': self.data3})
        return userdata


Instruction:
Write a Python 3 function for
returning a byte representation of ControlFlags.

Response:
def byte(self):
        """Return a byte representation of ControlFlags."""
        flags = int(self._in_use) << 7 \
            | int(self._controller) << 6 \
            | int(self._bit5) << 5 \
            | int(self._bit4) << 4 \
            | int(self._used_before) << 1
        return flags


Instruction:
How would you explain what the following Python 3 function does
def create_from_byte(control_flags):
        in_use = bool(control_flags & 1 << 7)
        controller = bool(control_flags & 1 << 6)
        bit5 = bool(control_flags & 1 << 5)
        bit4 = bool(control_flags & 1 << 4)
        used_before = bool(control_flags & 1 << 1)
        flags = ControlFlags(in_use, controller, used_before,
                             bit5=bit5, bit4=bit4)
        return flags

Response: Create a ControlFlags class from a control flags byte.


Instruction:
Write a Python 3 script to
add a callback to be run when the ALDB load is complete.

Response:
def add_loaded_callback(self, callback):
        """Add a callback to be run when the ALDB load is complete."""
        if callback not in self._cb_aldb_loaded:
            self._cb_aldb_loaded.append(callback)


Instruction:
Can you write a function in Python 3 where it
reads the device database and load.

Response:
async def load(self, mem_addr=0x0000, rec_count=0, retry=0):
        """Read the device database and load."""
        if self._version == ALDBVersion.Null:
            self._status = ALDBStatus.LOADED
            _LOGGER.debug('Device has no ALDB')
        else:
            self._status = ALDBStatus.LOADING
            _LOGGER.debug('Tring to lock from load')
            await self._rec_mgr_lock
            _LOGGER.debug('load yielded lock')

            mem_hi = mem_addr >> 8
            mem_lo = mem_addr & 0xff
            log_output = 'ALDB read'
            max_retries = 0
            if rec_count:
                max_retries = ALDB_RECORD_RETRIES
                if mem_addr == 0x0000:
                    log_output = '{:s} first record'.format(log_output)
                else:
                    log_output = '{:s} record {:04x}'.format(log_output,
                                                             mem_addr)
            else:
                max_retries = ALDB_ALL_RECORD_RETRIES
                log_output = '{:s} all records'.format(log_output)

            if retry:
                log_output = '{:s} retry {:d} of {:d}'.format(log_output,
                                                              retry,
                                                              max_retries)
            _LOGGER.info(log_output)
            userdata = Userdata({'d1': 0,
                                 'd2': 0,
                                 'd3': mem_hi,
                                 'd4': mem_lo,
                                 'd5': rec_count})
            msg = ExtendedSend(self._address,
                               COMMAND_EXTENDED_READ_WRITE_ALDB_0X2F_0X00,
                               userdata=userdata)
            msg.set_checksum()
            self._send_method(msg, self._handle_read_aldb_ack, True)

            if not self._load_action:
                self._set_load_action(mem_addr, rec_count, -1, False)


Instruction:
How would you code a function in Python 3 to
write an All - Link database record.

Response:
def write_record(self, mem_addr: int, mode: str, group: int, target,
                     data1=0x00, data2=0x00, data3=0x00):
        """Write an All-Link database record."""
        if not (self._have_first_record() and self._have_last_record()):
            _LOGGER.error('Must load the Insteon All-Link Database before '
                          'writing to it')
        else:
            self._prior_status = self._status
            self._status = ALDBStatus.LOADING
            mem_hi = mem_addr >> 8
            mem_lo = mem_addr & 0xff
            controller = mode == 'c'
            control_flag = ControlFlags(True, controller, True, False, False)
            addr = Address(target)
            addr_lo = addr.bytes[0]
            addr_mid = addr.bytes[1]
            addr_hi = addr.bytes[2]
            userdata = Userdata({'d1': 0,
                                 'd2': 0x02,
                                 'd3': mem_hi,
                                 'd4': mem_lo,
                                 'd5': 0x08,
                                 'd6': control_flag.byte,
                                 'd7': group,
                                 'd8': addr_lo,
                                 'd9': addr_mid,
                                 'd10': addr_hi,
                                 'd11': data1,
                                 'd12': data2,
                                 'd13': data3})
            msg = ExtendedSend(self._address,
                               COMMAND_EXTENDED_READ_WRITE_ALDB_0X2F_0X00,
                               userdata=userdata)
            msg.set_checksum()
            _LOGGER.debug('writing message %s', msg)
            self._send_method(msg, self._handle_write_aldb_ack, True)
            self._load_action = LoadAction(mem_addr, 1, 0)


Instruction:
Can you generate the documentation for the following Python 3 function
def del_record(self, mem_addr: int):
        record = self._records.get(mem_addr)
        if not record:
            _LOGGER.error('Must load the Insteon All-Link Database record '
                          'before deleting it')
        else:
            self._prior_status = self._status
            self._status = ALDBStatus.LOADING
            mem_hi = mem_addr >> 8
            mem_lo = mem_addr & 0xff
            controller = record.control_flags.is_controller
            control_flag = ControlFlags(False, controller, True, False, False)
            addr = record.address
            addr_lo = addr.bytes[0]
            addr_mid = addr.bytes[1]
            addr_hi = addr.bytes[2]
            group = record.group
            data1 = record.data1
            data2 = record.data2
            data3 = record.data3
            userdata = Userdata({'d1': 0,
                                 'd2': 0x02,
                                 'd3': mem_hi,
                                 'd4': mem_lo,
                                 'd5': 0x08,
                                 'd6': control_flag.byte,
                                 'd7': group,
                                 'd8': addr_lo,
                                 'd9': addr_mid,
                                 'd10': addr_hi,
                                 'd11': data1,
                                 'd12': data2,
                                 'd13': data3})
            msg = ExtendedSend(self._address,
                               COMMAND_EXTENDED_READ_WRITE_ALDB_0X2F_0X00,
                               userdata=userdata)
            msg.set_checksum()
            _LOGGER.debug('writing message %s', msg)
            self._send_method(msg, self._handle_write_aldb_ack, True)
            self._load_action = LoadAction(mem_addr, 1, 0)

Response: Write an All - Link database record.


Instruction:
Make a summary of the following Python 3 code
def find_matching_link(self, mode, group, addr):
        found_rec = None
        mode_test = None
        if mode.lower() in ['c', 'r']:
            link_group = int(group)
            link_addr = Address(addr)
            for mem_addr in self:
                rec = self[mem_addr]
                if mode.lower() == 'r':
                    mode_test = rec.control_flags.is_controller
                else:
                    mode_test = rec.control_flags.is_responder
                if (mode_test and
                        rec.group == link_group and
                        rec.address == link_addr):
                    found_rec = rec
        return found_rec

Response: Find a matching link in the current device.


Instruction:
How would you explain what the following Python 3 function does
def record_received(self, msg):
        release_lock = False
        userdata = msg.userdata
        rec = ALDBRecord.create_from_userdata(userdata)
        self._records[rec.mem_addr] = rec

        _LOGGER.debug('ALDB Record: %s', rec)

        rec_count = self._load_action.rec_count
        if rec_count == 1 or self._have_all_records():
            release_lock = True

        if self._is_first_record(rec):
            self._mem_addr = rec.mem_addr

        if release_lock and self._rec_mgr_lock.locked():
            _LOGGER.debug('Releasing lock because record received')
            self._rec_mgr_lock.release()

Response: Handle ALDB record received from device.


Instruction:
Create a Python 3 function to
load ALDB records from a set of saved records.

Response:
def load_saved_records(self, status, records):
        """Load ALDB records from a set of saved records."""
        if isinstance(status, ALDBStatus):
            self._status = status
        else:
            self._status = ALDBStatus(status)
        for mem_addr in records:
            rec = records[mem_addr]
            control_flags = int(rec.get('control_flags', 0))
            group = int(rec.get('group', 0))
            rec_addr = rec.get('address', '000000')
            data1 = int(rec.get('data1', 0))
            data2 = int(rec.get('data2', 0))
            data3 = int(rec.get('data3', 0))
            self[int(mem_addr)] = ALDBRecord(int(mem_addr), control_flags,
                                             group, rec_addr,
                                             data1, data2, data3)
        if self._status == ALDBStatus.LOADED:
            keys = list(self._records.keys())
            keys.sort(reverse=True)
            first_key = keys[0]
            self._mem_addr = first_key


Instruction:
Create a Python 3 function to
calculate the next record to read.

Response:
def _set_load_action(self, mem_addr, rec_count, retries,
                         read_complete=False):
        """Calculate the next record to read.

        If the last record was successful and one record was being read then
        look for the next record until we get to the high water mark.

        If the last read was successful and all records were being read then
        look for the first record.

        if the last read was unsuccessful and one record was being read then
        repeat the last read until max retries

        If the last read was unsuccessful and all records were being read then
        repeat the last read until max retries or look for the first record.
        """
        if self._have_all_records():
            mem_addr = None
            rec_count = 0
            retries = 0
        elif read_complete:
            retries = 0
            if rec_count:
                mem_addr = self._next_address(mem_addr)
            else:
                mem_addr = self._next_address(mem_addr)
                rec_count = 1
                retries = 0
        elif rec_count and retries < ALDB_RECORD_RETRIES:
            retries = retries + 1
        elif not rec_count and retries < ALDB_ALL_RECORD_RETRIES:
            retries = retries + 1
        elif not rec_count and retries >= ALDB_ALL_RECORD_RETRIES:
            mem_addr = self._next_address(mem_addr)
            rec_count = 1
            retries = 0
        else:
            mem_addr = None
            rec_count = 0
            retries = 0

        self._load_action = LoadAction(mem_addr, rec_count, retries)
        if mem_addr is not None:
            _LOGGER.debug('Load action: addr: %04x rec_count: %d retries: %d',
                          self._load_action.mem_addr,
                          self._load_action.rec_count,
                          self._load_action.retries)


Instruction:
Here you have a function in Python 3, explain what it does
def register_updates(self, callback):
        _LOGGER.debug("Registered callback for state: %s", self._stateName)
        self._observer_callbacks.append(callback)

Response: Register a callback to notify a listener of state changes.


Instruction:
Write a Python 3 script for
saving state value and notify subscribers of the change.

Response:
def _update_subscribers(self, val):
        """Save state value and notify listeners of the change."""
        self._value = val
        for callback in self._observer_callbacks:
            callback(self._address, self._group, val)


Instruction:
Explain what the following Python 3 code does
def from_raw_message(cls, rawmessage):
        userdata = Userdata.from_raw_message(rawmessage[11:25])
        return ExtendedReceive(rawmessage[2:5],
                               rawmessage[5:8],
                               {'cmd1': rawmessage[9],
                                'cmd2': rawmessage[10]},
                               userdata,
                               flags=rawmessage[8])

Response: Create a new message from a raw byte stream.


Instruction:
Given the following Python 3 function, write the documentation
def template(cls, address=None, target=None, commandtuple=None,
                 userdata=None, cmd2=-1, flags=None):
        """Create message template for callbacks."""
        msgraw = bytearray([0x02, cls._code])
        msgraw.extend(bytes(cls._receivedSize))
        msg = ExtendedReceive.from_raw_message(msgraw)

        if commandtuple:
            cmd1 = commandtuple.get('cmd1')
            cmd2out = commandtuple.get('cmd2')
        else:
            cmd1 = None
            cmd2out = None

        if cmd2 is not -1:
            cmd2out = cmd2

        msg._address = Address(address)
        msg._target = Address(target)
        msg._messageFlags = MessageFlags(flags)
        msg._cmd1 = cmd1
        msg._cmd2 = cmd2out
        msg._userdata = Userdata.create_pattern(userdata)
        return msg

Response: Create message template for callbacks.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def targetLow(self):
        low_byte = None
        if self.target is not None and self._messageFlags.isBroadcast:
            low_byte = self.target.bytes[0]
        return low_byte

Response: Return the low byte of the target address field.


Instruction:
How would you explain what the following Python 3 function does
def set_level(self, val):
        if val == 0:
            self.off()
        else:
            setlevel = 255
            if val < 1:
                setlevel = val * 100
            elif val <= 0xff:
                setlevel = val
            set_command = StandardSend(
                self._address, COMMAND_LIGHT_ON_0X11_NONE, cmd2=setlevel)
            self._send_method(set_command, self._on_message_received)

Response: Set the devive ON LEVEL.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def brighten(self):
        brighten_command = StandardSend(
            self._address, COMMAND_LIGHT_BRIGHTEN_ONE_STEP_0X15_0X00)
        self._send_method(brighten_command)

Response: Brighten the device one step.


Instruction:
Implement a function in Python 3 to
dim the device one step.

Response:
def dim(self):
        """Dim the device one step."""
        dim_command = StandardSend(
            self._address, COMMAND_LIGHT_DIM_ONE_STEP_0X16_0X00)
        self._send_method(dim_command)


Instruction:
Write a Python 3 script for
setting the fan speed.

Response:
def set_level(self, val):
        """Set the fan speed."""
        speed = self._value_to_fan_speed(val)
        if val == 0:
            self.off()
        else:
            set_command = ExtendedSend(self._address,
                                       COMMAND_LIGHT_ON_0X11_NONE,
                                       self._udata, cmd2=speed)
            set_command.set_checksum()
            self._send_method(set_command, self._on_message_received)


Instruction:
Implement a Python 3 function for
turning the device ON.

Response:
def open(self):
        """Turn the device ON."""
        open_command = StandardSend(self._address,
                                    COMMAND_LIGHT_ON_0X11_NONE, cmd2=0xff)
        self._send_method(open_command, self._open_message_received)


Instruction:
Make a summary of the following Python 3 code
def open_fast(self):
        open_command = StandardSend(self._address,
                                    COMMAND_LIGHT_ON_FAST_0X12_NONE, cmd2=0xff)
        self._send_method(open_command, self._open_message_received)

Response: Turn the device ON Fast.


Instruction:
Can you write a function in Python 3 where it
turns the device off.

Response:
def close(self):
        """Turn the device off."""
        close_command = StandardSend(self._address,
                                     COMMAND_LIGHT_OFF_0X13_0X00)
        self._send_method(close_command, self._closed_message_received)


Instruction:
Explain what the following Python 3 code does
def close_fast(self):
        close_command = StandardSend(self._address,
                                     COMMAND_LIGHT_OFF_FAST_0X14_0X00)
        self._send_method(close_command, self._closed_message_received)

Response: Turn the device off fast.


Instruction:
Can you tell what is the following Python 3 function doing
def set_position(self, val):
        if val == 0:
            self.close()
        else:
            setlevel = 255
            if val < 1:
                setlevel = val * 100
            elif val <= 0xff:
                setlevel = val
            set_command = StandardSend(
                self._address, COMMAND_LIGHT_ON_0X11_NONE, cmd2=setlevel)
            self._send_method(set_command, self._open_message_received)

Response: Set the devive OPEN LEVEL.


Instruction:
How would you explain what the following Python 3 function does
def set_position_fast(self, val):
        if val == 0:
            self.close_fast()
        else:
            setlevel = 255
            if val < 1:
                setlevel = val * 100
            elif val <= 0xff:
                setlevel = val
            set_command = StandardSend(
                self._address, COMMAND_LIGHT_ON_FAST_0X12_NONE, cmd2=setlevel)
            self._send_method(set_command, self._open_message_received)

Response: Set the devive OPEN LEVEL.


Instruction:
Create a Python 3 function to
request each state to provide status update.

Response:
def async_refresh_state(self):
        """Request each state to provide status update."""
        _LOGGER.debug('Setting up extended status')
        ext_status = ExtendedSend(
            address=self._address,
            commandtuple=COMMAND_EXTENDED_GET_SET_0X2E_0X00,
            cmd2=0x02,
            userdata=Userdata())
        ext_status.set_crc()
        _LOGGER.debug('Sending ext status: %s', ext_status)
        self._send_msg(ext_status)
        _LOGGER.debug('Sending temp status request')
        self.temperature.async_refresh_state()


Instruction:
How would you explain what the following Python 3 function does
def byte_to_housecode(bytecode):
    hc = list(HC_LOOKUP.keys())[list(HC_LOOKUP.values()).index(bytecode)]
    return hc.upper()

Response: Return an X10 housecode value from a byte value.


Instruction:
Can you generate the documentation for the following Python 3 function
def byte_to_unitcode(bytecode):
    return list(UC_LOOKUP.keys())[list(UC_LOOKUP.values()).index(bytecode)]

Response: Return an X10 unitcode value from a byte value.


Instruction:
How would you explain what the following Python 3 function does
def x10_command_type(command):
    command_type = X10CommandType.DIRECT
    if command in [X10_COMMAND_ALL_UNITS_OFF,
                   X10_COMMAND_ALL_LIGHTS_ON,
                   X10_COMMAND_ALL_LIGHTS_OFF]:
        command_type = X10CommandType.BROADCAST
    return command_type

Response: Return the X10 command type from an X10 command.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_bit(bitmask, bit, is_on):
    bitshift = bit - 1
    if is_on:
        return bitmask | (1 << bitshift)
    return bitmask & (0xff & ~(1 << bitshift))

Response: Set the value of a bit in a bitmask on or off.


Instruction:
Implement a Python 3 function for
creating a message from a raw byte stream.

Response:
def from_raw_message(cls, rawmessage):
        """Create a message from a raw byte stream."""
        if (rawmessage[5] &
                MESSAGE_FLAG_EXTENDED_0X10) == MESSAGE_FLAG_EXTENDED_0X10:
            if len(rawmessage) >= ExtendedSend.receivedSize:
                msg = ExtendedSend.from_raw_message(rawmessage)
            else:
                msg = None
        else:
            msg = StandardSend(rawmessage[2:5],
                               {'cmd1': rawmessage[6],
                                'cmd2': rawmessage[7]},
                               flags=rawmessage[5],
                               acknak=rawmessage[8:9])
        return msg


Instruction:
Can you generate the documentation for the following Python 3 function
def from_raw_message(cls, rawmessage):
        userdata_dict = Userdata(rawmessage[8:22])
        return ExtendedSend(rawmessage[2:5],
                            {'cmd1': rawmessage[6],
                             'cmd2': rawmessage[7]},
                            userdata_dict,
                            flags=rawmessage[5],
                            acknak=rawmessage[22:23])

Response: Create a message from a raw byte stream.


Instruction:
Make a summary of the following Python 3 code
def template(cls, address=None, commandtuple=None,
                 userdata=None, cmd2=-1, flags=None, acknak=None):
        """Create a message template used for callbacks."""
        msgraw = bytearray([0x02, cls._code])
        msgraw.extend(bytes(cls._receivedSize))
        msg = ExtendedSend.from_raw_message(msgraw)

        if commandtuple:
            cmd1 = commandtuple.get('cmd1')
            cmd2out = commandtuple.get('cmd2')
        else:
            cmd1 = None
            cmd2out = None

        if cmd2 is not -1:
            cmd2out = cmd2

        msg._address = Address(address)
        msg._messageFlags = MessageFlags(flags)
        msg._messageFlags.extended = 1
        msg._cmd1 = cmd1
        msg._cmd2 = cmd2out
        msg._userdata = Userdata.template(userdata)
        msg._acknak = acknak
        return msg

Response: Create a message template used for callbacks.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_checksum(self):
        data_sum = self.cmd1 + self.cmd2
        for i in range(1, 14):
            data_sum += self._userdata['d{:d}'.format(i)]
        chksum = 0xff - (data_sum & 0xff) + 1
        self._userdata['d14'] = chksum

Response: Set byte 14 of the userdata to a checksum value.