Instruction:
Explain what the following Python 3 code does
def device_event_list(self, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_event_list_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.device_event_list_with_http_info(**kwargs)  # noqa: E501
            return data

Response: List all device events for an account.


Instruction:
Make a summary of the following Python 3 code
def device_event_retrieve(self, device_event_id, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_event_retrieve_with_http_info(device_event_id, **kwargs)  # noqa: E501
        else:
            (data) = self.device_event_retrieve_with_http_info(device_event_id, **kwargs)  # noqa: E501
            return data

Response: Retrieve a specific device event.


Instruction:
Here you have a function in Python 3, explain what it does
def device_list(self, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_list_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.device_list_with_http_info(**kwargs)  # noqa: E501
            return data

Response:
List all devices.  # noqa: E501

        List all devices.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_list(asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param int limit: How many objects to retrieve in the page.
        :param str order: The order of the records based on creation time, `ASC` or `DESC`; by default `ASC`.
        :param str after: The ID of The item after which to retrieve the next page.
        :param str include: Comma-separated list of data fields to return. Currently supported: `total_count`.
        :param str filter: URL encoded query string parameter to filter returned data.  ##### Filtering  ```?filter={URL encoded query string}```  The query string is made up of key/value pairs separated by ampersands. So for a query of ```key1=value1&key2=value2&key3=value3``` this would be encoded as follows: ```?filter=key1%3Dvalue1%26key2%3Dvalue2%26key3%3Dvalue3```  ###### Filterable fields:  The below table lists all the fields that can be filtered on with certain filters:

       Field	       = / __eq / __neq	       __in /  __nin	       __lte / __gte

       account_id	       ✓	       ✓

       auto_update	       ✓	       ✓

       bootstrap_expiration_date	       ✓	       ✓	       ✓

       bootstrapped_timestamp	       ✓	       ✓	       ✓

       ca_id	       ✓	       ✓

       connector_expiration_date	       ✓	       ✓	       ✓

       created_at	       ✓	       ✓	       ✓

       custom_attributes	       ✓

       deployed_state	       ✓	       ✓

       deployment	       ✓	       ✓

       description	       ✓	       ✓

       device_class	       ✓	       ✓

       device_execution_mode	       ✓	       ✓

       device_key	       ✓	       ✓

       endpoint_name	       ✓	       ✓

       endpoint_type	       ✓	       ✓

       enrolment_list_timestamp	       ✓	       ✓	       ✓

       etag	       ✓	       ✓	       ✓

       firmware_checksum	       ✓	       ✓

       host_gateway	       ✓	       ✓

       id	       ✓	       ✓

       manifest	       ✓	       ✓

       manifest_timestamp	       ✓	       ✓	       ✓

       mechanism	       ✓	       ✓

       mechanism_url	       ✓	       ✓

       name	       ✓	       ✓

       serial_number	       ✓	       ✓

       state	       ✓	       ✓

       updated_at	       ✓	       ✓	       ✓

       vendor_id	       ✓	       ✓

    The examples below show the queries in *unencoded* form.  ###### By device properties (all properties are filterable):  ```state=[unenrolled|cloud_enrolling|bootstrapped|registered]``` ```device_class={value}```  ###### On date-time fields:  Date-time fields should be specified in UTC RFC3339 format ```YYYY-MM-DDThh:mm:ss.msZ```. There are three permitted variations:  * UTC RFC3339 with milliseconds e.g. 2016-11-30T16:25:12.1234Z * UTC RFC3339 without milliseconds e.g. 2016-11-30T16:25:12Z * UTC RFC3339 shortened - without milliseconds and punctuation e.g. 20161130T162512Z  Date-time filtering supports three operators:  * equality * greater than or equal to – field name suffixed with ```__gte``` * less than or equal to – field name suffixed with ```__lte```  Lower and upper limits to a date-time range may be specified by including both the ```__gte``` and ```__lte``` forms in the filter. ```{field name}[|__lte|__gte]={UTC RFC3339 date-time}```  ###### On device custom attributes:  ```custom_attributes__{param}={value}``` ```custom_attributes__tag=TAG1```  ##### Multi-field example  ```state=bootstrapped&created_at__gte=2016-11-30T16:25:12.1234Z&created_at__lte=2016-12-30T00:00:00Z```  Encoded:  ```?filter=state%3Dbootstrapped%26created_at__gte%3D2016-11-30T16%3A25%3A12.1234Z%26created_at__lte%3D2016-11-30T00%3A00%3A00Z```  ##### Filtering with filter operators  String field filtering supports the following operators:  * equality: `__eq` * non-equality: `__neq` * in : `__in` * not in: `__nin`  For `__in` and `__nin` filters list of parameters must be comma-separated: `state__nin=unenrolled,dergistered`
        :return: DevicePage
                 If the method is called asynchronously,
                 returns the request thread.


Instruction:
How would you implement a function in Python 3 that
lists all device events.

Response:
def device_log_list(self, **kwargs):  # noqa: E501
        """DEPRECATED: List all device events.  # noqa: E501

        DEPRECATED: List all device events. Use `/v3/device-events/` instead.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_log_list(asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param int limit: How many objects to retrieve in the page.
        :param str order: The order of the records based on creation time, `ASC` or `DESC`; by default `ASC`.
        :param str after: The ID of The item after which to retrieve the next page.
        :param str include: Comma-separated list of data fields to return. Currently supported: `total_count`.
        :param str filter: URL encoded query string parameter to filter returned data.  ##### Filtering  ```?filter={URL encoded query string}```  The query string is made up of key/value pairs separated by ampersands. So for a query of ```key1=value1&key2=value2&key3=value3``` this would be encoded as follows: ```?filter=key1%3Dvalue1%26key2%3Dvalue2%26key3%3Dvalue3```  ###### Filterable fields:  The below table lists all the fields that can be filtered on with certain filters:

       Field	       = / __eq / __neq	       __in /  __nin	       __lte / __gte

       date_time	       ✓	       ✓	       ✓

       description	       ✓	       ✓

       id	       ✓	       ✓

       device_id	       ✓	       ✓

       event_type	       ✓	       ✓

       state_change	       ✓	       ✓

    The examples below show the queries in *unencoded* form.  ###### By id:  ```id={id}```  ###### By state change:  ```state_change=[True|False]```  ###### By event type:  ```event_type={value}```  ###### On date-time fields:  Date-time fields should be specified in UTC RFC3339 format ```YYYY-MM-DDThh:mm:ss.msZ```. There are three permitted variations:  * UTC RFC3339 with milliseconds e.g. 2016-11-30T16:25:12.1234Z * UTC RFC3339 without milliseconds e.g. 2016-11-30T16:25:12Z * UTC RFC3339 shortened - without milliseconds and punctuation e.g. 20161130T162512Z  Date-time filtering supports three operators:  * equality * greater than or equal to – field name suffixed with ```__gte``` * less than or equal to – field name suffixed with ```__lte```  Lower and upper limits to a date-time range may be specified by including both the ```__gte``` and ```__lte``` forms in the filter. ```{field name}[|__lte|__gte]={UTC RFC3339 date-time}```  ##### Multi-field example ```id=0158d38771f70000000000010010038c&state_change=True&date_time__gte=2016-11-30T16:25:12.1234Z```  Encoded:  ```?filter=id%3D0158d38771f70000000000010010038c%26state_change%3DTrue%26date_time__gte%3D2016-11-30T16%3A25%3A12.1234Z```  ##### Filtering with filter operators  String field filtering supports the following operators:  * equality: `__eq` * non-equality: `__neq` * in : `__in` * not in: `__nin`  For `__in` and `__nin` filters list of parameters must be comma-separated: `event_type__in=update.device.device-created,update.device.device-updated`
        :return: DeviceEventPage
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_log_list_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.device_log_list_with_http_info(**kwargs)  # noqa: E501
            return data


Instruction:
Write a Python 3 function for
retrieving a specific device event.

Response:
def device_log_retrieve(self, device_event_id, **kwargs):  # noqa: E501
        """DEPRECATED: Retrieve a device event.  # noqa: E501

        Retrieve device event (deprecated, use /v3/device-events/{device_event_id}/ instead)  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_log_retrieve(device_event_id, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str device_event_id: (required)
        :return: DeviceEventData
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_log_retrieve_with_http_info(device_event_id, **kwargs)  # noqa: E501
        else:
            (data) = self.device_log_retrieve_with_http_info(device_event_id, **kwargs)  # noqa: E501
            return data


Instruction:
Can you create a Python 3 function that
creates a new device query.

Response:
def device_query_create(self, device, **kwargs):  # noqa: E501
        """Create a device query  # noqa: E501

        Create a new device query.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_query_create(device, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param DeviceQueryPostPutRequest device: (required)
        :return: DeviceQuery
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_query_create_with_http_info(device, **kwargs)  # noqa: E501
        else:
            (data) = self.device_query_create_with_http_info(device, **kwargs)  # noqa: E501
            return data


Instruction:
Implement a Python 3 function for
deleting a device query.

Response:
def device_query_destroy(self, query_id, **kwargs):  # noqa: E501
        """Delete a device query  # noqa: E501

        Delete a device query.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_query_destroy(query_id, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str query_id: (required)
        :return: None
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_query_destroy_with_http_info(query_id, **kwargs)  # noqa: E501
        else:
            (data) = self.device_query_destroy_with_http_info(query_id, **kwargs)  # noqa: E501
            return data


Instruction:
Explain what the following Python 3 code does
def device_query_list(self, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_query_list_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.device_query_list_with_http_info(**kwargs)  # noqa: E501
            return data

Response: List all device queries.


Instruction:
Implement a Python 3 function for
retrieving a specific device query.

Response:
def device_query_retrieve(self, query_id, **kwargs):  # noqa: E501
        """Retrieve a device query.  # noqa: E501

        Retrieve a specific device query.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_query_retrieve(query_id, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str query_id: (required)
        :return: DeviceQuery
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_query_retrieve_with_http_info(query_id, **kwargs)  # noqa: E501
        else:
            (data) = self.device_query_retrieve_with_http_info(query_id, **kwargs)  # noqa: E501
            return data


Instruction:
Can you write a function in Python 3 where it
updates a device query.

Response:
def device_query_update(self, query_id, body, **kwargs):  # noqa: E501
        """Update a device query  # noqa: E501

        Update a specifc device query.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_query_update(query_id, body, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str query_id: (required)
        :param DeviceQueryPostPutRequest body: Device query update object. (required)
        :return: DeviceQuery
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_query_update_with_http_info(query_id, body, **kwargs)  # noqa: E501
        else:
            (data) = self.device_query_update_with_http_info(query_id, body, **kwargs)  # noqa: E501
            return data


Instruction:
How would you explain what the following Python 3 function does
def device_retrieve(self, id, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_retrieve_with_http_info(id, **kwargs)  # noqa: E501
        else:
            (data) = self.device_retrieve_with_http_info(id, **kwargs)  # noqa: E501
            return data

Response:
Get a devices  # noqa: E501

        Retrieve information about a specific device.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.device_retrieve(id, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str id: (required)
        :return: DeviceData
                 If the method is called asynchronously,
                 returns the request thread.


Instruction:
Explain what the following Python 3 code does
def device_update(self, id, device, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.device_update_with_http_info(id, device, **kwargs)  # noqa: E501
        else:
            (data) = self.device_update_with_http_info(id, device, **kwargs)  # noqa: E501
            return data

Response: Update a specific device.


Instruction:
Explain what the following Python 3 code does
def group_create(self, group, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_create_with_http_info(group, **kwargs)  # noqa: E501
        else:
            (data) = self.group_create_with_http_info(group, **kwargs)  # noqa: E501
            return data

Response:
Create a group  # noqa: E501

        Create a group  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.group_create(group, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param Group group: Group (required)
        :return: DeviceGroup
                 If the method is called asynchronously,
                 returns the request thread.


Instruction:
Can you tell what is the following Python 3 function doing
def group_delete(self, device_group_id, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_delete_with_http_info(device_group_id, **kwargs)  # noqa: E501
        else:
            (data) = self.group_delete_with_http_info(device_group_id, **kwargs)  # noqa: E501
            return data

Response:
Delete a group  # noqa: E501

        Delete a group.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.group_delete(device_group_id, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str device_group_id: The ID of the group (required)
        :return: None
                 If the method is called asynchronously,
                 returns the request thread.


Instruction:
Write a Python 3 script for
listing all groups. # noqa: E501 List all groups. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.group_list(asynchronous=True) >>> result = thread.get() :param asynchronous bool :param int limit: How many objects to retrieve in the page. :param str order: The order of the records based on creation time, `ASC` or `DESC`; by default `ASC`. :param str after: The ID of The item after which to retrieve the next page. :param str include: Comma-separated list of data fields to return. Currently supported: `total_count`. :param str filter: URL-encoded query string parameter to filter returned data `?filter={URL-encoded query string}` ###### Filterable fields: The table lists all the fields that can be filtered on with certain filters:

 Field	 = / __eq / __neq	 __in / __nin	 __lte / __gte

 id	 ✓	 ✓

 devices_count	 ✓	 ✓	 ✓

 name	 ✓	 ✓

 description	 ✓	 ✓

 custom_attributes	 ✓

 created_at	 ✓	 ✓	 ✓

 updated_at	 ✓	 ✓	 ✓

 etag	 ✓	 ✓	 ✓

   The query string is made up of key-value pairs separated by ampersands. For example, this query: `key1=value1&key2=value2&key3=value3` would be URL-encoded as: `?filter=key1__eq%3Dvalue1%26key2__eq%3Dvalue2%26key3__eq%3Dvalue3` **Filtering by properties** `name__eq=mygroup` **Filtering on date-time fields** Date-time fields should be specified in UTC RFC3339 format, `YYYY-MM-DDThh:mm:ss.msZ`. There are three permitted variations: * UTC RFC3339 with milliseconds. Example: `2016-11-30T16:25:12.1234Z` * UTC RFC3339 without milliseconds. Example: `2016-11-30T16:25:12Z` * UTC RFC3339 shortened without milliseconds and punctuation. Example: `20161130T162512Z` Date-time filtering supports three operators: * equality by appending `__eq` to the field name * greater than or equal to by appending `__gte` to the field name * less than or equal to by appending `__lte` to the field name `{field name}[|__eq|__lte|__gte]={UTC RFC3339 date-time}` Time ranges may be specified by including both the `__gte` and `__lte` forms in the filter. For example: `created_at__gte=2016-11-30T16:25:12.1234Z&created_at__lte=2016-12-30T00:00:00Z` **Filtering on multiple fields** `name__eq=mygroup&created_at__gte=2016-11-30T16:25:12.1234Z&created_at__lte=2016-12-30T00:00:00Z` **Filtering with filter operators** String field filtering supports the following operators: * equality: `__eq` * non-equality: `__neq` * in : `__in` * not in: `__nin` For `__in` and `__nin` filters list of parameters must be comma-separated: `name__in=group1,group2` :return: DeviceGroupPage If the method is called asynchronously, returns the request thread.

Response:
def group_list(self, **kwargs):  # noqa: E501
        """List all groups.  # noqa: E501

        List all groups.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.group_list(asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param int limit: How many objects to retrieve in the page.
        :param str order: The order of the records based on creation time, `ASC` or `DESC`; by default `ASC`.
        :param str after: The ID of The item after which to retrieve the next page.
        :param str include: Comma-separated list of data fields to return. Currently supported: `total_count`.
        :param str filter: URL-encoded query string parameter to filter returned data  `?filter={URL-encoded query string}`  ###### Filterable fields:  The table lists all the fields that can be filtered on with certain filters:

       Field	       = / __eq / __neq	       __in /  __nin	       __lte / __gte

       id	       ✓	       ✓

       devices_count	       ✓	       ✓	       ✓

       name	       ✓	       ✓

       description	       ✓	       ✓

       custom_attributes	       ✓

       created_at	       ✓	       ✓	       ✓

       updated_at	       ✓	       ✓	       ✓

       etag	       ✓	       ✓	       ✓

    The query string is made up of key-value pairs separated by ampersands. For example, this query: `key1=value1&key2=value2&key3=value3`  would be URL-encoded as: `?filter=key1__eq%3Dvalue1%26key2__eq%3Dvalue2%26key3__eq%3Dvalue3`   **Filtering by properties** `name__eq=mygroup`  **Filtering on date-time fields**  Date-time fields should be specified in UTC RFC3339 format, `YYYY-MM-DDThh:mm:ss.msZ`. There are three permitted variations:  * UTC RFC3339 with milliseconds. Example: `2016-11-30T16:25:12.1234Z` * UTC RFC3339 without milliseconds. Example: `2016-11-30T16:25:12Z` * UTC RFC3339 shortened without milliseconds and punctuation. Example: `20161130T162512Z`  Date-time filtering supports three operators:  * equality by appending `__eq` to the field name * greater than or equal to by appending `__gte` to the field name * less than or equal to by appending `__lte` to the field name  `{field name}[|__eq|__lte|__gte]={UTC RFC3339 date-time}`  Time ranges may be specified by including both the `__gte` and `__lte` forms in the filter. For example:  `created_at__gte=2016-11-30T16:25:12.1234Z&created_at__lte=2016-12-30T00:00:00Z`  **Filtering on multiple fields**  `name__eq=mygroup&created_at__gte=2016-11-30T16:25:12.1234Z&created_at__lte=2016-12-30T00:00:00Z`  **Filtering with filter operators**  String field filtering supports the following operators:  * equality: `__eq` * non-equality: `__neq` * in : `__in` * not in: `__nin`  For `__in` and `__nin` filters list of parameters must be comma-separated:  `name__in=group1,group2`
        :return: DeviceGroupPage
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_list_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.group_list_with_http_info(**kwargs)  # noqa: E501
            return data


Instruction:
Here you have a function in Python 3, explain what it does
def group_members_add(self, device_group_id, body, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_members_add_with_http_info(device_group_id, body, **kwargs)  # noqa: E501
        else:
            (data) = self.group_members_add_with_http_info(device_group_id, body, **kwargs)  # noqa: E501
            return data

Response: Add a device to a group.


Instruction:
Write a Python 3 script for
removing one device from a group.

Response:
def group_members_remove(self, device_group_id, body, **kwargs):  # noqa: E501
        """Remove a device from a group  # noqa: E501

        Remove one device from a group  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.group_members_remove(device_group_id, body, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str device_group_id: The ID of the group (required)
        :param DeviceGroupManipulation body: Body of the request (required)
        :return: DevicePage
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_members_remove_with_http_info(device_group_id, body, **kwargs)  # noqa: E501
        else:
            (data) = self.group_members_remove_with_http_info(device_group_id, body, **kwargs)  # noqa: E501
            return data


Instruction:
Can you tell what is the following Python 3 function doing
def group_members_retrieve(self, device_group_id, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_members_retrieve_with_http_info(device_group_id, **kwargs)  # noqa: E501
        else:
            (data) = self.group_members_retrieve_with_http_info(device_group_id, **kwargs)  # noqa: E501
            return data

Response: Get a page of devices


Instruction:
Explain what the following Python 3 code does
def group_retrieve(self, device_group_id, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_retrieve_with_http_info(device_group_id, **kwargs)  # noqa: E501
        else:
            (data) = self.group_retrieve_with_http_info(device_group_id, **kwargs)  # noqa: E501
            return data

Response:
Get a group.  # noqa: E501

        Get a group.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.group_retrieve(device_group_id, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str device_group_id: The group ID (required)
        :return: DeviceGroup
                 If the method is called asynchronously,
                 returns the request thread.


Instruction:
Write a Python 3 function that can
update the attributes of a group.

Response:
def group_update(self, device_group_id, group, **kwargs):  # noqa: E501
        """Modify the attributes of a group.  # noqa: E501

        Modify the attributes of a group.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.group_update(device_group_id, group, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str device_group_id: (required)
        :param Group1 group: Group (required)
        :return: DeviceGroup
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.group_update_with_http_info(device_group_id, group, **kwargs)  # noqa: E501
        else:
            (data) = self.group_update_with_http_info(device_group_id, group, **kwargs)  # noqa: E501
            return data


Instruction:
Here you have a function in Python 3, explain what it does
def _notify(self, data):
        payload = tlv.decode(
            payload=data.get('payload'),
            content_type=data.get('ct'),
            decode_b64=True
        )
        super(CurrentResourceValue, self)._notify(payload)
        # after one response, close the channel
        self.ensure_stopped()

Response: Notify this channel of inbound data


Instruction:
Make a summary of the following Python 3 code
def account_id(self, account_id):
        if account_id is None:
            raise ValueError("Invalid value for `account_id`, must not be `None`")
        if account_id is not None and len(account_id) > 250:
            raise ValueError("Invalid value for `account_id`, length must be less than or equal to `250`")
        if account_id is not None and len(account_id) < 1:
            raise ValueError("Invalid value for `account_id`, length must be greater than or equal to `1`")

        self._account_id = account_id

Response: Sets the account_id of this ServicePackageQuotaHistoryReservation. The account_id of this ServicePackageQuotaHistoryReservation.


Instruction:
How would you code a function in Python 3 to
set the campaign_name of this ServicePackageQuotaHistoryReservation.

Response:
def campaign_name(self, campaign_name):
        """
        Sets the campaign_name of this ServicePackageQuotaHistoryReservation.
        Textual campaign name for this reservation.

        :param campaign_name: The campaign_name of this ServicePackageQuotaHistoryReservation.
        :type: str
        """
        if campaign_name is None:
            raise ValueError("Invalid value for `campaign_name`, must not be `None`")
        if campaign_name is not None and len(campaign_name) > 250:
            raise ValueError("Invalid value for `campaign_name`, length must be less than or equal to `250`")
        if campaign_name is not None and len(campaign_name) < 1:
            raise ValueError("Invalid value for `campaign_name`, length must be greater than or equal to `1`")

        self._campaign_name = campaign_name


Instruction:
How would you explain what the following Python 3 function does
def id(self, id):
        if id is None:
            raise ValueError("Invalid value for `id`, must not be `None`")
        if id is not None and len(id) > 250:
            raise ValueError("Invalid value for `id`, length must be less than or equal to `250`")
        if id is not None and len(id) < 1:
            raise ValueError("Invalid value for `id`, length must be greater than or equal to `1`")

        self._id = id

Response: Sets the id of this ServicePackageQuotaHistoryReservation. id


Instruction:
Can you write a function in Python 3 where it
notifies this channel of inbound data

Response:
def notify(self, data):
        """Notify this channel of inbound data"""
        string_channels = {
            ChannelIdentifiers.de_registrations,
            ChannelIdentifiers.registrations_expired
        }

        if data['channel'] in string_channels:
            message = {'device_id': data["value"], 'channel': data["channel"]}
        else:
            message = DeviceStateChanges._map_endpoint_data(data)

        return super(DeviceStateChanges, self).notify(message)


Instruction:
Here you have a function in Python 3, explain what it does
def get_connected_endpoints(self, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_connected_endpoints_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.get_connected_endpoints_with_http_info(**kwargs)  # noqa: E501
            return data

Response: Get all connected endpoints for a given resource type.


Instruction:
Here you have a function in Python 3, explain what it does
def get_endpoint_resources(self, device_id, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_endpoint_resources_with_http_info(device_id, **kwargs)  # noqa: E501
        else:
            (data) = self.get_endpoint_resources_with_http_info(device_id, **kwargs)  # noqa: E501
            return data

Response: Get the resources on an endpoint.


Instruction:
How would you explain what the following Python 3 function does
def metadata_wrapper(fn):
        @functools.wraps(fn)
        def wrapped_f(self, *args, **kwargs):
            self.last_metadata = {}
            self.last_metadata["url"] = self.configuration.host + args[0]
            self.last_metadata["method"] = args[1]
            self.last_metadata["timestamp"] = time.time()
            try:
                return fn(self, *args, **kwargs)
            except Exception as e:
                self.last_metadata["exception"] = e
                raise
        return wrapped_f

Response: Save metadata of last api call.


Instruction:
Create a Python 3 function for
making the HTTP request (synchronous) and return the deserialized data. To make an async request, set the asynchronous parameter. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Query parameters in the url. :param header_params: Header parameters to be placed in the request header. :param body: Request body. :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. :param response: Response data type. :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param asynchronous bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: If asynchronous parameter is True, the request will be called asynchronously. The method will return the request thread. If parameter asynchronous is False or missing, then the method will return the response directly.

Response:
def call_api(self, resource_path, method,
                 path_params=None, query_params=None, header_params=None,
                 body=None, post_params=None, files=None,
                 response_type=None, auth_settings=None, asynchronous=None,
                 _return_http_data_only=None, collection_formats=None, _preload_content=True,
                 _request_timeout=None):
        """
        Makes the HTTP request (synchronous) and return the deserialized data.
        To make an async request, set the asynchronous parameter.

        :param resource_path: Path to method endpoint.
        :param method: Method to call.
        :param path_params: Path parameters in the url.
        :param query_params: Query parameters in the url.
        :param header_params: Header parameters to be
            placed in the request header.
        :param body: Request body.
        :param post_params dict: Request post form parameters,
            for `application/x-www-form-urlencoded`, `multipart/form-data`.
        :param auth_settings list: Auth Settings names for the request.
        :param response: Response data type.
        :param files dict: key -> filename, value -> filepath,
            for `multipart/form-data`.
        :param asynchronous bool: execute request asynchronously
        :param _return_http_data_only: response data without head status code and headers
        :param collection_formats: dict of collection formats for path, query,
            header, and post parameters.
        :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without
                                 reading/decoding response data. Default is True.
        :param _request_timeout: timeout setting for this request. If one number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of (connection, read) timeouts.
        :return:
            If asynchronous parameter is True,
            the request will be called asynchronously.
            The method will return the request thread.
            If parameter asynchronous is False or missing,
            then the method will return the response directly.
        """
        if not asynchronous:
            return self.__call_api(resource_path, method,
                                   path_params, query_params, header_params,
                                   body, post_params, files,
                                   response_type, auth_settings,
                                   _return_http_data_only, collection_formats, _preload_content, _request_timeout)
        else:
            thread = self.pool.apply_async(self.__call_api, (resource_path, method,
                                           path_params, query_params,
                                           header_params, body,
                                           post_params, files,
                                           response_type, auth_settings,
                                           _return_http_data_only,
                                           collection_formats, _preload_content, _request_timeout))
        return thread


Instruction:
Write a Python 3 script to
prepare form parameters for post processing.

Response:
def prepare_post_parameters(self, post_params=None, files=None):
        """
        Builds form parameters.

        :param post_params: Normal form parameters.
        :param files: File parameters.
        :return: Form parameters with files.
        """
        params = post_params or []
        for key, values in (files or {}).items():
            for maybe_file_or_path in values if isinstance(values, list) else [values]:
                try:
                    # use the parameter as if it was an open file object
                    data = maybe_file_or_path.read()
                    maybe_file_or_path = maybe_file_or_path.name
                except AttributeError:
                    # then it is presumably a file path
                    with open(maybe_file_or_path, 'rb') as fh:
                        data = fh.read()
                basepath = os.path.basename(maybe_file_or_path)
                mimetype = mimetypes.guess_type(basepath)[0] or 'application/octet-stream'
                params.append((key, (basepath, data, mimetype)))
        return params


Instruction:
Write a Python 3 script to
convert nested dictionary filters into django - style key value pairs

Response:
def _normalise_key_values(filter_obj, attr_map=None):
    """Converts nested dictionary filters into django-style key value pairs

    Map filter operators and aliases to operator-land
    Additionally, perform replacements according to attribute map
    Automatically assumes __eq if not explicitly defined
    """
    new_filter = {}
    for key, constraints in filter_obj.items():
        aliased_key = key
        if attr_map is not None:
            aliased_key = attr_map.get(key)
            if aliased_key is None:
                raise CloudValueError(
                    'Invalid key %r for filter attribute; must be one of:\n%s' % (
                        key,
                        attr_map.keys()
                    )
                )
        if not isinstance(constraints, dict):
            constraints = {'eq': constraints}
        for operator, value in constraints.items():
            # FIXME: deprecate this $ nonsense
            canonical_operator = FILTER_OPERATOR_ALIASES.get(operator.lstrip('$'))
            if canonical_operator is None:
                raise CloudValueError(
                    'Invalid operator %r for filter key %s; must be one of:\n%s' % (
                        operator,
                        key,
                        FILTER_OPERATOR_ALIASES.keys()
                    )
                )
            canonical_key = str('%s__%s' % (aliased_key, canonical_operator))
            new_filter[canonical_key] = _normalise_value(value)
    return new_filter


Instruction:
Make a summary of the following Python 3 code
def legacy_filter_formatter(kwargs, attr_map):
    params = _depluralise_filters_key(copy.copy(kwargs))
    new_filter = _get_filter(sdk_filter=params.pop('filter', {}), attr_map=attr_map)
    if new_filter:
        new_filter = sorted([(k.rsplit('__eq')[0], v) for k, v in new_filter.items()])
        params['filter'] = urllib.parse.urlencode(new_filter)
    return params

Response: Build a filter for update and device apis


Instruction:
How would you code a function in Python 3 to
build a filter according to the cross - api specification

Response:
def filter_formatter(kwargs, attr_map):
    """Builds a filter according to the cross-api specification

    :param kwargs: expected to contain {'filter': {filter dict}}
    :returns: {validated filter dict}
    """
    params = _depluralise_filters_key(copy.copy(kwargs))
    params.update(_get_filter(sdk_filter=params.pop('filter', {}), attr_map=attr_map))
    return params


Instruction:
How would you implement a function in Python 3 that
approximates number of results according to the API

Response:
def count(self):
        """Approximate number of results, according to the API"""
        if self._total_count is None:
            self._total_count = self._get_total_count()
        return self._total_count


Instruction:
Can you create a Python 3 function that
returns the first item from the query or None if there are no results

Response:
def first(self):
        """Returns the first item from the query, or None if there are no results"""
        if self._results_cache:
            return self._results_cache[0]

        query = PaginatedResponse(func=self._func, lwrap_type=self._lwrap_type, **self._kwargs)
        try:
            return next(query)
        except StopIteration:
            return None


Instruction:
Make a summary of the following Python 3 code
def to_dict(self):
        return dict(
            after=self._kwargs.get('after'),
            data=list(self),
            has_more=self._has_more,
            limit=self._max_results,
            order=self._kwargs.get('order', 'ASC'),
            page_size=self._page_size,
            total_count=self.count(),
        )

Response: Returns a dictionary representation of the object.


Instruction:
Here you have a function in Python 3, explain what it does
def data(self):
        import warnings
        warnings.warn(
            '`data` attribute is deprecated and will be removed in a future release, '
            'use %s as an iterable instead' % (PaginatedResponse,),
            category=DeprecationWarning,
            stacklevel=2  # log wherever '.data' is referenced, rather than this line
        )
        return list(self)

Response: Deprecated. Returns the data as a list


Instruction:
Write a Python 3 function for
sending release notifications to interested parties

Response:
def main():
    """Sends release notifications to interested parties

    Currently this is an arm-internal slack channel.

     1. assumes you've set a token for an authorised slack user/bot.
     2. assumes said user/bot is already in channel.
     otherwise: https://github.com/slackapi/python-slackclient#joining-a-channel
    """
    slack_token = os.environ.get('SLACK_API_TOKEN')
    channel_id = os.environ.get('SLACK_CHANNEL', '#mbed-cloud-sdk')
    message = os.environ.get('SLACK_MESSAGE', (
        ':checkered_flag: New version of :snake: Python SDK released: *{version}* '
        '(<https://pypi.org/project/mbed-cloud-sdk/{version}/|PyPI>)'
    ))

    if not slack_token:
        print('no slack token')
        return

    version = os.environ.get('SLACK_NOTIFY_VERSION')
    if not version:
        try:
            import mbed_cloud
        except ImportError:
            pass
        else:
            version = mbed_cloud.__version__

    payload = message.format(version=version) if version else message

    print('notifying slack channel %s with payload:\n%s' % (channel_id, payload))

    sc = SlackClient(slack_token)
    sc.api_call(
        'chat.postMessage',
        channel=channel_id,
        text=payload,
    )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def service(self, service):
        if service is None:
            raise ValueError("Invalid value for `service`, must not be `None`")
        allowed_values = ["lwm2m", "bootstrap"]
        if service not in allowed_values:
            raise ValueError(
                "Invalid value for `service` ({0}), must be one of {1}"
                .format(service, allowed_values)
            )

        self._service = service

Response: Sets the service of this TrustedCertificateInternalResp.


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

Response:
def create_developer_certificate(self, authorization, body, **kwargs):  # noqa: E501
        """Create a new developer certificate to connect to the bootstrap server.  # noqa: E501

        This REST API is intended to be used by customers to get a developer certificate (a certificate that can be flashed into multiple devices to connect to bootstrap server).  **Note:** The number of developer certificates allowed per account is limited. Please see [Using your own certificate authority](/docs/current/mbed-cloud-deploy/instructions-for-factory-setup-and-device-provision.html#using-your-own-certificate-authority-with-mbed-cloud).  **Example usage:** curl -X POST \"http://api.us-east-1.mbedcloud.com/v3/developer-certificates\" -H \"accept: application/json\" -H \"Authorization: Bearer THE_ACCESS_TOKEN\" -H \"content-type: application/json\" -d \"{ \\\"name\\\": \\\"THE_CERTIFICATE_NAME\\\", \\\"description\\\": \\\"THE_CERTIFICATE_DESCRIPTION\\\"}\"   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.create_developer_certificate(authorization, body, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str authorization: Bearer {Access Token}.  (required)
        :param DeveloperCertificateRequestData body: (required)
        :return: DeveloperCertificateResponseData
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.create_developer_certificate_with_http_info(authorization, body, **kwargs)  # noqa: E501
        else:
            (data) = self.create_developer_certificate_with_http_info(authorization, body, **kwargs)  # noqa: E501
            return data


Instruction:
Can you tell what is the following Python 3 function doing
def get_developer_certificate(self, developer_certificate_id, authorization, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_developer_certificate_with_http_info(developer_certificate_id, authorization, **kwargs)  # noqa: E501
        else:
            (data) = self.get_developer_certificate_with_http_info(developer_certificate_id, authorization, **kwargs)  # noqa: E501
            return data

Response: Get an existing developer certificate.


Instruction:
Create a Python 3 function for
setting the month of this ReportResponse.

Response:
def month(self, month):
        """
        Sets the month of this ReportResponse.
        Month of requested billing report

        :param month: The month of this ReportResponse.
        :type: str
        """
        if month is None:
            raise ValueError("Invalid value for `month`, must not be `None`")
        if month is not None and not re.search('^\\d{4}-\\d{2}$', month):
            raise ValueError("Invalid value for `month`, must be a follow pattern or equal to `/^\\d{4}-\\d{2}$/`")

        self._month = month


Instruction:
Here you have a function in Python 3, explain what it does
def create_certificate_issuer_config(self, create_certificate_issuer_config, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.create_certificate_issuer_config_with_http_info(create_certificate_issuer_config, **kwargs)  # noqa: E501
        else:
            (data) = self.create_certificate_issuer_config_with_http_info(create_certificate_issuer_config, **kwargs)  # noqa: E501
            return data

Response: Create a certificate issuer configuration.


Instruction:
Write a Python 3 script to
delete a certificate issuer configuration.

Response:
def delete_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, **kwargs):  # noqa: E501
        """Delete certificate issuer configuration.  # noqa: E501

        Delete the configured certificate issuer configuration. You can only delete the configurations of custom certificates.   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.delete_certificate_issuer_config_by_id(certificate_issuer_configuration_id, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str certificate_issuer_configuration_id: The ID of the certificate issuer configuration.  (required)
        :return: None
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.delete_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs)  # noqa: E501
        else:
            (data) = self.delete_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs)  # noqa: E501
            return data


Instruction:
Explain what the following Python 3 code does
def get_certificate_issuer_config(self, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_certificate_issuer_config_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.get_certificate_issuer_config_with_http_info(**kwargs)  # noqa: E501
            return data

Response: Get certificate issuer configuration.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs)  # noqa: E501
        else:
            (data) = self.get_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, **kwargs)  # noqa: E501
            return data

Response: Get a certificate issuer configuration by ID.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_certificate_issuer_configs(self, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_certificate_issuer_configs_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.get_certificate_issuer_configs_with_http_info(**kwargs)  # noqa: E501
            return data

Response: Get certificate issuer configurations.


Instruction:
How would you explain what the following Python 3 function does
def update_certificate_issuer_config(self, certificate_issuer_config_request, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.update_certificate_issuer_config_with_http_info(certificate_issuer_config_request, **kwargs)  # noqa: E501
        else:
            (data) = self.update_certificate_issuer_config_with_http_info(certificate_issuer_config_request, **kwargs)  # noqa: E501
            return data

Response: Update the certificate issuer configuration.


Instruction:
Can you tell what is the following Python 3 function doing
def update_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, certificate_issuer_config_request, **kwargs):  # noqa: E501
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.update_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, certificate_issuer_config_request, **kwargs)  # noqa: E501
        else:
            (data) = self.update_certificate_issuer_config_by_id_with_http_info(certificate_issuer_configuration_id, certificate_issuer_config_request, **kwargs)  # noqa: E501
            return data

Response: Update the configured certificate issuer configuration.


Instruction:
Can you implement a function in Python 3 that
sets the active_devices of this ReportBillingData.

Response:
def active_devices(self, active_devices):
        """
        Sets the active_devices of this ReportBillingData.

        :param active_devices: The active_devices of this ReportBillingData.
        :type: int
        """
        if active_devices is None:
            raise ValueError("Invalid value for `active_devices`, must not be `None`")
        if active_devices is not None and active_devices < 0:
            raise ValueError("Invalid value for `active_devices`, must be a value greater than or equal to `0`")

        self._active_devices = active_devices


Instruction:
Write a Python 3 script to
set the firmware_updates of this ReportBillingData.

Response:
def firmware_updates(self, firmware_updates):
        """
        Sets the firmware_updates of this ReportBillingData.

        :param firmware_updates: The firmware_updates of this ReportBillingData.
        :type: int
        """
        if firmware_updates is None:
            raise ValueError("Invalid value for `firmware_updates`, must not be `None`")
        if firmware_updates is not None and firmware_updates < 0:
            raise ValueError("Invalid value for `firmware_updates`, must be a value greater than or equal to `0`")

        self._firmware_updates = firmware_updates


Instruction:
Make a summary of the following Python 3 code
def main():
    last_known = '0'
    if os.path.isfile(metafile):
        with open(metafile) as fh:
            last_known = fh.read()

    import mbed_cloud
    current = mbed_cloud.__version__

    # how significant a change in version scheme should trigger a new changelog entry
    # (api major, api minor, sdk major, sdk minor, sdk patch)
    sigfigs = 4
    current_version = LooseVersion(current).version
    last_known_version = LooseVersion(last_known).version

    should_towncrier = current_version[:sigfigs] != last_known_version[:sigfigs]

    print('%s -- %s :: current vs previous changelog build' % (current, last_known))
    if should_towncrier:
        print('%s >> %s :: running changelog build' % (current, last_known))
        subprocess.check_call(
            ['towncrier', '--yes'],
            cwd=os.path.join(PROJECT_ROOT, 'docs', 'changelog')
        )
        with open(metafile, 'w') as fh:
            fh.write(current)

Response: Writes out newsfile if significant version bump is needed


Instruction:
Here you have a function in Python 3, explain what it does
def paths(self):
        filename = '.mbed_cloud_config.json'
        return [
            # Global config in /etc for *nix users
            "/etc/%s" % filename,

            # Config file in home directory
            os.path.join(os.path.expanduser("~"), filename),

            # Config file in current directory
            os.path.join(os.getcwd(), filename),

            # Config file specified using environment variable
            os.environ.get(self.path_from_env_key)
        ]

Response: Get list of paths to look in for configuration data


Instruction:
Here you have a function in Python 3, explain what it does
def load(self, updates):
        # Go through in order and override the config (`.mbed_cloud_config.json` loader)
        for path in self.paths():
            if not path:
                continue
            abs_path = os.path.abspath(os.path.expanduser(path))
            if not os.path.isfile(abs_path):
                self._using_paths.append('missing: %s' % abs_path)
                continue
            self._using_paths.append(' exists: %s' % abs_path)
            with open(abs_path) as fh:
                self.update(json.load(fh))

        # New dotenv loader - requires explicit instructions to use current working directory
        load_dotenv(find_dotenv(usecwd=True))

        # Pluck config values out of the environment
        for env_var, key in {ENVVAR_API_HOST: 'host', ENVVAR_API_KEY: 'api_key'}.items():
            env_value = os.getenv(env_var)
            if env_value is not None:
                self[key] = env_value
        if updates:
            self.update(updates)
        self.validate()

Response: Load configuration data from file or environment variables.


Instruction:
How would you code a function in Python 3 to
validate the current config

Response:
def validate(self):
        """Validate / fix up the current config"""
        if not self.get('api_key'):
            raise ValueError("api_key not found in config. Please see documentation.")
        host = self.get('host') or DEFAULT_CLOUD_HOST
        if host:
            # remove extraneous slashes and force to byte string
            # otherwise msg += message_body in httplib will fail in python2
            # when message_body contains binary data, and url is unicode

            # remaining failure modes include at least:
            # passing bytes in python3 will fail as we try to strip unicode '/' characters
            # passing unicode code points in python2 will fail due to httplib host.encode('ascii')
            host = host.strip('/')
            if not isinstance(host, str):
                host = host.encode('utf-8')
            self['host'] = host

        self.setdefault('autostart_notification_thread', True)


Instruction:
Can you tell what is the following Python 3 function doing
def expand_dict_as_keys(d):
    to_product = []
    for key, values in sorted(d.items()):
        # if we sort the inputs here, itertools.product will keep a stable sort order for us later
        key_values = sorted([(key, v) for v in utils.ensure_listable(values) if v is not None])
        if key_values:
            to_product.append(key_values)
    return list(itertools.product(*to_product))

Response: Expands a dictionary into a list of immutables with cartesian product of the list parts


Instruction:
Can you create a Python 3 function that
stores a new item in routing map

Response:
def create_route(self, item, routes):
        """Stores a new item in routing map"""
        for route in routes:
            self._routes.setdefault(route, set()).add(item)
        return item


Instruction:
Can you create a Python 3 function that
removes item from matching routes

Response:
def remove_routes(self, item, routes):
        """Removes item from matching routes"""
        for route in routes:
            items = self._routes.get(route)
            try:
                items.remove(item)
                LOG.debug('removed item from route %s', route)
            except ValueError:
                pass
            if not items:
                self._routes.pop(route)
                LOG.debug('removed route %s', route)


Instruction:
Can you write a function in Python 3 where it
returns a list of all items in the routing table.

Response:
def list_all(self):
        """All items"""
        return list(set(
            item for items in self._routes.values() for item in items
        ))


Instruction:
Can you implement a function in Python 3 that
gets or start the requested channel

Response:
def get_channel(self, subscription_channel, **observer_params):
        """Get or start the requested channel"""
        keys = subscription_channel.get_routing_keys()
        # watch keys are unique sets of keys that we will attempt to extract from inbound items
        self.watch_keys.add(frozenset({k_v[0] for key in keys for k_v in key}))
        self.create_route(subscription_channel, keys)
        subscription_channel._configure(self, self.connect_api, observer_params)
        return subscription_channel


Instruction:
Make a summary of the following Python 3 code
def subscribe(self, subscription_channel, **observer_params):
        return self.get_channel(subscription_channel, **observer_params).ensure_started().observer

Response: Subscribe to a channel and returns its observer


Instruction:
How would you code a function in Python 3 to
route inbound items to individual channels

Response:
def _notify_single_item(self, item):
        """Route inbound items to individual channels"""
        # channels that this individual item has already triggered
        # (dont want to trigger them again)
        triggered_channels = set()
        for key_set in self.watch_keys:
            # only pluck keys if they exist
            plucked = {
                key_name: item[key_name]
                for key_name in key_set if key_name in item
            }
            route_keys = expand_dict_as_keys(plucked)
            for route in route_keys:
                channels = self.get_route_items(route) or {}
                LOG.debug('route table match: %s -> %s', route, channels)
                if not channels:
                    LOG.debug(
                        'no subscribers for message.\nkey %s\nroutes: %s',
                        route,
                        self._routes
                    )
                for channel in channels:
                    if channel in triggered_channels:
                        LOG.debug('skipping dispatch to %s', channel)
                        continue
                    LOG.debug('routing dispatch to %s: %s', channel, item)
                    try:
                        channel.notify(item) and triggered_channels.add(channel)
                    except Exception:  # noqa
                        LOG.exception('Channel notification failed')
        return triggered_channels


Instruction:
Can you create a Python 3 function that
notifies subscribers that data was received

Response:
def notify(self, data):
        """Notify subscribers that data was received"""
        triggered_channels = []
        for channel_name, items in data.items():
            for item in items or []:
                LOG.debug('notify received: %s', item)
                try:
                    # some channels return strings rather than objects (e.g. de-registrations),
                    # normalize them here
                    item = {'value': item} if isinstance(item, six.string_types) else dict(item)
                    # inject the channel name to the data (so channels can filter on it)
                    item['channel'] = channel_name
                    triggered_channels.extend(list(self._notify_single_item(item)))
                except Exception:  # noqa
                    LOG.exception('Subscription notification failed')
        return triggered_channels


Instruction:
Here you have a function in Python 3, explain what it does
def type(self, type):
        if type is None:
            raise ValueError("Invalid value for `type`, must not be `None`")
        allowed_values = ["reservation", "reservation_release", "reservation_termination", "package_renewal", "package_creation", "package_termination"]
        if type not in allowed_values:
            raise ValueError(
                "Invalid value for `type` ({0}), must be one of {1}"
                .format(type, allowed_values)
            )

        self._type = type

Response: Sets the type of this AggregatedQuotaUsageReport.


Instruction:
How would you explain what the following Python 3 function does
def list_campaigns(self, **kwargs):
        kwargs = self._verify_sort_options(kwargs)
        kwargs = self._verify_filters(kwargs, Campaign, True)
        api = self._get_api(update_service.DefaultApi)
        return PaginatedResponse(api.update_campaign_list, lwrap_type=Campaign, **kwargs)

Response: List all update campaigns.


Instruction:
Write a Python 3 function for
getting existing update campaign.

Response:
def get_campaign(self, campaign_id):
        """Get existing update campaign.

        :param str campaign_id: Campaign ID to retrieve (Required)
        :return: Update campaign object matching provided ID
        :rtype: Campaign
        """
        api = self._get_api(update_service.DefaultApi)
        return Campaign(api.update_campaign_retrieve(campaign_id))


Instruction:
Here you have a function in Python 3, explain what it does
def add_campaign(self, name, device_filter, **kwargs):
        device_filter = filters.legacy_filter_formatter(
            dict(filter=device_filter),
            Device._get_attributes_map()
        )
        campaign = Campaign._create_request_map(kwargs)
        if 'when' in campaign:
            # FIXME: randomly validating an input here is a sure route to nasty surprises elsewhere
            campaign['when'] = force_utc(campaign['when'])
        body = UpdateCampaignPostRequest(
            name=name,
            device_filter=device_filter['filter'],
            **campaign)
        api = self._get_api(update_service.DefaultApi)
        return Campaign(api.update_campaign_create(body))

Response: Add a new update campaign with a name and device filtering.


Instruction:
Create a Python 3 function for
updating an update campaign.

Response:
def update_campaign(self, campaign_object=None, campaign_id=None, **kwargs):
        """Update an update campaign.

        :param :class:`Campaign` campaign_object: Campaign object to update (Required)
        :return: updated campaign object
        :rtype: Campaign
        """
        api = self._get_api(update_service.DefaultApi)
        if campaign_object:
            campaign_id = campaign_object.id
            campaign_object = campaign_object._create_patch_request()
        else:
            campaign_object = Campaign._create_request_map(kwargs)
        if 'device_filter' in campaign_object:
            campaign_object["device_filter"] = filters.legacy_filter_formatter(
                dict(filter=campaign_object["device_filter"]),
                Device._get_attributes_map()
            )['filter']
        if 'when' in campaign_object:
            # FIXME: randomly validating an input here is a sure route to nasty surprises elsewhere
            campaign_object['when'] = force_utc(campaign_object['when'])
        return Campaign(api.update_campaign_update(campaign_id=campaign_id,
                                                   campaign=campaign_object))


Instruction:
Create a Python 3 function to
delete an update campaign.

Response:
def delete_campaign(self, campaign_id):
        """Delete an update campaign.

        :param str campaign_id: Campaign ID to delete (Required)
        :return: void
        """
        api = self._get_api(update_service.DefaultApi)
        api.update_campaign_destroy(campaign_id)
        return


Instruction:
How would you implement a function in Python 3 that
lists the state of all devices in the given campaign.

Response:
def list_campaign_device_states(self, campaign_id, **kwargs):
        """List campaign devices status.

        :param str campaign_id: Id of the update campaign (Required)
        :param int limit: number of devices state to retrieve
        :param str order: sort direction of device state when ordered by creation time (desc|asc)
        :param str after: get devices state after given id
        :return: List of :py:class:`CampaignDeviceState` objects
        :rtype: PaginatedResponse
        """
        kwargs = self._verify_sort_options(kwargs)
        kwargs = self._verify_filters(kwargs, CampaignDeviceState, True)
        kwargs["campaign_id"] = campaign_id
        api = self._get_api(update_service.DefaultApi)
        return PaginatedResponse(api.update_campaign_metadata_list,
                                 lwrap_type=CampaignDeviceState, **kwargs)


Instruction:
Can you tell what is the following Python 3 function doing
def get_firmware_image(self, image_id):
        api = self._get_api(update_service.DefaultApi)
        return FirmwareImage(api.firmware_image_retrieve(image_id))

Response: Get a firmware image with provided image_id.


Instruction:
Create a Python 3 function to
list all firmware images in the cache.

Response:
def list_firmware_images(self, **kwargs):
        """List all firmware images.

        :param int limit: number of firmware images to retrieve
        :param str order: ordering of images when ordered by time. 'desc' or 'asc'
        :param str after: get firmware images after given `image_id`
        :param dict filters: Dictionary of filters to apply
        :return: list of :py:class:`FirmwareImage` objects
        :rtype: PaginatedResponse
        """
        kwargs = self._verify_sort_options(kwargs)
        kwargs = self._verify_filters(kwargs, FirmwareImage, True)
        api = self._get_api(update_service.DefaultApi)
        return PaginatedResponse(api.firmware_image_list, lwrap_type=FirmwareImage, **kwargs)


Instruction:
Create a Python 3 function to
add a new firmware image.

Response:
def add_firmware_image(self, name, datafile, **kwargs):
        """Add a new firmware reference.

        :param str name: Firmware file short name (Required)
        :param str datafile: The file object or *path* to the firmware image file (Required)
        :param str description: Firmware file description
        :return: the newly created firmware file object
        :rtype: FirmwareImage
        """
        kwargs.update({'name': name})
        firmware_image = FirmwareImage._create_request_map(kwargs)
        firmware_image.update({'datafile': datafile})
        api = self._get_api(update_service.DefaultApi)
        return FirmwareImage(
            api.firmware_image_create(**firmware_image)
        )


Instruction:
How would you code a function in Python 3 to
delete a firmware image.

Response:
def delete_firmware_image(self, image_id):
        """Delete a firmware image.

        :param str image_id: image ID for the firmware to remove/delete (Required)
        :return: void
        """
        api = self._get_api(update_service.DefaultApi)
        api.firmware_image_destroy(image_id=image_id)
        return


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_firmware_manifest(self, manifest_id):
        api = self._get_api(update_service.DefaultApi)
        return FirmwareManifest(api.firmware_manifest_retrieve(manifest_id=manifest_id))

Response: Get a specific manifest with provided manifest_id.


Instruction:
Here you have a function in Python 3, explain what it does
def list_firmware_manifests(self, **kwargs):
        kwargs = self._verify_sort_options(kwargs)
        kwargs = self._verify_filters(kwargs, FirmwareManifest, True)
        api = self._get_api(update_service.DefaultApi)
        return PaginatedResponse(api.firmware_manifest_list, lwrap_type=FirmwareManifest, **kwargs)

Response:
List all manifests.

        :param int limit: number of manifests to retrieve
        :param str order: sort direction of manifests when ordered by time. 'desc' or 'asc'
        :param str after: get manifests after given `image_id`
        :param dict filters: Dictionary of filters to apply
        :return: list of :py:class:`FirmwareManifest` objects
        :rtype: PaginatedResponse


Instruction:
How would you implement a function in Python 3 that
adds a new manifest reference.

Response:
def add_firmware_manifest(self, name, datafile, key_table_file=None, **kwargs):
        """Add a new manifest reference.

        :param str name: Manifest file short name (Required)
        :param str datafile: The file object or path to the manifest file (Required)
        :param str key_table_file: The file object or path to the key_table file (Optional)
        :param str description: Manifest file description
        :return: the newly created manifest file object
        :rtype: FirmwareManifest
        """
        kwargs.update({
            'name': name,
            'url': datafile,  # really it's the datafile
        })
        if key_table_file is not None:
            kwargs.update({'key_table_url': key_table_file})  # really it's the key_table
        firmware_manifest = FirmwareManifest._create_request_map(kwargs)
        api = self._get_api(update_service.DefaultApi)
        return FirmwareManifest(
            api.firmware_manifest_create(**firmware_manifest)
        )


Instruction:
How would you implement a function in Python 3 that
deletes an existing manifest.

Response:
def delete_firmware_manifest(self, manifest_id):
        """Delete an existing manifest.

        :param str manifest_id: Manifest file ID to delete (Required)
        :return: void
        """
        api = self._get_api(update_service.DefaultApi)
        return api.firmware_manifest_destroy(manifest_id)


Instruction:
Here you have a function in Python 3, explain what it does
def device_filter(self):
        if isinstance(self._device_filter, str):
            return self._decode_query(self._device_filter)
        return self._device_filter

Response: The device filter to use.


Instruction:
Can you implement a function in Python 3 that
provides account - specific statistics for other cloud services.

Response:
def get_metrics(self, include, interval, **kwargs):  # noqa: E501
        """Provides account-specific statistics for other cloud services.  # noqa: E501

        This REST API is used to get account-specific statistics.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.get_metrics(include, interval, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str include: A comma-separated list of requested metrics and total_count (if included, the response will contain total_count to specify the total number of records available). Supported values are:  - `transactions` - `full_registrations` - `registration_updates` - `deleted_registrations` - `expired_registrations` - `bootstraps_successful` - `bootstraps_failed` - `bootstraps_pending` - `handshakes_successful` - `connect_rest_api_success` - `connect_rest_api_error` - `device_proxy_request_success` - `device_proxy_request_error` - `device_subscription_request_success` - `device_subscription_request_error` - `device_observations` - `total_count`  **Note:**  The metrics device_proxy_request_success, device_proxy_request_error, device_subscription_request_success, device_subscription_request_error and device_observations monitor only the response from the device to Mbed Cloud Connect and they do not confirm that the response is delivered to client callback URLs used when you try to access device resources using  [Connect API](/docs/current/service-api-references/mbed-cloud-connect.html) endpoints. New metrics will be added to monitor the response delivery to client callback URLs later.  **Example usage:**  ``` curl  -X GET \\       -H \"Authorization : Bearer <valid access Token>\"        'https://api.us-east-1.mbedcloud.com/v3/metrics?include=transactions,total_count&start=20170207&end=20170407&interval=1d'  {     \"object\": \"list\",     \"limit\": 20,     \"total_count\": 54,     \"after\": \"2017-07-26T00:00:00Z\",     \"has_more\": true,     \"data\": [         {             \"id\": \"015d8157c800015e306fffff005374617473000\",             \"timestamp\": \"2017-07-27T00:00:00Z\",             \"transactions\": 27366         },         {             \"id\": \"015d867e2400015e306fffff005374617473000\",             \"timestamp\": \"2017-07-28T00:00:00Z\",             \"transactions\": 27480         }     ] } ```  (required)
        :param str interval: Group the data by this interval in minutes, hours, days or weeks. Sample values: 5m, 2h, 3d, 4w. The maximum interval cannot exceed one year (365 days). The allowed ranges are 5m-525600m/1h-8760h/1d-365d/1w-53w.  (required)
        :param date start: UTC time/year/date in RFC3339 format. Fetch the data with timestamp greater than or equal to this value. Sample values: 20170207T092056990Z / 2017-02-07T09:20:56.990Z / 2017 / 20170207. The maximum time between start and end parameters cannot exceed more than one year (365 days). The parameter is not mandatory, if the period is specified.
        :param date end: UTC time/year/date in RFC3339 format. Fetch the data with timestamp less than this value. Sample values: 20170207T092056990Z / 2017-02-07T09:20:56.990Z / 2017 / 20170207. The maximum time between start and end parameters cannot exceed more than one year (365 days). The parameter is not mandatory, if the period is specified.
        :param str period: Period. Fetch the data for the period in minutes, hours, days or weeks. Sample values: 5m, 2h, 3d, 4w. The parameter is not mandatory, if the start and end time are specified. The maximum period cannot exceed one year (365 days). The allowed ranges are 5m-525600m/1h-8760h/1d-365d/1w-53w.
        :param int limit: The number of results to return. The default value is 50, minimum 2 and maximum 1000.
        :param str after: The metric ID after which to start fetching. This also can be used for pagination as follows.  **Example usage:**  ``` curl  -X GET \\       -H \"Authorization : Bearer <valid access Token>\"        'https://api.us-east-1.mbedcloud.com/v3/metrics?include=transactions,total_count&start=20170707&end=20170829&interval=1d&limit=20' {    \"object\": \"list\",    \"limit\": 20,    \"total_count\": 54,    \"has_more\": true,    \"data\": [        {            \"id\": \"015d1a589800015e306fffff005374617473000\",            \"timestamp\": \"2017-07-07T00:00:00Z\",            \"transactions\": 26381        },        .        .        .        {            \"id\": \"015d7c316c00015e306fffff005374617473000\",            \"timestamp\": \"2017-07-26T00:00:00Z\",            \"transactions\": 25569        }    ] } ```  If the parameter “has more” is true, it indicates that the list is not complete and more values are available. You can give the last ID of the list as the value of the “after” query parameter, and you get the next page of values. You can keep doing this until “has more” is false. ``` curl -X GET \\      -H \"Authorization : Bearer <valid access Token>\"      'https://api.us-east-1.mbedcloud.com/v3/metrics?include=transactions,total_count&start=20170707&end=20170829&interval=1d&limit=20&after=015d7c316c00015e306fffff005374617473000'  {    \"object\": \"list\",    \"limit\": 20,    \"total_count\": 54,    \"after\": \"2017-07-26T00:00:00Z\",    \"has_more\": true,    \"data\": [        {            \"id\": \"015d8157c800015e306fffff005374617473000\",            \"timestamp\": \"2017-07-27T00:00:00Z\",            \"transactions\": 27366        },      .      .      .        {            \"id\": \"015de3309c00015e306fffff005374617473000\",            \"timestamp\": \"2017-08-15T00:00:00Z\",            \"transactions\": 24707        }    ] } ```
        :param str order: The order of the records to return. Available values are ASC and DESC. The default value is ASC.
        :return: SuccessfulResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_metrics_with_http_info(include, interval, **kwargs)  # noqa: E501
        else:
            (data) = self.get_metrics_with_http_info(include, interval, **kwargs)  # noqa: E501
            return data


Instruction:
Can you generate a brief explanation for the following Python 3 code
def reason(self, reason):
        if reason is None:
            raise ValueError("Invalid value for `reason`, must not be `None`")
        allowed_values = ["reservation", "reservation_release", "reservation_termination", "package_creation", "package_renewal", "package_termination"]
        if reason not in allowed_values:
            raise ValueError(
                "Invalid value for `reason` ({0}), must be one of {1}"
                .format(reason, allowed_values)
            )

        self._reason = reason

Response: Sets the reason of this ServicePackageQuotaHistoryItem.


Instruction:
Write a Python 3 function that can
set the endpoint_name of this PreSharedKey.

Response:
def endpoint_name(self, endpoint_name):
        """
        Sets the endpoint_name of this PreSharedKey.
        The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.

        :param endpoint_name: The endpoint_name of this PreSharedKey.
        :type: str
        """
        if endpoint_name is None:
            raise ValueError("Invalid value for `endpoint_name`, must not be `None`")
        if endpoint_name is not None and not re.search('^[ -~]{16,64}$', endpoint_name):
            raise ValueError("Invalid value for `endpoint_name`, must be a follow pattern or equal to `/^[ -~]{16,64}$/`")

        self._endpoint_name = endpoint_name


Instruction:
Can you create a Python 3 function that
sets the secret_hex of this PreSharedKey.

Response:
def secret_hex(self, secret_hex):
        """
        Sets the secret_hex of this PreSharedKey.
        The secret of the pre-shared key in hexadecimal. It is not case sensitive; 4a is same as 4A, and it is allowed with or without 0x in the beginning. The minimum length of the secret is 128 bits and maximum 256 bits.

        :param secret_hex: The secret_hex of this PreSharedKey.
        :type: str
        """
        if secret_hex is None:
            raise ValueError("Invalid value for `secret_hex`, must not be `None`")
        if secret_hex is not None and not re.search('^(0[xX])?[0-9a-fA-F]{32,64}$', secret_hex):
            raise ValueError("Invalid value for `secret_hex`, must be a follow pattern or equal to `/^(0[xX])?[0-9a-fA-F]{32,64}$/`")

        self._secret_hex = secret_hex


Instruction:
Implement a function in Python 3 to
remove a pre - shared key.

Response:
def delete_pre_shared_key(self, endpoint_name, **kwargs):  # noqa: E501
        """Remove a pre-shared key.  # noqa: E501

        Remove a pre-shared key.  **Example usage:**  ``` curl -H \"authorization: Bearer ${API_TOKEN}\" -X DELETE https://api.us-east-1.mbedcloud.com/v2/device-shared-keys/my-endpoint-0001 ```   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.delete_pre_shared_key(endpoint_name, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str endpoint_name: The unique endpoint identifier that this pre-shared key applies to. [Reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters) must be percent-encoded. (required)
        :return: None
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.delete_pre_shared_key_with_http_info(endpoint_name, **kwargs)  # noqa: E501
        else:
            (data) = self.delete_pre_shared_key_with_http_info(endpoint_name, **kwargs)  # noqa: E501
            return data


Instruction:
How would you implement a function in Python 3 that
gets a pre - shared key for an endpoint.

Response:
def get_pre_shared_key(self, endpoint_name, **kwargs):  # noqa: E501
        """Get a pre-shared key.  # noqa: E501

        Check if a pre-shared key for an endpoint exists or not. The response does not contain the secret itself.  **Example usage:**  ``` curl -H \"authorization: Bearer ${API_TOKEN}\" https://api.us-east-1.mbedcloud.com/v2/device-shared-keys/my-endpoint-0001 ```   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.get_pre_shared_key(endpoint_name, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param str endpoint_name: The unique endpoint identifier that this pre-shared key applies to. [Reserved characters](https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters) must be percent-encoded. (required)
        :return: PreSharedKeyWithoutSecret
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.get_pre_shared_key_with_http_info(endpoint_name, **kwargs)  # noqa: E501
        else:
            (data) = self.get_pre_shared_key_with_http_info(endpoint_name, **kwargs)  # noqa: E501
            return data


Instruction:
Write a Python 3 script to
list pre - shared keys.

Response:
def list_pre_shared_keys(self, **kwargs):  # noqa: E501
        """List pre-shared keys.  # noqa: E501

        List pre-shared keys with pagination and default page size of 50 entries.  **Example usage:**  ``` curl -H \"authorization: Bearer ${API_TOKEN}\" https://api.us-east-1.mbedcloud.com/v2/device-shared-keys ```   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.list_pre_shared_keys(asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param int limit: The number of entries per page
        :param str after: An offset token for fetching a specific page. Provided by the server.
        :return: ListOfPreSharedKeysWithoutSecret
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.list_pre_shared_keys_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.list_pre_shared_keys_with_http_info(**kwargs)  # noqa: E501
            return data


Instruction:
Implement a function in Python 3 to
upload a pre - shared key to Pelion Device Management.

Response:
def upload_pre_shared_key(self, body, **kwargs):  # noqa: E501
        """Upload a pre-shared key to Pelion Device Management.  # noqa: E501

        Upload a pre-shared key (PSK) for an endpoint to allow it to bootstrap. The existing key will not be overwritten but needs to be deleted first in case of re-setting PSK for an endpoint.  **Note**: The PSK APIs are available only to accounts that have this feature enabled.  **Example usage:**  ``` curl -H \"authorization: Bearer ${API_TOKEN}\" -H \"content-type: application/json\" -X POST https://api.us-east-1.mbedcloud.com/v2/device-shared-keys \\      -d '{\"endpoint_name\": \"my-endpoint-0001\", \"secret_hex\": \"4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a\" }' ```   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass asynchronous=True
        >>> thread = api.upload_pre_shared_key(body, asynchronous=True)
        >>> result = thread.get()

        :param asynchronous bool
        :param PreSharedKey body: Pre-shared key to be uploaded. (required)
        :return: None
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('asynchronous'):
            return self.upload_pre_shared_key_with_http_info(body, **kwargs)  # noqa: E501
        else:
            (data) = self.upload_pre_shared_key_with_http_info(body, **kwargs)  # noqa: E501
            return data


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_value_length(byte):
    length_value = byte & length_type_mask
    return LengthTypes.to_ints.get(length_value, byte & length_mask)

Response: Get the length of the value in bytes.


Instruction:
How would you implement a function in Python 3 that
gives some bytes combine them together to make one long binary tree item

Response:
def combine_bytes(bytearr):
    """Given some bytes, join them together to make one long binary

    (e.g. 00001000 00000000   ->    0000100000000000)

    :param bytearr:
    :return:
    """
    bytes_count = len(bytearr)
    result = 0b0
    for index, byt in enumerate(bytearr):
        offset_bytes = bytes_count - index - 1
        result += byt << (8 * offset_bytes)
    return result


Instruction:
Can you tell what is the following Python 3 function doing
def binary_tlv_to_python(binary_string, result=None):
    result = {} if result is None else result

    if not binary_string:
        return result

    byte = binary_string[0]
    kind = byte & type_mask
    id_length = get_id_length(byte)
    payload_length = get_value_length(byte)

    # start after the type indicator
    offset = 1
    item_id = str(combine_bytes(binary_string[offset:offset + id_length]))
    offset += id_length

    # get length of payload from specifier
    value_length = payload_length
    if byte & length_type_mask != LengthTypes.SET_BYTE:
        value_length = combine_bytes(binary_string[offset:offset + payload_length])
        offset += payload_length

    if kind == Types.MULTI:
        binary_tlv_to_python(
            binary_string[offset:offset + value_length],
            result.setdefault(item_id, {})
        )
    else:
        value_binary = binary_string[offset: offset + value_length]
        result[item_id] = (
            combine_bytes(value_binary) if not all(value_binary) else value_binary.decode('utf8')
        )

    offset += value_length
    binary_tlv_to_python(binary_string[offset:], result)
    return result

Response: Recursively decode a bytearray object and store output in result object


Instruction:
Explain what the following Python 3 code does
def maybe_decode_payload(payload, content_type='application/nanoservice-tlv', decode_b64=True):
    if not payload:
        return None

    binary = b64decoder(payload) if decode_b64 else payload
    if content_type and 'tlv' in content_type.lower():
        return binary_tlv_to_python(bytearray(binary))
    return binary

Response: If the payload is tlv decode it otherwise passthrough


Instruction:
Write a Python 3 function that can
set the after of this ServicePackageQuotaHistoryResponse.

Response:
def after(self, after):
        """
        Sets the after of this ServicePackageQuotaHistoryResponse.
        After which quota history ID this paged response is fetched.

        :param after: The after of this ServicePackageQuotaHistoryResponse.
        :type: str
        """
        if after is not None and len(after) > 32:
            raise ValueError("Invalid value for `after`, length must be less than or equal to `32`")
        if after is not None and len(after) < 32:
            raise ValueError("Invalid value for `after`, length must be greater than or equal to `32`")

        self._after = after


Instruction:
How would you code a function in Python 3 to
set the object of this ServicePackageQuotaHistoryResponse.

Response:
def object(self, object):
        """
        Sets the object of this ServicePackageQuotaHistoryResponse.
        Always set to 'service-package-quota-history'.

        :param object: The object of this ServicePackageQuotaHistoryResponse.
        :type: str
        """
        if object is None:
            raise ValueError("Invalid value for `object`, must not be `None`")
        allowed_values = ["service-package-quota-history"]
        if object not in allowed_values:
            raise ValueError(
                "Invalid value for `object` ({0}), must be one of {1}"
                .format(object, allowed_values)
            )

        self._object = object


Instruction:
Explain what the following Python 3 code does
def total_count(self, total_count):
        if total_count is None:
            raise ValueError("Invalid value for `total_count`, must not be `None`")
        if total_count is not None and total_count < 0:
            raise ValueError("Invalid value for `total_count`, must be a value greater than or equal to `0`")

        self._total_count = total_count

Response: Sets the total_count of this ServicePackageQuotaHistoryResponse.


Instruction:
Can you write a function in Python 3 where it
sets the issuer_type of this CertificateIssuerInfo.

Response:
def issuer_type(self, issuer_type):
        """
        Sets the issuer_type of this CertificateIssuerInfo.
        The type of the certificate issuer. - GLOBAL_SIGN:   Certificates are issued by GlobalSign service. The users must provide their own GlobalSign account credentials. - CFSSL_AUTH:   Certificates are issued by CFSSL authenticated signing service.   The users must provide their own CFSSL host_url and credentials.

        :param issuer_type: The issuer_type of this CertificateIssuerInfo.
        :type: str
        """
        if issuer_type is None:
            raise ValueError("Invalid value for `issuer_type`, must not be `None`")
        allowed_values = ["GLOBAL_SIGN", "CFSSL_AUTH"]
        if issuer_type not in allowed_values:
            raise ValueError(
                "Invalid value for `issuer_type` ({0}), must be one of {1}"
                .format(issuer_type, allowed_values)
            )

        self._issuer_type = issuer_type


Instruction:
Can you generate a brief explanation for the following Python 3 code
def code(self, code):
        allowed_values = [400, 401, 404]
        if code not in allowed_values:
            raise ValueError(
                "Invalid value for `code` ({0}), must be one of {1}"
                .format(code, allowed_values)
            )

        self._code = code

Response: Sets the code of this ErrorResponse.


Instruction:
Create a Python 3 function for
setting the request_id of this ErrorResponse.

Response:
def request_id(self, request_id):
        """
        Sets the request_id of this ErrorResponse.
        Request ID.

        :param request_id: The request_id of this ErrorResponse.
        :type: str
        """
        if request_id is not None and not re.search('^[A-Za-z0-9]{32}', request_id):
            raise ValueError("Invalid value for `request_id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`")

        self._request_id = request_id


Instruction:
Write a Python 3 script for
starting the notifications thread.

Response:
def start_notifications(self):
        """Start the notifications thread.

        If an external callback is not set up (using `update_webhook`) then
        calling this function is mandatory to get or set resource.

        .. code-block:: python

            >>> api.start_notifications()
            >>> print(api.get_resource_value(device, path))
            Some value
            >>> api.stop_notifications()

        :returns: void
        """
        with self._notifications_lock:
            if self.has_active_notification_thread:
                return
            api = self._get_api(mds.NotificationsApi)
            self._notifications_thread = NotificationsThread(
                self._db,
                self._queues,
                b64decode=self.b64decode,
                notifications_api=api,
                subscription_manager=self.subscribe,
            )
            self._notifications_thread.daemon = True
            self._notifications_thread.start()


Instruction:
Create a Python 3 function to
stop the notifications thread.

Response:
def stop_notifications(self):
        """Stop the notifications thread.

        :returns:
        """
        with self._notifications_lock:
            if not self.has_active_notification_thread:
                return
            thread = self._notifications_thread
            self._notifications_thread = None
            stopping = thread.stop()
            api = self._get_api(mds.NotificationsApi)
            api.delete_long_poll_channel()
            return stopping.wait()