id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
12,900
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.delete_subscriptions
def delete_subscriptions(self): """Remove all subscriptions. Warning: This could be slow for large numbers of connected devices. If possible, explicitly delete subscriptions known to have been created. :returns: None """ warnings.warn('This could be slow for large numbers of connected devices.' 'If possible, explicitly delete subscriptions known to have been created.') for device in self.list_connected_devices(): try: self.delete_device_subscriptions(device_id=device.id) except CloudApiException as e: LOG.warning('failed to remove subscription for %s: %s', device.id, e) continue
python
def delete_subscriptions(self): warnings.warn('This could be slow for large numbers of connected devices.' 'If possible, explicitly delete subscriptions known to have been created.') for device in self.list_connected_devices(): try: self.delete_device_subscriptions(device_id=device.id) except CloudApiException as e: LOG.warning('failed to remove subscription for %s: %s', device.id, e) continue
[ "def", "delete_subscriptions", "(", "self", ")", ":", "warnings", ".", "warn", "(", "'This could be slow for large numbers of connected devices.'", "'If possible, explicitly delete subscriptions known to have been created.'", ")", "for", "device", "in", "self", ".", "list_connect...
Remove all subscriptions. Warning: This could be slow for large numbers of connected devices. If possible, explicitly delete subscriptions known to have been created. :returns: None
[ "Remove", "all", "subscriptions", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L547-L562
12,901
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.list_presubscriptions
def list_presubscriptions(self, **kwargs): """Get a list of pre-subscription data :returns: a list of `Presubscription` objects :rtype: list of mbed_cloud.presubscription.Presubscription """ api = self._get_api(mds.SubscriptionsApi) resp = api.get_pre_subscriptions(**kwargs) return [Presubscription(p) for p in resp]
python
def list_presubscriptions(self, **kwargs): api = self._get_api(mds.SubscriptionsApi) resp = api.get_pre_subscriptions(**kwargs) return [Presubscription(p) for p in resp]
[ "def", "list_presubscriptions", "(", "self", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "SubscriptionsApi", ")", "resp", "=", "api", ".", "get_pre_subscriptions", "(", "*", "*", "kwargs", ")", "return", "[", ...
Get a list of pre-subscription data :returns: a list of `Presubscription` objects :rtype: list of mbed_cloud.presubscription.Presubscription
[ "Get", "a", "list", "of", "pre", "-", "subscription", "data" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L565-L573
12,902
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.list_device_subscriptions
def list_device_subscriptions(self, device_id, **kwargs): """Lists all subscribed resources from a single device :param device_id: ID of the device (Required) :returns: a list of subscribed resources :rtype: list of str """ api = self._get_api(mds.SubscriptionsApi) resp = api.get_endpoint_subscriptions(device_id, **kwargs) return resp.split("\n")
python
def list_device_subscriptions(self, device_id, **kwargs): api = self._get_api(mds.SubscriptionsApi) resp = api.get_endpoint_subscriptions(device_id, **kwargs) return resp.split("\n")
[ "def", "list_device_subscriptions", "(", "self", ",", "device_id", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "SubscriptionsApi", ")", "resp", "=", "api", ".", "get_endpoint_subscriptions", "(", "device_id", ",",...
Lists all subscribed resources from a single device :param device_id: ID of the device (Required) :returns: a list of subscribed resources :rtype: list of str
[ "Lists", "all", "subscribed", "resources", "from", "a", "single", "device" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L576-L585
12,903
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.delete_device_subscriptions
def delete_device_subscriptions(self, device_id): """Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None """ api = self._get_api(mds.SubscriptionsApi) return api.delete_endpoint_subscriptions(device_id)
python
def delete_device_subscriptions(self, device_id): api = self._get_api(mds.SubscriptionsApi) return api.delete_endpoint_subscriptions(device_id)
[ "def", "delete_device_subscriptions", "(", "self", ",", "device_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "SubscriptionsApi", ")", "return", "api", ".", "delete_endpoint_subscriptions", "(", "device_id", ")" ]
Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None
[ "Removes", "a", "device", "s", "subscriptions" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L588-L595
12,904
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.notify_webhook_received
def notify_webhook_received(self, payload): """Callback function for triggering notification channel handlers. Use this in conjunction with a webserver to complete the loop when using webhooks as the notification channel. :param str payload: the encoded payload, as sent by the notification channel """ class PayloadContainer: # noqa # bodge to give attribute lookup data = payload notification = self._get_api(mds.NotificationsApi).api_client.deserialize( PayloadContainer, mds.NotificationMessage.__name__ ) handle_channel_message( db=self._db, queues=self._queues, b64decode=self.b64decode, notification_object=notification )
python
def notify_webhook_received(self, payload): class PayloadContainer: # noqa # bodge to give attribute lookup data = payload notification = self._get_api(mds.NotificationsApi).api_client.deserialize( PayloadContainer, mds.NotificationMessage.__name__ ) handle_channel_message( db=self._db, queues=self._queues, b64decode=self.b64decode, notification_object=notification )
[ "def", "notify_webhook_received", "(", "self", ",", "payload", ")", ":", "class", "PayloadContainer", ":", "# noqa", "# bodge to give attribute lookup", "data", "=", "payload", "notification", "=", "self", ".", "_get_api", "(", "mds", ".", "NotificationsApi", ")", ...
Callback function for triggering notification channel handlers. Use this in conjunction with a webserver to complete the loop when using webhooks as the notification channel. :param str payload: the encoded payload, as sent by the notification channel
[ "Callback", "function", "for", "triggering", "notification", "channel", "handlers", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L642-L662
12,905
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.get_webhook
def get_webhook(self): """Get the current callback URL if it exists. :return: The currently set webhook """ api = self._get_api(mds.NotificationsApi) return Webhook(api.get_webhook())
python
def get_webhook(self): api = self._get_api(mds.NotificationsApi) return Webhook(api.get_webhook())
[ "def", "get_webhook", "(", "self", ")", ":", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "NotificationsApi", ")", "return", "Webhook", "(", "api", ".", "get_webhook", "(", ")", ")" ]
Get the current callback URL if it exists. :return: The currently set webhook
[ "Get", "the", "current", "callback", "URL", "if", "it", "exists", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L665-L671
12,906
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.update_webhook
def update_webhook(self, url, headers=None): """Register new webhook for incoming subscriptions. If a webhook is already set, this will do an overwrite. :param str url: the URL with listening webhook (Required) :param dict headers: K/V dict with additional headers to send with request :return: void """ headers = headers or {} api = self._get_api(mds.NotificationsApi) # Delete notifications channel api.delete_long_poll_channel() # Send the request to register the webhook webhook_obj = WebhookData(url=url, headers=headers) api.register_webhook(webhook_obj) return
python
def update_webhook(self, url, headers=None): headers = headers or {} api = self._get_api(mds.NotificationsApi) # Delete notifications channel api.delete_long_poll_channel() # Send the request to register the webhook webhook_obj = WebhookData(url=url, headers=headers) api.register_webhook(webhook_obj) return
[ "def", "update_webhook", "(", "self", ",", "url", ",", "headers", "=", "None", ")", ":", "headers", "=", "headers", "or", "{", "}", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "NotificationsApi", ")", "# Delete notifications channel", "api", ".",...
Register new webhook for incoming subscriptions. If a webhook is already set, this will do an overwrite. :param str url: the URL with listening webhook (Required) :param dict headers: K/V dict with additional headers to send with request :return: void
[ "Register", "new", "webhook", "for", "incoming", "subscriptions", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L674-L692
12,907
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
ConnectAPI.list_metrics
def list_metrics(self, include=None, interval="1d", **kwargs): """Get statistics. :param list[str] include: List of fields included in response. None, or an empty list will return all fields. Fields: transactions, successful_api_calls, failed_api_calls, successful_handshakes, pending_bootstraps, successful_bootstraps, failed_bootstraps, registrations, updated_registrations, expired_registrations, deleted_registrations :param str interval: Group data by this interval in days, weeks or hours. Sample values: 2h, 3w, 4d. :param datetime start: Fetch the data with timestamp greater than or equal to this value. The parameter is not mandatory, if the period is specified. :param datetime end: Fetch the data with timestamp less than this value. The parameter is not mandatory, if the period is specified. :param str period: Period. Fetch the data for the period in days, weeks or hours. Sample values: 2h, 3w, 4d. The parameter is not mandatory, if the start and end time are specified :param int limit: The number of devices to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get metrics after/starting at given metric ID :returns: a list of :py:class:`Metric` objects :rtype: PaginatedResponse """ self._verify_arguments(interval, kwargs) include = Metric._map_includes(include) kwargs.update(dict(include=include, interval=interval)) api = self._get_api(statistics.StatisticsApi) return PaginatedResponse(api.get_metrics, lwrap_type=Metric, **kwargs)
python
def list_metrics(self, include=None, interval="1d", **kwargs): self._verify_arguments(interval, kwargs) include = Metric._map_includes(include) kwargs.update(dict(include=include, interval=interval)) api = self._get_api(statistics.StatisticsApi) return PaginatedResponse(api.get_metrics, lwrap_type=Metric, **kwargs)
[ "def", "list_metrics", "(", "self", ",", "include", "=", "None", ",", "interval", "=", "\"1d\"", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_verify_arguments", "(", "interval", ",", "kwargs", ")", "include", "=", "Metric", ".", "_map_includes", "("...
Get statistics. :param list[str] include: List of fields included in response. None, or an empty list will return all fields. Fields: transactions, successful_api_calls, failed_api_calls, successful_handshakes, pending_bootstraps, successful_bootstraps, failed_bootstraps, registrations, updated_registrations, expired_registrations, deleted_registrations :param str interval: Group data by this interval in days, weeks or hours. Sample values: 2h, 3w, 4d. :param datetime start: Fetch the data with timestamp greater than or equal to this value. The parameter is not mandatory, if the period is specified. :param datetime end: Fetch the data with timestamp less than this value. The parameter is not mandatory, if the period is specified. :param str period: Period. Fetch the data for the period in days, weeks or hours. Sample values: 2h, 3w, 4d. The parameter is not mandatory, if the start and end time are specified :param int limit: The number of devices to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get metrics after/starting at given metric ID :returns: a list of :py:class:`Metric` objects :rtype: PaginatedResponse
[ "Get", "statistics", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L713-L740
12,908
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/enrollment/models/enrollment_id.py
EnrollmentId.enrollment_identity
def enrollment_identity(self, enrollment_identity): """ Sets the enrollment_identity of this EnrollmentId. Enrollment identity. :param enrollment_identity: The enrollment_identity of this EnrollmentId. :type: str """ if enrollment_identity is None: raise ValueError("Invalid value for `enrollment_identity`, must not be `None`") if enrollment_identity is not None and not re.search('^A-[A-Za-z0-9:]{95}$', enrollment_identity): raise ValueError("Invalid value for `enrollment_identity`, must be a follow pattern or equal to `/^A-[A-Za-z0-9:]{95}$/`") self._enrollment_identity = enrollment_identity
python
def enrollment_identity(self, enrollment_identity): if enrollment_identity is None: raise ValueError("Invalid value for `enrollment_identity`, must not be `None`") if enrollment_identity is not None and not re.search('^A-[A-Za-z0-9:]{95}$', enrollment_identity): raise ValueError("Invalid value for `enrollment_identity`, must be a follow pattern or equal to `/^A-[A-Za-z0-9:]{95}$/`") self._enrollment_identity = enrollment_identity
[ "def", "enrollment_identity", "(", "self", ",", "enrollment_identity", ")", ":", "if", "enrollment_identity", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `enrollment_identity`, must not be `None`\"", ")", "if", "enrollment_identity", "is", "not", "...
Sets the enrollment_identity of this EnrollmentId. Enrollment identity. :param enrollment_identity: The enrollment_identity of this EnrollmentId. :type: str
[ "Sets", "the", "enrollment_identity", "of", "this", "EnrollmentId", ".", "Enrollment", "identity", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/enrollment/models/enrollment_id.py#L61-L74
12,909
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/channel.py
ChannelSubscription._filter_optional_keys
def _filter_optional_keys(self, data): """Filtering for this channel, based on key-value matching""" for filter_key, filter_value in (self._optional_filters or {}).items(): data_value = data.get(filter_key) LOG.debug( 'optional keys filter %s: %s (%s)', filter_key, filter_value, data_value ) if data_value is None or data_value != filter_value: LOG.debug( 'optional keys filter rejecting %s: %s (%s)', filter_key, filter_value, data_value ) return False return True
python
def _filter_optional_keys(self, data): for filter_key, filter_value in (self._optional_filters or {}).items(): data_value = data.get(filter_key) LOG.debug( 'optional keys filter %s: %s (%s)', filter_key, filter_value, data_value ) if data_value is None or data_value != filter_value: LOG.debug( 'optional keys filter rejecting %s: %s (%s)', filter_key, filter_value, data_value ) return False return True
[ "def", "_filter_optional_keys", "(", "self", ",", "data", ")", ":", "for", "filter_key", ",", "filter_value", "in", "(", "self", ".", "_optional_filters", "or", "{", "}", ")", ".", "items", "(", ")", ":", "data_value", "=", "data", ".", "get", "(", "fi...
Filtering for this channel, based on key-value matching
[ "Filtering", "for", "this", "channel", "based", "on", "key", "-", "value", "matching" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/channel.py#L109-L123
12,910
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/channel.py
ChannelSubscription._configure
def _configure(self, manager, connect_api_instance, observer_params): """Configure behind-the-scenes settings for the channel These are required in addition to the parameters provided on instantiation """ self._manager = manager self._api = connect_api_instance self._observer_params = self._observer_params or {} self._observer_params.update(observer_params)
python
def _configure(self, manager, connect_api_instance, observer_params): self._manager = manager self._api = connect_api_instance self._observer_params = self._observer_params or {} self._observer_params.update(observer_params)
[ "def", "_configure", "(", "self", ",", "manager", ",", "connect_api_instance", ",", "observer_params", ")", ":", "self", ".", "_manager", "=", "manager", "self", ".", "_api", "=", "connect_api_instance", "self", ".", "_observer_params", "=", "self", ".", "_obs...
Configure behind-the-scenes settings for the channel These are required in addition to the parameters provided on instantiation
[ "Configure", "behind", "-", "the", "-", "scenes", "settings", "for", "the", "channel" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/channel.py#L156-L165
12,911
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/channel.py
ChannelSubscription.ensure_started
def ensure_started(self): """Idempotent channel start""" if self.active: return self self._observer = self._observer_class(**self._observer_params) self.start() self._active = True return self
python
def ensure_started(self): if self.active: return self self._observer = self._observer_class(**self._observer_params) self.start() self._active = True return self
[ "def", "ensure_started", "(", "self", ")", ":", "if", "self", ".", "active", ":", "return", "self", "self", ".", "_observer", "=", "self", ".", "_observer_class", "(", "*", "*", "self", ".", "_observer_params", ")", "self", ".", "start", "(", ")", "sel...
Idempotent channel start
[ "Idempotent", "channel", "start" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/channel.py#L167-L174
12,912
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/channel.py
ChannelSubscription.ensure_stopped
def ensure_stopped(self): """Idempotent channel stop""" if not self.active: return self self.stop() self.observer.cancel() self._manager.remove_routes(self, self.get_routing_keys()) self._active = False return self
python
def ensure_stopped(self): if not self.active: return self self.stop() self.observer.cancel() self._manager.remove_routes(self, self.get_routing_keys()) self._active = False return self
[ "def", "ensure_stopped", "(", "self", ")", ":", "if", "not", "self", ".", "active", ":", "return", "self", "self", ".", "stop", "(", ")", "self", ".", "observer", ".", "cancel", "(", ")", "self", ".", "_manager", ".", "remove_routes", "(", "self", ",...
Idempotent channel stop
[ "Idempotent", "channel", "stop" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/channel.py#L176-L184
12,913
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/billing/billing.py
BillingAPI.get_quota_remaining
def get_quota_remaining(self): """Get the remaining value""" api = self._get_api(billing.DefaultApi) quota = api.get_service_package_quota() return None if quota is None else int(quota.quota)
python
def get_quota_remaining(self): api = self._get_api(billing.DefaultApi) quota = api.get_service_package_quota() return None if quota is None else int(quota.quota)
[ "def", "get_quota_remaining", "(", "self", ")", ":", "api", "=", "self", ".", "_get_api", "(", "billing", ".", "DefaultApi", ")", "quota", "=", "api", ".", "get_service_package_quota", "(", ")", "return", "None", "if", "quota", "is", "None", "else", "int",...
Get the remaining value
[ "Get", "the", "remaining", "value" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/billing/billing.py#L50-L54
12,914
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/billing/billing.py
BillingAPI.get_quota_history
def get_quota_history(self, **kwargs): """Get quota usage history""" kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, ServicePackage) api = self._get_api(billing.DefaultApi) return PaginatedResponse( api.get_service_package_quota_history, lwrap_type=QuotaHistory, **kwargs )
python
def get_quota_history(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, ServicePackage) api = self._get_api(billing.DefaultApi) return PaginatedResponse( api.get_service_package_quota_history, lwrap_type=QuotaHistory, **kwargs )
[ "def", "get_quota_history", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "ServicePackage", ")", "api", "=", "self"...
Get quota usage history
[ "Get", "quota", "usage", "history" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/billing/billing.py#L57-L66
12,915
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/billing/billing.py
BillingAPI.get_service_packages
def get_service_packages(self): """Get all service packages""" api = self._get_api(billing.DefaultApi) package_response = api.get_service_packages() packages = [] for state in PACKAGE_STATES: # iterate states in order items = getattr(package_response, state) or [] for item in ensure_listable(items): params = item.to_dict() params['state'] = state packages.append(ServicePackage(params)) return packages
python
def get_service_packages(self): api = self._get_api(billing.DefaultApi) package_response = api.get_service_packages() packages = [] for state in PACKAGE_STATES: # iterate states in order items = getattr(package_response, state) or [] for item in ensure_listable(items): params = item.to_dict() params['state'] = state packages.append(ServicePackage(params)) return packages
[ "def", "get_service_packages", "(", "self", ")", ":", "api", "=", "self", ".", "_get_api", "(", "billing", ".", "DefaultApi", ")", "package_response", "=", "api", ".", "get_service_packages", "(", ")", "packages", "=", "[", "]", "for", "state", "in", "PACK...
Get all service packages
[ "Get", "all", "service", "packages" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/billing/billing.py#L69-L81
12,916
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/billing/billing.py
BillingAPI._month_converter
def _month_converter(self, date_time): """Returns Billing API format YYYY-DD""" if not date_time: date_time = datetime.datetime.utcnow() if isinstance(date_time, datetime.datetime): date_time = '%s-%02d' % (date_time.year, date_time.month) return date_time
python
def _month_converter(self, date_time): if not date_time: date_time = datetime.datetime.utcnow() if isinstance(date_time, datetime.datetime): date_time = '%s-%02d' % (date_time.year, date_time.month) return date_time
[ "def", "_month_converter", "(", "self", ",", "date_time", ")", ":", "if", "not", "date_time", ":", "date_time", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "if", "isinstance", "(", "date_time", ",", "datetime", ".", "datetime", ")", ":", "...
Returns Billing API format YYYY-DD
[ "Returns", "Billing", "API", "format", "YYYY", "-", "DD" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/billing/billing.py#L83-L89
12,917
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/billing/billing.py
BillingAPI._filepath_converter
def _filepath_converter(self, user_path, file_name): """Logic for obtaining a file path :param user_path: a path as provided by the user. perhaps a file or directory? :param file_name: the name of the remote file :return: """ path = user_path or os.path.join(os.getcwd(), 'billing_reports', os.path.sep) dir_specified = path.endswith(os.sep) if dir_specified: path = os.path.join(path, file_name) path = os.path.abspath(path) directory = os.path.dirname(path) if not os.path.isdir(directory): os.makedirs(directory) if os.path.exists(path): raise IOError('SDK will not write into an existing path: %r' % path) return path
python
def _filepath_converter(self, user_path, file_name): path = user_path or os.path.join(os.getcwd(), 'billing_reports', os.path.sep) dir_specified = path.endswith(os.sep) if dir_specified: path = os.path.join(path, file_name) path = os.path.abspath(path) directory = os.path.dirname(path) if not os.path.isdir(directory): os.makedirs(directory) if os.path.exists(path): raise IOError('SDK will not write into an existing path: %r' % path) return path
[ "def", "_filepath_converter", "(", "self", ",", "user_path", ",", "file_name", ")", ":", "path", "=", "user_path", "or", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'billing_reports'", ",", "os", ".", "path", ".", "sep", ...
Logic for obtaining a file path :param user_path: a path as provided by the user. perhaps a file or directory? :param file_name: the name of the remote file :return:
[ "Logic", "for", "obtaining", "a", "file", "path" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/billing/billing.py#L91-L111
12,918
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/billing/billing.py
BillingAPI.get_report_overview
def get_report_overview(self, month, file_path): """Downloads a report overview :param month: month as datetime instance, or string in YYYY-MM format :type month: str or datetime :param str file_path: location to store output file :return: outcome :rtype: True or None """ api = self._get_api(billing.DefaultApi) month = self._month_converter(month) response = api.get_billing_report(month=month) if file_path and response: content = api.api_client.sanitize_for_serialization(response.to_dict()) with open(file_path, 'w') as fh: fh.write( json.dumps( content, sort_keys=True, indent=2, ) ) return response
python
def get_report_overview(self, month, file_path): api = self._get_api(billing.DefaultApi) month = self._month_converter(month) response = api.get_billing_report(month=month) if file_path and response: content = api.api_client.sanitize_for_serialization(response.to_dict()) with open(file_path, 'w') as fh: fh.write( json.dumps( content, sort_keys=True, indent=2, ) ) return response
[ "def", "get_report_overview", "(", "self", ",", "month", ",", "file_path", ")", ":", "api", "=", "self", ".", "_get_api", "(", "billing", ".", "DefaultApi", ")", "month", "=", "self", ".", "_month_converter", "(", "month", ")", "response", "=", "api", "....
Downloads a report overview :param month: month as datetime instance, or string in YYYY-MM format :type month: str or datetime :param str file_path: location to store output file :return: outcome :rtype: True or None
[ "Downloads", "a", "report", "overview" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/billing/billing.py#L114-L136
12,919
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/billing/billing.py
BillingAPI.get_report_firmware_updates
def get_report_firmware_updates(self, month=None, file_path=None): """Downloads a report of the firmware updates :param str file_path: [optional] location to store output file :param month: [default: utcnow] month as datetime instance, or string in YYYY-MM format :type month: str or datetime :return: The report structure :rtype: dict """ api = self._get_api(billing.DefaultApi) month = self._month_converter(month) response = api.get_billing_report_firmware_updates(month=month) download_url = response.url file_path = self._filepath_converter(file_path, response.filename) if file_path: urllib.request.urlretrieve(download_url, file_path) return response
python
def get_report_firmware_updates(self, month=None, file_path=None): api = self._get_api(billing.DefaultApi) month = self._month_converter(month) response = api.get_billing_report_firmware_updates(month=month) download_url = response.url file_path = self._filepath_converter(file_path, response.filename) if file_path: urllib.request.urlretrieve(download_url, file_path) return response
[ "def", "get_report_firmware_updates", "(", "self", ",", "month", "=", "None", ",", "file_path", "=", "None", ")", ":", "api", "=", "self", ".", "_get_api", "(", "billing", ".", "DefaultApi", ")", "month", "=", "self", ".", "_month_converter", "(", "month",...
Downloads a report of the firmware updates :param str file_path: [optional] location to store output file :param month: [default: utcnow] month as datetime instance, or string in YYYY-MM format :type month: str or datetime :return: The report structure :rtype: dict
[ "Downloads", "a", "report", "of", "the", "firmware", "updates" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/billing/billing.py#L159-L176
12,920
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/models/device_event_data.py
DeviceEventData.event_type
def event_type(self, event_type): """ Sets the event_type of this DeviceEventData. Event code :param event_type: The event_type of this DeviceEventData. :type: str """ if event_type is not None and len(event_type) > 100: raise ValueError("Invalid value for `event_type`, length must be less than or equal to `100`") self._event_type = event_type
python
def event_type(self, event_type): if event_type is not None and len(event_type) > 100: raise ValueError("Invalid value for `event_type`, length must be less than or equal to `100`") self._event_type = event_type
[ "def", "event_type", "(", "self", ",", "event_type", ")", ":", "if", "event_type", "is", "not", "None", "and", "len", "(", "event_type", ")", ">", "100", ":", "raise", "ValueError", "(", "\"Invalid value for `event_type`, length must be less than or equal to `100`\"",...
Sets the event_type of this DeviceEventData. Event code :param event_type: The event_type of this DeviceEventData. :type: str
[ "Sets", "the", "event_type", "of", "this", "DeviceEventData", ".", "Event", "code" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/models/device_event_data.py#L248-L259
12,921
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/resource_values.py
ResourceValues._pattern_match
def _pattern_match(self, item, pattern): """Determine whether the item supplied is matched by the pattern.""" if pattern.endswith('*'): return item.startswith(pattern[:-1]) else: return item == pattern
python
def _pattern_match(self, item, pattern): if pattern.endswith('*'): return item.startswith(pattern[:-1]) else: return item == pattern
[ "def", "_pattern_match", "(", "self", ",", "item", ",", "pattern", ")", ":", "if", "pattern", ".", "endswith", "(", "'*'", ")", ":", "return", "item", ".", "startswith", "(", "pattern", "[", ":", "-", "1", "]", ")", "else", ":", "return", "item", "...
Determine whether the item supplied is matched by the pattern.
[ "Determine", "whether", "the", "item", "supplied", "is", "matched", "by", "the", "pattern", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/resource_values.py#L140-L145
12,922
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/resource_values.py
ResourceValues.stop
def stop(self): """Stop the channel""" self._presubs.remove(self._sdk_presub_params) if self._immediacy == FirstValue.on_value_update: self._unsubscribe_all_matching() super(ResourceValues, self).stop()
python
def stop(self): self._presubs.remove(self._sdk_presub_params) if self._immediacy == FirstValue.on_value_update: self._unsubscribe_all_matching() super(ResourceValues, self).stop()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_presubs", ".", "remove", "(", "self", ".", "_sdk_presub_params", ")", "if", "self", ".", "_immediacy", "==", "FirstValue", ".", "on_value_update", ":", "self", ".", "_unsubscribe_all_matching", "(", ")", ...
Stop the channel
[ "Stop", "the", "channel" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/resource_values.py#L219-L224
12,923
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/resource_values.py
PreSubscriptionRegistry.load_from_cloud
def load_from_cloud(self): """Sync - read""" self.current = [ {k: v for k, v in p.to_dict().items() if v is not None} for p in self.api.list_presubscriptions() ]
python
def load_from_cloud(self): self.current = [ {k: v for k, v in p.to_dict().items() if v is not None} for p in self.api.list_presubscriptions() ]
[ "def", "load_from_cloud", "(", "self", ")", ":", "self", ".", "current", "=", "[", "{", "k", ":", "v", "for", "k", ",", "v", "in", "p", ".", "to_dict", "(", ")", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "for", "p", "in", ...
Sync - read
[ "Sync", "-", "read" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/resource_values.py#L235-L240
12,924
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/resource_values.py
PreSubscriptionRegistry.add
def add(self, items): """Add entry to global presubs list""" with _presub_lock: self.load_from_cloud() for entry in utils.ensure_listable(items): # add new entries, but only if they're unique if entry not in self.current: self.current.append(entry) self.save_to_cloud()
python
def add(self, items): with _presub_lock: self.load_from_cloud() for entry in utils.ensure_listable(items): # add new entries, but only if they're unique if entry not in self.current: self.current.append(entry) self.save_to_cloud()
[ "def", "add", "(", "self", ",", "items", ")", ":", "with", "_presub_lock", ":", "self", ".", "load_from_cloud", "(", ")", "for", "entry", "in", "utils", ".", "ensure_listable", "(", "items", ")", ":", "# add new entries, but only if they're unique", "if", "ent...
Add entry to global presubs list
[ "Add", "entry", "to", "global", "presubs", "list" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/resource_values.py#L246-L254
12,925
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/channels/resource_values.py
PreSubscriptionRegistry.remove
def remove(self, items): """Remove entry from global presubs list""" with _presub_lock: self.load_from_cloud() for entry in utils.ensure_listable(items): # remove all matching entries while entry in self.current: self.current.remove(entry) self.save_to_cloud()
python
def remove(self, items): with _presub_lock: self.load_from_cloud() for entry in utils.ensure_listable(items): # remove all matching entries while entry in self.current: self.current.remove(entry) self.save_to_cloud()
[ "def", "remove", "(", "self", ",", "items", ")", ":", "with", "_presub_lock", ":", "self", ".", "load_from_cloud", "(", ")", "for", "entry", "in", "utils", ".", "ensure_listable", "(", "items", ")", ":", "# remove all matching entries", "while", "entry", "in...
Remove entry from global presubs list
[ "Remove", "entry", "from", "global", "presubs", "list" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/channels/resource_values.py#L256-L264
12,926
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/utils.py
force_utc
def force_utc(time, name='field', precision=6): """Appending 'Z' to isoformatted time - explicit timezone is required for most APIs""" if not isinstance(time, datetime.datetime): raise CloudValueError("%s should be of type datetime" % (name,)) clip = 6 - precision timestring = time.isoformat() if clip: timestring = timestring[:-clip] return timestring + "Z"
python
def force_utc(time, name='field', precision=6): if not isinstance(time, datetime.datetime): raise CloudValueError("%s should be of type datetime" % (name,)) clip = 6 - precision timestring = time.isoformat() if clip: timestring = timestring[:-clip] return timestring + "Z"
[ "def", "force_utc", "(", "time", ",", "name", "=", "'field'", ",", "precision", "=", "6", ")", ":", "if", "not", "isinstance", "(", "time", ",", "datetime", ".", "datetime", ")", ":", "raise", "CloudValueError", "(", "\"%s should be of type datetime\"", "%",...
Appending 'Z' to isoformatted time - explicit timezone is required for most APIs
[ "Appending", "Z", "to", "isoformatted", "time", "-", "explicit", "timezone", "is", "required", "for", "most", "APIs" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/utils.py#L39-L47
12,927
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/decorators.py
catch_exceptions
def catch_exceptions(*exceptions): """Catch all exceptions provided as arguments, and raise CloudApiException instead.""" def wrap(fn): @functools.wraps(fn) def wrapped_f(*args, **kwargs): try: return fn(*args, **kwargs) except exceptions: t, value, traceback = sys.exc_info() # If any resource does not exist, return None instead of raising if str(value.status) == '404': return None e = CloudApiException(str(value), value.reason, value.status) raise_(CloudApiException, e, traceback) return wrapped_f return wrap
python
def catch_exceptions(*exceptions): def wrap(fn): @functools.wraps(fn) def wrapped_f(*args, **kwargs): try: return fn(*args, **kwargs) except exceptions: t, value, traceback = sys.exc_info() # If any resource does not exist, return None instead of raising if str(value.status) == '404': return None e = CloudApiException(str(value), value.reason, value.status) raise_(CloudApiException, e, traceback) return wrapped_f return wrap
[ "def", "catch_exceptions", "(", "*", "exceptions", ")", ":", "def", "wrap", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapped_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "fn", ...
Catch all exceptions provided as arguments, and raise CloudApiException instead.
[ "Catch", "all", "exceptions", "provided", "as", "arguments", "and", "raise", "CloudApiException", "instead", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/decorators.py#L27-L42
12,928
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py
DeviceDataPostRequest.endpoint_name
def endpoint_name(self, endpoint_name): """ Sets the endpoint_name of this DeviceDataPostRequest. The endpoint name given to the device. :param endpoint_name: The endpoint_name of this DeviceDataPostRequest. :type: str """ if endpoint_name is not None and len(endpoint_name) > 64: raise ValueError("Invalid value for `endpoint_name`, length must be less than or equal to `64`") self._endpoint_name = endpoint_name
python
def endpoint_name(self, endpoint_name): if endpoint_name is not None and len(endpoint_name) > 64: raise ValueError("Invalid value for `endpoint_name`, length must be less than or equal to `64`") self._endpoint_name = endpoint_name
[ "def", "endpoint_name", "(", "self", ",", "endpoint_name", ")", ":", "if", "endpoint_name", "is", "not", "None", "and", "len", "(", "endpoint_name", ")", ">", "64", ":", "raise", "ValueError", "(", "\"Invalid value for `endpoint_name`, length must be less than or equa...
Sets the endpoint_name of this DeviceDataPostRequest. The endpoint name given to the device. :param endpoint_name: The endpoint_name of this DeviceDataPostRequest. :type: str
[ "Sets", "the", "endpoint_name", "of", "this", "DeviceDataPostRequest", ".", "The", "endpoint", "name", "given", "to", "the", "device", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py#L391-L402
12,929
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py
DeviceDataPostRequest.firmware_checksum
def firmware_checksum(self, firmware_checksum): """ Sets the firmware_checksum of this DeviceDataPostRequest. The SHA256 checksum of the current firmware image. :param firmware_checksum: The firmware_checksum of this DeviceDataPostRequest. :type: str """ if firmware_checksum is not None and len(firmware_checksum) > 64: raise ValueError("Invalid value for `firmware_checksum`, length must be less than or equal to `64`") self._firmware_checksum = firmware_checksum
python
def firmware_checksum(self, firmware_checksum): if firmware_checksum is not None and len(firmware_checksum) > 64: raise ValueError("Invalid value for `firmware_checksum`, length must be less than or equal to `64`") self._firmware_checksum = firmware_checksum
[ "def", "firmware_checksum", "(", "self", ",", "firmware_checksum", ")", ":", "if", "firmware_checksum", "is", "not", "None", "and", "len", "(", "firmware_checksum", ")", ">", "64", ":", "raise", "ValueError", "(", "\"Invalid value for `firmware_checksum`, length must ...
Sets the firmware_checksum of this DeviceDataPostRequest. The SHA256 checksum of the current firmware image. :param firmware_checksum: The firmware_checksum of this DeviceDataPostRequest. :type: str
[ "Sets", "the", "firmware_checksum", "of", "this", "DeviceDataPostRequest", ".", "The", "SHA256", "checksum", "of", "the", "current", "firmware", "image", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py#L441-L452
12,930
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py
DeviceDataPostRequest.serial_number
def serial_number(self, serial_number): """ Sets the serial_number of this DeviceDataPostRequest. The serial number of the device. :param serial_number: The serial_number of this DeviceDataPostRequest. :type: str """ if serial_number is not None and len(serial_number) > 64: raise ValueError("Invalid value for `serial_number`, length must be less than or equal to `64`") self._serial_number = serial_number
python
def serial_number(self, serial_number): if serial_number is not None and len(serial_number) > 64: raise ValueError("Invalid value for `serial_number`, length must be less than or equal to `64`") self._serial_number = serial_number
[ "def", "serial_number", "(", "self", ",", "serial_number", ")", ":", "if", "serial_number", "is", "not", "None", "and", "len", "(", "serial_number", ")", ">", "64", ":", "raise", "ValueError", "(", "\"Invalid value for `serial_number`, length must be less than or equa...
Sets the serial_number of this DeviceDataPostRequest. The serial number of the device. :param serial_number: The serial_number of this DeviceDataPostRequest. :type: str
[ "Sets", "the", "serial_number", "of", "this", "DeviceDataPostRequest", ".", "The", "serial", "number", "of", "the", "device", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py#L635-L646
12,931
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py
DeviceDataPostRequest.vendor_id
def vendor_id(self, vendor_id): """ Sets the vendor_id of this DeviceDataPostRequest. The device vendor ID. :param vendor_id: The vendor_id of this DeviceDataPostRequest. :type: str """ if vendor_id is not None and len(vendor_id) > 255: raise ValueError("Invalid value for `vendor_id`, length must be less than or equal to `255`") self._vendor_id = vendor_id
python
def vendor_id(self, vendor_id): if vendor_id is not None and len(vendor_id) > 255: raise ValueError("Invalid value for `vendor_id`, length must be less than or equal to `255`") self._vendor_id = vendor_id
[ "def", "vendor_id", "(", "self", ",", "vendor_id", ")", ":", "if", "vendor_id", "is", "not", "None", "and", "len", "(", "vendor_id", ")", ">", "255", ":", "raise", "ValueError", "(", "\"Invalid value for `vendor_id`, length must be less than or equal to `255`\"", ")...
Sets the vendor_id of this DeviceDataPostRequest. The device vendor ID. :param vendor_id: The vendor_id of this DeviceDataPostRequest. :type: str
[ "Sets", "the", "vendor_id", "of", "this", "DeviceDataPostRequest", ".", "The", "device", "vendor", "ID", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/models/device_data_post_request.py#L689-L700
12,932
ARMmbed/mbed-cloud-sdk-python
scripts/ci_summary.py
main
def main(): """Collects results from CI run""" source_files = ( ('integration', r'results/results.xml'), ('unittests', r'results/unittests.xml'), ('coverage', r'results/coverage.xml') ) parsed = {k: ElementTree.parse(v).getroot().attrib for k, v in source_files} with open(r'results/summary.json', 'w') as fh: json.dump(parsed, fh)
python
def main(): source_files = ( ('integration', r'results/results.xml'), ('unittests', r'results/unittests.xml'), ('coverage', r'results/coverage.xml') ) parsed = {k: ElementTree.parse(v).getroot().attrib for k, v in source_files} with open(r'results/summary.json', 'w') as fh: json.dump(parsed, fh)
[ "def", "main", "(", ")", ":", "source_files", "=", "(", "(", "'integration'", ",", "r'results/results.xml'", ")", ",", "(", "'unittests'", ",", "r'results/unittests.xml'", ")", ",", "(", "'coverage'", ",", "r'results/coverage.xml'", ")", ")", "parsed", "=", "{...
Collects results from CI run
[ "Collects", "results", "from", "CI", "run" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/ci_summary.py#L24-L35
12,933
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.list_devices
def list_devices(self, **kwargs): """List devices in the device catalog. Example usage, listing all registered devices in the catalog: .. code-block:: python filters = { 'state': {'$eq': 'registered' } } devices = api.list_devices(order='asc', filters=filters) for idx, d in enumerate(devices): print(idx, d.id) :param int limit: The number of devices to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get devices after/starting at given `device_id` :param filters: Dictionary of filters to apply. :returns: a list of :py:class:`Device` objects registered in the catalog. :rtype: PaginatedResponse """ kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Device, True) api = self._get_api(device_directory.DefaultApi) return PaginatedResponse(api.device_list, lwrap_type=Device, **kwargs)
python
def list_devices(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Device, True) api = self._get_api(device_directory.DefaultApi) return PaginatedResponse(api.device_list, lwrap_type=Device, **kwargs)
[ "def", "list_devices", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "Device", ",", "True", ")", "api", "=", "s...
List devices in the device catalog. Example usage, listing all registered devices in the catalog: .. code-block:: python filters = { 'state': {'$eq': 'registered' } } devices = api.list_devices(order='asc', filters=filters) for idx, d in enumerate(devices): print(idx, d.id) :param int limit: The number of devices to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get devices after/starting at given `device_id` :param filters: Dictionary of filters to apply. :returns: a list of :py:class:`Device` objects registered in the catalog. :rtype: PaginatedResponse
[ "List", "devices", "in", "the", "device", "catalog", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L54-L77
12,934
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.get_device
def get_device(self, device_id): """Get device details from catalog. :param str device_id: the ID of the device to retrieve (Required) :returns: device object matching the `device_id`. :rtype: Device """ api = self._get_api(device_directory.DefaultApi) return Device(api.device_retrieve(device_id))
python
def get_device(self, device_id): api = self._get_api(device_directory.DefaultApi) return Device(api.device_retrieve(device_id))
[ "def", "get_device", "(", "self", ",", "device_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "device_directory", ".", "DefaultApi", ")", "return", "Device", "(", "api", ".", "device_retrieve", "(", "device_id", ")", ")" ]
Get device details from catalog. :param str device_id: the ID of the device to retrieve (Required) :returns: device object matching the `device_id`. :rtype: Device
[ "Get", "device", "details", "from", "catalog", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L80-L88
12,935
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.update_device
def update_device(self, device_id, **kwargs): """Update existing device in catalog. .. code-block:: python existing_device = api.get_device(...) updated_device = api.update_device( existing_device.id, certificate_fingerprint = "something new" ) :param str device_id: The ID of the device to update (Required) :param obj custom_attributes: Up to 5 custom JSON attributes :param str description: The description of the device :param str name: The name of the device :param str alias: The alias of the device :param str device_type: The endpoint type of the device - e.g. if the device is a gateway :param str host_gateway: The endpoint_name of the host gateway, if appropriate :param str certificate_fingerprint: Fingerprint of the device certificate :param str certificate_issuer_id: ID of the issuer of the certificate :returns: the updated device object :rtype: Device """ api = self._get_api(device_directory.DefaultApi) device = Device._create_request_map(kwargs) body = DeviceDataPostRequest(**device) return Device(api.device_update(device_id, body))
python
def update_device(self, device_id, **kwargs): api = self._get_api(device_directory.DefaultApi) device = Device._create_request_map(kwargs) body = DeviceDataPostRequest(**device) return Device(api.device_update(device_id, body))
[ "def", "update_device", "(", "self", ",", "device_id", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "device_directory", ".", "DefaultApi", ")", "device", "=", "Device", ".", "_create_request_map", "(", "kwargs", ")", "body",...
Update existing device in catalog. .. code-block:: python existing_device = api.get_device(...) updated_device = api.update_device( existing_device.id, certificate_fingerprint = "something new" ) :param str device_id: The ID of the device to update (Required) :param obj custom_attributes: Up to 5 custom JSON attributes :param str description: The description of the device :param str name: The name of the device :param str alias: The alias of the device :param str device_type: The endpoint type of the device - e.g. if the device is a gateway :param str host_gateway: The endpoint_name of the host gateway, if appropriate :param str certificate_fingerprint: Fingerprint of the device certificate :param str certificate_issuer_id: ID of the issuer of the certificate :returns: the updated device object :rtype: Device
[ "Update", "existing", "device", "in", "catalog", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L91-L117
12,936
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.add_device
def add_device(self, **kwargs): """Add a new device to catalog. .. code-block:: python device = { "mechanism": "connector", "certificate_fingerprint": "<certificate>", "name": "New device name", "certificate_issuer_id": "<id>" } resp = api.add_device(**device) print(resp.created_at) :param str certificate_fingerprint: Fingerprint of the device certificate :param str certificate_issuer_id: ID of the issuer of the certificate :param str name: The name of the device :param str account_id: The owning Identity and Access Managment (IAM) account ID :param obj custom_attributes: Up to 5 custom JSON attributes :param str description: The description of the device :param str device_class: Class of the device :param str id: The ID of the device :param str manifest_url: URL for the current device manifest :param str mechanism: The ID of the channel used to communicate with the device :param str mechanism_url: The address of the connector to use :param str serial_number: The serial number of the device :param str state: The current state of the device :param int trust_class: The device trust class :param str vendor_id: The device vendor ID :param str alias: The alias of the device :parama str device_type: The endpoint type of the device - e.g. if the device is a gateway :param str host_gateway: The endpoint_name of the host gateway, if appropriate :param datetime bootstrap_certificate_expiration: :param datetime connector_certificate_expiration: Expiration date of the certificate used to connect to connector server :param int device_execution_mode: The device class :param str firmware_checksum: The SHA256 checksum of the current firmware image :param datetime manifest_timestamp: The timestamp of the current manifest version :return: the newly created device object. :rtype: Device """ api = self._get_api(device_directory.DefaultApi) device = Device._create_request_map(kwargs) device = DeviceData(**device) return Device(api.device_create(device))
python
def add_device(self, **kwargs): api = self._get_api(device_directory.DefaultApi) device = Device._create_request_map(kwargs) device = DeviceData(**device) return Device(api.device_create(device))
[ "def", "add_device", "(", "self", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "device_directory", ".", "DefaultApi", ")", "device", "=", "Device", ".", "_create_request_map", "(", "kwargs", ")", "device", "=", "DeviceData",...
Add a new device to catalog. .. code-block:: python device = { "mechanism": "connector", "certificate_fingerprint": "<certificate>", "name": "New device name", "certificate_issuer_id": "<id>" } resp = api.add_device(**device) print(resp.created_at) :param str certificate_fingerprint: Fingerprint of the device certificate :param str certificate_issuer_id: ID of the issuer of the certificate :param str name: The name of the device :param str account_id: The owning Identity and Access Managment (IAM) account ID :param obj custom_attributes: Up to 5 custom JSON attributes :param str description: The description of the device :param str device_class: Class of the device :param str id: The ID of the device :param str manifest_url: URL for the current device manifest :param str mechanism: The ID of the channel used to communicate with the device :param str mechanism_url: The address of the connector to use :param str serial_number: The serial number of the device :param str state: The current state of the device :param int trust_class: The device trust class :param str vendor_id: The device vendor ID :param str alias: The alias of the device :parama str device_type: The endpoint type of the device - e.g. if the device is a gateway :param str host_gateway: The endpoint_name of the host gateway, if appropriate :param datetime bootstrap_certificate_expiration: :param datetime connector_certificate_expiration: Expiration date of the certificate used to connect to connector server :param int device_execution_mode: The device class :param str firmware_checksum: The SHA256 checksum of the current firmware image :param datetime manifest_timestamp: The timestamp of the current manifest version :return: the newly created device object. :rtype: Device
[ "Add", "a", "new", "device", "to", "catalog", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L120-L164
12,937
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.delete_device
def delete_device(self, device_id): """Delete device from catalog. :param str device_id: ID of device in catalog to delete (Required) :return: void """ api = self._get_api(device_directory.DefaultApi) return api.device_destroy(id=device_id)
python
def delete_device(self, device_id): api = self._get_api(device_directory.DefaultApi) return api.device_destroy(id=device_id)
[ "def", "delete_device", "(", "self", ",", "device_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "device_directory", ".", "DefaultApi", ")", "return", "api", ".", "device_destroy", "(", "id", "=", "device_id", ")" ]
Delete device from catalog. :param str device_id: ID of device in catalog to delete (Required) :return: void
[ "Delete", "device", "from", "catalog", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L167-L174
12,938
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.list_queries
def list_queries(self, **kwargs): """List queries in device query service. :param int limit: The number of devices to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get devices after/starting at given `device_id` :param filters: Dictionary of filters to apply. :returns: a list of :py:class:`Query` objects. :rtype: PaginatedResponse """ kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Query, True) api = self._get_api(device_directory.DefaultApi) return PaginatedResponse(api.device_query_list, lwrap_type=Query, **kwargs)
python
def list_queries(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Query, True) api = self._get_api(device_directory.DefaultApi) return PaginatedResponse(api.device_query_list, lwrap_type=Query, **kwargs)
[ "def", "list_queries", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "Query", ",", "True", ")", "api", "=", "se...
List queries in device query service. :param int limit: The number of devices to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get devices after/starting at given `device_id` :param filters: Dictionary of filters to apply. :returns: a list of :py:class:`Query` objects. :rtype: PaginatedResponse
[ "List", "queries", "in", "device", "query", "service", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L177-L191
12,939
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.add_query
def add_query(self, name, filter, **kwargs): """Add a new query to device query service. .. code-block:: python f = api.add_query( name = "Query name", filter = { "device_id": {"$eq": "01234"}, custom_attributes = { "foo": {"$eq": "bar"} } } ) print(f.created_at) :param str name: Name of query (Required) :param dict filter: Filter properties to apply (Required) :param return: The newly created query object. :return: the newly created query object :rtype: Query """ # Ensure we have the correct types and get the new query object filter_obj = filters.legacy_filter_formatter( dict(filter=filter), Device._get_attributes_map() ) if filter else None query_map = Query._create_request_map(kwargs) # Create the DeviceQuery object f = DeviceQuery(name=name, query=filter_obj['filter'], **query_map) api = self._get_api(device_directory.DefaultApi) return Query(api.device_query_create(f))
python
def add_query(self, name, filter, **kwargs): # Ensure we have the correct types and get the new query object filter_obj = filters.legacy_filter_formatter( dict(filter=filter), Device._get_attributes_map() ) if filter else None query_map = Query._create_request_map(kwargs) # Create the DeviceQuery object f = DeviceQuery(name=name, query=filter_obj['filter'], **query_map) api = self._get_api(device_directory.DefaultApi) return Query(api.device_query_create(f))
[ "def", "add_query", "(", "self", ",", "name", ",", "filter", ",", "*", "*", "kwargs", ")", ":", "# Ensure we have the correct types and get the new query object", "filter_obj", "=", "filters", ".", "legacy_filter_formatter", "(", "dict", "(", "filter", "=", "filter"...
Add a new query to device query service. .. code-block:: python f = api.add_query( name = "Query name", filter = { "device_id": {"$eq": "01234"}, custom_attributes = { "foo": {"$eq": "bar"} } } ) print(f.created_at) :param str name: Name of query (Required) :param dict filter: Filter properties to apply (Required) :param return: The newly created query object. :return: the newly created query object :rtype: Query
[ "Add", "a", "new", "query", "to", "device", "query", "service", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L194-L225
12,940
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.update_query
def update_query(self, query_id, name=None, filter=None, **kwargs): """Update existing query in device query service. .. code-block:: python q = api.get_query(...) q.filter["custom_attributes"]["foo"] = { "$eq": "bar" } new_q = api.update_query( query_id = q.id, name = "new name", filter = q.filter ) :param str query_id: Existing query ID to update (Required) :param str name: name of query :param dict filter: query properties to apply :return: the newly updated query object. :rtype: Query """ # Get urlencoded query attribute filter_obj = filters.legacy_filter_formatter( dict(filter=filter), Device._get_attributes_map() ) if filter else None query_map = Query._create_request_map(kwargs) # The filter option is optional on update but DeviceQueryPostPutRequest sets it None, which is invalid. # Manually create a resource body without the filter parameter if only the name is provided. if filter is None: body = {"name": name} else: body = DeviceQueryPostPutRequest(name=name, query=filter_obj['filter'], **query_map) api = self._get_api(device_directory.DefaultApi) return Query(api.device_query_update(query_id, body))
python
def update_query(self, query_id, name=None, filter=None, **kwargs): # Get urlencoded query attribute filter_obj = filters.legacy_filter_formatter( dict(filter=filter), Device._get_attributes_map() ) if filter else None query_map = Query._create_request_map(kwargs) # The filter option is optional on update but DeviceQueryPostPutRequest sets it None, which is invalid. # Manually create a resource body without the filter parameter if only the name is provided. if filter is None: body = {"name": name} else: body = DeviceQueryPostPutRequest(name=name, query=filter_obj['filter'], **query_map) api = self._get_api(device_directory.DefaultApi) return Query(api.device_query_update(query_id, body))
[ "def", "update_query", "(", "self", ",", "query_id", ",", "name", "=", "None", ",", "filter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Get urlencoded query attribute", "filter_obj", "=", "filters", ".", "legacy_filter_formatter", "(", "dict", "(", ...
Update existing query in device query service. .. code-block:: python q = api.get_query(...) q.filter["custom_attributes"]["foo"] = { "$eq": "bar" } new_q = api.update_query( query_id = q.id, name = "new name", filter = q.filter ) :param str query_id: Existing query ID to update (Required) :param str name: name of query :param dict filter: query properties to apply :return: the newly updated query object. :rtype: Query
[ "Update", "existing", "query", "in", "device", "query", "service", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L228-L265
12,941
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.delete_query
def delete_query(self, query_id): """Delete query in device query service. :param int query_id: ID of the query to delete (Required) :return: void """ api = self._get_api(device_directory.DefaultApi) api.device_query_destroy(query_id) return
python
def delete_query(self, query_id): api = self._get_api(device_directory.DefaultApi) api.device_query_destroy(query_id) return
[ "def", "delete_query", "(", "self", ",", "query_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "device_directory", ".", "DefaultApi", ")", "api", ".", "device_query_destroy", "(", "query_id", ")", "return" ]
Delete query in device query service. :param int query_id: ID of the query to delete (Required) :return: void
[ "Delete", "query", "in", "device", "query", "service", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L268-L276
12,942
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.get_query
def get_query(self, query_id): """Get query in device query service. :param int query_id: ID of the query to get (Required) :returns: device query object :rtype: Query """ api = self._get_api(device_directory.DefaultApi) return Query(api.device_query_retrieve(query_id))
python
def get_query(self, query_id): api = self._get_api(device_directory.DefaultApi) return Query(api.device_query_retrieve(query_id))
[ "def", "get_query", "(", "self", ",", "query_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "device_directory", ".", "DefaultApi", ")", "return", "Query", "(", "api", ".", "device_query_retrieve", "(", "query_id", ")", ")" ]
Get query in device query service. :param int query_id: ID of the query to get (Required) :returns: device query object :rtype: Query
[ "Get", "query", "in", "device", "query", "service", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L279-L287
12,943
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.list_device_events
def list_device_events(self, **kwargs): """List all device logs. :param int limit: The number of logs to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get logs after/starting at given `device_event_id` :param dict filters: Dictionary of filters to apply. :return: list of :py:class:`DeviceEvent` objects :rtype: PaginatedResponse """ kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, DeviceEvent, True) api = self._get_api(device_directory.DefaultApi) return PaginatedResponse(api.device_log_list, lwrap_type=DeviceEvent, **kwargs)
python
def list_device_events(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, DeviceEvent, True) api = self._get_api(device_directory.DefaultApi) return PaginatedResponse(api.device_log_list, lwrap_type=DeviceEvent, **kwargs)
[ "def", "list_device_events", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "DeviceEvent", ",", "True", ")", "api", ...
List all device logs. :param int limit: The number of logs to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get logs after/starting at given `device_event_id` :param dict filters: Dictionary of filters to apply. :return: list of :py:class:`DeviceEvent` objects :rtype: PaginatedResponse
[ "List", "all", "device", "logs", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L290-L305
12,944
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
DeviceDirectoryAPI.get_device_event
def get_device_event(self, device_event_id): """Get device event with provided ID. :param int device_event_id: id of the event to get (Required) :rtype: DeviceEvent """ api = self._get_api(device_directory.DefaultApi) return DeviceEvent(api.device_log_retrieve(device_event_id))
python
def get_device_event(self, device_event_id): api = self._get_api(device_directory.DefaultApi) return DeviceEvent(api.device_log_retrieve(device_event_id))
[ "def", "get_device_event", "(", "self", ",", "device_event_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "device_directory", ".", "DefaultApi", ")", "return", "DeviceEvent", "(", "api", ".", "device_log_retrieve", "(", "device_event_id", ")", ")" ]
Get device event with provided ID. :param int device_event_id: id of the event to get (Required) :rtype: DeviceEvent
[ "Get", "device", "event", "with", "provided", "ID", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L308-L315
12,945
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/device_directory/device_directory.py
Query.filter
def filter(self): """Get the query of this Query. The device query :return: The query of this Query. :rtype: dict """ if isinstance(self._filter, str): return self._decode_query(self._filter) return self._filter
python
def filter(self): if isinstance(self._filter, str): return self._decode_query(self._filter) return self._filter
[ "def", "filter", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_filter", ",", "str", ")", ":", "return", "self", ".", "_decode_query", "(", "self", ".", "_filter", ")", "return", "self", ".", "_filter" ]
Get the query of this Query. The device query :return: The query of this Query. :rtype: dict
[ "Get", "the", "query", "of", "this", "Query", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/device_directory/device_directory.py#L664-L674
12,946
ARMmbed/mbed-cloud-sdk-python
scripts/tpip.py
get_metadata
def get_metadata(item): """Get metadata information from the distribution. Depending on the package this may either be in METADATA or PKG-INFO :param item: pkg_resources WorkingSet item :returns: metadata resource as list of non-blank non-comment lines """ for metadata_key in ('METADATA', 'PKG-INFO'): try: metadata_lines = item.get_metadata_lines(metadata_key) break except (KeyError, IOError): # The package will be shown in the report without any license information # if a metadata key is not found. metadata_lines = [] return metadata_lines
python
def get_metadata(item): for metadata_key in ('METADATA', 'PKG-INFO'): try: metadata_lines = item.get_metadata_lines(metadata_key) break except (KeyError, IOError): # The package will be shown in the report without any license information # if a metadata key is not found. metadata_lines = [] return metadata_lines
[ "def", "get_metadata", "(", "item", ")", ":", "for", "metadata_key", "in", "(", "'METADATA'", ",", "'PKG-INFO'", ")", ":", "try", ":", "metadata_lines", "=", "item", ".", "get_metadata_lines", "(", "metadata_key", ")", "break", "except", "(", "KeyError", ","...
Get metadata information from the distribution. Depending on the package this may either be in METADATA or PKG-INFO :param item: pkg_resources WorkingSet item :returns: metadata resource as list of non-blank non-comment lines
[ "Get", "metadata", "information", "from", "the", "distribution", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L67-L84
12,947
ARMmbed/mbed-cloud-sdk-python
scripts/tpip.py
license_cleanup
def license_cleanup(text): """Tidy up a license string e.g. "::OSI:: mit software license" -> "MIT" """ if not text: return None text = text.rsplit(':', 1)[-1] replacements = [ 'licenses', 'license', 'licences', 'licence', 'software', ',', ] for replacement in replacements: text = text.replace(replacement, '') text = text.strip().upper() text = text.replace(' ', '_') text = text.replace('-', '_') if any(trigger.upper() in text for trigger in BAD_LICENSES): return None return text
python
def license_cleanup(text): if not text: return None text = text.rsplit(':', 1)[-1] replacements = [ 'licenses', 'license', 'licences', 'licence', 'software', ',', ] for replacement in replacements: text = text.replace(replacement, '') text = text.strip().upper() text = text.replace(' ', '_') text = text.replace('-', '_') if any(trigger.upper() in text for trigger in BAD_LICENSES): return None return text
[ "def", "license_cleanup", "(", "text", ")", ":", "if", "not", "text", ":", "return", "None", "text", "=", "text", ".", "rsplit", "(", "':'", ",", "1", ")", "[", "-", "1", "]", "replacements", "=", "[", "'licenses'", ",", "'license'", ",", "'licences'...
Tidy up a license string e.g. "::OSI:: mit software license" -> "MIT"
[ "Tidy", "up", "a", "license", "string" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L87-L110
12,948
ARMmbed/mbed-cloud-sdk-python
scripts/tpip.py
get_package_info_from_line
def get_package_info_from_line(tpip_pkg, line): """Given a line of text from metadata, extract semantic info""" lower_line = line.lower() try: metadata_key, metadata_value = lower_line.split(':', 1) except ValueError: return metadata_key = metadata_key.strip() metadata_value = metadata_value.strip() if metadata_value == 'unknown': return # extract exact matches if metadata_key in TPIP_FIELD_MAPPINGS: tpip_pkg[TPIP_FIELD_MAPPINGS[metadata_key]] = metadata_value return if metadata_key.startswith('version') and not tpip_pkg.get('PkgVersion'): # ... but if not, we'll use whatever we find tpip_pkg['PkgVersion'] = metadata_value return # Handle british and american spelling of licence/license if 'licen' in lower_line: if metadata_key.startswith('classifier') or '::' in metadata_value: license = lower_line.rsplit(':')[-1].strip().lower() license = license_cleanup(license) if license: tpip_pkg.setdefault('PkgLicenses', []).append(license)
python
def get_package_info_from_line(tpip_pkg, line): lower_line = line.lower() try: metadata_key, metadata_value = lower_line.split(':', 1) except ValueError: return metadata_key = metadata_key.strip() metadata_value = metadata_value.strip() if metadata_value == 'unknown': return # extract exact matches if metadata_key in TPIP_FIELD_MAPPINGS: tpip_pkg[TPIP_FIELD_MAPPINGS[metadata_key]] = metadata_value return if metadata_key.startswith('version') and not tpip_pkg.get('PkgVersion'): # ... but if not, we'll use whatever we find tpip_pkg['PkgVersion'] = metadata_value return # Handle british and american spelling of licence/license if 'licen' in lower_line: if metadata_key.startswith('classifier') or '::' in metadata_value: license = lower_line.rsplit(':')[-1].strip().lower() license = license_cleanup(license) if license: tpip_pkg.setdefault('PkgLicenses', []).append(license)
[ "def", "get_package_info_from_line", "(", "tpip_pkg", ",", "line", ")", ":", "lower_line", "=", "line", ".", "lower", "(", ")", "try", ":", "metadata_key", ",", "metadata_value", "=", "lower_line", ".", "split", "(", "':'", ",", "1", ")", "except", "ValueE...
Given a line of text from metadata, extract semantic info
[ "Given", "a", "line", "of", "text", "from", "metadata", "extract", "semantic", "info" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L113-L144
12,949
ARMmbed/mbed-cloud-sdk-python
scripts/tpip.py
process_metadata
def process_metadata(pkg_name, metadata_lines): """Create a dictionary containing the relevant fields. The following is an example of the generated dictionary: :Example: { 'name': 'six', 'version': '1.11.0', 'repository': 'pypi.python.org/pypi/six', 'licence': 'MIT', 'classifier': 'MIT License' } :param str pkg_name: name of the package :param metadata_lines: metadata resource as list of non-blank non-comment lines :returns: Dictionary of each of the fields :rtype: Dict[str, str] """ # Initialise a dictionary with all the fields to report on. tpip_pkg = dict( PkgName=pkg_name, PkgType='python package', PkgMgrURL='https://pypi.org/project/%s/' % pkg_name, ) # Extract the metadata into a list for each field as there may be multiple # entries for each one. for line in metadata_lines: get_package_info_from_line(tpip_pkg, line) # condense PkgAuthorEmail into the Originator field if 'PkgAuthorEmail' in tpip_pkg: tpip_pkg['PkgOriginator'] = '%s <%s>' % ( tpip_pkg['PkgOriginator'], tpip_pkg.pop('PkgAuthorEmail') ) explicit_license = license_cleanup(tpip_pkg.get('PkgLicense')) license_candidates = tpip_pkg.pop('PkgLicenses', []) if explicit_license: tpip_pkg['PkgLicense'] = explicit_license else: tpip_pkg['PkgLicense'] = ' '.join(set(license_candidates)) return tpip_pkg
python
def process_metadata(pkg_name, metadata_lines): # Initialise a dictionary with all the fields to report on. tpip_pkg = dict( PkgName=pkg_name, PkgType='python package', PkgMgrURL='https://pypi.org/project/%s/' % pkg_name, ) # Extract the metadata into a list for each field as there may be multiple # entries for each one. for line in metadata_lines: get_package_info_from_line(tpip_pkg, line) # condense PkgAuthorEmail into the Originator field if 'PkgAuthorEmail' in tpip_pkg: tpip_pkg['PkgOriginator'] = '%s <%s>' % ( tpip_pkg['PkgOriginator'], tpip_pkg.pop('PkgAuthorEmail') ) explicit_license = license_cleanup(tpip_pkg.get('PkgLicense')) license_candidates = tpip_pkg.pop('PkgLicenses', []) if explicit_license: tpip_pkg['PkgLicense'] = explicit_license else: tpip_pkg['PkgLicense'] = ' '.join(set(license_candidates)) return tpip_pkg
[ "def", "process_metadata", "(", "pkg_name", ",", "metadata_lines", ")", ":", "# Initialise a dictionary with all the fields to report on.", "tpip_pkg", "=", "dict", "(", "PkgName", "=", "pkg_name", ",", "PkgType", "=", "'python package'", ",", "PkgMgrURL", "=", "'https:...
Create a dictionary containing the relevant fields. The following is an example of the generated dictionary: :Example: { 'name': 'six', 'version': '1.11.0', 'repository': 'pypi.python.org/pypi/six', 'licence': 'MIT', 'classifier': 'MIT License' } :param str pkg_name: name of the package :param metadata_lines: metadata resource as list of non-blank non-comment lines :returns: Dictionary of each of the fields :rtype: Dict[str, str]
[ "Create", "a", "dictionary", "containing", "the", "relevant", "fields", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L147-L194
12,950
ARMmbed/mbed-cloud-sdk-python
scripts/tpip.py
write_csv_file
def write_csv_file(output_filename, tpip_pkgs): """Write the TPIP report out to a CSV file. :param str output_filename: filename for CSV. :param List tpip_pkgs: a list of dictionaries compatible with DictWriter. """ dirname = os.path.dirname(os.path.abspath(os.path.expanduser(output_filename))) if dirname and not os.path.exists(dirname): os.makedirs(dirname) with open(output_filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=FIELDNAMES) writer.writeheader() writer.writerows(tpip_pkgs)
python
def write_csv_file(output_filename, tpip_pkgs): dirname = os.path.dirname(os.path.abspath(os.path.expanduser(output_filename))) if dirname and not os.path.exists(dirname): os.makedirs(dirname) with open(output_filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=FIELDNAMES) writer.writeheader() writer.writerows(tpip_pkgs)
[ "def", "write_csv_file", "(", "output_filename", ",", "tpip_pkgs", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "output_filename", ")", ")", ")", "i...
Write the TPIP report out to a CSV file. :param str output_filename: filename for CSV. :param List tpip_pkgs: a list of dictionaries compatible with DictWriter.
[ "Write", "the", "TPIP", "report", "out", "to", "a", "CSV", "file", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L197-L211
12,951
ARMmbed/mbed-cloud-sdk-python
scripts/tpip.py
force_ascii_values
def force_ascii_values(data): """Ensures each value is ascii-only""" return { k: v.encode('utf8').decode('ascii', 'backslashreplace') for k, v in data.items() }
python
def force_ascii_values(data): return { k: v.encode('utf8').decode('ascii', 'backslashreplace') for k, v in data.items() }
[ "def", "force_ascii_values", "(", "data", ")", ":", "return", "{", "k", ":", "v", ".", "encode", "(", "'utf8'", ")", ".", "decode", "(", "'ascii'", ",", "'backslashreplace'", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", "}" ]
Ensures each value is ascii-only
[ "Ensures", "each", "value", "is", "ascii", "-", "only" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L214-L219
12,952
ARMmbed/mbed-cloud-sdk-python
scripts/tpip.py
main
def main(): """Generate a TPIP report.""" parser = argparse.ArgumentParser(description='Generate a TPIP report as a CSV file.') parser.add_argument('output_filename', type=str, metavar='output-file', help='the output path and filename', nargs='?') parser.add_argument('--only', type=str, help='only parse this package') args = parser.parse_args() output_path = os.path.abspath(args.output_filename) if args.output_filename else None skips = [] tpip_pkgs = [] for pkg_name, pkg_item in sorted(pkg_resources.working_set.by_key.items()): if args.only and args.only not in pkg_name.lower(): continue if pkg_name in EXCLUDED_PACKAGES: skips.append(pkg_name) continue metadata_lines = get_metadata(pkg_item) tpip_pkg = process_metadata(pkg_name, metadata_lines) tpip_pkgs.append(force_ascii_values(tpip_pkg)) print(json.dumps(tpip_pkgs, indent=2, sort_keys=True)) print('Parsed %s packages\nOutput to CSV: `%s`\nIgnored packages: %s' % ( len(tpip_pkgs), output_path, ', '.join(skips), )) output_path and write_csv_file(output_path, tpip_pkgs)
python
def main(): parser = argparse.ArgumentParser(description='Generate a TPIP report as a CSV file.') parser.add_argument('output_filename', type=str, metavar='output-file', help='the output path and filename', nargs='?') parser.add_argument('--only', type=str, help='only parse this package') args = parser.parse_args() output_path = os.path.abspath(args.output_filename) if args.output_filename else None skips = [] tpip_pkgs = [] for pkg_name, pkg_item in sorted(pkg_resources.working_set.by_key.items()): if args.only and args.only not in pkg_name.lower(): continue if pkg_name in EXCLUDED_PACKAGES: skips.append(pkg_name) continue metadata_lines = get_metadata(pkg_item) tpip_pkg = process_metadata(pkg_name, metadata_lines) tpip_pkgs.append(force_ascii_values(tpip_pkg)) print(json.dumps(tpip_pkgs, indent=2, sort_keys=True)) print('Parsed %s packages\nOutput to CSV: `%s`\nIgnored packages: %s' % ( len(tpip_pkgs), output_path, ', '.join(skips), )) output_path and write_csv_file(output_path, tpip_pkgs)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Generate a TPIP report as a CSV file.'", ")", "parser", ".", "add_argument", "(", "'output_filename'", ",", "type", "=", "str", ",", "metavar", "=", "'outp...
Generate a TPIP report.
[ "Generate", "a", "TPIP", "report", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/tpip.py#L222-L250
12,953
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/billing/models/service_package_metadata.py
ServicePackageMetadata.remaining_quota
def remaining_quota(self, remaining_quota): """ Sets the remaining_quota of this ServicePackageMetadata. Current available service package quota. :param remaining_quota: The remaining_quota of this ServicePackageMetadata. :type: int """ if remaining_quota is None: raise ValueError("Invalid value for `remaining_quota`, must not be `None`") if remaining_quota is not None and remaining_quota < 0: raise ValueError("Invalid value for `remaining_quota`, must be a value greater than or equal to `0`") self._remaining_quota = remaining_quota
python
def remaining_quota(self, remaining_quota): if remaining_quota is None: raise ValueError("Invalid value for `remaining_quota`, must not be `None`") if remaining_quota is not None and remaining_quota < 0: raise ValueError("Invalid value for `remaining_quota`, must be a value greater than or equal to `0`") self._remaining_quota = remaining_quota
[ "def", "remaining_quota", "(", "self", ",", "remaining_quota", ")", ":", "if", "remaining_quota", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `remaining_quota`, must not be `None`\"", ")", "if", "remaining_quota", "is", "not", "None", "and", "r...
Sets the remaining_quota of this ServicePackageMetadata. Current available service package quota. :param remaining_quota: The remaining_quota of this ServicePackageMetadata. :type: int
[ "Sets", "the", "remaining_quota", "of", "this", "ServicePackageMetadata", ".", "Current", "available", "service", "package", "quota", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/billing/models/service_package_metadata.py#L95-L108
12,954
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/billing/models/service_package_metadata.py
ServicePackageMetadata.reserved_quota
def reserved_quota(self, reserved_quota): """ Sets the reserved_quota of this ServicePackageMetadata. Sum of all open reservations for this account. :param reserved_quota: The reserved_quota of this ServicePackageMetadata. :type: int """ if reserved_quota is None: raise ValueError("Invalid value for `reserved_quota`, must not be `None`") if reserved_quota is not None and reserved_quota < 0: raise ValueError("Invalid value for `reserved_quota`, must be a value greater than or equal to `0`") self._reserved_quota = reserved_quota
python
def reserved_quota(self, reserved_quota): if reserved_quota is None: raise ValueError("Invalid value for `reserved_quota`, must not be `None`") if reserved_quota is not None and reserved_quota < 0: raise ValueError("Invalid value for `reserved_quota`, must be a value greater than or equal to `0`") self._reserved_quota = reserved_quota
[ "def", "reserved_quota", "(", "self", ",", "reserved_quota", ")", ":", "if", "reserved_quota", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `reserved_quota`, must not be `None`\"", ")", "if", "reserved_quota", "is", "not", "None", "and", "reserv...
Sets the reserved_quota of this ServicePackageMetadata. Sum of all open reservations for this account. :param reserved_quota: The reserved_quota of this ServicePackageMetadata. :type: int
[ "Sets", "the", "reserved_quota", "of", "this", "ServicePackageMetadata", ".", "Sum", "of", "all", "open", "reservations", "for", "this", "account", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/billing/models/service_package_metadata.py#L122-L135
12,955
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/update_service/models/update_campaign_put_request.py
UpdateCampaignPutRequest.root_manifest_id
def root_manifest_id(self, root_manifest_id): """ Sets the root_manifest_id of this UpdateCampaignPutRequest. :param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest. :type: str """ if root_manifest_id is not None and len(root_manifest_id) > 32: raise ValueError("Invalid value for `root_manifest_id`, length must be less than or equal to `32`") self._root_manifest_id = root_manifest_id
python
def root_manifest_id(self, root_manifest_id): if root_manifest_id is not None and len(root_manifest_id) > 32: raise ValueError("Invalid value for `root_manifest_id`, length must be less than or equal to `32`") self._root_manifest_id = root_manifest_id
[ "def", "root_manifest_id", "(", "self", ",", "root_manifest_id", ")", ":", "if", "root_manifest_id", "is", "not", "None", "and", "len", "(", "root_manifest_id", ")", ">", "32", ":", "raise", "ValueError", "(", "\"Invalid value for `root_manifest_id`, length must be le...
Sets the root_manifest_id of this UpdateCampaignPutRequest. :param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest. :type: str
[ "Sets", "the", "root_manifest_id", "of", "this", "UpdateCampaignPutRequest", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/update_service/models/update_campaign_put_request.py#L174-L184
12,956
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/update_service/models/update_campaign_put_request.py
UpdateCampaignPutRequest.state
def state(self, state): """ Sets the state of this UpdateCampaignPutRequest. The state of the campaign :param state: The state of this UpdateCampaignPutRequest. :type: str """ allowed_values = ["draft", "scheduled", "allocatingquota", "allocatedquota", "quotaallocationfailed", "checkingmanifest", "checkedmanifest", "devicefetch", "devicecopy", "devicecheck", "publishing", "deploying", "deployed", "manifestremoved", "expired", "stopping", "autostopped", "userstopped", "conflict"] if state not in allowed_values: raise ValueError( "Invalid value for `state` ({0}), must be one of {1}" .format(state, allowed_values) ) self._state = state
python
def state(self, state): allowed_values = ["draft", "scheduled", "allocatingquota", "allocatedquota", "quotaallocationfailed", "checkingmanifest", "checkedmanifest", "devicefetch", "devicecopy", "devicecheck", "publishing", "deploying", "deployed", "manifestremoved", "expired", "stopping", "autostopped", "userstopped", "conflict"] if state not in allowed_values: raise ValueError( "Invalid value for `state` ({0}), must be one of {1}" .format(state, allowed_values) ) self._state = state
[ "def", "state", "(", "self", ",", "state", ")", ":", "allowed_values", "=", "[", "\"draft\"", ",", "\"scheduled\"", ",", "\"allocatingquota\"", ",", "\"allocatedquota\"", ",", "\"quotaallocationfailed\"", ",", "\"checkingmanifest\"", ",", "\"checkedmanifest\"", ",", ...
Sets the state of this UpdateCampaignPutRequest. The state of the campaign :param state: The state of this UpdateCampaignPutRequest. :type: str
[ "Sets", "the", "state", "of", "this", "UpdateCampaignPutRequest", ".", "The", "state", "of", "the", "campaign" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/update_service/models/update_campaign_put_request.py#L198-L213
12,957
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/observer.py
Observer.notify
def notify(self, data): """Notify this observer that data has arrived""" LOG.debug('notify received: %s', data) self._notify_count += 1 if self._cancelled: LOG.debug('notify skipping due to `cancelled`') return self if self._once_done and self._once: LOG.debug('notify skipping due to `once`') return self with self._lock: try: # notify next consumer immediately self._waitables.get_nowait().put_nowait(data) LOG.debug('found a consumer, notifying') except queue.Empty: # store the notification try: self._notifications.put_nowait(data) LOG.debug('no consumers, queueing data') except queue.Full: LOG.warning('notification queue full - discarding new data') # callbacks are sent straight away # bombproofing should be handled by individual callbacks for callback in self._callbacks: LOG.debug('callback: %s', callback) callback(data) self._once_done = True return self
python
def notify(self, data): LOG.debug('notify received: %s', data) self._notify_count += 1 if self._cancelled: LOG.debug('notify skipping due to `cancelled`') return self if self._once_done and self._once: LOG.debug('notify skipping due to `once`') return self with self._lock: try: # notify next consumer immediately self._waitables.get_nowait().put_nowait(data) LOG.debug('found a consumer, notifying') except queue.Empty: # store the notification try: self._notifications.put_nowait(data) LOG.debug('no consumers, queueing data') except queue.Full: LOG.warning('notification queue full - discarding new data') # callbacks are sent straight away # bombproofing should be handled by individual callbacks for callback in self._callbacks: LOG.debug('callback: %s', callback) callback(data) self._once_done = True return self
[ "def", "notify", "(", "self", ",", "data", ")", ":", "LOG", ".", "debug", "(", "'notify received: %s'", ",", "data", ")", "self", ".", "_notify_count", "+=", "1", "if", "self", ".", "_cancelled", ":", "LOG", ".", "debug", "(", "'notify skipping due to `can...
Notify this observer that data has arrived
[ "Notify", "this", "observer", "that", "data", "has", "arrived" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/observer.py#L127-L156
12,958
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/observer.py
Observer.cancel
def cancel(self): """Cancels the observer No more notifications will be passed on """ LOG.debug('cancelling %s', self) self._cancelled = True self.clear_callbacks() # not strictly necessary, but may release references while True: try: self._waitables.get_nowait().put_nowait(self.sentinel) except queue.Empty: break
python
def cancel(self): LOG.debug('cancelling %s', self) self._cancelled = True self.clear_callbacks() # not strictly necessary, but may release references while True: try: self._waitables.get_nowait().put_nowait(self.sentinel) except queue.Empty: break
[ "def", "cancel", "(", "self", ")", ":", "LOG", ".", "debug", "(", "'cancelling %s'", ",", "self", ")", "self", ".", "_cancelled", "=", "True", "self", ".", "clear_callbacks", "(", ")", "# not strictly necessary, but may release references", "while", "True", ":",...
Cancels the observer No more notifications will be passed on
[ "Cancels", "the", "observer" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/observer.py#L163-L175
12,959
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/external_ca/models/cfssl_auth_credentials.py
CfsslAuthCredentials.hmac_hex_key
def hmac_hex_key(self, hmac_hex_key): """ Sets the hmac_hex_key of this CfsslAuthCredentials. The key that is used to compute the HMAC of the request using the HMAC-SHA-256 algorithm. Must contain an even number of hexadecimal characters. :param hmac_hex_key: The hmac_hex_key of this CfsslAuthCredentials. :type: str """ if hmac_hex_key is None: raise ValueError("Invalid value for `hmac_hex_key`, must not be `None`") if hmac_hex_key is not None and len(hmac_hex_key) > 64: raise ValueError("Invalid value for `hmac_hex_key`, length must be less than or equal to `64`") if hmac_hex_key is not None and not re.search('^([a-fA-F0-9][a-fA-F0-9]){1,32}$', hmac_hex_key): raise ValueError("Invalid value for `hmac_hex_key`, must be a follow pattern or equal to `/^([a-fA-F0-9][a-fA-F0-9]){1,32}$/`") self._hmac_hex_key = hmac_hex_key
python
def hmac_hex_key(self, hmac_hex_key): if hmac_hex_key is None: raise ValueError("Invalid value for `hmac_hex_key`, must not be `None`") if hmac_hex_key is not None and len(hmac_hex_key) > 64: raise ValueError("Invalid value for `hmac_hex_key`, length must be less than or equal to `64`") if hmac_hex_key is not None and not re.search('^([a-fA-F0-9][a-fA-F0-9]){1,32}$', hmac_hex_key): raise ValueError("Invalid value for `hmac_hex_key`, must be a follow pattern or equal to `/^([a-fA-F0-9][a-fA-F0-9]){1,32}$/`") self._hmac_hex_key = hmac_hex_key
[ "def", "hmac_hex_key", "(", "self", ",", "hmac_hex_key", ")", ":", "if", "hmac_hex_key", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `hmac_hex_key`, must not be `None`\"", ")", "if", "hmac_hex_key", "is", "not", "None", "and", "len", "(", "...
Sets the hmac_hex_key of this CfsslAuthCredentials. The key that is used to compute the HMAC of the request using the HMAC-SHA-256 algorithm. Must contain an even number of hexadecimal characters. :param hmac_hex_key: The hmac_hex_key of this CfsslAuthCredentials. :type: str
[ "Sets", "the", "hmac_hex_key", "of", "this", "CfsslAuthCredentials", ".", "The", "key", "that", "is", "used", "to", "compute", "the", "HMAC", "of", "the", "request", "using", "the", "HMAC", "-", "SHA", "-", "256", "algorithm", ".", "Must", "contain", "an",...
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/external_ca/models/cfssl_auth_credentials.py#L61-L76
12,960
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/models/device_query_post_put_request.py
DeviceQueryPostPutRequest.name
def name(self, name): """ Sets the name of this DeviceQueryPostPutRequest. The name of the query. :param name: The name of this DeviceQueryPostPutRequest. :type: str """ if name is None: raise ValueError("Invalid value for `name`, must not be `None`") if name is not None and len(name) > 200: raise ValueError("Invalid value for `name`, length must be less than or equal to `200`") self._name = name
python
def name(self, name): if name is None: raise ValueError("Invalid value for `name`, must not be `None`") if name is not None and len(name) > 200: raise ValueError("Invalid value for `name`, length must be less than or equal to `200`") self._name = name
[ "def", "name", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `name`, must not be `None`\"", ")", "if", "name", "is", "not", "None", "and", "len", "(", "name", ")", ">", "200", ":", "...
Sets the name of this DeviceQueryPostPutRequest. The name of the query. :param name: The name of this DeviceQueryPostPutRequest. :type: str
[ "Sets", "the", "name", "of", "this", "DeviceQueryPostPutRequest", ".", "The", "name", "of", "the", "query", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/models/device_query_post_put_request.py#L64-L77
12,961
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/models/device_query_post_put_request.py
DeviceQueryPostPutRequest.query
def query(self, query): """ Sets the query of this DeviceQueryPostPutRequest. The device query. :param query: The query of this DeviceQueryPostPutRequest. :type: str """ if query is None: raise ValueError("Invalid value for `query`, must not be `None`") if query is not None and len(query) > 1000: raise ValueError("Invalid value for `query`, length must be less than or equal to `1000`") self._query = query
python
def query(self, query): if query is None: raise ValueError("Invalid value for `query`, must not be `None`") if query is not None and len(query) > 1000: raise ValueError("Invalid value for `query`, length must be less than or equal to `1000`") self._query = query
[ "def", "query", "(", "self", ",", "query", ")", ":", "if", "query", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `query`, must not be `None`\"", ")", "if", "query", "is", "not", "None", "and", "len", "(", "query", ")", ">", "1000", "...
Sets the query of this DeviceQueryPostPutRequest. The device query. :param query: The query of this DeviceQueryPostPutRequest. :type: str
[ "Sets", "the", "query", "of", "this", "DeviceQueryPostPutRequest", ".", "The", "device", "query", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/models/device_query_post_put_request.py#L91-L104
12,962
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.list_api_keys
def list_api_keys(self, **kwargs): """List the API keys registered in the organisation. List api keys Example: .. code-block:: python account_management_api = AccountManagementAPI() # List api keys api_keys_paginated_response = account_management_api.list_api_keys() # get single api key api_keys_paginated_response.data[0] :param int limit: Number of API keys to get :param str after: Entity ID after which to start fetching :param str order: Order of the records to return (asc|desc) :param dict filters: Dictionary of filters to apply: str owner (eq) :returns: a list of :class:`ApiKey` objects :rtype: PaginatedResponse :raises: ApiException """ kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, ApiKey) api = self._get_api(iam.DeveloperApi) # Return the data array return PaginatedResponse(api.get_all_api_keys, lwrap_type=ApiKey, **kwargs)
python
def list_api_keys(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, ApiKey) api = self._get_api(iam.DeveloperApi) # Return the data array return PaginatedResponse(api.get_all_api_keys, lwrap_type=ApiKey, **kwargs)
[ "def", "list_api_keys", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "ApiKey", ")", "api", "=", "self", ".", "...
List the API keys registered in the organisation. List api keys Example: .. code-block:: python account_management_api = AccountManagementAPI() # List api keys api_keys_paginated_response = account_management_api.list_api_keys() # get single api key api_keys_paginated_response.data[0] :param int limit: Number of API keys to get :param str after: Entity ID after which to start fetching :param str order: Order of the records to return (asc|desc) :param dict filters: Dictionary of filters to apply: str owner (eq) :returns: a list of :class:`ApiKey` objects :rtype: PaginatedResponse :raises: ApiException
[ "List", "the", "API", "keys", "registered", "in", "the", "organisation", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L44-L72
12,963
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.get_api_key
def get_api_key(self, api_key_id): """Get API key details for key registered in organisation. :param str api_key_id: The ID of the API key to be updated (Required) :returns: API key object :rtype: ApiKey """ api = self._get_api(iam.DeveloperApi) return ApiKey(api.get_api_key(api_key_id))
python
def get_api_key(self, api_key_id): api = self._get_api(iam.DeveloperApi) return ApiKey(api.get_api_key(api_key_id))
[ "def", "get_api_key", "(", "self", ",", "api_key_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "return", "ApiKey", "(", "api", ".", "get_api_key", "(", "api_key_id", ")", ")" ]
Get API key details for key registered in organisation. :param str api_key_id: The ID of the API key to be updated (Required) :returns: API key object :rtype: ApiKey
[ "Get", "API", "key", "details", "for", "key", "registered", "in", "organisation", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L75-L83
12,964
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.delete_api_key
def delete_api_key(self, api_key_id): """Delete an API key registered in the organisation. :param str api_key_id: The ID of the API key (Required) :returns: void """ api = self._get_api(iam.DeveloperApi) api.delete_api_key(api_key_id) return
python
def delete_api_key(self, api_key_id): api = self._get_api(iam.DeveloperApi) api.delete_api_key(api_key_id) return
[ "def", "delete_api_key", "(", "self", ",", "api_key_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "api", ".", "delete_api_key", "(", "api_key_id", ")", "return" ]
Delete an API key registered in the organisation. :param str api_key_id: The ID of the API key (Required) :returns: void
[ "Delete", "an", "API", "key", "registered", "in", "the", "organisation", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L86-L94
12,965
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.add_api_key
def add_api_key(self, name, **kwargs): """Create new API key registered to organisation. :param str name: The name of the API key (Required) :param list groups: List of group IDs (`str`) :param str owner: User ID owning the API key :param str status: The status of the API key. Values: ACTIVE, INACTIVE :returns: Newly created API key object :rtype: ApiKey """ api = self._get_api(iam.DeveloperApi) kwargs.update({'name': name}) api_key = ApiKey._create_request_map(kwargs) body = iam.ApiKeyInfoReq(**api_key) return ApiKey(api.create_api_key(body))
python
def add_api_key(self, name, **kwargs): api = self._get_api(iam.DeveloperApi) kwargs.update({'name': name}) api_key = ApiKey._create_request_map(kwargs) body = iam.ApiKeyInfoReq(**api_key) return ApiKey(api.create_api_key(body))
[ "def", "add_api_key", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "kwargs", ".", "update", "(", "{", "'name'", ":", "name", "}", ")", "api_key", "=", "ApiKe...
Create new API key registered to organisation. :param str name: The name of the API key (Required) :param list groups: List of group IDs (`str`) :param str owner: User ID owning the API key :param str status: The status of the API key. Values: ACTIVE, INACTIVE :returns: Newly created API key object :rtype: ApiKey
[ "Create", "new", "API", "key", "registered", "to", "organisation", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L97-L111
12,966
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.update_api_key
def update_api_key(self, api_key_id, **kwargs): """Update API key. :param str api_key_id: The ID of the API key to be updated (Required) :param str name: The name of the API key :param str owner: User ID owning the API key :param str status: The status of the API key. Values: ACTIVE, INACTIVE :returns: Newly created API key object :rtype: ApiKey """ api = self._get_api(iam.DeveloperApi) apikey = ApiKey._create_request_map(kwargs) body = iam.ApiKeyUpdateReq(**apikey) return ApiKey(api.update_api_key(api_key_id, body))
python
def update_api_key(self, api_key_id, **kwargs): api = self._get_api(iam.DeveloperApi) apikey = ApiKey._create_request_map(kwargs) body = iam.ApiKeyUpdateReq(**apikey) return ApiKey(api.update_api_key(api_key_id, body))
[ "def", "update_api_key", "(", "self", ",", "api_key_id", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "apikey", "=", "ApiKey", ".", "_create_request_map", "(", "kwargs", ")", "body", "=", ...
Update API key. :param str api_key_id: The ID of the API key to be updated (Required) :param str name: The name of the API key :param str owner: User ID owning the API key :param str status: The status of the API key. Values: ACTIVE, INACTIVE :returns: Newly created API key object :rtype: ApiKey
[ "Update", "API", "key", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L114-L127
12,967
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.list_users
def list_users(self, **kwargs): """List all users in organisation. :param int limit: The number of users to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get users after/starting at given user ID :param dict filters: Dictionary of filters to apply: str status (eq) :returns: a list of :py:class:`User` objects :rtype: PaginatedResponse """ kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, User) api = self._get_api(iam.AccountAdminApi) return PaginatedResponse(api.get_all_users, lwrap_type=User, **kwargs)
python
def list_users(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, User) api = self._get_api(iam.AccountAdminApi) return PaginatedResponse(api.get_all_users, lwrap_type=User, **kwargs)
[ "def", "list_users", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "User", ")", "api", "=", "self", ".", "_get_...
List all users in organisation. :param int limit: The number of users to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get users after/starting at given user ID :param dict filters: Dictionary of filters to apply: str status (eq) :returns: a list of :py:class:`User` objects :rtype: PaginatedResponse
[ "List", "all", "users", "in", "organisation", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L130-L143
12,968
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.get_user
def get_user(self, user_id): """Get user details of specified user. :param str user_id: the ID of the user to get (Required) :returns: the user object with details about the user. :rtype: User """ api = self._get_api(iam.AccountAdminApi) return User(api.get_user(user_id))
python
def get_user(self, user_id): api = self._get_api(iam.AccountAdminApi) return User(api.get_user(user_id))
[ "def", "get_user", "(", "self", ",", "user_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "AccountAdminApi", ")", "return", "User", "(", "api", ".", "get_user", "(", "user_id", ")", ")" ]
Get user details of specified user. :param str user_id: the ID of the user to get (Required) :returns: the user object with details about the user. :rtype: User
[ "Get", "user", "details", "of", "specified", "user", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L146-L154
12,969
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.update_user
def update_user(self, user_id, **kwargs): """Update user properties of specified user. :param str user_id: The ID of the user to update (Required) :param str username: The unique username of the user :param str email: The unique email of the user :param str full_name: The full name of the user :param str password: The password string of the user. :param str phone_number: Phone number of the user :param bool terms_accepted: Is 'General Terms & Conditions' accepted :param bool marketing_accepted: Is receiving marketing information accepted? :returns: the updated user object :rtype: User """ api = self._get_api(iam.AccountAdminApi) user = User._create_request_map(kwargs) body = iam.UserUpdateReq(**user) return User(api.update_user(user_id, body))
python
def update_user(self, user_id, **kwargs): api = self._get_api(iam.AccountAdminApi) user = User._create_request_map(kwargs) body = iam.UserUpdateReq(**user) return User(api.update_user(user_id, body))
[ "def", "update_user", "(", "self", ",", "user_id", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "AccountAdminApi", ")", "user", "=", "User", ".", "_create_request_map", "(", "kwargs", ")", "body", "=", "iam",...
Update user properties of specified user. :param str user_id: The ID of the user to update (Required) :param str username: The unique username of the user :param str email: The unique email of the user :param str full_name: The full name of the user :param str password: The password string of the user. :param str phone_number: Phone number of the user :param bool terms_accepted: Is 'General Terms & Conditions' accepted :param bool marketing_accepted: Is receiving marketing information accepted? :returns: the updated user object :rtype: User
[ "Update", "user", "properties", "of", "specified", "user", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L157-L174
12,970
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.delete_user
def delete_user(self, user_id): """Delete user specified user. :param str user_id: the ID of the user to delete (Required) :returns: void """ api = self._get_api(iam.AccountAdminApi) api.delete_user(user_id) return
python
def delete_user(self, user_id): api = self._get_api(iam.AccountAdminApi) api.delete_user(user_id) return
[ "def", "delete_user", "(", "self", ",", "user_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "AccountAdminApi", ")", "api", ".", "delete_user", "(", "user_id", ")", "return" ]
Delete user specified user. :param str user_id: the ID of the user to delete (Required) :returns: void
[ "Delete", "user", "specified", "user", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L177-L185
12,971
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.add_user
def add_user(self, username, email, **kwargs): """Create a new user with provided details. Add user example: .. code-block:: python account_management_api = AccountManagementAPI() # Add user user = { "username": "test_user", "email": "test@gmail.com", "phone_number": "0123456789" } new_user = account_management_api.add_user(**user) :param str username: The unique username of the user (Required) :param str email: The unique email of the user (Required) :param str full_name: The full name of the user :param list groups: List of group IDs (`str`) which this user belongs to :param str password: The password string of the user :param str phone_number: Phone number of the user :param bool terms_accepted: 'General Terms & Conditions' have been accepted :param bool marketing_accepted: Marketing Information opt-in :returns: the new user object :rtype: User """ api = self._get_api(iam.AccountAdminApi) kwargs.update({'username': username, 'email': email}) user = User._create_request_map(kwargs) body = iam.UserUpdateReq(**user) return User(api.create_user(body))
python
def add_user(self, username, email, **kwargs): api = self._get_api(iam.AccountAdminApi) kwargs.update({'username': username, 'email': email}) user = User._create_request_map(kwargs) body = iam.UserUpdateReq(**user) return User(api.create_user(body))
[ "def", "add_user", "(", "self", ",", "username", ",", "email", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "AccountAdminApi", ")", "kwargs", ".", "update", "(", "{", "'username'", ":", "username", ",", "'e...
Create a new user with provided details. Add user example: .. code-block:: python account_management_api = AccountManagementAPI() # Add user user = { "username": "test_user", "email": "test@gmail.com", "phone_number": "0123456789" } new_user = account_management_api.add_user(**user) :param str username: The unique username of the user (Required) :param str email: The unique email of the user (Required) :param str full_name: The full name of the user :param list groups: List of group IDs (`str`) which this user belongs to :param str password: The password string of the user :param str phone_number: Phone number of the user :param bool terms_accepted: 'General Terms & Conditions' have been accepted :param bool marketing_accepted: Marketing Information opt-in :returns: the new user object :rtype: User
[ "Create", "a", "new", "user", "with", "provided", "details", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L188-L219
12,972
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.get_account
def get_account(self): """Get details of the current account. :returns: an account object. :rtype: Account """ api = self._get_api(iam.DeveloperApi) return Account(api.get_my_account_info(include="limits, policies"))
python
def get_account(self): api = self._get_api(iam.DeveloperApi) return Account(api.get_my_account_info(include="limits, policies"))
[ "def", "get_account", "(", "self", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "return", "Account", "(", "api", ".", "get_my_account_info", "(", "include", "=", "\"limits, policies\"", ")", ")" ]
Get details of the current account. :returns: an account object. :rtype: Account
[ "Get", "details", "of", "the", "current", "account", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L222-L229
12,973
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.update_account
def update_account(self, **kwargs): """Update details of account associated with current API key. :param str address_line1: Postal address line 1. :param str address_line2: Postal address line 2. :param str city: The city part of the postal address. :param str display_name: The display name for the account. :param str country: The country part of the postal address. :param str company: The name of the company. :param str state: The state part of the postal address. :param str contact: The name of the contact person for this account. :param str postal_code: The postal code part of the postal address. :param str parent_id: The ID of the parent account. :param str phone_number: The phone number of the company. :param str email: Email address for this account. :param list[str] aliases: List of aliases :returns: an account object. :rtype: Account """ api = self._get_api(iam.AccountAdminApi) account = Account._create_request_map(kwargs) body = AccountUpdateReq(**account) return Account(api.update_my_account(body))
python
def update_account(self, **kwargs): api = self._get_api(iam.AccountAdminApi) account = Account._create_request_map(kwargs) body = AccountUpdateReq(**account) return Account(api.update_my_account(body))
[ "def", "update_account", "(", "self", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "AccountAdminApi", ")", "account", "=", "Account", ".", "_create_request_map", "(", "kwargs", ")", "body", "=", "AccountUpdateReq...
Update details of account associated with current API key. :param str address_line1: Postal address line 1. :param str address_line2: Postal address line 2. :param str city: The city part of the postal address. :param str display_name: The display name for the account. :param str country: The country part of the postal address. :param str company: The name of the company. :param str state: The state part of the postal address. :param str contact: The name of the contact person for this account. :param str postal_code: The postal code part of the postal address. :param str parent_id: The ID of the parent account. :param str phone_number: The phone number of the company. :param str email: Email address for this account. :param list[str] aliases: List of aliases :returns: an account object. :rtype: Account
[ "Update", "details", "of", "account", "associated", "with", "current", "API", "key", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L232-L254
12,974
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.list_groups
def list_groups(self, **kwargs): """List all groups in organisation. :param int limit: The number of groups to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get groups after/starting at given group ID :returns: a list of :py:class:`Group` objects. :rtype: PaginatedResponse """ kwargs = self._verify_sort_options(kwargs) api = self._get_api(iam.DeveloperApi) return PaginatedResponse(api.get_all_groups, lwrap_type=Group, **kwargs)
python
def list_groups(self, **kwargs): kwargs = self._verify_sort_options(kwargs) api = self._get_api(iam.DeveloperApi) return PaginatedResponse(api.get_all_groups, lwrap_type=Group, **kwargs)
[ "def", "list_groups", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "return", "PaginatedResponse", "(", "...
List all groups in organisation. :param int limit: The number of groups to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get groups after/starting at given group ID :returns: a list of :py:class:`Group` objects. :rtype: PaginatedResponse
[ "List", "all", "groups", "in", "organisation", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L257-L268
12,975
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.get_group
def get_group(self, group_id): """Get details of the group. :param str group_id: The group ID (Required) :returns: :py:class:`Group` object. :rtype: Group """ api = self._get_api(iam.DeveloperApi) return Group(api.get_group_summary(group_id))
python
def get_group(self, group_id): api = self._get_api(iam.DeveloperApi) return Group(api.get_group_summary(group_id))
[ "def", "get_group", "(", "self", ",", "group_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "return", "Group", "(", "api", ".", "get_group_summary", "(", "group_id", ")", ")" ]
Get details of the group. :param str group_id: The group ID (Required) :returns: :py:class:`Group` object. :rtype: Group
[ "Get", "details", "of", "the", "group", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L271-L279
12,976
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.list_group_users
def list_group_users(self, group_id, **kwargs): """List users of a group. :param str group_id: The group ID (Required) :param int limit: The number of users to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get API keys after/starting at given user ID :returns: a list of :py:class:`User` objects. :rtype: PaginatedResponse """ kwargs["group_id"] = group_id kwargs = self._verify_sort_options(kwargs) api = self._get_api(iam.AccountAdminApi) return PaginatedResponse(api.get_users_of_group, lwrap_type=User, **kwargs)
python
def list_group_users(self, group_id, **kwargs): kwargs["group_id"] = group_id kwargs = self._verify_sort_options(kwargs) api = self._get_api(iam.AccountAdminApi) return PaginatedResponse(api.get_users_of_group, lwrap_type=User, **kwargs)
[ "def", "list_group_users", "(", "self", ",", "group_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"group_id\"", "]", "=", "group_id", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "api", "=", "self", ".", "_get_api", ...
List users of a group. :param str group_id: The group ID (Required) :param int limit: The number of users to retrieve :param str order: The ordering direction, ascending (asc) or descending (desc) :param str after: Get API keys after/starting at given user ID :returns: a list of :py:class:`User` objects. :rtype: PaginatedResponse
[ "List", "users", "of", "a", "group", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L282-L295
12,977
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/account_management/account_management.py
AccountManagementAPI.list_group_api_keys
def list_group_api_keys(self, group_id, **kwargs): """List API keys of a group. :param str group_id: The group ID (Required) :param int limit: The number of api keys to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc). :param str after: Get API keys after/starting at given api key ID. :returns: a list of :py:class:`ApiKey` objects. :rtype: PaginatedResponse """ kwargs["group_id"] = group_id kwargs = self._verify_sort_options(kwargs) api = self._get_api(iam.DeveloperApi) return PaginatedResponse(api.get_api_keys_of_group, lwrap_type=ApiKey, **kwargs)
python
def list_group_api_keys(self, group_id, **kwargs): kwargs["group_id"] = group_id kwargs = self._verify_sort_options(kwargs) api = self._get_api(iam.DeveloperApi) return PaginatedResponse(api.get_api_keys_of_group, lwrap_type=ApiKey, **kwargs)
[ "def", "list_group_api_keys", "(", "self", ",", "group_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"group_id\"", "]", "=", "group_id", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "api", "=", "self", ".", "_get_api",...
List API keys of a group. :param str group_id: The group ID (Required) :param int limit: The number of api keys to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc). :param str after: Get API keys after/starting at given api key ID. :returns: a list of :py:class:`ApiKey` objects. :rtype: PaginatedResponse
[ "List", "API", "keys", "of", "a", "group", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/account_management/account_management.py#L298-L311
12,978
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/async_wrapper.py
AsyncWrapper.defer
def defer(self, *args, **kwargs): """Call the function and immediately return an asynchronous object. The calling code will need to check for the result at a later time using: In Python 2/3 using ThreadPools - an AsyncResult (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.AsyncResult) In Python 3 using Asyncio - a Future (https://docs.python.org/3/library/asyncio-task.html#future) :param args: :param kwargs: :return: """ LOG.debug( '%s on %s (awaitable %s async %s provider %s)', 'deferring', self._func, self._is_awaitable, self._is_asyncio_provider, self._concurrency_provider ) if self._blocked: raise RuntimeError('Already activated this deferred call by blocking on it') with self._lock: if not self._deferable: func_partial = functools.partial(self._func, *args, **kwargs) # we are either: # - pure asyncio # - asyncio but with blocking function # - not asyncio, use threadpool self._deferable = ( # pure asyncio asyncio.ensure_future(func_partial(), loop=self._concurrency_provider) if self._is_awaitable else ( # asyncio blocked self._concurrency_provider.run_in_executor( func=func_partial, executor=None ) if self._is_asyncio_provider else ( # not asyncio self._concurrency_provider.apply_async(func_partial) ) ) ) return self._deferable
python
def defer(self, *args, **kwargs): LOG.debug( '%s on %s (awaitable %s async %s provider %s)', 'deferring', self._func, self._is_awaitable, self._is_asyncio_provider, self._concurrency_provider ) if self._blocked: raise RuntimeError('Already activated this deferred call by blocking on it') with self._lock: if not self._deferable: func_partial = functools.partial(self._func, *args, **kwargs) # we are either: # - pure asyncio # - asyncio but with blocking function # - not asyncio, use threadpool self._deferable = ( # pure asyncio asyncio.ensure_future(func_partial(), loop=self._concurrency_provider) if self._is_awaitable else ( # asyncio blocked self._concurrency_provider.run_in_executor( func=func_partial, executor=None ) if self._is_asyncio_provider else ( # not asyncio self._concurrency_provider.apply_async(func_partial) ) ) ) return self._deferable
[ "def", "defer", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "'%s on %s (awaitable %s async %s provider %s)'", ",", "'deferring'", ",", "self", ".", "_func", ",", "self", ".", "_is_awaitable", ",", "self", "."...
Call the function and immediately return an asynchronous object. The calling code will need to check for the result at a later time using: In Python 2/3 using ThreadPools - an AsyncResult (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.AsyncResult) In Python 3 using Asyncio - a Future (https://docs.python.org/3/library/asyncio-task.html#future) :param args: :param kwargs: :return:
[ "Call", "the", "function", "and", "immediately", "return", "an", "asynchronous", "object", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/async_wrapper.py#L70-L119
12,979
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/subscribe/async_wrapper.py
AsyncWrapper.block
def block(self, *args, **kwargs): """Call the wrapped function, and wait for the result in a blocking fashion Returns the result of the function call. :param args: :param kwargs: :return: result of function call """ LOG.debug( '%s on %s (awaitable %s async %s provider %s)', 'blocking', self._func, self._is_awaitable, self._is_asyncio_provider, self._concurrency_provider ) if self._deferable: raise RuntimeError('Already activated this call by deferring it') with self._lock: if not hasattr(self, '_result'): try: self._result = ( self._concurrency_provider.run_until_complete(self.defer(*args, **kwargs)) if self._is_asyncio_provider else self._func(*args, **kwargs) ) except queue.Empty: raise CloudTimeoutError("No data received after %.1f seconds." % kwargs.get("timeout", 0)) self._blocked = True return self._result
python
def block(self, *args, **kwargs): LOG.debug( '%s on %s (awaitable %s async %s provider %s)', 'blocking', self._func, self._is_awaitable, self._is_asyncio_provider, self._concurrency_provider ) if self._deferable: raise RuntimeError('Already activated this call by deferring it') with self._lock: if not hasattr(self, '_result'): try: self._result = ( self._concurrency_provider.run_until_complete(self.defer(*args, **kwargs)) if self._is_asyncio_provider else self._func(*args, **kwargs) ) except queue.Empty: raise CloudTimeoutError("No data received after %.1f seconds." % kwargs.get("timeout", 0)) self._blocked = True return self._result
[ "def", "block", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "'%s on %s (awaitable %s async %s provider %s)'", ",", "'blocking'", ",", "self", ".", "_func", ",", "self", ".", "_is_awaitable", ",", "self", ".",...
Call the wrapped function, and wait for the result in a blocking fashion Returns the result of the function call. :param args: :param kwargs: :return: result of function call
[ "Call", "the", "wrapped", "function", "and", "wait", "for", "the", "result", "in", "a", "blocking", "fashion" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/subscribe/async_wrapper.py#L121-L151
12,980
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/enrollment/models/enrollment_identities.py
EnrollmentIdentities.after
def after(self, after): """ Sets the after of this EnrollmentIdentities. ID :param after: The after of this EnrollmentIdentities. :type: str """ if after is None: raise ValueError("Invalid value for `after`, must not be `None`") if after is not None and not re.search('^[A-Za-z0-9]{32}', after): raise ValueError("Invalid value for `after`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`") self._after = after
python
def after(self, after): if after is None: raise ValueError("Invalid value for `after`, must not be `None`") if after is not None and not re.search('^[A-Za-z0-9]{32}', after): raise ValueError("Invalid value for `after`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`") self._after = after
[ "def", "after", "(", "self", ",", "after", ")", ":", "if", "after", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `after`, must not be `None`\"", ")", "if", "after", "is", "not", "None", "and", "not", "re", ".", "search", "(", "'^[A-Za-...
Sets the after of this EnrollmentIdentities. ID :param after: The after of this EnrollmentIdentities. :type: str
[ "Sets", "the", "after", "of", "this", "EnrollmentIdentities", ".", "ID" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/enrollment/models/enrollment_identities.py#L79-L92
12,981
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/enrollment/models/enrollment_identities.py
EnrollmentIdentities.order
def order(self, order): """ Sets the order of this EnrollmentIdentities. :param order: The order of this EnrollmentIdentities. :type: str """ if order is None: raise ValueError("Invalid value for `order`, must not be `None`") allowed_values = ["ASC", "DESC"] if order not in allowed_values: raise ValueError( "Invalid value for `order` ({0}), must be one of {1}" .format(order, allowed_values) ) self._order = order
python
def order(self, order): if order is None: raise ValueError("Invalid value for `order`, must not be `None`") allowed_values = ["ASC", "DESC"] if order not in allowed_values: raise ValueError( "Invalid value for `order` ({0}), must be one of {1}" .format(order, allowed_values) ) self._order = order
[ "def", "order", "(", "self", ",", "order", ")", ":", "if", "order", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `order`, must not be `None`\"", ")", "allowed_values", "=", "[", "\"ASC\"", ",", "\"DESC\"", "]", "if", "order", "not", "in"...
Sets the order of this EnrollmentIdentities. :param order: The order of this EnrollmentIdentities. :type: str
[ "Sets", "the", "order", "of", "this", "EnrollmentIdentities", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/enrollment/models/enrollment_identities.py#L209-L225
12,982
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/update_service/models/update_campaign.py
UpdateCampaign.health_indicator
def health_indicator(self, health_indicator): """ Sets the health_indicator of this UpdateCampaign. An indication to the condition of the campaign. :param health_indicator: The health_indicator of this UpdateCampaign. :type: str """ allowed_values = ["ok", "warning", "error"] if health_indicator not in allowed_values: raise ValueError( "Invalid value for `health_indicator` ({0}), must be one of {1}" .format(health_indicator, allowed_values) ) self._health_indicator = health_indicator
python
def health_indicator(self, health_indicator): allowed_values = ["ok", "warning", "error"] if health_indicator not in allowed_values: raise ValueError( "Invalid value for `health_indicator` ({0}), must be one of {1}" .format(health_indicator, allowed_values) ) self._health_indicator = health_indicator
[ "def", "health_indicator", "(", "self", ",", "health_indicator", ")", ":", "allowed_values", "=", "[", "\"ok\"", ",", "\"warning\"", ",", "\"error\"", "]", "if", "health_indicator", "not", "in", "allowed_values", ":", "raise", "ValueError", "(", "\"Invalid value f...
Sets the health_indicator of this UpdateCampaign. An indication to the condition of the campaign. :param health_indicator: The health_indicator of this UpdateCampaign. :type: str
[ "Sets", "the", "health_indicator", "of", "this", "UpdateCampaign", ".", "An", "indication", "to", "the", "condition", "of", "the", "campaign", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/update_service/models/update_campaign.py#L249-L264
12,983
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/billing/models/service_package_quota.py
ServicePackageQuota.quota
def quota(self, quota): """ Sets the quota of this ServicePackageQuota. Available quota for the service package. :param quota: The quota of this ServicePackageQuota. :type: int """ if quota is None: raise ValueError("Invalid value for `quota`, must not be `None`") if quota is not None and quota < 0: raise ValueError("Invalid value for `quota`, must be a value greater than or equal to `0`") self._quota = quota
python
def quota(self, quota): if quota is None: raise ValueError("Invalid value for `quota`, must not be `None`") if quota is not None and quota < 0: raise ValueError("Invalid value for `quota`, must be a value greater than or equal to `0`") self._quota = quota
[ "def", "quota", "(", "self", ",", "quota", ")", ":", "if", "quota", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `quota`, must not be `None`\"", ")", "if", "quota", "is", "not", "None", "and", "quota", "<", "0", ":", "raise", "ValueErr...
Sets the quota of this ServicePackageQuota. Available quota for the service package. :param quota: The quota of this ServicePackageQuota. :type: int
[ "Sets", "the", "quota", "of", "this", "ServicePackageQuota", ".", "Available", "quota", "for", "the", "service", "package", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/billing/models/service_package_quota.py#L95-L108
12,984
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/enrollment/models/enrollment_identity.py
EnrollmentIdentity.enrolled_device_id
def enrolled_device_id(self, enrolled_device_id): """ Sets the enrolled_device_id of this EnrollmentIdentity. The ID of the device in the Device Directory once it has been registered. :param enrolled_device_id: The enrolled_device_id of this EnrollmentIdentity. :type: str """ if enrolled_device_id is None: raise ValueError("Invalid value for `enrolled_device_id`, must not be `None`") if enrolled_device_id is not None and not re.search('^[A-Za-z0-9]{32}', enrolled_device_id): raise ValueError("Invalid value for `enrolled_device_id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`") self._enrolled_device_id = enrolled_device_id
python
def enrolled_device_id(self, enrolled_device_id): if enrolled_device_id is None: raise ValueError("Invalid value for `enrolled_device_id`, must not be `None`") if enrolled_device_id is not None and not re.search('^[A-Za-z0-9]{32}', enrolled_device_id): raise ValueError("Invalid value for `enrolled_device_id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`") self._enrolled_device_id = enrolled_device_id
[ "def", "enrolled_device_id", "(", "self", ",", "enrolled_device_id", ")", ":", "if", "enrolled_device_id", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `enrolled_device_id`, must not be `None`\"", ")", "if", "enrolled_device_id", "is", "not", "None"...
Sets the enrolled_device_id of this EnrollmentIdentity. The ID of the device in the Device Directory once it has been registered. :param enrolled_device_id: The enrolled_device_id of this EnrollmentIdentity. :type: str
[ "Sets", "the", "enrolled_device_id", "of", "this", "EnrollmentIdentity", ".", "The", "ID", "of", "the", "device", "in", "the", "Device", "Directory", "once", "it", "has", "been", "registered", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/enrollment/models/enrollment_identity.py#L160-L173
12,985
ARMmbed/mbed-cloud-sdk-python
scripts/assert_news.py
main
def main(news_dir=None): """Checks for existence of a new newsfile""" if news_dir is None: from generate_news import news_dir news_dir = os.path.abspath(news_dir) # assume the name of the remote alias is just 'origin' remote_alias = 'origin' # figure out what the 'default branch' for the origin is origin_stats = subprocess.check_output( ['git', 'remote', 'show', remote_alias], cwd=news_dir ).decode() # the output of the git command looks like: # ' HEAD branch: master' origin_branch = 'master' # unless we prove otherwise for line in origin_stats.splitlines(): if 'head branch:' in line.lower(): origin_branch = line.split(':', 1)[-1].strip() break origin = '%s/%s' % (remote_alias, origin_branch) # figure out the current branch current_branch = subprocess.check_output( ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], cwd=news_dir ).decode().strip() print(':: Finding news in `%s` to add to remote `%s`' % (current_branch, origin)) diff_command = ['git', 'diff', '%s...%s' % (origin, current_branch), '--name-status', news_dir] file_diff = subprocess.check_output( diff_command, cwd=news_dir ).decode() # the output of the git command looks like: # 'A docs/news/789.feature' # [optional] ensure we have an addition, rather than just modify/delete added_news = [line for line in file_diff.splitlines() if line.lower().strip().startswith('a')] # pass or fail if not added_news: print( '! Error: Uh-oh, did not find any news files!\n' '! Please add a news file to `%s`\n' '+ File diff:\n%s\n' '{} Git diff command:\n`%s`\n' % ( news_dir, file_diff.strip(), subprocess.list2cmdline(diff_command) ) ) exit(1) # exit with an error status, no need for a traceback print(':: %s new files in `%s`' % (len(added_news), news_dir))
python
def main(news_dir=None): if news_dir is None: from generate_news import news_dir news_dir = os.path.abspath(news_dir) # assume the name of the remote alias is just 'origin' remote_alias = 'origin' # figure out what the 'default branch' for the origin is origin_stats = subprocess.check_output( ['git', 'remote', 'show', remote_alias], cwd=news_dir ).decode() # the output of the git command looks like: # ' HEAD branch: master' origin_branch = 'master' # unless we prove otherwise for line in origin_stats.splitlines(): if 'head branch:' in line.lower(): origin_branch = line.split(':', 1)[-1].strip() break origin = '%s/%s' % (remote_alias, origin_branch) # figure out the current branch current_branch = subprocess.check_output( ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], cwd=news_dir ).decode().strip() print(':: Finding news in `%s` to add to remote `%s`' % (current_branch, origin)) diff_command = ['git', 'diff', '%s...%s' % (origin, current_branch), '--name-status', news_dir] file_diff = subprocess.check_output( diff_command, cwd=news_dir ).decode() # the output of the git command looks like: # 'A docs/news/789.feature' # [optional] ensure we have an addition, rather than just modify/delete added_news = [line for line in file_diff.splitlines() if line.lower().strip().startswith('a')] # pass or fail if not added_news: print( '! Error: Uh-oh, did not find any news files!\n' '! Please add a news file to `%s`\n' '+ File diff:\n%s\n' '{} Git diff command:\n`%s`\n' % ( news_dir, file_diff.strip(), subprocess.list2cmdline(diff_command) ) ) exit(1) # exit with an error status, no need for a traceback print(':: %s new files in `%s`' % (len(added_news), news_dir))
[ "def", "main", "(", "news_dir", "=", "None", ")", ":", "if", "news_dir", "is", "None", ":", "from", "generate_news", "import", "news_dir", "news_dir", "=", "os", ".", "path", ".", "abspath", "(", "news_dir", ")", "# assume the name of the remote alias is just 'o...
Checks for existence of a new newsfile
[ "Checks", "for", "existence", "of", "a", "new", "newsfile" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/assert_news.py#L24-L81
12,986
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/update_service/models/campaign_device_metadata.py
CampaignDeviceMetadata.deployment_state
def deployment_state(self, deployment_state): """ Sets the deployment_state of this CampaignDeviceMetadata. The state of the update campaign on the device :param deployment_state: The deployment_state of this CampaignDeviceMetadata. :type: str """ allowed_values = ["pending", "updated_connector_channel", "failed_connector_channel_update", "deployed", "manifestremoved", "deregistered"] if deployment_state not in allowed_values: raise ValueError( "Invalid value for `deployment_state` ({0}), must be one of {1}" .format(deployment_state, allowed_values) ) self._deployment_state = deployment_state
python
def deployment_state(self, deployment_state): allowed_values = ["pending", "updated_connector_channel", "failed_connector_channel_update", "deployed", "manifestremoved", "deregistered"] if deployment_state not in allowed_values: raise ValueError( "Invalid value for `deployment_state` ({0}), must be one of {1}" .format(deployment_state, allowed_values) ) self._deployment_state = deployment_state
[ "def", "deployment_state", "(", "self", ",", "deployment_state", ")", ":", "allowed_values", "=", "[", "\"pending\"", ",", "\"updated_connector_channel\"", ",", "\"failed_connector_channel_update\"", ",", "\"deployed\"", ",", "\"manifestremoved\"", ",", "\"deregistered\"", ...
Sets the deployment_state of this CampaignDeviceMetadata. The state of the update campaign on the device :param deployment_state: The deployment_state of this CampaignDeviceMetadata. :type: str
[ "Sets", "the", "deployment_state", "of", "this", "CampaignDeviceMetadata", ".", "The", "state", "of", "the", "update", "campaign", "on", "the", "device" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/update_service/models/campaign_device_metadata.py#L140-L155
12,987
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/certificates/certificates.py
CertificatesAPI.list_certificates
def list_certificates(self, **kwargs): """List certificates registered to organisation. Currently returns partially populated certificates. To obtain the full certificate object: `[get_certificate(certificate_id=cert['id']) for cert in list_certificates]` :param int limit: The number of certificates to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc). :param str after: Get certificates after/starting at given `certificate_id`. :param dict filters: Dictionary of filters to apply: type (eq), expire (eq), owner (eq) :return: list of :py:class:`Certificate` objects :rtype: Certificate """ kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Certificate) if "service__eq" in kwargs: if kwargs["service__eq"] == CertificateType.bootstrap: pass elif kwargs["service__eq"] == CertificateType.developer: kwargs["device_execution_mode__eq"] = 1 kwargs.pop("service__eq") elif kwargs["service__eq"] == CertificateType.lwm2m: pass else: raise CloudValueError( "Incorrect value for CertificateType filter: %s" % (kwargs["service__eq"]) ) owner = kwargs.pop('owner_id__eq', None) if owner is not None: kwargs['owner__eq'] = owner api = self._get_api(iam.DeveloperApi) return PaginatedResponse(api.get_all_certificates, lwrap_type=Certificate, **kwargs)
python
def list_certificates(self, **kwargs): kwargs = self._verify_sort_options(kwargs) kwargs = self._verify_filters(kwargs, Certificate) if "service__eq" in kwargs: if kwargs["service__eq"] == CertificateType.bootstrap: pass elif kwargs["service__eq"] == CertificateType.developer: kwargs["device_execution_mode__eq"] = 1 kwargs.pop("service__eq") elif kwargs["service__eq"] == CertificateType.lwm2m: pass else: raise CloudValueError( "Incorrect value for CertificateType filter: %s" % (kwargs["service__eq"]) ) owner = kwargs.pop('owner_id__eq', None) if owner is not None: kwargs['owner__eq'] = owner api = self._get_api(iam.DeveloperApi) return PaginatedResponse(api.get_all_certificates, lwrap_type=Certificate, **kwargs)
[ "def", "list_certificates", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_verify_sort_options", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_verify_filters", "(", "kwargs", ",", "Certificate", ")", "if", "\"service__eq\""...
List certificates registered to organisation. Currently returns partially populated certificates. To obtain the full certificate object: `[get_certificate(certificate_id=cert['id']) for cert in list_certificates]` :param int limit: The number of certificates to retrieve. :param str order: The ordering direction, ascending (asc) or descending (desc). :param str after: Get certificates after/starting at given `certificate_id`. :param dict filters: Dictionary of filters to apply: type (eq), expire (eq), owner (eq) :return: list of :py:class:`Certificate` objects :rtype: Certificate
[ "List", "certificates", "registered", "to", "organisation", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/certificates/certificates.py#L52-L84
12,988
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/certificates/certificates.py
CertificatesAPI.get_certificate
def get_certificate(self, certificate_id): """Get certificate by id. :param str certificate_id: The certificate id (Required) :returns: Certificate object :rtype: Certificate """ api = self._get_api(iam.DeveloperApi) certificate = Certificate(api.get_certificate(certificate_id)) self._extend_certificate(certificate) return certificate
python
def get_certificate(self, certificate_id): api = self._get_api(iam.DeveloperApi) certificate = Certificate(api.get_certificate(certificate_id)) self._extend_certificate(certificate) return certificate
[ "def", "get_certificate", "(", "self", ",", "certificate_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "iam", ".", "DeveloperApi", ")", "certificate", "=", "Certificate", "(", "api", ".", "get_certificate", "(", "certificate_id", ")", ")", "self",...
Get certificate by id. :param str certificate_id: The certificate id (Required) :returns: Certificate object :rtype: Certificate
[ "Get", "certificate", "by", "id", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/certificates/certificates.py#L87-L97
12,989
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/certificates/certificates.py
CertificatesAPI.add_certificate
def add_certificate(self, name, type, certificate_data, signature=None, **kwargs): """Add a new BYOC certificate. :param str name: name of the certificate (Required) :param str type: type of the certificate. Values: lwm2m or bootstrap (Required) :param str certificate_data: X509.v3 trusted certificate in PEM format. (Required) :param str signature: This parameter has been DEPRECATED in the API and does not need to be provided. :param str status: Status of the certificate. Allowed values: "ACTIVE" | "INACTIVE". :param str description: Human readable description of this certificate, not longer than 500 characters. :returns: Certificate object :rtype: Certificate """ kwargs.update({'name': name}) kwargs.update({'type': type}) api = self._get_api(iam.AccountAdminApi) kwargs.update({'certificate_data': certificate_data}) certificate = Certificate._create_request_map(kwargs) if not certificate.get('enrollment_mode') and signature: certificate.update({'signature': signature}) body = iam.TrustedCertificateReq(**certificate) prod_cert = api.add_certificate(body) return self.get_certificate(prod_cert.id)
python
def add_certificate(self, name, type, certificate_data, signature=None, **kwargs): kwargs.update({'name': name}) kwargs.update({'type': type}) api = self._get_api(iam.AccountAdminApi) kwargs.update({'certificate_data': certificate_data}) certificate = Certificate._create_request_map(kwargs) if not certificate.get('enrollment_mode') and signature: certificate.update({'signature': signature}) body = iam.TrustedCertificateReq(**certificate) prod_cert = api.add_certificate(body) return self.get_certificate(prod_cert.id)
[ "def", "add_certificate", "(", "self", ",", "name", ",", "type", ",", "certificate_data", ",", "signature", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'name'", ":", "name", "}", ")", "kwargs", ".", "update", "...
Add a new BYOC certificate. :param str name: name of the certificate (Required) :param str type: type of the certificate. Values: lwm2m or bootstrap (Required) :param str certificate_data: X509.v3 trusted certificate in PEM format. (Required) :param str signature: This parameter has been DEPRECATED in the API and does not need to be provided. :param str status: Status of the certificate. Allowed values: "ACTIVE" | "INACTIVE". :param str description: Human readable description of this certificate, not longer than 500 characters. :returns: Certificate object :rtype: Certificate
[ "Add", "a", "new", "BYOC", "certificate", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/certificates/certificates.py#L126-L151
12,990
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/certificates/certificates.py
CertificatesAPI.add_developer_certificate
def add_developer_certificate(self, name, **kwargs): """Add a new developer certificate. :param str name: name of the certificate (Required) :param str description: Human readable description of this certificate, not longer than 500 characters. :returns: Certificate object :rtype: Certificate """ kwargs['name'] = name api = self._get_api(cert.DeveloperCertificateApi) certificate = Certificate._create_request_map(kwargs) # just pull the fields we care about subset = cert.DeveloperCertificateRequestData.attribute_map certificate = {k: v for k, v in certificate.items() if k in subset} body = cert.DeveloperCertificateRequestData(**certificate) dev_cert = api.create_developer_certificate(self.auth, body) return self.get_certificate(dev_cert.id)
python
def add_developer_certificate(self, name, **kwargs): kwargs['name'] = name api = self._get_api(cert.DeveloperCertificateApi) certificate = Certificate._create_request_map(kwargs) # just pull the fields we care about subset = cert.DeveloperCertificateRequestData.attribute_map certificate = {k: v for k, v in certificate.items() if k in subset} body = cert.DeveloperCertificateRequestData(**certificate) dev_cert = api.create_developer_certificate(self.auth, body) return self.get_certificate(dev_cert.id)
[ "def", "add_developer_certificate", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'name'", "]", "=", "name", "api", "=", "self", ".", "_get_api", "(", "cert", ".", "DeveloperCertificateApi", ")", "certificate", "=", "Certific...
Add a new developer certificate. :param str name: name of the certificate (Required) :param str description: Human readable description of this certificate, not longer than 500 characters. :returns: Certificate object :rtype: Certificate
[ "Add", "a", "new", "developer", "certificate", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/certificates/certificates.py#L154-L173
12,991
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/certificates/certificates.py
Certificate.type
def type(self): """Certificate type. :return: The type of the certificate. :rtype: CertificateType """ if self._device_mode == 1 or self._type == CertificateType.developer: return CertificateType.developer elif self._type == CertificateType.bootstrap: return CertificateType.bootstrap else: return CertificateType.lwm2m
python
def type(self): if self._device_mode == 1 or self._type == CertificateType.developer: return CertificateType.developer elif self._type == CertificateType.bootstrap: return CertificateType.bootstrap else: return CertificateType.lwm2m
[ "def", "type", "(", "self", ")", ":", "if", "self", ".", "_device_mode", "==", "1", "or", "self", ".", "_type", "==", "CertificateType", ".", "developer", ":", "return", "CertificateType", ".", "developer", "elif", "self", ".", "_type", "==", "CertificateT...
Certificate type. :return: The type of the certificate. :rtype: CertificateType
[ "Certificate", "type", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/certificates/certificates.py#L321-L332
12,992
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/notifications.py
handle_channel_message
def handle_channel_message(db, queues, b64decode, notification_object): """Handler for notification channels Given a NotificationMessage object, update internal state, notify any subscribers and resolve async deferred tasks. :param db: :param queues: :param b64decode: :param notification_object: :return: """ for notification in getattr(notification_object, 'notifications') or []: # Ensure we have subscribed for the path we received a notification for subscriber_queue = queues[notification.ep].get(notification.path) if subscriber_queue is None: LOG.debug( "Ignoring notification on %s (%s) as no subscription is registered", notification.ep, notification.path ) break payload = tlv.decode( payload=notification.payload, content_type=notification.ct, decode_b64=b64decode ) subscriber_queue.put(payload) for response in getattr(notification_object, 'async_responses') or []: payload = tlv.decode( payload=response.payload, content_type=response.ct, decode_b64=b64decode ) db.update({response.id: dict( payload=payload, error=response.error, status_code=response.status )})
python
def handle_channel_message(db, queues, b64decode, notification_object): for notification in getattr(notification_object, 'notifications') or []: # Ensure we have subscribed for the path we received a notification for subscriber_queue = queues[notification.ep].get(notification.path) if subscriber_queue is None: LOG.debug( "Ignoring notification on %s (%s) as no subscription is registered", notification.ep, notification.path ) break payload = tlv.decode( payload=notification.payload, content_type=notification.ct, decode_b64=b64decode ) subscriber_queue.put(payload) for response in getattr(notification_object, 'async_responses') or []: payload = tlv.decode( payload=response.payload, content_type=response.ct, decode_b64=b64decode ) db.update({response.id: dict( payload=payload, error=response.error, status_code=response.status )})
[ "def", "handle_channel_message", "(", "db", ",", "queues", ",", "b64decode", ",", "notification_object", ")", ":", "for", "notification", "in", "getattr", "(", "notification_object", ",", "'notifications'", ")", "or", "[", "]", ":", "# Ensure we have subscribed for ...
Handler for notification channels Given a NotificationMessage object, update internal state, notify any subscribers and resolve async deferred tasks. :param db: :param queues: :param b64decode: :param notification_object: :return:
[ "Handler", "for", "notification", "channels" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/notifications.py#L167-L207
12,993
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/notifications.py
AsyncConsumer.value
def value(self): """Get the value of the finished async request, if it is available. :raises CloudUnhandledError: When not checking value of `error` or `is_done` first :return: the payload value :rtype: str """ status_code, error_msg, payload = self.check_error() if not self._status_ok(status_code) and not payload: raise CloudUnhandledError("Attempted to decode async request which returned an error.", reason=error_msg, status=status_code) return self.db[self.async_id]["payload"]
python
def value(self): status_code, error_msg, payload = self.check_error() if not self._status_ok(status_code) and not payload: raise CloudUnhandledError("Attempted to decode async request which returned an error.", reason=error_msg, status=status_code) return self.db[self.async_id]["payload"]
[ "def", "value", "(", "self", ")", ":", "status_code", ",", "error_msg", ",", "payload", "=", "self", ".", "check_error", "(", ")", "if", "not", "self", ".", "_status_ok", "(", "status_code", ")", "and", "not", "payload", ":", "raise", "CloudUnhandledError"...
Get the value of the finished async request, if it is available. :raises CloudUnhandledError: When not checking value of `error` or `is_done` first :return: the payload value :rtype: str
[ "Get", "the", "value", "of", "the", "finished", "async", "request", "if", "it", "is", "available", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/notifications.py#L143-L156
12,994
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/notifications.py
NotificationsThread.run
def run(self): """Thread main loop""" retries = 0 try: while not self._stopping: try: data = self.notifications_api.long_poll_notifications() except mds.rest.ApiException as e: # An HTTP 410 can be raised when stopping so don't log anything if not self._stopping: backoff = 2 ** retries - random.randint(int(retries / 2), retries) LOG.error('Notification long poll failed with exception (retry in %d seconds):\n%s', backoff, e) retries += 1 # Backoff for an increasing amount of time until we have tried 10 times, then reset the backoff. if retries >= 10: retries = 0 time.sleep(backoff) else: handle_channel_message( db=self.db, queues=self.queues, b64decode=self._b64decode, notification_object=data ) if self.subscription_manager: self.subscription_manager.notify(data.to_dict()) finally: self._stopped.set()
python
def run(self): retries = 0 try: while not self._stopping: try: data = self.notifications_api.long_poll_notifications() except mds.rest.ApiException as e: # An HTTP 410 can be raised when stopping so don't log anything if not self._stopping: backoff = 2 ** retries - random.randint(int(retries / 2), retries) LOG.error('Notification long poll failed with exception (retry in %d seconds):\n%s', backoff, e) retries += 1 # Backoff for an increasing amount of time until we have tried 10 times, then reset the backoff. if retries >= 10: retries = 0 time.sleep(backoff) else: handle_channel_message( db=self.db, queues=self.queues, b64decode=self._b64decode, notification_object=data ) if self.subscription_manager: self.subscription_manager.notify(data.to_dict()) finally: self._stopped.set()
[ "def", "run", "(", "self", ")", ":", "retries", "=", "0", "try", ":", "while", "not", "self", ".", "_stopping", ":", "try", ":", "data", "=", "self", ".", "notifications_api", ".", "long_poll_notifications", "(", ")", "except", "mds", ".", "rest", ".",...
Thread main loop
[ "Thread", "main", "loop" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/notifications.py#L230-L257
12,995
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/external_ca/models/create_certificate_issuer_config.py
CreateCertificateIssuerConfig.certificate_issuer_id
def certificate_issuer_id(self, certificate_issuer_id): """ Sets the certificate_issuer_id of this CreateCertificateIssuerConfig. The ID of the certificate issuer. :param certificate_issuer_id: The certificate_issuer_id of this CreateCertificateIssuerConfig. :type: str """ if certificate_issuer_id is None: raise ValueError("Invalid value for `certificate_issuer_id`, must not be `None`") if certificate_issuer_id is not None and len(certificate_issuer_id) > 32: raise ValueError("Invalid value for `certificate_issuer_id`, length must be less than or equal to `32`") self._certificate_issuer_id = certificate_issuer_id
python
def certificate_issuer_id(self, certificate_issuer_id): if certificate_issuer_id is None: raise ValueError("Invalid value for `certificate_issuer_id`, must not be `None`") if certificate_issuer_id is not None and len(certificate_issuer_id) > 32: raise ValueError("Invalid value for `certificate_issuer_id`, length must be less than or equal to `32`") self._certificate_issuer_id = certificate_issuer_id
[ "def", "certificate_issuer_id", "(", "self", ",", "certificate_issuer_id", ")", ":", "if", "certificate_issuer_id", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `certificate_issuer_id`, must not be `None`\"", ")", "if", "certificate_issuer_id", "is", ...
Sets the certificate_issuer_id of this CreateCertificateIssuerConfig. The ID of the certificate issuer. :param certificate_issuer_id: The certificate_issuer_id of this CreateCertificateIssuerConfig. :type: str
[ "Sets", "the", "certificate_issuer_id", "of", "this", "CreateCertificateIssuerConfig", ".", "The", "ID", "of", "the", "certificate", "issuer", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/external_ca/models/create_certificate_issuer_config.py#L64-L77
12,996
ARMmbed/mbed-cloud-sdk-python
examples/connect/webhook_ngrok.py
my_application
def my_application(api): """An example application. - Registers a webhook with mbed cloud services - Requests the value of a resource - Prints the value when it arrives """ device = api.list_connected_devices().first() print('using device #', device.id) api.delete_device_subscriptions(device.id) try: print('setting webhook url to:', ngrok_url) api.update_webhook(ngrok_url) print('requesting resource value for:', resource_path) deferred = api.get_resource_value_async(device_id=device.id, resource_path=resource_path) print('waiting for async #', deferred.async_id) result = deferred.wait(15) print('webhook sent us this payload value:', repr(result)) return result except Exception: print(traceback.format_exc()) finally: api.delete_webhook() print("Deregistered and unsubscribed from all resources. Exiting.") exit(1)
python
def my_application(api): device = api.list_connected_devices().first() print('using device #', device.id) api.delete_device_subscriptions(device.id) try: print('setting webhook url to:', ngrok_url) api.update_webhook(ngrok_url) print('requesting resource value for:', resource_path) deferred = api.get_resource_value_async(device_id=device.id, resource_path=resource_path) print('waiting for async #', deferred.async_id) result = deferred.wait(15) print('webhook sent us this payload value:', repr(result)) return result except Exception: print(traceback.format_exc()) finally: api.delete_webhook() print("Deregistered and unsubscribed from all resources. Exiting.") exit(1)
[ "def", "my_application", "(", "api", ")", ":", "device", "=", "api", ".", "list_connected_devices", "(", ")", ".", "first", "(", ")", "print", "(", "'using device #'", ",", "device", ".", "id", ")", "api", ".", "delete_device_subscriptions", "(", "device", ...
An example application. - Registers a webhook with mbed cloud services - Requests the value of a resource - Prints the value when it arrives
[ "An", "example", "application", "." ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/examples/connect/webhook_ngrok.py#L82-L107
12,997
ARMmbed/mbed-cloud-sdk-python
examples/connect/webhook_ngrok.py
webhook_handler
def webhook_handler(request): """Receives the webhook from mbed cloud services Passes the raw http body directly to mbed sdk, to notify that a webhook was received """ body = request.stream.read().decode('utf8') print('webhook handler saw:', body) api.notify_webhook_received(payload=body) # nb. protected references are not part of the API. # this is just to demonstrate that the asyncid is stored print('key store contains:', api._db.keys())
python
def webhook_handler(request): body = request.stream.read().decode('utf8') print('webhook handler saw:', body) api.notify_webhook_received(payload=body) # nb. protected references are not part of the API. # this is just to demonstrate that the asyncid is stored print('key store contains:', api._db.keys())
[ "def", "webhook_handler", "(", "request", ")", ":", "body", "=", "request", ".", "stream", ".", "read", "(", ")", ".", "decode", "(", "'utf8'", ")", "print", "(", "'webhook handler saw:'", ",", "body", ")", "api", ".", "notify_webhook_received", "(", "payl...
Receives the webhook from mbed cloud services Passes the raw http body directly to mbed sdk, to notify that a webhook was received
[ "Receives", "the", "webhook", "from", "mbed", "cloud", "services" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/examples/connect/webhook_ngrok.py#L111-L122
12,998
ARMmbed/mbed-cloud-sdk-python
examples/connect/webhook_ngrok.py
start_sequence
def start_sequence(): """Start the demo sequence We must start this thread in the same process as the webserver to be certain we are sharing the api instance in memory. (ideally in future the async id database will be capable of being more than just a dictionary) """ print('getting started!...') t = threading.Thread(target=my_application, kwargs=dict(api=api)) t.daemon = True t.start() return 'ok, starting webhook to: %s' % (ngrok_url,)
python
def start_sequence(): print('getting started!...') t = threading.Thread(target=my_application, kwargs=dict(api=api)) t.daemon = True t.start() return 'ok, starting webhook to: %s' % (ngrok_url,)
[ "def", "start_sequence", "(", ")", ":", "print", "(", "'getting started!...'", ")", "t", "=", "threading", ".", "Thread", "(", "target", "=", "my_application", ",", "kwargs", "=", "dict", "(", "api", "=", "api", ")", ")", "t", ".", "daemon", "=", "True...
Start the demo sequence We must start this thread in the same process as the webserver to be certain we are sharing the api instance in memory. (ideally in future the async id database will be capable of being more than just a dictionary)
[ "Start", "the", "demo", "sequence" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/examples/connect/webhook_ngrok.py#L126-L139
12,999
ARMmbed/mbed-cloud-sdk-python
scripts/generate_ci_config.py
new_preload
def new_preload(): """Job running prior to builds - fetches TestRunner image""" testrunner_image = get_testrunner_image() local_image = testrunner_image.rsplit(':')[-2].rsplit('/')[-1] version_file = 'testrunner_version.txt' template = yaml.safe_load(f""" machine: image: 'circleci/classic:201710-02' steps: - run: name: AWS login command: |- login="$(aws ecr get-login --no-include-email)" ${{login}} - run: name: Pull TestRunner Image command: docker pull {testrunner_image} - run: name: Make cache directory command: mkdir -p {cache_dir} - run: name: Obtain Testrunner Version command: echo $(docker run {testrunner_image} python -m trunner --version) > {cache_dir}/{version_file} - run: name: Export docker image layer cache command: docker save -o {cache_dir}/{testrunner_cache} {testrunner_image} - persist_to_workspace: # workspace is used later in this same build root: {cache_dir} paths: '{testrunner_cache}' - persist_to_workspace: # workspace is used later in this same build root: {cache_dir} paths: '{version_file}' - store_artifacts: path: {version_file} """) return 'preload', template
python
def new_preload(): testrunner_image = get_testrunner_image() local_image = testrunner_image.rsplit(':')[-2].rsplit('/')[-1] version_file = 'testrunner_version.txt' template = yaml.safe_load(f""" machine: image: 'circleci/classic:201710-02' steps: - run: name: AWS login command: |- login="$(aws ecr get-login --no-include-email)" ${{login}} - run: name: Pull TestRunner Image command: docker pull {testrunner_image} - run: name: Make cache directory command: mkdir -p {cache_dir} - run: name: Obtain Testrunner Version command: echo $(docker run {testrunner_image} python -m trunner --version) > {cache_dir}/{version_file} - run: name: Export docker image layer cache command: docker save -o {cache_dir}/{testrunner_cache} {testrunner_image} - persist_to_workspace: # workspace is used later in this same build root: {cache_dir} paths: '{testrunner_cache}' - persist_to_workspace: # workspace is used later in this same build root: {cache_dir} paths: '{version_file}' - store_artifacts: path: {version_file} """) return 'preload', template
[ "def", "new_preload", "(", ")", ":", "testrunner_image", "=", "get_testrunner_image", "(", ")", "local_image", "=", "testrunner_image", ".", "rsplit", "(", "':'", ")", "[", "-", "2", "]", ".", "rsplit", "(", "'/'", ")", "[", "-", "1", "]", "version_file"...
Job running prior to builds - fetches TestRunner image
[ "Job", "running", "prior", "to", "builds", "-", "fetches", "TestRunner", "image" ]
c0af86fb2cdd4dc7ed26f236139241067d293509
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/generate_ci_config.py#L123-L158