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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.search
def search(self, q, resolve=True, result_type=None, account_id=None, offset=None, min_id=None, max_id=None): """ Fetch matching hashtags, accounts and statuses. Will perform webfinger lookups if resolve is True. Full-text search is only enabled if the instance supports it, and is restricted to statuses the logged-in user wrote or was mentioned in. `result_type` can be one of "accounts", "hashtags" or "statuses", to only search for that type of object. Specify `account_id` to only get results from the account with that id. `offset`, `min_id` and `max_id` can be used to paginate. Returns a `search result dict`_, with tags as `hashtag dicts`_. """ return self.search_v2(q, resolve=resolve, result_type=result_type, account_id=account_id, offset=offset, min_id=min_id, max_id=max_id)
python
def search(self, q, resolve=True, result_type=None, account_id=None, offset=None, min_id=None, max_id=None): """ Fetch matching hashtags, accounts and statuses. Will perform webfinger lookups if resolve is True. Full-text search is only enabled if the instance supports it, and is restricted to statuses the logged-in user wrote or was mentioned in. `result_type` can be one of "accounts", "hashtags" or "statuses", to only search for that type of object. Specify `account_id` to only get results from the account with that id. `offset`, `min_id` and `max_id` can be used to paginate. Returns a `search result dict`_, with tags as `hashtag dicts`_. """ return self.search_v2(q, resolve=resolve, result_type=result_type, account_id=account_id, offset=offset, min_id=min_id, max_id=max_id)
[ "def", "search", "(", "self", ",", "q", ",", "resolve", "=", "True", ",", "result_type", "=", "None", ",", "account_id", "=", "None", ",", "offset", "=", "None", ",", "min_id", "=", "None", ",", "max_id", "=", "None", ")", ":", "return", "self", ".", "search_v2", "(", "q", ",", "resolve", "=", "resolve", ",", "result_type", "=", "result_type", ",", "account_id", "=", "account_id", ",", "offset", "=", "offset", ",", "min_id", "=", "min_id", ",", "max_id", "=", "max_id", ")" ]
Fetch matching hashtags, accounts and statuses. Will perform webfinger lookups if resolve is True. Full-text search is only enabled if the instance supports it, and is restricted to statuses the logged-in user wrote or was mentioned in. `result_type` can be one of "accounts", "hashtags" or "statuses", to only search for that type of object. Specify `account_id` to only get results from the account with that id. `offset`, `min_id` and `max_id` can be used to paginate. Returns a `search result dict`_, with tags as `hashtag dicts`_.
[ "Fetch", "matching", "hashtags", "accounts", "and", "statuses", ".", "Will", "perform", "webfinger", "lookups", "if", "resolve", "is", "True", ".", "Full", "-", "text", "search", "is", "only", "enabled", "if", "the", "instance", "supports", "it", "and", "is", "restricted", "to", "statuses", "the", "logged", "-", "in", "user", "wrote", "or", "was", "mentioned", "in", ".", "result_type", "can", "be", "one", "of", "accounts", "hashtags", "or", "statuses", "to", "only", "search", "for", "that", "type", "of", "object", ".", "Specify", "account_id", "to", "only", "get", "results", "from", "the", "account", "with", "that", "id", ".", "offset", "min_id", "and", "max_id", "can", "be", "used", "to", "paginate", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1110-L1127
train
238,700
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.list
def list(self, id): """ Fetch info about a specific list. Returns a `list dict`_. """ id = self.__unpack_id(id) return self.__api_request('GET', '/api/v1/lists/{0}'.format(id))
python
def list(self, id): """ Fetch info about a specific list. Returns a `list dict`_. """ id = self.__unpack_id(id) return self.__api_request('GET', '/api/v1/lists/{0}'.format(id))
[ "def", "list", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "return", "self", ".", "__api_request", "(", "'GET'", ",", "'/api/v1/lists/{0}'", ".", "format", "(", "id", ")", ")" ]
Fetch info about a specific list. Returns a `list dict`_.
[ "Fetch", "info", "about", "a", "specific", "list", ".", "Returns", "a", "list", "dict", "_", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1174-L1181
train
238,701
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.list_accounts
def list_accounts(self, id, max_id=None, min_id=None, since_id=None, limit=None): """ Get the accounts that are on the given list. A `limit` of 0 can be specified to get all accounts without pagination. Returns a list of `user dicts`_. """ id = self.__unpack_id(id) if max_id != None: max_id = self.__unpack_id(max_id) if min_id != None: min_id = self.__unpack_id(min_id) if since_id != None: since_id = self.__unpack_id(since_id) params = self.__generate_params(locals(), ['id']) return self.__api_request('GET', '/api/v1/lists/{0}/accounts'.format(id))
python
def list_accounts(self, id, max_id=None, min_id=None, since_id=None, limit=None): """ Get the accounts that are on the given list. A `limit` of 0 can be specified to get all accounts without pagination. Returns a list of `user dicts`_. """ id = self.__unpack_id(id) if max_id != None: max_id = self.__unpack_id(max_id) if min_id != None: min_id = self.__unpack_id(min_id) if since_id != None: since_id = self.__unpack_id(since_id) params = self.__generate_params(locals(), ['id']) return self.__api_request('GET', '/api/v1/lists/{0}/accounts'.format(id))
[ "def", "list_accounts", "(", "self", ",", "id", ",", "max_id", "=", "None", ",", "min_id", "=", "None", ",", "since_id", "=", "None", ",", "limit", "=", "None", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "if", "max_id", "!=", "None", ":", "max_id", "=", "self", ".", "__unpack_id", "(", "max_id", ")", "if", "min_id", "!=", "None", ":", "min_id", "=", "self", ".", "__unpack_id", "(", "min_id", ")", "if", "since_id", "!=", "None", ":", "since_id", "=", "self", ".", "__unpack_id", "(", "since_id", ")", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ",", "[", "'id'", "]", ")", "return", "self", ".", "__api_request", "(", "'GET'", ",", "'/api/v1/lists/{0}/accounts'", ".", "format", "(", "id", ")", ")" ]
Get the accounts that are on the given list. A `limit` of 0 can be specified to get all accounts without pagination. Returns a list of `user dicts`_.
[ "Get", "the", "accounts", "that", "are", "on", "the", "given", "list", ".", "A", "limit", "of", "0", "can", "be", "specified", "to", "get", "all", "accounts", "without", "pagination", ".", "Returns", "a", "list", "of", "user", "dicts", "_", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1184-L1203
train
238,702
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_reply
def status_reply(self, to_status, status, media_ids=None, sensitive=False, visibility=None, spoiler_text=None, language=None, idempotency_key=None, content_type=None, scheduled_at=None, poll=None, untag=False): """ Helper function - acts like status_post, but prepends the name of all the users that are being replied to to the status text and retains CW and visibility if not explicitly overridden. Set `untag` to True if you want the reply to only go to the user you are replying to, removing every other mentioned user from the conversation. """ user_id = self.__get_logged_in_id() # Determine users to mention mentioned_accounts = collections.OrderedDict() mentioned_accounts[to_status.account.id] = to_status.account.acct if not untag: for account in to_status.mentions: if account.id != user_id and not account.id in mentioned_accounts.keys(): mentioned_accounts[account.id] = account.acct # Join into one piece of text. The space is added inside because of self-replies. status = "".join(map(lambda x: "@" + x + " ", mentioned_accounts.values())) + status # Retain visibility / cw if visibility == None and 'visibility' in to_status: visibility = to_status.visibility if spoiler_text == None and 'spoiler_text' in to_status: spoiler_text = to_status.spoiler_text return self.status_post(status, in_reply_to_id = to_status.id, media_ids = media_ids, sensitive = sensitive, visibility = visibility, spoiler_text = spoiler_text, language = language, idempotency_key = idempotency_key, content_type = content_type, scheduled_at = scheduled_at, poll = poll)
python
def status_reply(self, to_status, status, media_ids=None, sensitive=False, visibility=None, spoiler_text=None, language=None, idempotency_key=None, content_type=None, scheduled_at=None, poll=None, untag=False): """ Helper function - acts like status_post, but prepends the name of all the users that are being replied to to the status text and retains CW and visibility if not explicitly overridden. Set `untag` to True if you want the reply to only go to the user you are replying to, removing every other mentioned user from the conversation. """ user_id = self.__get_logged_in_id() # Determine users to mention mentioned_accounts = collections.OrderedDict() mentioned_accounts[to_status.account.id] = to_status.account.acct if not untag: for account in to_status.mentions: if account.id != user_id and not account.id in mentioned_accounts.keys(): mentioned_accounts[account.id] = account.acct # Join into one piece of text. The space is added inside because of self-replies. status = "".join(map(lambda x: "@" + x + " ", mentioned_accounts.values())) + status # Retain visibility / cw if visibility == None and 'visibility' in to_status: visibility = to_status.visibility if spoiler_text == None and 'spoiler_text' in to_status: spoiler_text = to_status.spoiler_text return self.status_post(status, in_reply_to_id = to_status.id, media_ids = media_ids, sensitive = sensitive, visibility = visibility, spoiler_text = spoiler_text, language = language, idempotency_key = idempotency_key, content_type = content_type, scheduled_at = scheduled_at, poll = poll)
[ "def", "status_reply", "(", "self", ",", "to_status", ",", "status", ",", "media_ids", "=", "None", ",", "sensitive", "=", "False", ",", "visibility", "=", "None", ",", "spoiler_text", "=", "None", ",", "language", "=", "None", ",", "idempotency_key", "=", "None", ",", "content_type", "=", "None", ",", "scheduled_at", "=", "None", ",", "poll", "=", "None", ",", "untag", "=", "False", ")", ":", "user_id", "=", "self", ".", "__get_logged_in_id", "(", ")", "# Determine users to mention", "mentioned_accounts", "=", "collections", ".", "OrderedDict", "(", ")", "mentioned_accounts", "[", "to_status", ".", "account", ".", "id", "]", "=", "to_status", ".", "account", ".", "acct", "if", "not", "untag", ":", "for", "account", "in", "to_status", ".", "mentions", ":", "if", "account", ".", "id", "!=", "user_id", "and", "not", "account", ".", "id", "in", "mentioned_accounts", ".", "keys", "(", ")", ":", "mentioned_accounts", "[", "account", ".", "id", "]", "=", "account", ".", "acct", "# Join into one piece of text. The space is added inside because of self-replies.", "status", "=", "\"\"", ".", "join", "(", "map", "(", "lambda", "x", ":", "\"@\"", "+", "x", "+", "\" \"", ",", "mentioned_accounts", ".", "values", "(", ")", ")", ")", "+", "status", "# Retain visibility / cw", "if", "visibility", "==", "None", "and", "'visibility'", "in", "to_status", ":", "visibility", "=", "to_status", ".", "visibility", "if", "spoiler_text", "==", "None", "and", "'spoiler_text'", "in", "to_status", ":", "spoiler_text", "=", "to_status", ".", "spoiler_text", "return", "self", ".", "status_post", "(", "status", ",", "in_reply_to_id", "=", "to_status", ".", "id", ",", "media_ids", "=", "media_ids", ",", "sensitive", "=", "sensitive", ",", "visibility", "=", "visibility", ",", "spoiler_text", "=", "spoiler_text", ",", "language", "=", "language", ",", "idempotency_key", "=", "idempotency_key", ",", "content_type", "=", "content_type", ",", "scheduled_at", "=", "scheduled_at", ",", "poll", "=", "poll", ")" ]
Helper function - acts like status_post, but prepends the name of all the users that are being replied to to the status text and retains CW and visibility if not explicitly overridden. Set `untag` to True if you want the reply to only go to the user you are replying to, removing every other mentioned user from the conversation.
[ "Helper", "function", "-", "acts", "like", "status_post", "but", "prepends", "the", "name", "of", "all", "the", "users", "that", "are", "being", "replied", "to", "to", "the", "status", "text", "and", "retains", "CW", "and", "visibility", "if", "not", "explicitly", "overridden", ".", "Set", "untag", "to", "True", "if", "you", "want", "the", "reply", "to", "only", "go", "to", "the", "user", "you", "are", "replying", "to", "removing", "every", "other", "mentioned", "user", "from", "the", "conversation", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1506-L1541
train
238,703
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_delete
def status_delete(self, id): """ Delete a status """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}'.format(str(id)) self.__api_request('DELETE', url)
python
def status_delete(self, id): """ Delete a status """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}'.format(str(id)) self.__api_request('DELETE', url)
[ "def", "status_delete", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}'", ".", "format", "(", "str", "(", "id", ")", ")", "self", ".", "__api_request", "(", "'DELETE'", ",", "url", ")" ]
Delete a status
[ "Delete", "a", "status" ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1558-L1564
train
238,704
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_unreblog
def status_unreblog(self, id): """ Un-reblog a status. Returns a `toot dict`_ with the status that used to be reblogged. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unreblog'.format(str(id)) return self.__api_request('POST', url)
python
def status_unreblog(self, id): """ Un-reblog a status. Returns a `toot dict`_ with the status that used to be reblogged. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unreblog'.format(str(id)) return self.__api_request('POST', url)
[ "def", "status_unreblog", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}/unreblog'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Un-reblog a status. Returns a `toot dict`_ with the status that used to be reblogged.
[ "Un", "-", "reblog", "a", "status", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1589-L1597
train
238,705
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_favourite
def status_favourite(self, id): """ Favourite a status. Returns a `toot dict`_ with the favourited status. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/favourite'.format(str(id)) return self.__api_request('POST', url)
python
def status_favourite(self, id): """ Favourite a status. Returns a `toot dict`_ with the favourited status. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/favourite'.format(str(id)) return self.__api_request('POST', url)
[ "def", "status_favourite", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}/favourite'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Favourite a status. Returns a `toot dict`_ with the favourited status.
[ "Favourite", "a", "status", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1600-L1608
train
238,706
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_unfavourite
def status_unfavourite(self, id): """ Un-favourite a status. Returns a `toot dict`_ with the un-favourited status. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unfavourite'.format(str(id)) return self.__api_request('POST', url)
python
def status_unfavourite(self, id): """ Un-favourite a status. Returns a `toot dict`_ with the un-favourited status. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unfavourite'.format(str(id)) return self.__api_request('POST', url)
[ "def", "status_unfavourite", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}/unfavourite'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Un-favourite a status. Returns a `toot dict`_ with the un-favourited status.
[ "Un", "-", "favourite", "a", "status", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1611-L1619
train
238,707
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_mute
def status_mute(self, id): """ Mute notifications for a status. Returns a `toot dict`_ with the now muted status """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/mute'.format(str(id)) return self.__api_request('POST', url)
python
def status_mute(self, id): """ Mute notifications for a status. Returns a `toot dict`_ with the now muted status """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/mute'.format(str(id)) return self.__api_request('POST', url)
[ "def", "status_mute", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}/mute'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Mute notifications for a status. Returns a `toot dict`_ with the now muted status
[ "Mute", "notifications", "for", "a", "status", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1622-L1630
train
238,708
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_unmute
def status_unmute(self, id): """ Unmute notifications for a status. Returns a `toot dict`_ with the status that used to be muted. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unmute'.format(str(id)) return self.__api_request('POST', url)
python
def status_unmute(self, id): """ Unmute notifications for a status. Returns a `toot dict`_ with the status that used to be muted. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unmute'.format(str(id)) return self.__api_request('POST', url)
[ "def", "status_unmute", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}/unmute'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Unmute notifications for a status. Returns a `toot dict`_ with the status that used to be muted.
[ "Unmute", "notifications", "for", "a", "status", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1633-L1641
train
238,709
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_pin
def status_pin(self, id): """ Pin a status for the logged-in user. Returns a `toot dict`_ with the now pinned status """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/pin'.format(str(id)) return self.__api_request('POST', url)
python
def status_pin(self, id): """ Pin a status for the logged-in user. Returns a `toot dict`_ with the now pinned status """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/pin'.format(str(id)) return self.__api_request('POST', url)
[ "def", "status_pin", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}/pin'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Pin a status for the logged-in user. Returns a `toot dict`_ with the now pinned status
[ "Pin", "a", "status", "for", "the", "logged", "-", "in", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1644-L1652
train
238,710
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.status_unpin
def status_unpin(self, id): """ Unpin a pinned status for the logged-in user. Returns a `toot dict`_ with the status that used to be pinned. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unpin'.format(str(id)) return self.__api_request('POST', url)
python
def status_unpin(self, id): """ Unpin a pinned status for the logged-in user. Returns a `toot dict`_ with the status that used to be pinned. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unpin'.format(str(id)) return self.__api_request('POST', url)
[ "def", "status_unpin", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}/unpin'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Unpin a pinned status for the logged-in user. Returns a `toot dict`_ with the status that used to be pinned.
[ "Unpin", "a", "pinned", "status", "for", "the", "logged", "-", "in", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1655-L1663
train
238,711
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.scheduled_status_update
def scheduled_status_update(self, id, scheduled_at): """ Update the scheduled time of a scheduled status. New time must be at least 5 minutes into the future. Returns a `scheduled toot dict`_ """ scheduled_at = self.__consistent_isoformat_utc(scheduled_at) id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) return self.__api_request('PUT', url, params)
python
def scheduled_status_update(self, id, scheduled_at): """ Update the scheduled time of a scheduled status. New time must be at least 5 minutes into the future. Returns a `scheduled toot dict`_ """ scheduled_at = self.__consistent_isoformat_utc(scheduled_at) id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) return self.__api_request('PUT', url, params)
[ "def", "scheduled_status_update", "(", "self", ",", "id", ",", "scheduled_at", ")", ":", "scheduled_at", "=", "self", ".", "__consistent_isoformat_utc", "(", "scheduled_at", ")", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ",", "[", "'id'", "]", ")", "url", "=", "'/api/v1/scheduled_statuses/{0}'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'PUT'", ",", "url", ",", "params", ")" ]
Update the scheduled time of a scheduled status. New time must be at least 5 minutes into the future. Returns a `scheduled toot dict`_
[ "Update", "the", "scheduled", "time", "of", "a", "scheduled", "status", ".", "New", "time", "must", "be", "at", "least", "5", "minutes", "into", "the", "future", ".", "Returns", "a", "scheduled", "toot", "dict", "_" ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1669-L1681
train
238,712
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.scheduled_status_delete
def scheduled_status_delete(self, id): """ Deletes a scheduled status. """ id = self.__unpack_id(id) url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) self.__api_request('DELETE', url)
python
def scheduled_status_delete(self, id): """ Deletes a scheduled status. """ id = self.__unpack_id(id) url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) self.__api_request('DELETE', url)
[ "def", "scheduled_status_delete", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/scheduled_statuses/{0}'", ".", "format", "(", "str", "(", "id", ")", ")", "self", ".", "__api_request", "(", "'DELETE'", ",", "url", ")" ]
Deletes a scheduled status.
[ "Deletes", "a", "scheduled", "status", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1684-L1690
train
238,713
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.poll_vote
def poll_vote(self, id, choices): """ Vote in the given poll. `choices` is the index of the choice you wish to register a vote for (i.e. its index in the corresponding polls `options` field. In case of a poll that allows selection of more than one option, a list of indices can be passed. You can only submit choices for any given poll once in case of single-option polls, or only once per option in case of multi-option polls. Returns the updated `poll dict`_ """ id = self.__unpack_id(id) if not isinstance(choices, list): choices = [choices] params = self.__generate_params(locals(), ['id']) url = '/api/v1/polls/{0}/votes'.format(id) self.__api_request('POST', url, params)
python
def poll_vote(self, id, choices): """ Vote in the given poll. `choices` is the index of the choice you wish to register a vote for (i.e. its index in the corresponding polls `options` field. In case of a poll that allows selection of more than one option, a list of indices can be passed. You can only submit choices for any given poll once in case of single-option polls, or only once per option in case of multi-option polls. Returns the updated `poll dict`_ """ id = self.__unpack_id(id) if not isinstance(choices, list): choices = [choices] params = self.__generate_params(locals(), ['id']) url = '/api/v1/polls/{0}/votes'.format(id) self.__api_request('POST', url, params)
[ "def", "poll_vote", "(", "self", ",", "id", ",", "choices", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "if", "not", "isinstance", "(", "choices", ",", "list", ")", ":", "choices", "=", "[", "choices", "]", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ",", "[", "'id'", "]", ")", "url", "=", "'/api/v1/polls/{0}/votes'", ".", "format", "(", "id", ")", "self", ".", "__api_request", "(", "'POST'", ",", "url", ",", "params", ")" ]
Vote in the given poll. `choices` is the index of the choice you wish to register a vote for (i.e. its index in the corresponding polls `options` field. In case of a poll that allows selection of more than one option, a list of indices can be passed. You can only submit choices for any given poll once in case of single-option polls, or only once per option in case of multi-option polls. Returns the updated `poll dict`_
[ "Vote", "in", "the", "given", "poll", ".", "choices", "is", "the", "index", "of", "the", "choice", "you", "wish", "to", "register", "a", "vote", "for", "(", "i", ".", "e", ".", "its", "index", "in", "the", "corresponding", "polls", "options", "field", ".", "In", "case", "of", "a", "poll", "that", "allows", "selection", "of", "more", "than", "one", "option", "a", "list", "of", "indices", "can", "be", "passed", ".", "You", "can", "only", "submit", "choices", "for", "any", "given", "poll", "once", "in", "case", "of", "single", "-", "option", "polls", "or", "only", "once", "per", "option", "in", "case", "of", "multi", "-", "option", "polls", ".", "Returns", "the", "updated", "poll", "dict", "_" ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1696-L1717
train
238,714
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.notifications_dismiss
def notifications_dismiss(self, id): """ Deletes a single notification """ id = self.__unpack_id(id) params = self.__generate_params(locals()) self.__api_request('POST', '/api/v1/notifications/dismiss', params)
python
def notifications_dismiss(self, id): """ Deletes a single notification """ id = self.__unpack_id(id) params = self.__generate_params(locals()) self.__api_request('POST', '/api/v1/notifications/dismiss', params)
[ "def", "notifications_dismiss", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ")", "self", ".", "__api_request", "(", "'POST'", ",", "'/api/v1/notifications/dismiss'", ",", "params", ")" ]
Deletes a single notification
[ "Deletes", "a", "single", "notification" ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1732-L1738
train
238,715
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.account_block
def account_block(self, id): """ Block a user. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) url = '/api/v1/accounts/{0}/block'.format(str(id)) return self.__api_request('POST', url)
python
def account_block(self, id): """ Block a user. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) url = '/api/v1/accounts/{0}/block'.format(str(id)) return self.__api_request('POST', url)
[ "def", "account_block", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/accounts/{0}/block'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Block a user. Returns a `relationship dict`_ containing the updated relationship to the user.
[ "Block", "a", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1801-L1809
train
238,716
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.account_unblock
def account_unblock(self, id): """ Unblock a user. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) url = '/api/v1/accounts/{0}/unblock'.format(str(id)) return self.__api_request('POST', url)
python
def account_unblock(self, id): """ Unblock a user. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) url = '/api/v1/accounts/{0}/unblock'.format(str(id)) return self.__api_request('POST', url)
[ "def", "account_unblock", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/accounts/{0}/unblock'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Unblock a user. Returns a `relationship dict`_ containing the updated relationship to the user.
[ "Unblock", "a", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1812-L1820
train
238,717
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.account_mute
def account_mute(self, id, notifications=True): """ Mute a user. Set `notifications` to False to receive notifications even though the user is muted from timelines. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) url = '/api/v1/accounts/{0}/mute'.format(str(id)) return self.__api_request('POST', url, params)
python
def account_mute(self, id, notifications=True): """ Mute a user. Set `notifications` to False to receive notifications even though the user is muted from timelines. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) url = '/api/v1/accounts/{0}/mute'.format(str(id)) return self.__api_request('POST', url, params)
[ "def", "account_mute", "(", "self", ",", "id", ",", "notifications", "=", "True", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ",", "[", "'id'", "]", ")", "url", "=", "'/api/v1/accounts/{0}/mute'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ",", "params", ")" ]
Mute a user. Set `notifications` to False to receive notifications even though the user is muted from timelines. Returns a `relationship dict`_ containing the updated relationship to the user.
[ "Mute", "a", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1823-L1835
train
238,718
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.account_unmute
def account_unmute(self, id): """ Unmute a user. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) url = '/api/v1/accounts/{0}/unmute'.format(str(id)) return self.__api_request('POST', url)
python
def account_unmute(self, id): """ Unmute a user. Returns a `relationship dict`_ containing the updated relationship to the user. """ id = self.__unpack_id(id) url = '/api/v1/accounts/{0}/unmute'.format(str(id)) return self.__api_request('POST', url)
[ "def", "account_unmute", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/accounts/{0}/unmute'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Unmute a user. Returns a `relationship dict`_ containing the updated relationship to the user.
[ "Unmute", "a", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1838-L1846
train
238,719
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.account_update_credentials
def account_update_credentials(self, display_name=None, note=None, avatar=None, avatar_mime_type=None, header=None, header_mime_type=None, locked=None, fields=None): """ Update the profile for the currently logged-in user. 'note' is the user's bio. 'avatar' and 'header' are images. As with media uploads, it is possible to either pass image data and a mime type, or a filename of an image file, for either. 'locked' specifies whether the user needs to manually approve follow requests. 'fields' can be a list of up to four name-value pairs (specified as tuples) to appear as semi-structured information in the users profile. Returns the updated `user dict` of the logged-in user. """ params_initial = collections.OrderedDict(locals()) # Load avatar, if specified if not avatar is None: if avatar_mime_type is None and (isinstance(avatar, str) and os.path.isfile(avatar)): avatar_mime_type = guess_type(avatar) avatar = open(avatar, 'rb') if avatar_mime_type is None: raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.') # Load header, if specified if not header is None: if header_mime_type is None and (isinstance(avatar, str) and os.path.isfile(header)): header_mime_type = guess_type(header) header = open(header, 'rb') if header_mime_type is None: raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.') # Convert fields if fields != None: if len(fields) > 4: raise MastodonIllegalArgumentError('A maximum of four fields are allowed.') fields_attributes = [] for idx, (field_name, field_value) in enumerate(fields): params_initial['fields_attributes[' + str(idx) + '][name]'] = field_name params_initial['fields_attributes[' + str(idx) + '][value]'] = field_value # Clean up params for param in ["avatar", "avatar_mime_type", "header", "header_mime_type", "fields"]: if param in params_initial: del params_initial[param] # Create file info files = {} if not avatar is None: avatar_file_name = "mastodonpyupload_" + mimetypes.guess_extension(avatar_mime_type) files["avatar"] = (avatar_file_name, avatar, avatar_mime_type) if not header is None: header_file_name = "mastodonpyupload_" + mimetypes.guess_extension(header_mime_type) files["header"] = (header_file_name, header, header_mime_type) params = self.__generate_params(params_initial) return self.__api_request('PATCH', '/api/v1/accounts/update_credentials', params, files=files)
python
def account_update_credentials(self, display_name=None, note=None, avatar=None, avatar_mime_type=None, header=None, header_mime_type=None, locked=None, fields=None): """ Update the profile for the currently logged-in user. 'note' is the user's bio. 'avatar' and 'header' are images. As with media uploads, it is possible to either pass image data and a mime type, or a filename of an image file, for either. 'locked' specifies whether the user needs to manually approve follow requests. 'fields' can be a list of up to four name-value pairs (specified as tuples) to appear as semi-structured information in the users profile. Returns the updated `user dict` of the logged-in user. """ params_initial = collections.OrderedDict(locals()) # Load avatar, if specified if not avatar is None: if avatar_mime_type is None and (isinstance(avatar, str) and os.path.isfile(avatar)): avatar_mime_type = guess_type(avatar) avatar = open(avatar, 'rb') if avatar_mime_type is None: raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.') # Load header, if specified if not header is None: if header_mime_type is None and (isinstance(avatar, str) and os.path.isfile(header)): header_mime_type = guess_type(header) header = open(header, 'rb') if header_mime_type is None: raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.') # Convert fields if fields != None: if len(fields) > 4: raise MastodonIllegalArgumentError('A maximum of four fields are allowed.') fields_attributes = [] for idx, (field_name, field_value) in enumerate(fields): params_initial['fields_attributes[' + str(idx) + '][name]'] = field_name params_initial['fields_attributes[' + str(idx) + '][value]'] = field_value # Clean up params for param in ["avatar", "avatar_mime_type", "header", "header_mime_type", "fields"]: if param in params_initial: del params_initial[param] # Create file info files = {} if not avatar is None: avatar_file_name = "mastodonpyupload_" + mimetypes.guess_extension(avatar_mime_type) files["avatar"] = (avatar_file_name, avatar, avatar_mime_type) if not header is None: header_file_name = "mastodonpyupload_" + mimetypes.guess_extension(header_mime_type) files["header"] = (header_file_name, header, header_mime_type) params = self.__generate_params(params_initial) return self.__api_request('PATCH', '/api/v1/accounts/update_credentials', params, files=files)
[ "def", "account_update_credentials", "(", "self", ",", "display_name", "=", "None", ",", "note", "=", "None", ",", "avatar", "=", "None", ",", "avatar_mime_type", "=", "None", ",", "header", "=", "None", ",", "header_mime_type", "=", "None", ",", "locked", "=", "None", ",", "fields", "=", "None", ")", ":", "params_initial", "=", "collections", ".", "OrderedDict", "(", "locals", "(", ")", ")", "# Load avatar, if specified", "if", "not", "avatar", "is", "None", ":", "if", "avatar_mime_type", "is", "None", "and", "(", "isinstance", "(", "avatar", ",", "str", ")", "and", "os", ".", "path", ".", "isfile", "(", "avatar", ")", ")", ":", "avatar_mime_type", "=", "guess_type", "(", "avatar", ")", "avatar", "=", "open", "(", "avatar", ",", "'rb'", ")", "if", "avatar_mime_type", "is", "None", ":", "raise", "MastodonIllegalArgumentError", "(", "'Could not determine mime type or data passed directly without mime type.'", ")", "# Load header, if specified", "if", "not", "header", "is", "None", ":", "if", "header_mime_type", "is", "None", "and", "(", "isinstance", "(", "avatar", ",", "str", ")", "and", "os", ".", "path", ".", "isfile", "(", "header", ")", ")", ":", "header_mime_type", "=", "guess_type", "(", "header", ")", "header", "=", "open", "(", "header", ",", "'rb'", ")", "if", "header_mime_type", "is", "None", ":", "raise", "MastodonIllegalArgumentError", "(", "'Could not determine mime type or data passed directly without mime type.'", ")", "# Convert fields", "if", "fields", "!=", "None", ":", "if", "len", "(", "fields", ")", ">", "4", ":", "raise", "MastodonIllegalArgumentError", "(", "'A maximum of four fields are allowed.'", ")", "fields_attributes", "=", "[", "]", "for", "idx", ",", "(", "field_name", ",", "field_value", ")", "in", "enumerate", "(", "fields", ")", ":", "params_initial", "[", "'fields_attributes['", "+", "str", "(", "idx", ")", "+", "'][name]'", "]", "=", "field_name", "params_initial", "[", "'fields_attributes['", "+", "str", "(", "idx", ")", "+", "'][value]'", "]", "=", "field_value", "# Clean up params", "for", "param", "in", "[", "\"avatar\"", ",", "\"avatar_mime_type\"", ",", "\"header\"", ",", "\"header_mime_type\"", ",", "\"fields\"", "]", ":", "if", "param", "in", "params_initial", ":", "del", "params_initial", "[", "param", "]", "# Create file info", "files", "=", "{", "}", "if", "not", "avatar", "is", "None", ":", "avatar_file_name", "=", "\"mastodonpyupload_\"", "+", "mimetypes", ".", "guess_extension", "(", "avatar_mime_type", ")", "files", "[", "\"avatar\"", "]", "=", "(", "avatar_file_name", ",", "avatar", ",", "avatar_mime_type", ")", "if", "not", "header", "is", "None", ":", "header_file_name", "=", "\"mastodonpyupload_\"", "+", "mimetypes", ".", "guess_extension", "(", "header_mime_type", ")", "files", "[", "\"header\"", "]", "=", "(", "header_file_name", ",", "header", ",", "header_mime_type", ")", "params", "=", "self", ".", "__generate_params", "(", "params_initial", ")", "return", "self", ".", "__api_request", "(", "'PATCH'", ",", "'/api/v1/accounts/update_credentials'", ",", "params", ",", "files", "=", "files", ")" ]
Update the profile for the currently logged-in user. 'note' is the user's bio. 'avatar' and 'header' are images. As with media uploads, it is possible to either pass image data and a mime type, or a filename of an image file, for either. 'locked' specifies whether the user needs to manually approve follow requests. 'fields' can be a list of up to four name-value pairs (specified as tuples) to appear as semi-structured information in the users profile. Returns the updated `user dict` of the logged-in user.
[ "Update", "the", "profile", "for", "the", "currently", "logged", "-", "in", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1849-L1913
train
238,720
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.filter_create
def filter_create(self, phrase, context, irreversible = False, whole_word = True, expires_in = None): """ Creates a new keyword filter. `phrase` is the phrase that should be filtered out, `context` specifies from where to filter the keywords. Valid contexts are 'home', 'notifications', 'public' and 'thread'. Set `irreversible` to True if you want the filter to just delete statuses server side. This works only for the 'home' and 'notifications' contexts. Set `whole_word` to False if you want to allow filter matches to start or end within a word, not only at word boundaries. Set `expires_in` to specify for how many seconds the filter should be kept around. Returns the `filter dict`_ of the newly created filter. """ params = self.__generate_params(locals()) for context_val in context: if not context_val in ['home', 'notifications', 'public', 'thread']: raise MastodonIllegalArgumentError('Invalid filter context.') return self.__api_request('POST', '/api/v1/filters', params)
python
def filter_create(self, phrase, context, irreversible = False, whole_word = True, expires_in = None): """ Creates a new keyword filter. `phrase` is the phrase that should be filtered out, `context` specifies from where to filter the keywords. Valid contexts are 'home', 'notifications', 'public' and 'thread'. Set `irreversible` to True if you want the filter to just delete statuses server side. This works only for the 'home' and 'notifications' contexts. Set `whole_word` to False if you want to allow filter matches to start or end within a word, not only at word boundaries. Set `expires_in` to specify for how many seconds the filter should be kept around. Returns the `filter dict`_ of the newly created filter. """ params = self.__generate_params(locals()) for context_val in context: if not context_val in ['home', 'notifications', 'public', 'thread']: raise MastodonIllegalArgumentError('Invalid filter context.') return self.__api_request('POST', '/api/v1/filters', params)
[ "def", "filter_create", "(", "self", ",", "phrase", ",", "context", ",", "irreversible", "=", "False", ",", "whole_word", "=", "True", ",", "expires_in", "=", "None", ")", ":", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ")", "for", "context_val", "in", "context", ":", "if", "not", "context_val", "in", "[", "'home'", ",", "'notifications'", ",", "'public'", ",", "'thread'", "]", ":", "raise", "MastodonIllegalArgumentError", "(", "'Invalid filter context.'", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "'/api/v1/filters'", ",", "params", ")" ]
Creates a new keyword filter. `phrase` is the phrase that should be filtered out, `context` specifies from where to filter the keywords. Valid contexts are 'home', 'notifications', 'public' and 'thread'. Set `irreversible` to True if you want the filter to just delete statuses server side. This works only for the 'home' and 'notifications' contexts. Set `whole_word` to False if you want to allow filter matches to start or end within a word, not only at word boundaries. Set `expires_in` to specify for how many seconds the filter should be kept around. Returns the `filter dict`_ of the newly created filter.
[ "Creates", "a", "new", "keyword", "filter", ".", "phrase", "is", "the", "phrase", "that", "should", "be", "filtered", "out", "context", "specifies", "from", "where", "to", "filter", "the", "keywords", ".", "Valid", "contexts", "are", "home", "notifications", "public", "and", "thread", ".", "Set", "irreversible", "to", "True", "if", "you", "want", "the", "filter", "to", "just", "delete", "statuses", "server", "side", ".", "This", "works", "only", "for", "the", "home", "and", "notifications", "contexts", ".", "Set", "whole_word", "to", "False", "if", "you", "want", "to", "allow", "filter", "matches", "to", "start", "or", "end", "within", "a", "word", "not", "only", "at", "word", "boundaries", ".", "Set", "expires_in", "to", "specify", "for", "how", "many", "seconds", "the", "filter", "should", "be", "kept", "around", ".", "Returns", "the", "filter", "dict", "_", "of", "the", "newly", "created", "filter", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1942-L1965
train
238,721
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.filter_delete
def filter_delete(self, id): """ Deletes the filter with the given `id`. """ id = self.__unpack_id(id) url = '/api/v1/filters/{0}'.format(str(id)) self.__api_request('DELETE', url)
python
def filter_delete(self, id): """ Deletes the filter with the given `id`. """ id = self.__unpack_id(id) url = '/api/v1/filters/{0}'.format(str(id)) self.__api_request('DELETE', url)
[ "def", "filter_delete", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/filters/{0}'", ".", "format", "(", "str", "(", "id", ")", ")", "self", ".", "__api_request", "(", "'DELETE'", ",", "url", ")" ]
Deletes the filter with the given `id`.
[ "Deletes", "the", "filter", "with", "the", "given", "id", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1981-L1987
train
238,722
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.suggestion_delete
def suggestion_delete(self, account_id): """ Remove the user with the given `account_id` from the follow suggestions. """ account_id = self.__unpack_id(account_id) url = '/api/v1/suggestions/{0}'.format(str(account_id)) self.__api_request('DELETE', url)
python
def suggestion_delete(self, account_id): """ Remove the user with the given `account_id` from the follow suggestions. """ account_id = self.__unpack_id(account_id) url = '/api/v1/suggestions/{0}'.format(str(account_id)) self.__api_request('DELETE', url)
[ "def", "suggestion_delete", "(", "self", ",", "account_id", ")", ":", "account_id", "=", "self", ".", "__unpack_id", "(", "account_id", ")", "url", "=", "'/api/v1/suggestions/{0}'", ".", "format", "(", "str", "(", "account_id", ")", ")", "self", ".", "__api_request", "(", "'DELETE'", ",", "url", ")" ]
Remove the user with the given `account_id` from the follow suggestions.
[ "Remove", "the", "user", "with", "the", "given", "account_id", "from", "the", "follow", "suggestions", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1993-L1999
train
238,723
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.list_create
def list_create(self, title): """ Create a new list with the given `title`. Returns the `list dict`_ of the created list. """ params = self.__generate_params(locals()) return self.__api_request('POST', '/api/v1/lists', params)
python
def list_create(self, title): """ Create a new list with the given `title`. Returns the `list dict`_ of the created list. """ params = self.__generate_params(locals()) return self.__api_request('POST', '/api/v1/lists', params)
[ "def", "list_create", "(", "self", ",", "title", ")", ":", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "'/api/v1/lists'", ",", "params", ")" ]
Create a new list with the given `title`. Returns the `list dict`_ of the created list.
[ "Create", "a", "new", "list", "with", "the", "given", "title", ".", "Returns", "the", "list", "dict", "_", "of", "the", "created", "list", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2005-L2012
train
238,724
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.list_update
def list_update(self, id, title): """ Update info about a list, where "info" is really the lists `title`. Returns the `list dict`_ of the modified list. """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) return self.__api_request('PUT', '/api/v1/lists/{0}'.format(id), params)
python
def list_update(self, id, title): """ Update info about a list, where "info" is really the lists `title`. Returns the `list dict`_ of the modified list. """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) return self.__api_request('PUT', '/api/v1/lists/{0}'.format(id), params)
[ "def", "list_update", "(", "self", ",", "id", ",", "title", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ",", "[", "'id'", "]", ")", "return", "self", ".", "__api_request", "(", "'PUT'", ",", "'/api/v1/lists/{0}'", ".", "format", "(", "id", ")", ",", "params", ")" ]
Update info about a list, where "info" is really the lists `title`. Returns the `list dict`_ of the modified list.
[ "Update", "info", "about", "a", "list", "where", "info", "is", "really", "the", "lists", "title", ".", "Returns", "the", "list", "dict", "_", "of", "the", "modified", "list", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2015-L2023
train
238,725
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.list_delete
def list_delete(self, id): """ Delete a list. """ id = self.__unpack_id(id) self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id))
python
def list_delete(self, id): """ Delete a list. """ id = self.__unpack_id(id) self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id))
[ "def", "list_delete", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "self", ".", "__api_request", "(", "'DELETE'", ",", "'/api/v1/lists/{0}'", ".", "format", "(", "id", ")", ")" ]
Delete a list.
[ "Delete", "a", "list", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2026-L2031
train
238,726
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.report
def report(self, account_id, status_ids = None, comment = None, forward = False): """ Report statuses to the instances administrators. Accepts a list of toot IDs associated with the report, and a comment. Set forward to True to forward a report of a remote user to that users instance as well as sending it to the instance local administrators. Returns a `report dict`_. """ account_id = self.__unpack_id(account_id) if not status_ids is None: if not isinstance(status_ids, list): status_ids = [status_ids] status_ids = list(map(lambda x: self.__unpack_id(x), status_ids)) params_initial = locals() if forward == False: del params_initial['forward'] params = self.__generate_params(params_initial) return self.__api_request('POST', '/api/v1/reports/', params)
python
def report(self, account_id, status_ids = None, comment = None, forward = False): """ Report statuses to the instances administrators. Accepts a list of toot IDs associated with the report, and a comment. Set forward to True to forward a report of a remote user to that users instance as well as sending it to the instance local administrators. Returns a `report dict`_. """ account_id = self.__unpack_id(account_id) if not status_ids is None: if not isinstance(status_ids, list): status_ids = [status_ids] status_ids = list(map(lambda x: self.__unpack_id(x), status_ids)) params_initial = locals() if forward == False: del params_initial['forward'] params = self.__generate_params(params_initial) return self.__api_request('POST', '/api/v1/reports/', params)
[ "def", "report", "(", "self", ",", "account_id", ",", "status_ids", "=", "None", ",", "comment", "=", "None", ",", "forward", "=", "False", ")", ":", "account_id", "=", "self", ".", "__unpack_id", "(", "account_id", ")", "if", "not", "status_ids", "is", "None", ":", "if", "not", "isinstance", "(", "status_ids", ",", "list", ")", ":", "status_ids", "=", "[", "status_ids", "]", "status_ids", "=", "list", "(", "map", "(", "lambda", "x", ":", "self", ".", "__unpack_id", "(", "x", ")", ",", "status_ids", ")", ")", "params_initial", "=", "locals", "(", ")", "if", "forward", "==", "False", ":", "del", "params_initial", "[", "'forward'", "]", "params", "=", "self", ".", "__generate_params", "(", "params_initial", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "'/api/v1/reports/'", ",", "params", ")" ]
Report statuses to the instances administrators. Accepts a list of toot IDs associated with the report, and a comment. Set forward to True to forward a report of a remote user to that users instance as well as sending it to the instance local administrators. Returns a `report dict`_.
[ "Report", "statuses", "to", "the", "instances", "administrators", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2065-L2088
train
238,727
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.follow_request_authorize
def follow_request_authorize(self, id): """ Accept an incoming follow request. """ id = self.__unpack_id(id) url = '/api/v1/follow_requests/{0}/authorize'.format(str(id)) self.__api_request('POST', url)
python
def follow_request_authorize(self, id): """ Accept an incoming follow request. """ id = self.__unpack_id(id) url = '/api/v1/follow_requests/{0}/authorize'.format(str(id)) self.__api_request('POST', url)
[ "def", "follow_request_authorize", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/follow_requests/{0}/authorize'", ".", "format", "(", "str", "(", "id", ")", ")", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Accept an incoming follow request.
[ "Accept", "an", "incoming", "follow", "request", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2094-L2100
train
238,728
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.follow_request_reject
def follow_request_reject(self, id): """ Reject an incoming follow request. """ id = self.__unpack_id(id) url = '/api/v1/follow_requests/{0}/reject'.format(str(id)) self.__api_request('POST', url)
python
def follow_request_reject(self, id): """ Reject an incoming follow request. """ id = self.__unpack_id(id) url = '/api/v1/follow_requests/{0}/reject'.format(str(id)) self.__api_request('POST', url)
[ "def", "follow_request_reject", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/follow_requests/{0}/reject'", ".", "format", "(", "str", "(", "id", ")", ")", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Reject an incoming follow request.
[ "Reject", "an", "incoming", "follow", "request", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2103-L2109
train
238,729
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.domain_block
def domain_block(self, domain=None): """ Add a block for all statuses originating from the specified domain for the logged-in user. """ params = self.__generate_params(locals()) self.__api_request('POST', '/api/v1/domain_blocks', params)
python
def domain_block(self, domain=None): """ Add a block for all statuses originating from the specified domain for the logged-in user. """ params = self.__generate_params(locals()) self.__api_request('POST', '/api/v1/domain_blocks', params)
[ "def", "domain_block", "(", "self", ",", "domain", "=", "None", ")", ":", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ")", "self", ".", "__api_request", "(", "'POST'", ",", "'/api/v1/domain_blocks'", ",", "params", ")" ]
Add a block for all statuses originating from the specified domain for the logged-in user.
[ "Add", "a", "block", "for", "all", "statuses", "originating", "from", "the", "specified", "domain", "for", "the", "logged", "-", "in", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2174-L2179
train
238,730
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.domain_unblock
def domain_unblock(self, domain=None): """ Remove a domain block for the logged-in user. """ params = self.__generate_params(locals()) self.__api_request('DELETE', '/api/v1/domain_blocks', params)
python
def domain_unblock(self, domain=None): """ Remove a domain block for the logged-in user. """ params = self.__generate_params(locals()) self.__api_request('DELETE', '/api/v1/domain_blocks', params)
[ "def", "domain_unblock", "(", "self", ",", "domain", "=", "None", ")", ":", "params", "=", "self", ".", "__generate_params", "(", "locals", "(", ")", ")", "self", ".", "__api_request", "(", "'DELETE'", ",", "'/api/v1/domain_blocks'", ",", "params", ")" ]
Remove a domain block for the logged-in user.
[ "Remove", "a", "domain", "block", "for", "the", "logged", "-", "in", "user", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2182-L2187
train
238,731
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.push_subscription_update
def push_subscription_update(self, follow_events=None, favourite_events=None, reblog_events=None, mention_events=None): """ Modifies what kind of events the app wishes to subscribe to. Returns the updated `push subscription dict`_. """ params = {} if follow_events != None: params['data[alerts][follow]'] = follow_events if favourite_events != None: params['data[alerts][favourite]'] = favourite_events if reblog_events != None: params['data[alerts][reblog]'] = reblog_events if mention_events != None: params['data[alerts][mention]'] = mention_events return self.__api_request('PUT', '/api/v1/push/subscription', params)
python
def push_subscription_update(self, follow_events=None, favourite_events=None, reblog_events=None, mention_events=None): """ Modifies what kind of events the app wishes to subscribe to. Returns the updated `push subscription dict`_. """ params = {} if follow_events != None: params['data[alerts][follow]'] = follow_events if favourite_events != None: params['data[alerts][favourite]'] = favourite_events if reblog_events != None: params['data[alerts][reblog]'] = reblog_events if mention_events != None: params['data[alerts][mention]'] = mention_events return self.__api_request('PUT', '/api/v1/push/subscription', params)
[ "def", "push_subscription_update", "(", "self", ",", "follow_events", "=", "None", ",", "favourite_events", "=", "None", ",", "reblog_events", "=", "None", ",", "mention_events", "=", "None", ")", ":", "params", "=", "{", "}", "if", "follow_events", "!=", "None", ":", "params", "[", "'data[alerts][follow]'", "]", "=", "follow_events", "if", "favourite_events", "!=", "None", ":", "params", "[", "'data[alerts][favourite]'", "]", "=", "favourite_events", "if", "reblog_events", "!=", "None", ":", "params", "[", "'data[alerts][reblog]'", "]", "=", "reblog_events", "if", "mention_events", "!=", "None", ":", "params", "[", "'data[alerts][mention]'", "]", "=", "mention_events", "return", "self", ".", "__api_request", "(", "'PUT'", ",", "'/api/v1/push/subscription'", ",", "params", ")" ]
Modifies what kind of events the app wishes to subscribe to. Returns the updated `push subscription dict`_.
[ "Modifies", "what", "kind", "of", "events", "the", "app", "wishes", "to", "subscribe", "to", ".", "Returns", "the", "updated", "push", "subscription", "dict", "_", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2235-L2257
train
238,732
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.stream_user
def stream_user(self, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): """ Streams events that are relevant to the authorized user, i.e. home timeline and notifications. """ return self.__stream('/api/v1/streaming/user', listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec)
python
def stream_user(self, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): """ Streams events that are relevant to the authorized user, i.e. home timeline and notifications. """ return self.__stream('/api/v1/streaming/user', listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec)
[ "def", "stream_user", "(", "self", ",", "listener", ",", "run_async", "=", "False", ",", "timeout", "=", "__DEFAULT_STREAM_TIMEOUT", ",", "reconnect_async", "=", "False", ",", "reconnect_async_wait_sec", "=", "__DEFAULT_STREAM_RECONNECT_WAIT_SEC", ")", ":", "return", "self", ".", "__stream", "(", "'/api/v1/streaming/user'", ",", "listener", ",", "run_async", "=", "run_async", ",", "timeout", "=", "timeout", ",", "reconnect_async", "=", "reconnect_async", ",", "reconnect_async_wait_sec", "=", "reconnect_async_wait_sec", ")" ]
Streams events that are relevant to the authorized user, i.e. home timeline and notifications.
[ "Streams", "events", "that", "are", "relevant", "to", "the", "authorized", "user", "i", ".", "e", ".", "home", "timeline", "and", "notifications", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2393-L2398
train
238,733
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.stream_hashtag
def stream_hashtag(self, tag, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): """ Stream for all public statuses for the hashtag 'tag' seen by the connected instance. """ if tag.startswith("#"): raise MastodonIllegalArgumentError("Tag parameter should omit leading #") return self.__stream("/api/v1/streaming/hashtag?tag={}".format(tag), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec)
python
def stream_hashtag(self, tag, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): """ Stream for all public statuses for the hashtag 'tag' seen by the connected instance. """ if tag.startswith("#"): raise MastodonIllegalArgumentError("Tag parameter should omit leading #") return self.__stream("/api/v1/streaming/hashtag?tag={}".format(tag), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec)
[ "def", "stream_hashtag", "(", "self", ",", "tag", ",", "listener", ",", "run_async", "=", "False", ",", "timeout", "=", "__DEFAULT_STREAM_TIMEOUT", ",", "reconnect_async", "=", "False", ",", "reconnect_async_wait_sec", "=", "__DEFAULT_STREAM_RECONNECT_WAIT_SEC", ")", ":", "if", "tag", ".", "startswith", "(", "\"#\"", ")", ":", "raise", "MastodonIllegalArgumentError", "(", "\"Tag parameter should omit leading #\"", ")", "return", "self", ".", "__stream", "(", "\"/api/v1/streaming/hashtag?tag={}\"", ".", "format", "(", "tag", ")", ",", "listener", ",", "run_async", "=", "run_async", ",", "timeout", "=", "timeout", ",", "reconnect_async", "=", "reconnect_async", ",", "reconnect_async_wait_sec", "=", "reconnect_async_wait_sec", ")" ]
Stream for all public statuses for the hashtag 'tag' seen by the connected instance.
[ "Stream", "for", "all", "public", "statuses", "for", "the", "hashtag", "tag", "seen", "by", "the", "connected", "instance", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2415-L2422
train
238,734
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.stream_list
def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): """ Stream events for the current user, restricted to accounts on the given list. """ id = self.__unpack_id(id) return self.__stream("/api/v1/streaming/list?list={}".format(id), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec)
python
def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): """ Stream events for the current user, restricted to accounts on the given list. """ id = self.__unpack_id(id) return self.__stream("/api/v1/streaming/list?list={}".format(id), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec)
[ "def", "stream_list", "(", "self", ",", "id", ",", "listener", ",", "run_async", "=", "False", ",", "timeout", "=", "__DEFAULT_STREAM_TIMEOUT", ",", "reconnect_async", "=", "False", ",", "reconnect_async_wait_sec", "=", "__DEFAULT_STREAM_RECONNECT_WAIT_SEC", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "return", "self", ".", "__stream", "(", "\"/api/v1/streaming/list?list={}\"", ".", "format", "(", "id", ")", ",", "listener", ",", "run_async", "=", "run_async", ",", "timeout", "=", "timeout", ",", "reconnect_async", "=", "reconnect_async", ",", "reconnect_async_wait_sec", "=", "reconnect_async_wait_sec", ")" ]
Stream events for the current user, restricted to accounts on the given list.
[ "Stream", "events", "for", "the", "current", "user", "restricted", "to", "accounts", "on", "the", "given", "list", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2425-L2431
train
238,735
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__datetime_to_epoch
def __datetime_to_epoch(self, date_time): """ Converts a python datetime to unix epoch, accounting for time zones and such. Assumes UTC if timezone is not given. """ date_time_utc = None if date_time.tzinfo is None: date_time_utc = date_time.replace(tzinfo=pytz.utc) else: date_time_utc = date_time.astimezone(pytz.utc) epoch_utc = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc) return (date_time_utc - epoch_utc).total_seconds()
python
def __datetime_to_epoch(self, date_time): """ Converts a python datetime to unix epoch, accounting for time zones and such. Assumes UTC if timezone is not given. """ date_time_utc = None if date_time.tzinfo is None: date_time_utc = date_time.replace(tzinfo=pytz.utc) else: date_time_utc = date_time.astimezone(pytz.utc) epoch_utc = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc) return (date_time_utc - epoch_utc).total_seconds()
[ "def", "__datetime_to_epoch", "(", "self", ",", "date_time", ")", ":", "date_time_utc", "=", "None", "if", "date_time", ".", "tzinfo", "is", "None", ":", "date_time_utc", "=", "date_time", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "else", ":", "date_time_utc", "=", "date_time", ".", "astimezone", "(", "pytz", ".", "utc", ")", "epoch_utc", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "0", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "return", "(", "date_time_utc", "-", "epoch_utc", ")", ".", "total_seconds", "(", ")" ]
Converts a python datetime to unix epoch, accounting for time zones and such. Assumes UTC if timezone is not given.
[ "Converts", "a", "python", "datetime", "to", "unix", "epoch", "accounting", "for", "time", "zones", "and", "such", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2443-L2458
train
238,736
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__get_logged_in_id
def __get_logged_in_id(self): """ Fetch the logged in users ID, with caching. ID is reset on calls to log_in. """ if self.__logged_in_id == None: self.__logged_in_id = self.account_verify_credentials().id return self.__logged_in_id
python
def __get_logged_in_id(self): """ Fetch the logged in users ID, with caching. ID is reset on calls to log_in. """ if self.__logged_in_id == None: self.__logged_in_id = self.account_verify_credentials().id return self.__logged_in_id
[ "def", "__get_logged_in_id", "(", "self", ")", ":", "if", "self", ".", "__logged_in_id", "==", "None", ":", "self", ".", "__logged_in_id", "=", "self", ".", "account_verify_credentials", "(", ")", ".", "id", "return", "self", ".", "__logged_in_id" ]
Fetch the logged in users ID, with caching. ID is reset on calls to log_in.
[ "Fetch", "the", "logged", "in", "users", "ID", "with", "caching", ".", "ID", "is", "reset", "on", "calls", "to", "log_in", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2460-L2466
train
238,737
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__json_date_parse
def __json_date_parse(json_object): """ Parse dates in certain known json fields, if possible. """ known_date_fields = ["created_at", "week", "day", "expires_at", "scheduled_at"] for k, v in json_object.items(): if k in known_date_fields: if v != None: try: if isinstance(v, int): json_object[k] = datetime.datetime.fromtimestamp(v, pytz.utc) else: json_object[k] = dateutil.parser.parse(v) except: raise MastodonAPIError('Encountered invalid date.') return json_object
python
def __json_date_parse(json_object): """ Parse dates in certain known json fields, if possible. """ known_date_fields = ["created_at", "week", "day", "expires_at", "scheduled_at"] for k, v in json_object.items(): if k in known_date_fields: if v != None: try: if isinstance(v, int): json_object[k] = datetime.datetime.fromtimestamp(v, pytz.utc) else: json_object[k] = dateutil.parser.parse(v) except: raise MastodonAPIError('Encountered invalid date.') return json_object
[ "def", "__json_date_parse", "(", "json_object", ")", ":", "known_date_fields", "=", "[", "\"created_at\"", ",", "\"week\"", ",", "\"day\"", ",", "\"expires_at\"", ",", "\"scheduled_at\"", "]", "for", "k", ",", "v", "in", "json_object", ".", "items", "(", ")", ":", "if", "k", "in", "known_date_fields", ":", "if", "v", "!=", "None", ":", "try", ":", "if", "isinstance", "(", "v", ",", "int", ")", ":", "json_object", "[", "k", "]", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "v", ",", "pytz", ".", "utc", ")", "else", ":", "json_object", "[", "k", "]", "=", "dateutil", ".", "parser", ".", "parse", "(", "v", ")", "except", ":", "raise", "MastodonAPIError", "(", "'Encountered invalid date.'", ")", "return", "json_object" ]
Parse dates in certain known json fields, if possible.
[ "Parse", "dates", "in", "certain", "known", "json", "fields", "if", "possible", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2480-L2495
train
238,738
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__json_strnum_to_bignum
def __json_strnum_to_bignum(json_object): """ Converts json string numerals to native python bignums. """ for key in ('id', 'week', 'in_reply_to_id', 'in_reply_to_account_id', 'logins', 'registrations', 'statuses'): if (key in json_object and isinstance(json_object[key], six.text_type)): try: json_object[key] = int(json_object[key]) except ValueError: pass return json_object
python
def __json_strnum_to_bignum(json_object): """ Converts json string numerals to native python bignums. """ for key in ('id', 'week', 'in_reply_to_id', 'in_reply_to_account_id', 'logins', 'registrations', 'statuses'): if (key in json_object and isinstance(json_object[key], six.text_type)): try: json_object[key] = int(json_object[key]) except ValueError: pass return json_object
[ "def", "__json_strnum_to_bignum", "(", "json_object", ")", ":", "for", "key", "in", "(", "'id'", ",", "'week'", ",", "'in_reply_to_id'", ",", "'in_reply_to_account_id'", ",", "'logins'", ",", "'registrations'", ",", "'statuses'", ")", ":", "if", "(", "key", "in", "json_object", "and", "isinstance", "(", "json_object", "[", "key", "]", ",", "six", ".", "text_type", ")", ")", ":", "try", ":", "json_object", "[", "key", "]", "=", "int", "(", "json_object", "[", "key", "]", ")", "except", "ValueError", ":", "pass", "return", "json_object" ]
Converts json string numerals to native python bignums.
[ "Converts", "json", "string", "numerals", "to", "native", "python", "bignums", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2511-L2522
train
238,739
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__json_hooks
def __json_hooks(json_object): """ All the json hooks. Used in request parsing. """ json_object = Mastodon.__json_strnum_to_bignum(json_object) json_object = Mastodon.__json_date_parse(json_object) json_object = Mastodon.__json_truefalse_parse(json_object) json_object = Mastodon.__json_allow_dict_attrs(json_object) return json_object
python
def __json_hooks(json_object): """ All the json hooks. Used in request parsing. """ json_object = Mastodon.__json_strnum_to_bignum(json_object) json_object = Mastodon.__json_date_parse(json_object) json_object = Mastodon.__json_truefalse_parse(json_object) json_object = Mastodon.__json_allow_dict_attrs(json_object) return json_object
[ "def", "__json_hooks", "(", "json_object", ")", ":", "json_object", "=", "Mastodon", ".", "__json_strnum_to_bignum", "(", "json_object", ")", "json_object", "=", "Mastodon", ".", "__json_date_parse", "(", "json_object", ")", "json_object", "=", "Mastodon", ".", "__json_truefalse_parse", "(", "json_object", ")", "json_object", "=", "Mastodon", ".", "__json_allow_dict_attrs", "(", "json_object", ")", "return", "json_object" ]
All the json hooks. Used in request parsing.
[ "All", "the", "json", "hooks", ".", "Used", "in", "request", "parsing", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2525-L2533
train
238,740
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__consistent_isoformat_utc
def __consistent_isoformat_utc(datetime_val): """ Function that does what isoformat does but it actually does the same every time instead of randomly doing different things on some systems and also it represents that time as the equivalent UTC time. """ isotime = datetime_val.astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S%z") if isotime[-2] != ":": isotime = isotime[:-2] + ":" + isotime[-2:] return isotime
python
def __consistent_isoformat_utc(datetime_val): """ Function that does what isoformat does but it actually does the same every time instead of randomly doing different things on some systems and also it represents that time as the equivalent UTC time. """ isotime = datetime_val.astimezone(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S%z") if isotime[-2] != ":": isotime = isotime[:-2] + ":" + isotime[-2:] return isotime
[ "def", "__consistent_isoformat_utc", "(", "datetime_val", ")", ":", "isotime", "=", "datetime_val", ".", "astimezone", "(", "pytz", ".", "utc", ")", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%S%z\"", ")", "if", "isotime", "[", "-", "2", "]", "!=", "\":\"", ":", "isotime", "=", "isotime", "[", ":", "-", "2", "]", "+", "\":\"", "+", "isotime", "[", "-", "2", ":", "]", "return", "isotime" ]
Function that does what isoformat does but it actually does the same every time instead of randomly doing different things on some systems and also it represents that time as the equivalent UTC time.
[ "Function", "that", "does", "what", "isoformat", "does", "but", "it", "actually", "does", "the", "same", "every", "time", "instead", "of", "randomly", "doing", "different", "things", "on", "some", "systems", "and", "also", "it", "represents", "that", "time", "as", "the", "equivalent", "UTC", "time", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2536-L2545
train
238,741
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__generate_params
def __generate_params(self, params, exclude=[]): """ Internal named-parameters-to-dict helper. Note for developers: If called with locals() as params, as is the usual practice in this code, the __generate_params call (or at least the locals() call) should generally be the first thing in your function. """ params = collections.OrderedDict(params) del params['self'] param_keys = list(params.keys()) for key in param_keys: if isinstance(params[key], bool) and params[key] == False: params[key] = '0' if isinstance(params[key], bool) and params[key] == True: params[key] = '1' for key in param_keys: if params[key] is None or key in exclude: del params[key] param_keys = list(params.keys()) for key in param_keys: if isinstance(params[key], list): params[key + "[]"] = params[key] del params[key] return params
python
def __generate_params(self, params, exclude=[]): """ Internal named-parameters-to-dict helper. Note for developers: If called with locals() as params, as is the usual practice in this code, the __generate_params call (or at least the locals() call) should generally be the first thing in your function. """ params = collections.OrderedDict(params) del params['self'] param_keys = list(params.keys()) for key in param_keys: if isinstance(params[key], bool) and params[key] == False: params[key] = '0' if isinstance(params[key], bool) and params[key] == True: params[key] = '1' for key in param_keys: if params[key] is None or key in exclude: del params[key] param_keys = list(params.keys()) for key in param_keys: if isinstance(params[key], list): params[key + "[]"] = params[key] del params[key] return params
[ "def", "__generate_params", "(", "self", ",", "params", ",", "exclude", "=", "[", "]", ")", ":", "params", "=", "collections", ".", "OrderedDict", "(", "params", ")", "del", "params", "[", "'self'", "]", "param_keys", "=", "list", "(", "params", ".", "keys", "(", ")", ")", "for", "key", "in", "param_keys", ":", "if", "isinstance", "(", "params", "[", "key", "]", ",", "bool", ")", "and", "params", "[", "key", "]", "==", "False", ":", "params", "[", "key", "]", "=", "'0'", "if", "isinstance", "(", "params", "[", "key", "]", ",", "bool", ")", "and", "params", "[", "key", "]", "==", "True", ":", "params", "[", "key", "]", "=", "'1'", "for", "key", "in", "param_keys", ":", "if", "params", "[", "key", "]", "is", "None", "or", "key", "in", "exclude", ":", "del", "params", "[", "key", "]", "param_keys", "=", "list", "(", "params", ".", "keys", "(", ")", ")", "for", "key", "in", "param_keys", ":", "if", "isinstance", "(", "params", "[", "key", "]", ",", "list", ")", ":", "params", "[", "key", "+", "\"[]\"", "]", "=", "params", "[", "key", "]", "del", "params", "[", "key", "]", "return", "params" ]
Internal named-parameters-to-dict helper. Note for developers: If called with locals() as params, as is the usual practice in this code, the __generate_params call (or at least the locals() call) should generally be the first thing in your function.
[ "Internal", "named", "-", "parameters", "-", "to", "-", "dict", "helper", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2867-L2896
train
238,742
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__decode_webpush_b64
def __decode_webpush_b64(self, data): """ Re-pads and decodes urlsafe base64. """ missing_padding = len(data) % 4 if missing_padding != 0: data += '=' * (4 - missing_padding) return base64.urlsafe_b64decode(data)
python
def __decode_webpush_b64(self, data): """ Re-pads and decodes urlsafe base64. """ missing_padding = len(data) % 4 if missing_padding != 0: data += '=' * (4 - missing_padding) return base64.urlsafe_b64decode(data)
[ "def", "__decode_webpush_b64", "(", "self", ",", "data", ")", ":", "missing_padding", "=", "len", "(", "data", ")", "%", "4", "if", "missing_padding", "!=", "0", ":", "data", "+=", "'='", "*", "(", "4", "-", "missing_padding", ")", "return", "base64", ".", "urlsafe_b64decode", "(", "data", ")" ]
Re-pads and decodes urlsafe base64.
[ "Re", "-", "pads", "and", "decodes", "urlsafe", "base64", "." ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2911-L2918
train
238,743
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__set_token_expired
def __set_token_expired(self, value): """Internal helper for oauth code""" self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value) return
python
def __set_token_expired(self, value): """Internal helper for oauth code""" self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value) return
[ "def", "__set_token_expired", "(", "self", ",", "value", ")", ":", "self", ".", "_token_expired", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "value", ")", "return" ]
Internal helper for oauth code
[ "Internal", "helper", "for", "oauth", "code" ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2924-L2927
train
238,744
halcy/Mastodon.py
mastodon/Mastodon.py
Mastodon.__protocolize
def __protocolize(base_url): """Internal add-protocol-to-url helper""" if not base_url.startswith("http://") and not base_url.startswith("https://"): base_url = "https://" + base_url # Some API endpoints can't handle extra /'s in path requests base_url = base_url.rstrip("/") return base_url
python
def __protocolize(base_url): """Internal add-protocol-to-url helper""" if not base_url.startswith("http://") and not base_url.startswith("https://"): base_url = "https://" + base_url # Some API endpoints can't handle extra /'s in path requests base_url = base_url.rstrip("/") return base_url
[ "def", "__protocolize", "(", "base_url", ")", ":", "if", "not", "base_url", ".", "startswith", "(", "\"http://\"", ")", "and", "not", "base_url", ".", "startswith", "(", "\"https://\"", ")", ":", "base_url", "=", "\"https://\"", "+", "base_url", "# Some API endpoints can't handle extra /'s in path requests", "base_url", "=", "base_url", ".", "rstrip", "(", "\"/\"", ")", "return", "base_url" ]
Internal add-protocol-to-url helper
[ "Internal", "add", "-", "protocol", "-", "to", "-", "url", "helper" ]
35c43562dd3d34d6ebf7a0f757c09e8fcccc957c
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2939-L2946
train
238,745
faucamp/python-gsmmodem
gsmmodem/modem.py
SentSms.status
def status(self): """ Status of this SMS. Can be ENROUTE, DELIVERED or FAILED The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED' """ if self.report == None: return SentSms.ENROUTE else: return SentSms.DELIVERED if self.report.deliveryStatus == StatusReport.DELIVERED else SentSms.FAILED
python
def status(self): """ Status of this SMS. Can be ENROUTE, DELIVERED or FAILED The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED' """ if self.report == None: return SentSms.ENROUTE else: return SentSms.DELIVERED if self.report.deliveryStatus == StatusReport.DELIVERED else SentSms.FAILED
[ "def", "status", "(", "self", ")", ":", "if", "self", ".", "report", "==", "None", ":", "return", "SentSms", ".", "ENROUTE", "else", ":", "return", "SentSms", ".", "DELIVERED", "if", "self", ".", "report", ".", "deliveryStatus", "==", "StatusReport", ".", "DELIVERED", "else", "SentSms", ".", "FAILED" ]
Status of this SMS. Can be ENROUTE, DELIVERED or FAILED The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED'
[ "Status", "of", "this", "SMS", ".", "Can", "be", "ENROUTE", "DELIVERED", "or", "FAILED", "The", "actual", "status", "report", "object", "may", "be", "accessed", "via", "the", "report", "attribute", "if", "status", "is", "DELIVERED", "or", "FAILED" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L76-L85
train
238,746
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem.write
def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): """ Write data to the modem. This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and writes it to the modem. :param data: Command/data to be written to the modem :type data: str :param waitForResponse: Whether this method should block and return the response from the modem or not :type waitForResponse: bool :param timeout: Maximum amount of time in seconds to wait for a response from the modem :type timeout: int :param parseError: If True, a CommandError is raised if the modem responds with an error (otherwise the response is returned as-is) :type parseError: bool :param writeTerm: The terminating sequence to append to the written data :type writeTerm: str :param expectedResponseTermSeq: The expected terminating sequence that marks the end of the modem's response (defaults to ``\\r\\n``) :type expectedResponseTermSeq: str :raise CommandError: if the command returns an error (only if parseError parameter is True) :raise TimeoutException: if no response to the command was received from the modem :return: A list containing the response lines from the modem, or None if waitForResponse is False :rtype: list """ self.log.debug('write: %s', data) responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq) if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load) time.sleep(self._writeWait) if waitForResponse: cmdStatusLine = responseLines[-1] if parseError: if 'ERROR' in cmdStatusLine: cmErrorMatch = self.CM_ERROR_REGEX.match(cmdStatusLine) if cmErrorMatch: errorType = cmErrorMatch.group(1) errorCode = int(cmErrorMatch.group(2)) if errorCode == 515 or errorCode == 14: # 515 means: "Please wait, init or command processing in progress." # 14 means "SIM busy" self._writeWait += 0.2 # Increase waiting period temporarily # Retry the command after waiting a bit self.log.debug('Device/SIM busy error detected; self._writeWait adjusted to %fs', self._writeWait) time.sleep(self._writeWait) result = self.write(data, waitForResponse, timeout, parseError, writeTerm, expectedResponseTermSeq) self.log.debug('self_writeWait set to 0.1 because of recovering from device busy (515) error') if errorCode == 515: self._writeWait = 0.1 # Set this to something sane for further commands (slow modem) else: self._writeWait = 0 # The modem was just waiting for the SIM card return result if errorType == 'CME': raise CmeError(data, int(errorCode)) else: # CMS error raise CmsError(data, int(errorCode)) else: raise CommandError(data) elif cmdStatusLine == 'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands raise CommandError(data + '({0})'.format(cmdStatusLine)) return responseLines
python
def write(self, data, waitForResponse=True, timeout=5, parseError=True, writeTerm='\r', expectedResponseTermSeq=None): """ Write data to the modem. This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and writes it to the modem. :param data: Command/data to be written to the modem :type data: str :param waitForResponse: Whether this method should block and return the response from the modem or not :type waitForResponse: bool :param timeout: Maximum amount of time in seconds to wait for a response from the modem :type timeout: int :param parseError: If True, a CommandError is raised if the modem responds with an error (otherwise the response is returned as-is) :type parseError: bool :param writeTerm: The terminating sequence to append to the written data :type writeTerm: str :param expectedResponseTermSeq: The expected terminating sequence that marks the end of the modem's response (defaults to ``\\r\\n``) :type expectedResponseTermSeq: str :raise CommandError: if the command returns an error (only if parseError parameter is True) :raise TimeoutException: if no response to the command was received from the modem :return: A list containing the response lines from the modem, or None if waitForResponse is False :rtype: list """ self.log.debug('write: %s', data) responseLines = super(GsmModem, self).write(data + writeTerm, waitForResponse=waitForResponse, timeout=timeout, expectedResponseTermSeq=expectedResponseTermSeq) if self._writeWait > 0: # Sleep a bit if required (some older modems suffer under load) time.sleep(self._writeWait) if waitForResponse: cmdStatusLine = responseLines[-1] if parseError: if 'ERROR' in cmdStatusLine: cmErrorMatch = self.CM_ERROR_REGEX.match(cmdStatusLine) if cmErrorMatch: errorType = cmErrorMatch.group(1) errorCode = int(cmErrorMatch.group(2)) if errorCode == 515 or errorCode == 14: # 515 means: "Please wait, init or command processing in progress." # 14 means "SIM busy" self._writeWait += 0.2 # Increase waiting period temporarily # Retry the command after waiting a bit self.log.debug('Device/SIM busy error detected; self._writeWait adjusted to %fs', self._writeWait) time.sleep(self._writeWait) result = self.write(data, waitForResponse, timeout, parseError, writeTerm, expectedResponseTermSeq) self.log.debug('self_writeWait set to 0.1 because of recovering from device busy (515) error') if errorCode == 515: self._writeWait = 0.1 # Set this to something sane for further commands (slow modem) else: self._writeWait = 0 # The modem was just waiting for the SIM card return result if errorType == 'CME': raise CmeError(data, int(errorCode)) else: # CMS error raise CmsError(data, int(errorCode)) else: raise CommandError(data) elif cmdStatusLine == 'COMMAND NOT SUPPORT': # Some Huawei modems respond with this for unknown commands raise CommandError(data + '({0})'.format(cmdStatusLine)) return responseLines
[ "def", "write", "(", "self", ",", "data", ",", "waitForResponse", "=", "True", ",", "timeout", "=", "5", ",", "parseError", "=", "True", ",", "writeTerm", "=", "'\\r'", ",", "expectedResponseTermSeq", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "'write: %s'", ",", "data", ")", "responseLines", "=", "super", "(", "GsmModem", ",", "self", ")", ".", "write", "(", "data", "+", "writeTerm", ",", "waitForResponse", "=", "waitForResponse", ",", "timeout", "=", "timeout", ",", "expectedResponseTermSeq", "=", "expectedResponseTermSeq", ")", "if", "self", ".", "_writeWait", ">", "0", ":", "# Sleep a bit if required (some older modems suffer under load) ", "time", ".", "sleep", "(", "self", ".", "_writeWait", ")", "if", "waitForResponse", ":", "cmdStatusLine", "=", "responseLines", "[", "-", "1", "]", "if", "parseError", ":", "if", "'ERROR'", "in", "cmdStatusLine", ":", "cmErrorMatch", "=", "self", ".", "CM_ERROR_REGEX", ".", "match", "(", "cmdStatusLine", ")", "if", "cmErrorMatch", ":", "errorType", "=", "cmErrorMatch", ".", "group", "(", "1", ")", "errorCode", "=", "int", "(", "cmErrorMatch", ".", "group", "(", "2", ")", ")", "if", "errorCode", "==", "515", "or", "errorCode", "==", "14", ":", "# 515 means: \"Please wait, init or command processing in progress.\"", "# 14 means \"SIM busy\"", "self", ".", "_writeWait", "+=", "0.2", "# Increase waiting period temporarily", "# Retry the command after waiting a bit", "self", ".", "log", ".", "debug", "(", "'Device/SIM busy error detected; self._writeWait adjusted to %fs'", ",", "self", ".", "_writeWait", ")", "time", ".", "sleep", "(", "self", ".", "_writeWait", ")", "result", "=", "self", ".", "write", "(", "data", ",", "waitForResponse", ",", "timeout", ",", "parseError", ",", "writeTerm", ",", "expectedResponseTermSeq", ")", "self", ".", "log", ".", "debug", "(", "'self_writeWait set to 0.1 because of recovering from device busy (515) error'", ")", "if", "errorCode", "==", "515", ":", "self", ".", "_writeWait", "=", "0.1", "# Set this to something sane for further commands (slow modem)", "else", ":", "self", ".", "_writeWait", "=", "0", "# The modem was just waiting for the SIM card", "return", "result", "if", "errorType", "==", "'CME'", ":", "raise", "CmeError", "(", "data", ",", "int", "(", "errorCode", ")", ")", "else", ":", "# CMS error", "raise", "CmsError", "(", "data", ",", "int", "(", "errorCode", ")", ")", "else", ":", "raise", "CommandError", "(", "data", ")", "elif", "cmdStatusLine", "==", "'COMMAND NOT SUPPORT'", ":", "# Some Huawei modems respond with this for unknown commands", "raise", "CommandError", "(", "data", "+", "'({0})'", ".", "format", "(", "cmdStatusLine", ")", ")", "return", "responseLines" ]
Write data to the modem. This method adds the ``\\r\\n`` end-of-line sequence to the data parameter, and writes it to the modem. :param data: Command/data to be written to the modem :type data: str :param waitForResponse: Whether this method should block and return the response from the modem or not :type waitForResponse: bool :param timeout: Maximum amount of time in seconds to wait for a response from the modem :type timeout: int :param parseError: If True, a CommandError is raised if the modem responds with an error (otherwise the response is returned as-is) :type parseError: bool :param writeTerm: The terminating sequence to append to the written data :type writeTerm: str :param expectedResponseTermSeq: The expected terminating sequence that marks the end of the modem's response (defaults to ``\\r\\n``) :type expectedResponseTermSeq: str :raise CommandError: if the command returns an error (only if parseError parameter is True) :raise TimeoutException: if no response to the command was received from the modem :return: A list containing the response lines from the modem, or None if waitForResponse is False :rtype: list
[ "Write", "data", "to", "the", "modem", "." ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L387-L446
train
238,747
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem.smsTextMode
def smsTextMode(self, textMode): """ Set to True for the modem to use text mode for SMS, or False for it to use PDU mode """ if textMode != self._smsTextMode: if self.alive: self.write('AT+CMGF={0}'.format(1 if textMode else 0)) self._smsTextMode = textMode self._compileSmsRegexes()
python
def smsTextMode(self, textMode): """ Set to True for the modem to use text mode for SMS, or False for it to use PDU mode """ if textMode != self._smsTextMode: if self.alive: self.write('AT+CMGF={0}'.format(1 if textMode else 0)) self._smsTextMode = textMode self._compileSmsRegexes()
[ "def", "smsTextMode", "(", "self", ",", "textMode", ")", ":", "if", "textMode", "!=", "self", ".", "_smsTextMode", ":", "if", "self", ".", "alive", ":", "self", ".", "write", "(", "'AT+CMGF={0}'", ".", "format", "(", "1", "if", "textMode", "else", "0", ")", ")", "self", ".", "_smsTextMode", "=", "textMode", "self", ".", "_compileSmsRegexes", "(", ")" ]
Set to True for the modem to use text mode for SMS, or False for it to use PDU mode
[ "Set", "to", "True", "for", "the", "modem", "to", "use", "text", "mode", "for", "SMS", "or", "False", "for", "it", "to", "use", "PDU", "mode" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L524-L530
train
238,748
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem._compileSmsRegexes
def _compileSmsRegexes(self): """ Compiles regular expression used for parsing SMS messages based on current mode """ if self._smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$')
python
def _compileSmsRegexes(self): """ Compiles regular expression used for parsing SMS messages based on current mode """ if self._smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$')
[ "def", "_compileSmsRegexes", "(", "self", ")", ":", "if", "self", ".", "_smsTextMode", ":", "if", "self", ".", "CMGR_SM_DELIVER_REGEX_TEXT", "==", "None", ":", "self", ".", "CMGR_SM_DELIVER_REGEX_TEXT", "=", "re", ".", "compile", "(", "r'^\\+CMGR: \"([^\"]+)\",\"([^\"]+)\",[^,]*,\"([^\"]+)\"$'", ")", "self", ".", "CMGR_SM_REPORT_REGEXT_TEXT", "=", "re", ".", "compile", "(", "r'^\\+CMGR: ([^,]*),\\d+,(\\d+),\"{0,1}([^\"]*)\"{0,1},\\d*,\"([^\"]+)\",\"([^\"]+)\",(\\d+)$'", ")", "elif", "self", ".", "CMGR_REGEX_PDU", "==", "None", ":", "self", ".", "CMGR_REGEX_PDU", "=", "re", ".", "compile", "(", "r'^\\+CMGR: (\\d*),\"{0,1}([^\"]*)\"{0,1},(\\d+)$'", ")" ]
Compiles regular expression used for parsing SMS messages based on current mode
[ "Compiles", "regular", "expression", "used", "for", "parsing", "SMS", "messages", "based", "on", "current", "mode" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L545-L552
train
238,749
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem.smsc
def smsc(self, smscNumber): """ Set the default SMSC number to use when sending SMS messages """ if smscNumber != self._smscNumber: if self.alive: self.write('AT+CSCA="{0}"'.format(smscNumber)) self._smscNumber = smscNumber
python
def smsc(self, smscNumber): """ Set the default SMSC number to use when sending SMS messages """ if smscNumber != self._smscNumber: if self.alive: self.write('AT+CSCA="{0}"'.format(smscNumber)) self._smscNumber = smscNumber
[ "def", "smsc", "(", "self", ",", "smscNumber", ")", ":", "if", "smscNumber", "!=", "self", ".", "_smscNumber", ":", "if", "self", ".", "alive", ":", "self", ".", "write", "(", "'AT+CSCA=\"{0}\"'", ".", "format", "(", "smscNumber", ")", ")", "self", ".", "_smscNumber", "=", "smscNumber" ]
Set the default SMSC number to use when sending SMS messages
[ "Set", "the", "default", "SMSC", "number", "to", "use", "when", "sending", "SMS", "messages" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L568-L573
train
238,750
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem.dial
def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call :param number: The phone number to dial :param timeout: Maximum time to wait for the call to be established :param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to remote events (i.e. when it is answered, the call is ended by the remote party) :return: The outgoing call :rtype: gsmmodem.modem.Call """ if self._waitForCallInitUpdate: # Wait for the "call originated" notification message self._dialEvent = threading.Event() try: self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) except Exception: self._dialEvent = None # Cancel the thread sync lock raise else: # Don't wait for a call init update - base the call ID on the number of active calls self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) self.log.debug("Not waiting for outgoing call init update message") callId = len(self.activeCalls) + 1 callType = 0 # Assume voice call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) self.activeCalls[callId] = call return call if self._mustPollCallStatus: # Fake a call notification by polling call status until the status indicates that the call is being dialed threading.Thread(target=self._pollCallStatus, kwargs={'expectedState': 0, 'timeout': timeout}).start() if self._dialEvent.wait(timeout): self._dialEvent = None callId, callType = self._dialResponse call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) self.activeCalls[callId] = call return call else: # Call establishing timed out self._dialEvent = None raise TimeoutException()
python
def dial(self, number, timeout=5, callStatusUpdateCallbackFunc=None): """ Calls the specified phone number using a voice phone call :param number: The phone number to dial :param timeout: Maximum time to wait for the call to be established :param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to remote events (i.e. when it is answered, the call is ended by the remote party) :return: The outgoing call :rtype: gsmmodem.modem.Call """ if self._waitForCallInitUpdate: # Wait for the "call originated" notification message self._dialEvent = threading.Event() try: self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) except Exception: self._dialEvent = None # Cancel the thread sync lock raise else: # Don't wait for a call init update - base the call ID on the number of active calls self.write('ATD{0};'.format(number), timeout=timeout, waitForResponse=self._waitForAtdResponse) self.log.debug("Not waiting for outgoing call init update message") callId = len(self.activeCalls) + 1 callType = 0 # Assume voice call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) self.activeCalls[callId] = call return call if self._mustPollCallStatus: # Fake a call notification by polling call status until the status indicates that the call is being dialed threading.Thread(target=self._pollCallStatus, kwargs={'expectedState': 0, 'timeout': timeout}).start() if self._dialEvent.wait(timeout): self._dialEvent = None callId, callType = self._dialResponse call = Call(self, callId, callType, number, callStatusUpdateCallbackFunc) self.activeCalls[callId] = call return call else: # Call establishing timed out self._dialEvent = None raise TimeoutException()
[ "def", "dial", "(", "self", ",", "number", ",", "timeout", "=", "5", ",", "callStatusUpdateCallbackFunc", "=", "None", ")", ":", "if", "self", ".", "_waitForCallInitUpdate", ":", "# Wait for the \"call originated\" notification message", "self", ".", "_dialEvent", "=", "threading", ".", "Event", "(", ")", "try", ":", "self", ".", "write", "(", "'ATD{0};'", ".", "format", "(", "number", ")", ",", "timeout", "=", "timeout", ",", "waitForResponse", "=", "self", ".", "_waitForAtdResponse", ")", "except", "Exception", ":", "self", ".", "_dialEvent", "=", "None", "# Cancel the thread sync lock", "raise", "else", ":", "# Don't wait for a call init update - base the call ID on the number of active calls", "self", ".", "write", "(", "'ATD{0};'", ".", "format", "(", "number", ")", ",", "timeout", "=", "timeout", ",", "waitForResponse", "=", "self", ".", "_waitForAtdResponse", ")", "self", ".", "log", ".", "debug", "(", "\"Not waiting for outgoing call init update message\"", ")", "callId", "=", "len", "(", "self", ".", "activeCalls", ")", "+", "1", "callType", "=", "0", "# Assume voice", "call", "=", "Call", "(", "self", ",", "callId", ",", "callType", ",", "number", ",", "callStatusUpdateCallbackFunc", ")", "self", ".", "activeCalls", "[", "callId", "]", "=", "call", "return", "call", "if", "self", ".", "_mustPollCallStatus", ":", "# Fake a call notification by polling call status until the status indicates that the call is being dialed", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_pollCallStatus", ",", "kwargs", "=", "{", "'expectedState'", ":", "0", ",", "'timeout'", ":", "timeout", "}", ")", ".", "start", "(", ")", "if", "self", ".", "_dialEvent", ".", "wait", "(", "timeout", ")", ":", "self", ".", "_dialEvent", "=", "None", "callId", ",", "callType", "=", "self", ".", "_dialResponse", "call", "=", "Call", "(", "self", ",", "callId", ",", "callType", ",", "number", ",", "callStatusUpdateCallbackFunc", ")", "self", ".", "activeCalls", "[", "callId", "]", "=", "call", "return", "call", "else", ":", "# Call establishing timed out", "self", ".", "_dialEvent", "=", "None", "raise", "TimeoutException", "(", ")" ]
Calls the specified phone number using a voice phone call :param number: The phone number to dial :param timeout: Maximum time to wait for the call to be established :param callStatusUpdateCallbackFunc: Callback function that is executed if the call's status changes due to remote events (i.e. when it is answered, the call is ended by the remote party) :return: The outgoing call :rtype: gsmmodem.modem.Call
[ "Calls", "the", "specified", "phone", "number", "using", "a", "voice", "phone", "call" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L701-L742
train
238,751
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem._handleCallInitiated
def _handleCallInitiated(self, regexMatch, callId=None, callType=1): """ Handler for "outgoing call initiated" event notification line """ if self._dialEvent: if regexMatch: groups = regexMatch.groups() # Set self._dialReponse to (callId, callType) if len(groups) >= 2: self._dialResponse = (int(groups[0]) , int(groups[1])) else: self._dialResponse = (int(groups[0]), 1) # assume call type: VOICE else: self._dialResponse = callId, callType self._dialEvent.set()
python
def _handleCallInitiated(self, regexMatch, callId=None, callType=1): """ Handler for "outgoing call initiated" event notification line """ if self._dialEvent: if regexMatch: groups = regexMatch.groups() # Set self._dialReponse to (callId, callType) if len(groups) >= 2: self._dialResponse = (int(groups[0]) , int(groups[1])) else: self._dialResponse = (int(groups[0]), 1) # assume call type: VOICE else: self._dialResponse = callId, callType self._dialEvent.set()
[ "def", "_handleCallInitiated", "(", "self", ",", "regexMatch", ",", "callId", "=", "None", ",", "callType", "=", "1", ")", ":", "if", "self", ".", "_dialEvent", ":", "if", "regexMatch", ":", "groups", "=", "regexMatch", ".", "groups", "(", ")", "# Set self._dialReponse to (callId, callType)", "if", "len", "(", "groups", ")", ">=", "2", ":", "self", ".", "_dialResponse", "=", "(", "int", "(", "groups", "[", "0", "]", ")", ",", "int", "(", "groups", "[", "1", "]", ")", ")", "else", ":", "self", ".", "_dialResponse", "=", "(", "int", "(", "groups", "[", "0", "]", ")", ",", "1", ")", "# assume call type: VOICE", "else", ":", "self", ".", "_dialResponse", "=", "callId", ",", "callType", "self", ".", "_dialEvent", ".", "set", "(", ")" ]
Handler for "outgoing call initiated" event notification line
[ "Handler", "for", "outgoing", "call", "initiated", "event", "notification", "line" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L935-L947
train
238,752
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem._handleCallAnswered
def _handleCallAnswered(self, regexMatch, callId=None): """ Handler for "outgoing call answered" event notification line """ if regexMatch: groups = regexMatch.groups() if len(groups) > 1: callId = int(groups[0]) self.activeCalls[callId].answered = True else: # Call ID not available for this notificition - check for the first outgoing call that has not been answered for call in dictValuesIter(self.activeCalls): if call.answered == False and type(call) == Call: call.answered = True return else: # Use supplied values self.activeCalls[callId].answered = True
python
def _handleCallAnswered(self, regexMatch, callId=None): """ Handler for "outgoing call answered" event notification line """ if regexMatch: groups = regexMatch.groups() if len(groups) > 1: callId = int(groups[0]) self.activeCalls[callId].answered = True else: # Call ID not available for this notificition - check for the first outgoing call that has not been answered for call in dictValuesIter(self.activeCalls): if call.answered == False and type(call) == Call: call.answered = True return else: # Use supplied values self.activeCalls[callId].answered = True
[ "def", "_handleCallAnswered", "(", "self", ",", "regexMatch", ",", "callId", "=", "None", ")", ":", "if", "regexMatch", ":", "groups", "=", "regexMatch", ".", "groups", "(", ")", "if", "len", "(", "groups", ")", ">", "1", ":", "callId", "=", "int", "(", "groups", "[", "0", "]", ")", "self", ".", "activeCalls", "[", "callId", "]", ".", "answered", "=", "True", "else", ":", "# Call ID not available for this notificition - check for the first outgoing call that has not been answered", "for", "call", "in", "dictValuesIter", "(", "self", ".", "activeCalls", ")", ":", "if", "call", ".", "answered", "==", "False", "and", "type", "(", "call", ")", "==", "Call", ":", "call", ".", "answered", "=", "True", "return", "else", ":", "# Use supplied values", "self", ".", "activeCalls", "[", "callId", "]", ".", "answered", "=", "True" ]
Handler for "outgoing call answered" event notification line
[ "Handler", "for", "outgoing", "call", "answered", "event", "notification", "line" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L949-L964
train
238,753
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem._handleSmsReceived
def _handleSmsReceived(self, notificationLine): """ Handler for "new SMS" unsolicited notification line """ self.log.debug('SMS message received') cmtiMatch = self.CMTI_REGEX.match(notificationLine) if cmtiMatch: msgMemory = cmtiMatch.group(1) msgIndex = cmtiMatch.group(2) sms = self.readStoredSms(msgIndex, msgMemory) self.deleteStoredSms(msgIndex) self.smsReceivedCallback(sms)
python
def _handleSmsReceived(self, notificationLine): """ Handler for "new SMS" unsolicited notification line """ self.log.debug('SMS message received') cmtiMatch = self.CMTI_REGEX.match(notificationLine) if cmtiMatch: msgMemory = cmtiMatch.group(1) msgIndex = cmtiMatch.group(2) sms = self.readStoredSms(msgIndex, msgMemory) self.deleteStoredSms(msgIndex) self.smsReceivedCallback(sms)
[ "def", "_handleSmsReceived", "(", "self", ",", "notificationLine", ")", ":", "self", ".", "log", ".", "debug", "(", "'SMS message received'", ")", "cmtiMatch", "=", "self", ".", "CMTI_REGEX", ".", "match", "(", "notificationLine", ")", "if", "cmtiMatch", ":", "msgMemory", "=", "cmtiMatch", ".", "group", "(", "1", ")", "msgIndex", "=", "cmtiMatch", ".", "group", "(", "2", ")", "sms", "=", "self", ".", "readStoredSms", "(", "msgIndex", ",", "msgMemory", ")", "self", ".", "deleteStoredSms", "(", "msgIndex", ")", "self", ".", "smsReceivedCallback", "(", "sms", ")" ]
Handler for "new SMS" unsolicited notification line
[ "Handler", "for", "new", "SMS", "unsolicited", "notification", "line" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L991-L1000
train
238,754
faucamp/python-gsmmodem
gsmmodem/modem.py
GsmModem._handleSmsStatusReport
def _handleSmsStatusReport(self, notificationLine): """ Handler for SMS status reports """ self.log.debug('SMS status report received') cdsiMatch = self.CDSI_REGEX.match(notificationLine) if cdsiMatch: msgMemory = cdsiMatch.group(1) msgIndex = cdsiMatch.group(2) report = self.readStoredSms(msgIndex, msgMemory) self.deleteStoredSms(msgIndex) # Update sent SMS status if possible if report.reference in self.sentSms: self.sentSms[report.reference].report = report if self._smsStatusReportEvent: # A sendSms() call is waiting for this response - notify waiting thread self._smsStatusReportEvent.set() else: # Nothing is waiting for this report directly - use callback self.smsStatusReportCallback(report)
python
def _handleSmsStatusReport(self, notificationLine): """ Handler for SMS status reports """ self.log.debug('SMS status report received') cdsiMatch = self.CDSI_REGEX.match(notificationLine) if cdsiMatch: msgMemory = cdsiMatch.group(1) msgIndex = cdsiMatch.group(2) report = self.readStoredSms(msgIndex, msgMemory) self.deleteStoredSms(msgIndex) # Update sent SMS status if possible if report.reference in self.sentSms: self.sentSms[report.reference].report = report if self._smsStatusReportEvent: # A sendSms() call is waiting for this response - notify waiting thread self._smsStatusReportEvent.set() else: # Nothing is waiting for this report directly - use callback self.smsStatusReportCallback(report)
[ "def", "_handleSmsStatusReport", "(", "self", ",", "notificationLine", ")", ":", "self", ".", "log", ".", "debug", "(", "'SMS status report received'", ")", "cdsiMatch", "=", "self", ".", "CDSI_REGEX", ".", "match", "(", "notificationLine", ")", "if", "cdsiMatch", ":", "msgMemory", "=", "cdsiMatch", ".", "group", "(", "1", ")", "msgIndex", "=", "cdsiMatch", ".", "group", "(", "2", ")", "report", "=", "self", ".", "readStoredSms", "(", "msgIndex", ",", "msgMemory", ")", "self", ".", "deleteStoredSms", "(", "msgIndex", ")", "# Update sent SMS status if possible ", "if", "report", ".", "reference", "in", "self", ".", "sentSms", ":", "self", ".", "sentSms", "[", "report", ".", "reference", "]", ".", "report", "=", "report", "if", "self", ".", "_smsStatusReportEvent", ":", "# A sendSms() call is waiting for this response - notify waiting thread", "self", ".", "_smsStatusReportEvent", ".", "set", "(", ")", "else", ":", "# Nothing is waiting for this report directly - use callback", "self", ".", "smsStatusReportCallback", "(", "report", ")" ]
Handler for SMS status reports
[ "Handler", "for", "SMS", "status", "reports" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L1002-L1019
train
238,755
faucamp/python-gsmmodem
gsmmodem/modem.py
Call.hangup
def hangup(self): """ End the phone call. Does nothing if the call is already inactive. """ if self.active: self._gsmModem.write('ATH') self.answered = False self.active = False if self.id in self._gsmModem.activeCalls: del self._gsmModem.activeCalls[self.id]
python
def hangup(self): """ End the phone call. Does nothing if the call is already inactive. """ if self.active: self._gsmModem.write('ATH') self.answered = False self.active = False if self.id in self._gsmModem.activeCalls: del self._gsmModem.activeCalls[self.id]
[ "def", "hangup", "(", "self", ")", ":", "if", "self", ".", "active", ":", "self", ".", "_gsmModem", ".", "write", "(", "'ATH'", ")", "self", ".", "answered", "=", "False", "self", ".", "active", "=", "False", "if", "self", ".", "id", "in", "self", ".", "_gsmModem", ".", "activeCalls", ":", "del", "self", ".", "_gsmModem", ".", "activeCalls", "[", "self", ".", "id", "]" ]
End the phone call. Does nothing if the call is already inactive.
[ "End", "the", "phone", "call", ".", "Does", "nothing", "if", "the", "call", "is", "already", "inactive", "." ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L1272-L1282
train
238,756
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._color
def _color(self, color, msg): """ Converts a message to be printed to the user's terminal in red """ if self.useColor: return '{0}{1}{2}'.format(color, msg, self.RESET_SEQ) else: return msg
python
def _color(self, color, msg): """ Converts a message to be printed to the user's terminal in red """ if self.useColor: return '{0}{1}{2}'.format(color, msg, self.RESET_SEQ) else: return msg
[ "def", "_color", "(", "self", ",", "color", ",", "msg", ")", ":", "if", "self", ".", "useColor", ":", "return", "'{0}{1}{2}'", ".", "format", "(", "color", ",", "msg", ",", "self", ".", "RESET_SEQ", ")", "else", ":", "return", "msg" ]
Converts a message to be printed to the user's terminal in red
[ "Converts", "a", "message", "to", "be", "printed", "to", "the", "user", "s", "terminal", "in", "red" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L216-L221
train
238,757
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._cursorLeft
def _cursorLeft(self): """ Handles "cursor left" events """ if self.cursorPos > 0: self.cursorPos -= 1 sys.stdout.write(console.CURSOR_LEFT) sys.stdout.flush()
python
def _cursorLeft(self): """ Handles "cursor left" events """ if self.cursorPos > 0: self.cursorPos -= 1 sys.stdout.write(console.CURSOR_LEFT) sys.stdout.flush()
[ "def", "_cursorLeft", "(", "self", ")", ":", "if", "self", ".", "cursorPos", ">", "0", ":", "self", ".", "cursorPos", "-=", "1", "sys", ".", "stdout", ".", "write", "(", "console", ".", "CURSOR_LEFT", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Handles "cursor left" events
[ "Handles", "cursor", "left", "events" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L311-L316
train
238,758
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._cursorRight
def _cursorRight(self): """ Handles "cursor right" events """ if self.cursorPos < len(self.inputBuffer): self.cursorPos += 1 sys.stdout.write(console.CURSOR_RIGHT) sys.stdout.flush()
python
def _cursorRight(self): """ Handles "cursor right" events """ if self.cursorPos < len(self.inputBuffer): self.cursorPos += 1 sys.stdout.write(console.CURSOR_RIGHT) sys.stdout.flush()
[ "def", "_cursorRight", "(", "self", ")", ":", "if", "self", ".", "cursorPos", "<", "len", "(", "self", ".", "inputBuffer", ")", ":", "self", ".", "cursorPos", "+=", "1", "sys", ".", "stdout", ".", "write", "(", "console", ".", "CURSOR_RIGHT", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Handles "cursor right" events
[ "Handles", "cursor", "right", "events" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L318-L323
train
238,759
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._cursorUp
def _cursorUp(self): """ Handles "cursor up" events """ if self.historyPos > 0: self.historyPos -= 1 clearLen = len(self.inputBuffer) self.inputBuffer = list(self.history[self.historyPos]) self.cursorPos = len(self.inputBuffer) self._refreshInputPrompt(clearLen)
python
def _cursorUp(self): """ Handles "cursor up" events """ if self.historyPos > 0: self.historyPos -= 1 clearLen = len(self.inputBuffer) self.inputBuffer = list(self.history[self.historyPos]) self.cursorPos = len(self.inputBuffer) self._refreshInputPrompt(clearLen)
[ "def", "_cursorUp", "(", "self", ")", ":", "if", "self", ".", "historyPos", ">", "0", ":", "self", ".", "historyPos", "-=", "1", "clearLen", "=", "len", "(", "self", ".", "inputBuffer", ")", "self", ".", "inputBuffer", "=", "list", "(", "self", ".", "history", "[", "self", ".", "historyPos", "]", ")", "self", ".", "cursorPos", "=", "len", "(", "self", ".", "inputBuffer", ")", "self", ".", "_refreshInputPrompt", "(", "clearLen", ")" ]
Handles "cursor up" events
[ "Handles", "cursor", "up", "events" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L325-L332
train
238,760
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._handleBackspace
def _handleBackspace(self): """ Handles backspace characters """ if self.cursorPos > 0: #print( 'cp:',self.cursorPos,'was:', self.inputBuffer) self.inputBuffer = self.inputBuffer[0:self.cursorPos-1] + self.inputBuffer[self.cursorPos:] self.cursorPos -= 1 #print ('cp:', self.cursorPos,'is:', self.inputBuffer) self._refreshInputPrompt(len(self.inputBuffer)+1)
python
def _handleBackspace(self): """ Handles backspace characters """ if self.cursorPos > 0: #print( 'cp:',self.cursorPos,'was:', self.inputBuffer) self.inputBuffer = self.inputBuffer[0:self.cursorPos-1] + self.inputBuffer[self.cursorPos:] self.cursorPos -= 1 #print ('cp:', self.cursorPos,'is:', self.inputBuffer) self._refreshInputPrompt(len(self.inputBuffer)+1)
[ "def", "_handleBackspace", "(", "self", ")", ":", "if", "self", ".", "cursorPos", ">", "0", ":", "#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)", "self", ".", "inputBuffer", "=", "self", ".", "inputBuffer", "[", "0", ":", "self", ".", "cursorPos", "-", "1", "]", "+", "self", ".", "inputBuffer", "[", "self", ".", "cursorPos", ":", "]", "self", ".", "cursorPos", "-=", "1", "#print ('cp:', self.cursorPos,'is:', self.inputBuffer) ", "self", ".", "_refreshInputPrompt", "(", "len", "(", "self", ".", "inputBuffer", ")", "+", "1", ")" ]
Handles backspace characters
[ "Handles", "backspace", "characters" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L343-L350
train
238,761
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._handleDelete
def _handleDelete(self): """ Handles "delete" characters """ if self.cursorPos < len(self.inputBuffer): self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:] self._refreshInputPrompt(len(self.inputBuffer)+1)
python
def _handleDelete(self): """ Handles "delete" characters """ if self.cursorPos < len(self.inputBuffer): self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:] self._refreshInputPrompt(len(self.inputBuffer)+1)
[ "def", "_handleDelete", "(", "self", ")", ":", "if", "self", ".", "cursorPos", "<", "len", "(", "self", ".", "inputBuffer", ")", ":", "self", ".", "inputBuffer", "=", "self", ".", "inputBuffer", "[", "0", ":", "self", ".", "cursorPos", "]", "+", "self", ".", "inputBuffer", "[", "self", ".", "cursorPos", "+", "1", ":", "]", "self", ".", "_refreshInputPrompt", "(", "len", "(", "self", ".", "inputBuffer", ")", "+", "1", ")" ]
Handles "delete" characters
[ "Handles", "delete", "characters" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L352-L356
train
238,762
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._handleEnd
def _handleEnd(self): """ Handles "end" character """ self.cursorPos = len(self.inputBuffer) self._refreshInputPrompt(len(self.inputBuffer))
python
def _handleEnd(self): """ Handles "end" character """ self.cursorPos = len(self.inputBuffer) self._refreshInputPrompt(len(self.inputBuffer))
[ "def", "_handleEnd", "(", "self", ")", ":", "self", ".", "cursorPos", "=", "len", "(", "self", ".", "inputBuffer", ")", "self", ".", "_refreshInputPrompt", "(", "len", "(", "self", ".", "inputBuffer", ")", ")" ]
Handles "end" character
[ "Handles", "end", "character" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L363-L366
train
238,763
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
GsmTerm._doCommandCompletion
def _doCommandCompletion(self): """ Command-completion method """ prefix = ''.join(self.inputBuffer).strip().upper() matches = self.completion.keys(prefix) matchLen = len(matches) if matchLen == 0 and prefix[-1] == '=': try: command = prefix[:-1] except KeyError: pass else: self.__printCommandSyntax(command) elif matchLen > 0: if matchLen == 1: if matches[0] == prefix: # User has already entered command - show command syntax self.__printCommandSyntax(prefix) else: # Complete only possible command self.inputBuffer = list(matches[0]) self.cursorPos = len(self.inputBuffer) self._refreshInputPrompt(len(self.inputBuffer)) return else: commonPrefix = self.completion.longestCommonPrefix(''.join(self.inputBuffer)) self.inputBuffer = list(commonPrefix) self.cursorPos = len(self.inputBuffer) if matchLen > 20: matches = matches[:20] matches.append('... ({0} more)'.format(matchLen - 20)) sys.stdout.write('\n') for match in matches: sys.stdout.write(' {0} '.format(match)) sys.stdout.write('\n') sys.stdout.flush() self._refreshInputPrompt(len(self.inputBuffer))
python
def _doCommandCompletion(self): """ Command-completion method """ prefix = ''.join(self.inputBuffer).strip().upper() matches = self.completion.keys(prefix) matchLen = len(matches) if matchLen == 0 and prefix[-1] == '=': try: command = prefix[:-1] except KeyError: pass else: self.__printCommandSyntax(command) elif matchLen > 0: if matchLen == 1: if matches[0] == prefix: # User has already entered command - show command syntax self.__printCommandSyntax(prefix) else: # Complete only possible command self.inputBuffer = list(matches[0]) self.cursorPos = len(self.inputBuffer) self._refreshInputPrompt(len(self.inputBuffer)) return else: commonPrefix = self.completion.longestCommonPrefix(''.join(self.inputBuffer)) self.inputBuffer = list(commonPrefix) self.cursorPos = len(self.inputBuffer) if matchLen > 20: matches = matches[:20] matches.append('... ({0} more)'.format(matchLen - 20)) sys.stdout.write('\n') for match in matches: sys.stdout.write(' {0} '.format(match)) sys.stdout.write('\n') sys.stdout.flush() self._refreshInputPrompt(len(self.inputBuffer))
[ "def", "_doCommandCompletion", "(", "self", ")", ":", "prefix", "=", "''", ".", "join", "(", "self", ".", "inputBuffer", ")", ".", "strip", "(", ")", ".", "upper", "(", ")", "matches", "=", "self", ".", "completion", ".", "keys", "(", "prefix", ")", "matchLen", "=", "len", "(", "matches", ")", "if", "matchLen", "==", "0", "and", "prefix", "[", "-", "1", "]", "==", "'='", ":", "try", ":", "command", "=", "prefix", "[", ":", "-", "1", "]", "except", "KeyError", ":", "pass", "else", ":", "self", ".", "__printCommandSyntax", "(", "command", ")", "elif", "matchLen", ">", "0", ":", "if", "matchLen", "==", "1", ":", "if", "matches", "[", "0", "]", "==", "prefix", ":", "# User has already entered command - show command syntax", "self", ".", "__printCommandSyntax", "(", "prefix", ")", "else", ":", "# Complete only possible command", "self", ".", "inputBuffer", "=", "list", "(", "matches", "[", "0", "]", ")", "self", ".", "cursorPos", "=", "len", "(", "self", ".", "inputBuffer", ")", "self", ".", "_refreshInputPrompt", "(", "len", "(", "self", ".", "inputBuffer", ")", ")", "return", "else", ":", "commonPrefix", "=", "self", ".", "completion", ".", "longestCommonPrefix", "(", "''", ".", "join", "(", "self", ".", "inputBuffer", ")", ")", "self", ".", "inputBuffer", "=", "list", "(", "commonPrefix", ")", "self", ".", "cursorPos", "=", "len", "(", "self", ".", "inputBuffer", ")", "if", "matchLen", ">", "20", ":", "matches", "=", "matches", "[", ":", "20", "]", "matches", ".", "append", "(", "'... ({0} more)'", ".", "format", "(", "matchLen", "-", "20", ")", ")", "sys", ".", "stdout", ".", "write", "(", "'\\n'", ")", "for", "match", "in", "matches", ":", "sys", ".", "stdout", ".", "write", "(", "' {0} '", ".", "format", "(", "match", ")", ")", "sys", ".", "stdout", ".", "write", "(", "'\\n'", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "self", ".", "_refreshInputPrompt", "(", "len", "(", "self", ".", "inputBuffer", ")", ")" ]
Command-completion method
[ "Command", "-", "completion", "method" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L533-L568
train
238,764
faucamp/python-gsmmodem
gsmmodem/serial_comms.py
SerialComms.connect
def connect(self): """ Connects to the device and starts the read thread """ self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout) # Start read thread self.alive = True self.rxThread = threading.Thread(target=self._readLoop) self.rxThread.daemon = True self.rxThread.start()
python
def connect(self): """ Connects to the device and starts the read thread """ self.serial = serial.Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout) # Start read thread self.alive = True self.rxThread = threading.Thread(target=self._readLoop) self.rxThread.daemon = True self.rxThread.start()
[ "def", "connect", "(", "self", ")", ":", "self", ".", "serial", "=", "serial", ".", "Serial", "(", "port", "=", "self", ".", "port", ",", "baudrate", "=", "self", ".", "baudrate", ",", "timeout", "=", "self", ".", "timeout", ")", "# Start read thread", "self", ".", "alive", "=", "True", "self", ".", "rxThread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_readLoop", ")", "self", ".", "rxThread", ".", "daemon", "=", "True", "self", ".", "rxThread", ".", "start", "(", ")" ]
Connects to the device and starts the read thread
[ "Connects", "to", "the", "device", "and", "starts", "the", "read", "thread" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/serial_comms.py#L45-L52
train
238,765
faucamp/python-gsmmodem
gsmmodem/serial_comms.py
SerialComms.close
def close(self): """ Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """ self.alive = False self.rxThread.join() self.serial.close()
python
def close(self): """ Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """ self.alive = False self.rxThread.join() self.serial.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "alive", "=", "False", "self", ".", "rxThread", ".", "join", "(", ")", "self", ".", "serial", ".", "close", "(", ")" ]
Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port
[ "Stops", "the", "read", "thread", "waits", "for", "it", "to", "exit", "cleanly", "then", "closes", "the", "underlying", "serial", "port" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/serial_comms.py#L54-L58
train
238,766
faucamp/python-gsmmodem
gsmmodem/serial_comms.py
SerialComms._readLoop
def _readLoop(self): """ Read thread main loop Reads lines from the connected device """ try: readTermSeq = list(self.RX_EOL_SEQ) readTermLen = len(readTermSeq) rxBuffer = [] while self.alive: data = self.serial.read(1) if data != '': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(data) if rxBuffer[-readTermLen:] == readTermSeq: # A line (or other logical segment) has been read line = ''.join(rxBuffer[:-readTermLen]) rxBuffer = [] if len(line) > 0: #print 'calling handler' self._handleLineRead(line) elif self._expectResponseTermSeq: if rxBuffer[-len(self._expectResponseTermSeq):] == self._expectResponseTermSeq: line = ''.join(rxBuffer) rxBuffer = [] self._handleLineRead(line, checkForResponseTerm=False) #else: #' <RX timeout>' except serial.SerialException as e: self.alive = False try: self.serial.close() except Exception: #pragma: no cover pass # Notify the fatal error handler self.fatalErrorCallback(e)
python
def _readLoop(self): """ Read thread main loop Reads lines from the connected device """ try: readTermSeq = list(self.RX_EOL_SEQ) readTermLen = len(readTermSeq) rxBuffer = [] while self.alive: data = self.serial.read(1) if data != '': # check for timeout #print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data)) rxBuffer.append(data) if rxBuffer[-readTermLen:] == readTermSeq: # A line (or other logical segment) has been read line = ''.join(rxBuffer[:-readTermLen]) rxBuffer = [] if len(line) > 0: #print 'calling handler' self._handleLineRead(line) elif self._expectResponseTermSeq: if rxBuffer[-len(self._expectResponseTermSeq):] == self._expectResponseTermSeq: line = ''.join(rxBuffer) rxBuffer = [] self._handleLineRead(line, checkForResponseTerm=False) #else: #' <RX timeout>' except serial.SerialException as e: self.alive = False try: self.serial.close() except Exception: #pragma: no cover pass # Notify the fatal error handler self.fatalErrorCallback(e)
[ "def", "_readLoop", "(", "self", ")", ":", "try", ":", "readTermSeq", "=", "list", "(", "self", ".", "RX_EOL_SEQ", ")", "readTermLen", "=", "len", "(", "readTermSeq", ")", "rxBuffer", "=", "[", "]", "while", "self", ".", "alive", ":", "data", "=", "self", ".", "serial", ".", "read", "(", "1", ")", "if", "data", "!=", "''", ":", "# check for timeout", "#print >> sys.stderr, ' RX:', data,'({0})'.format(ord(data))", "rxBuffer", ".", "append", "(", "data", ")", "if", "rxBuffer", "[", "-", "readTermLen", ":", "]", "==", "readTermSeq", ":", "# A line (or other logical segment) has been read", "line", "=", "''", ".", "join", "(", "rxBuffer", "[", ":", "-", "readTermLen", "]", ")", "rxBuffer", "=", "[", "]", "if", "len", "(", "line", ")", ">", "0", ":", "#print 'calling handler' ", "self", ".", "_handleLineRead", "(", "line", ")", "elif", "self", ".", "_expectResponseTermSeq", ":", "if", "rxBuffer", "[", "-", "len", "(", "self", ".", "_expectResponseTermSeq", ")", ":", "]", "==", "self", ".", "_expectResponseTermSeq", ":", "line", "=", "''", ".", "join", "(", "rxBuffer", ")", "rxBuffer", "=", "[", "]", "self", ".", "_handleLineRead", "(", "line", ",", "checkForResponseTerm", "=", "False", ")", "#else:", "#' <RX timeout>'", "except", "serial", ".", "SerialException", "as", "e", ":", "self", ".", "alive", "=", "False", "try", ":", "self", ".", "serial", ".", "close", "(", ")", "except", "Exception", ":", "#pragma: no cover", "pass", "# Notify the fatal error handler", "self", ".", "fatalErrorCallback", "(", "e", ")" ]
Read thread main loop Reads lines from the connected device
[ "Read", "thread", "main", "loop", "Reads", "lines", "from", "the", "connected", "device" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/serial_comms.py#L83-L118
train
238,767
faucamp/python-gsmmodem
gsmmodem/pdu.py
_decodeTimestamp
def _decodeTimestamp(byteIter): """ Decodes a 7-octet timestamp """ dateStr = decodeSemiOctets(byteIter, 7) timeZoneStr = dateStr[-2:] return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr))
python
def _decodeTimestamp(byteIter): """ Decodes a 7-octet timestamp """ dateStr = decodeSemiOctets(byteIter, 7) timeZoneStr = dateStr[-2:] return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr))
[ "def", "_decodeTimestamp", "(", "byteIter", ")", ":", "dateStr", "=", "decodeSemiOctets", "(", "byteIter", ",", "7", ")", "timeZoneStr", "=", "dateStr", "[", "-", "2", ":", "]", "return", "datetime", ".", "strptime", "(", "dateStr", "[", ":", "-", "2", "]", ",", "'%y%m%d%H%M%S'", ")", ".", "replace", "(", "tzinfo", "=", "SmsPduTzInfo", "(", "timeZoneStr", ")", ")" ]
Decodes a 7-octet timestamp
[ "Decodes", "a", "7", "-", "octet", "timestamp" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L494-L498
train
238,768
faucamp/python-gsmmodem
gsmmodem/pdu.py
decodeUcs2
def decodeUcs2(byteIter, numBytes): """ Decodes UCS2-encoded text from the specified byte iterator, up to a maximum of numBytes """ userData = [] i = 0 try: while i < numBytes: userData.append(unichr((next(byteIter) << 8) | next(byteIter))) i += 2 except StopIteration: # Not enough bytes in iterator to reach numBytes; return what we have pass return ''.join(userData)
python
def decodeUcs2(byteIter, numBytes): """ Decodes UCS2-encoded text from the specified byte iterator, up to a maximum of numBytes """ userData = [] i = 0 try: while i < numBytes: userData.append(unichr((next(byteIter) << 8) | next(byteIter))) i += 2 except StopIteration: # Not enough bytes in iterator to reach numBytes; return what we have pass return ''.join(userData)
[ "def", "decodeUcs2", "(", "byteIter", ",", "numBytes", ")", ":", "userData", "=", "[", "]", "i", "=", "0", "try", ":", "while", "i", "<", "numBytes", ":", "userData", ".", "append", "(", "unichr", "(", "(", "next", "(", "byteIter", ")", "<<", "8", ")", "|", "next", "(", "byteIter", ")", ")", ")", "i", "+=", "2", "except", "StopIteration", ":", "# Not enough bytes in iterator to reach numBytes; return what we have", "pass", "return", "''", ".", "join", "(", "userData", ")" ]
Decodes UCS2-encoded text from the specified byte iterator, up to a maximum of numBytes
[ "Decodes", "UCS2", "-", "encoded", "text", "from", "the", "specified", "byte", "iterator", "up", "to", "a", "maximum", "of", "numBytes" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L795-L806
train
238,769
faucamp/python-gsmmodem
gsmmodem/pdu.py
InformationElement.encode
def encode(self): """ Encodes this IE and returns the resulting bytes """ result = bytearray() result.append(self.id) result.append(self.dataLength) result.extend(self.data) return result
python
def encode(self): """ Encodes this IE and returns the resulting bytes """ result = bytearray() result.append(self.id) result.append(self.dataLength) result.extend(self.data) return result
[ "def", "encode", "(", "self", ")", ":", "result", "=", "bytearray", "(", ")", "result", ".", "append", "(", "self", ".", "id", ")", "result", ".", "append", "(", "self", ".", "dataLength", ")", "result", ".", "extend", "(", "self", ".", "data", ")", "return", "result" ]
Encodes this IE and returns the resulting bytes
[ "Encodes", "this", "IE", "and", "returns", "the", "resulting", "bytes" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L123-L129
train
238,770
faucamp/python-gsmmodem
tools/sendsms.py
parseArgsPy26
def parseArgsPy26(): """ Argument parser for Python 2.6 """ from gsmtermlib.posoptparse import PosOptionParser, Option parser = PosOptionParser(description='Simple script for sending SMS messages') parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report') parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number')) options, args = parser.parse_args() if len(args) != 1: parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0])) else: options.destination = args[0] return options
python
def parseArgsPy26(): """ Argument parser for Python 2.6 """ from gsmtermlib.posoptparse import PosOptionParser, Option parser = PosOptionParser(description='Simple script for sending SMS messages') parser.add_option('-i', '--port', metavar='PORT', help='port to which the GSM modem is connected; a number or a device name.') parser.add_option('-b', '--baud', metavar='BAUDRATE', default=115200, help='set baud rate') parser.add_option('-p', '--pin', metavar='PIN', default=None, help='SIM card PIN') parser.add_option('-d', '--deliver', action='store_true', help='wait for SMS delivery report') parser.add_positional_argument(Option('--destination', metavar='DESTINATION', help='destination mobile number')) options, args = parser.parse_args() if len(args) != 1: parser.error('Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'.format(sys.argv[0])) else: options.destination = args[0] return options
[ "def", "parseArgsPy26", "(", ")", ":", "from", "gsmtermlib", ".", "posoptparse", "import", "PosOptionParser", ",", "Option", "parser", "=", "PosOptionParser", "(", "description", "=", "'Simple script for sending SMS messages'", ")", "parser", ".", "add_option", "(", "'-i'", ",", "'--port'", ",", "metavar", "=", "'PORT'", ",", "help", "=", "'port to which the GSM modem is connected; a number or a device name.'", ")", "parser", ".", "add_option", "(", "'-b'", ",", "'--baud'", ",", "metavar", "=", "'BAUDRATE'", ",", "default", "=", "115200", ",", "help", "=", "'set baud rate'", ")", "parser", ".", "add_option", "(", "'-p'", ",", "'--pin'", ",", "metavar", "=", "'PIN'", ",", "default", "=", "None", ",", "help", "=", "'SIM card PIN'", ")", "parser", ".", "add_option", "(", "'-d'", ",", "'--deliver'", ",", "action", "=", "'store_true'", ",", "help", "=", "'wait for SMS delivery report'", ")", "parser", ".", "add_positional_argument", "(", "Option", "(", "'--destination'", ",", "metavar", "=", "'DESTINATION'", ",", "help", "=", "'destination mobile number'", ")", ")", "options", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "parser", ".", "error", "(", "'Incorrect number of arguments - please specify a DESTINATION to send to, e.g. {0} 012789456'", ".", "format", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", "else", ":", "options", ".", "destination", "=", "args", "[", "0", "]", "return", "options" ]
Argument parser for Python 2.6
[ "Argument", "parser", "for", "Python", "2", ".", "6" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/sendsms.py#L26-L40
train
238,771
faucamp/python-gsmmodem
gsmmodem/util.py
lineMatching
def lineMatching(regexStr, lines): """ Searches through the specified list of strings and returns the regular expression match for the first line that matches the specified regex string, or None if no match was found Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() instead :type regexStr: Regular expression string to use :type lines: List of lines to search :return: the regular expression match for the first line that matches the specified regex, or None if no match was found :rtype: re.Match """ regex = re.compile(regexStr) for line in lines: m = regex.match(line) if m: return m else: return None
python
def lineMatching(regexStr, lines): """ Searches through the specified list of strings and returns the regular expression match for the first line that matches the specified regex string, or None if no match was found Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() instead :type regexStr: Regular expression string to use :type lines: List of lines to search :return: the regular expression match for the first line that matches the specified regex, or None if no match was found :rtype: re.Match """ regex = re.compile(regexStr) for line in lines: m = regex.match(line) if m: return m else: return None
[ "def", "lineMatching", "(", "regexStr", ",", "lines", ")", ":", "regex", "=", "re", ".", "compile", "(", "regexStr", ")", "for", "line", "in", "lines", ":", "m", "=", "regex", ".", "match", "(", "line", ")", "if", "m", ":", "return", "m", "else", ":", "return", "None" ]
Searches through the specified list of strings and returns the regular expression match for the first line that matches the specified regex string, or None if no match was found Note: if you have a pre-compiled regex pattern, use lineMatchingPattern() instead :type regexStr: Regular expression string to use :type lines: List of lines to search :return: the regular expression match for the first line that matches the specified regex, or None if no match was found :rtype: re.Match
[ "Searches", "through", "the", "specified", "list", "of", "strings", "and", "returns", "the", "regular", "expression", "match", "for", "the", "first", "line", "that", "matches", "the", "specified", "regex", "string", "or", "None", "if", "no", "match", "was", "found" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/util.py#L57-L75
train
238,772
faucamp/python-gsmmodem
gsmmodem/util.py
lineMatchingPattern
def lineMatchingPattern(pattern, lines): """ Searches through the specified list of strings and returns the regular expression match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead :type pattern: Compiled regular expression pattern to use :type lines: List of lines to search :return: the regular expression match for the first line that matches the specified regex, or None if no match was found :rtype: re.Match """ for line in lines: m = pattern.match(line) if m: return m else: return None
python
def lineMatchingPattern(pattern, lines): """ Searches through the specified list of strings and returns the regular expression match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead :type pattern: Compiled regular expression pattern to use :type lines: List of lines to search :return: the regular expression match for the first line that matches the specified regex, or None if no match was found :rtype: re.Match """ for line in lines: m = pattern.match(line) if m: return m else: return None
[ "def", "lineMatchingPattern", "(", "pattern", ",", "lines", ")", ":", "for", "line", "in", "lines", ":", "m", "=", "pattern", ".", "match", "(", "line", ")", "if", "m", ":", "return", "m", "else", ":", "return", "None" ]
Searches through the specified list of strings and returns the regular expression match for the first line that matches the specified pre-compiled regex pattern, or None if no match was found Note: if you are using a regex pattern string (i.e. not already compiled), use lineMatching() instead :type pattern: Compiled regular expression pattern to use :type lines: List of lines to search :return: the regular expression match for the first line that matches the specified regex, or None if no match was found :rtype: re.Match
[ "Searches", "through", "the", "specified", "list", "of", "strings", "and", "returns", "the", "regular", "expression", "match", "for", "the", "first", "line", "that", "matches", "the", "specified", "pre", "-", "compiled", "regex", "pattern", "or", "None", "if", "no", "match", "was", "found" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/util.py#L77-L94
train
238,773
faucamp/python-gsmmodem
gsmmodem/util.py
allLinesMatchingPattern
def allLinesMatchingPattern(pattern, lines): """ Like lineMatchingPattern, but returns all lines that match the specified pattern :type pattern: Compiled regular expression pattern to use :type lines: List of lines to search :return: list of re.Match objects for each line matched, or an empty list if none matched :rtype: list """ result = [] for line in lines: m = pattern.match(line) if m: result.append(m) return result
python
def allLinesMatchingPattern(pattern, lines): """ Like lineMatchingPattern, but returns all lines that match the specified pattern :type pattern: Compiled regular expression pattern to use :type lines: List of lines to search :return: list of re.Match objects for each line matched, or an empty list if none matched :rtype: list """ result = [] for line in lines: m = pattern.match(line) if m: result.append(m) return result
[ "def", "allLinesMatchingPattern", "(", "pattern", ",", "lines", ")", ":", "result", "=", "[", "]", "for", "line", "in", "lines", ":", "m", "=", "pattern", ".", "match", "(", "line", ")", "if", "m", ":", "result", ".", "append", "(", "m", ")", "return", "result" ]
Like lineMatchingPattern, but returns all lines that match the specified pattern :type pattern: Compiled regular expression pattern to use :type lines: List of lines to search :return: list of re.Match objects for each line matched, or an empty list if none matched :rtype: list
[ "Like", "lineMatchingPattern", "but", "returns", "all", "lines", "that", "match", "the", "specified", "pattern" ]
834c68b1387ca2c91e2210faa8f75526b39723b5
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/util.py#L96-L110
train
238,774
n8henrie/pycookiecheat
src/pycookiecheat/pycookiecheat.py
clean
def clean(decrypted: bytes) -> str: r"""Strip padding from decrypted value. Remove number indicated by padding e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14. Args: decrypted: decrypted value Returns: Decrypted stripped of junk padding """ last = decrypted[-1] if isinstance(last, int): return decrypted[:-last].decode('utf8') return decrypted[:-ord(last)].decode('utf8')
python
def clean(decrypted: bytes) -> str: r"""Strip padding from decrypted value. Remove number indicated by padding e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14. Args: decrypted: decrypted value Returns: Decrypted stripped of junk padding """ last = decrypted[-1] if isinstance(last, int): return decrypted[:-last].decode('utf8') return decrypted[:-ord(last)].decode('utf8')
[ "def", "clean", "(", "decrypted", ":", "bytes", ")", "->", "str", ":", "last", "=", "decrypted", "[", "-", "1", "]", "if", "isinstance", "(", "last", ",", "int", ")", ":", "return", "decrypted", "[", ":", "-", "last", "]", ".", "decode", "(", "'utf8'", ")", "return", "decrypted", "[", ":", "-", "ord", "(", "last", ")", "]", ".", "decode", "(", "'utf8'", ")" ]
r"""Strip padding from decrypted value. Remove number indicated by padding e.g. if last is '\x0e' then ord('\x0e') == 14, so take off 14. Args: decrypted: decrypted value Returns: Decrypted stripped of junk padding
[ "r", "Strip", "padding", "from", "decrypted", "value", "." ]
1e0ba783da31689f5b37f9706205ff366d72f03d
https://github.com/n8henrie/pycookiecheat/blob/1e0ba783da31689f5b37f9706205ff366d72f03d/src/pycookiecheat/pycookiecheat.py#L26-L41
train
238,775
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.set_pattern_step_setpoint
def set_pattern_step_setpoint(self, patternnumber, stepnumber, setpointvalue): """Set the setpoint value for a step. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * setpointvalue (float): Setpoint value """ _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) _checkSetpointValue(setpointvalue, self.setpoint_max) address = _calculateRegisterAddress('setpoint', patternnumber, stepnumber) self.write_register(address, setpointvalue, 1)
python
def set_pattern_step_setpoint(self, patternnumber, stepnumber, setpointvalue): """Set the setpoint value for a step. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * setpointvalue (float): Setpoint value """ _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) _checkSetpointValue(setpointvalue, self.setpoint_max) address = _calculateRegisterAddress('setpoint', patternnumber, stepnumber) self.write_register(address, setpointvalue, 1)
[ "def", "set_pattern_step_setpoint", "(", "self", ",", "patternnumber", ",", "stepnumber", ",", "setpointvalue", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "_checkStepNumber", "(", "stepnumber", ")", "_checkSetpointValue", "(", "setpointvalue", ",", "self", ".", "setpoint_max", ")", "address", "=", "_calculateRegisterAddress", "(", "'setpoint'", ",", "patternnumber", ",", "stepnumber", ")", "self", ".", "write_register", "(", "address", ",", "setpointvalue", ",", "1", ")" ]
Set the setpoint value for a step. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * setpointvalue (float): Setpoint value
[ "Set", "the", "setpoint", "value", "for", "a", "step", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L237-L250
train
238,776
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.get_pattern_step_time
def get_pattern_step_time(self, patternnumber, stepnumber): """Get the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 Returns: The step time (int??). """ _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) address = _calculateRegisterAddress('time', patternnumber, stepnumber) return self.read_register(address, 0)
python
def get_pattern_step_time(self, patternnumber, stepnumber): """Get the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 Returns: The step time (int??). """ _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) address = _calculateRegisterAddress('time', patternnumber, stepnumber) return self.read_register(address, 0)
[ "def", "get_pattern_step_time", "(", "self", ",", "patternnumber", ",", "stepnumber", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "_checkStepNumber", "(", "stepnumber", ")", "address", "=", "_calculateRegisterAddress", "(", "'time'", ",", "patternnumber", ",", "stepnumber", ")", "return", "self", ".", "read_register", "(", "address", ",", "0", ")" ]
Get the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 Returns: The step time (int??).
[ "Get", "the", "step", "time", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L253-L268
train
238,777
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.set_pattern_step_time
def set_pattern_step_time(self, patternnumber, stepnumber, timevalue): """Set the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * timevalue (integer??): 0-900 """ _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) _checkTimeValue(timevalue, self.time_max) address = _calculateRegisterAddress('time', patternnumber, stepnumber) self.write_register(address, timevalue, 0)
python
def set_pattern_step_time(self, patternnumber, stepnumber, timevalue): """Set the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * timevalue (integer??): 0-900 """ _checkPatternNumber(patternnumber) _checkStepNumber(stepnumber) _checkTimeValue(timevalue, self.time_max) address = _calculateRegisterAddress('time', patternnumber, stepnumber) self.write_register(address, timevalue, 0)
[ "def", "set_pattern_step_time", "(", "self", ",", "patternnumber", ",", "stepnumber", ",", "timevalue", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "_checkStepNumber", "(", "stepnumber", ")", "_checkTimeValue", "(", "timevalue", ",", "self", ".", "time_max", ")", "address", "=", "_calculateRegisterAddress", "(", "'time'", ",", "patternnumber", ",", "stepnumber", ")", "self", ".", "write_register", "(", "address", ",", "timevalue", ",", "0", ")" ]
Set the step time. Args: * patternnumber (integer): 0-7 * stepnumber (integer): 0-7 * timevalue (integer??): 0-900
[ "Set", "the", "step", "time", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L271-L284
train
238,778
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.get_pattern_actual_step
def get_pattern_actual_step(self, patternnumber): """Get the 'actual step' parameter for a given pattern. Args: patternnumber (integer): 0-7 Returns: The 'actual step' parameter (int). """ _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('actualstep', patternnumber) return self.read_register(address, 0)
python
def get_pattern_actual_step(self, patternnumber): """Get the 'actual step' parameter for a given pattern. Args: patternnumber (integer): 0-7 Returns: The 'actual step' parameter (int). """ _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('actualstep', patternnumber) return self.read_register(address, 0)
[ "def", "get_pattern_actual_step", "(", "self", ",", "patternnumber", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "address", "=", "_calculateRegisterAddress", "(", "'actualstep'", ",", "patternnumber", ")", "return", "self", ".", "read_register", "(", "address", ",", "0", ")" ]
Get the 'actual step' parameter for a given pattern. Args: patternnumber (integer): 0-7 Returns: The 'actual step' parameter (int).
[ "Get", "the", "actual", "step", "parameter", "for", "a", "given", "pattern", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L287-L300
train
238,779
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.set_pattern_actual_step
def set_pattern_actual_step(self, patternnumber, value): """Set the 'actual step' parameter for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-7 """ _checkPatternNumber(patternnumber) _checkStepNumber(value) address = _calculateRegisterAddress('actualstep', patternnumber) self.write_register(address, value, 0)
python
def set_pattern_actual_step(self, patternnumber, value): """Set the 'actual step' parameter for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-7 """ _checkPatternNumber(patternnumber) _checkStepNumber(value) address = _calculateRegisterAddress('actualstep', patternnumber) self.write_register(address, value, 0)
[ "def", "set_pattern_actual_step", "(", "self", ",", "patternnumber", ",", "value", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "_checkStepNumber", "(", "value", ")", "address", "=", "_calculateRegisterAddress", "(", "'actualstep'", ",", "patternnumber", ")", "self", ".", "write_register", "(", "address", ",", "value", ",", "0", ")" ]
Set the 'actual step' parameter for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-7
[ "Set", "the", "actual", "step", "parameter", "for", "a", "given", "pattern", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L303-L314
train
238,780
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.get_pattern_additional_cycles
def get_pattern_additional_cycles(self, patternnumber): """Get the number of additional cycles for a given pattern. Args: patternnumber (integer): 0-7 Returns: The number of additional cycles (int). """ _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('cycles', patternnumber) return self.read_register(address)
python
def get_pattern_additional_cycles(self, patternnumber): """Get the number of additional cycles for a given pattern. Args: patternnumber (integer): 0-7 Returns: The number of additional cycles (int). """ _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('cycles', patternnumber) return self.read_register(address)
[ "def", "get_pattern_additional_cycles", "(", "self", ",", "patternnumber", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "address", "=", "_calculateRegisterAddress", "(", "'cycles'", ",", "patternnumber", ")", "return", "self", ".", "read_register", "(", "address", ")" ]
Get the number of additional cycles for a given pattern. Args: patternnumber (integer): 0-7 Returns: The number of additional cycles (int).
[ "Get", "the", "number", "of", "additional", "cycles", "for", "a", "given", "pattern", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L317-L330
train
238,781
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.set_pattern_additional_cycles
def set_pattern_additional_cycles(self, patternnumber, value): """Set the number of additional cycles for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-99 """ _checkPatternNumber(patternnumber) minimalmodbus._checkInt(value, minvalue=0, maxvalue=99, description='number of additional cycles') address = _calculateRegisterAddress('cycles', patternnumber) self.write_register(address, value, 0)
python
def set_pattern_additional_cycles(self, patternnumber, value): """Set the number of additional cycles for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-99 """ _checkPatternNumber(patternnumber) minimalmodbus._checkInt(value, minvalue=0, maxvalue=99, description='number of additional cycles') address = _calculateRegisterAddress('cycles', patternnumber) self.write_register(address, value, 0)
[ "def", "set_pattern_additional_cycles", "(", "self", ",", "patternnumber", ",", "value", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "minimalmodbus", ".", "_checkInt", "(", "value", ",", "minvalue", "=", "0", ",", "maxvalue", "=", "99", ",", "description", "=", "'number of additional cycles'", ")", "address", "=", "_calculateRegisterAddress", "(", "'cycles'", ",", "patternnumber", ")", "self", ".", "write_register", "(", "address", ",", "value", ",", "0", ")" ]
Set the number of additional cycles for a given pattern. Args: * patternnumber (integer): 0-7 * value (integer): 0-99
[ "Set", "the", "number", "of", "additional", "cycles", "for", "a", "given", "pattern", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L333-L344
train
238,782
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.get_pattern_link_topattern
def get_pattern_link_topattern(self, patternnumber): """Get the 'linked pattern' value for a given pattern. Args: patternnumber (integer): From 0-7 Returns: The 'linked pattern' value (int). """ _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('linkpattern', patternnumber) return self.read_register(address)
python
def get_pattern_link_topattern(self, patternnumber): """Get the 'linked pattern' value for a given pattern. Args: patternnumber (integer): From 0-7 Returns: The 'linked pattern' value (int). """ _checkPatternNumber(patternnumber) address = _calculateRegisterAddress('linkpattern', patternnumber) return self.read_register(address)
[ "def", "get_pattern_link_topattern", "(", "self", ",", "patternnumber", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "address", "=", "_calculateRegisterAddress", "(", "'linkpattern'", ",", "patternnumber", ")", "return", "self", ".", "read_register", "(", "address", ")" ]
Get the 'linked pattern' value for a given pattern. Args: patternnumber (integer): From 0-7 Returns: The 'linked pattern' value (int).
[ "Get", "the", "linked", "pattern", "value", "for", "a", "given", "pattern", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L347-L359
train
238,783
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.get_all_pattern_variables
def get_all_pattern_variables(self, patternnumber): """Get all variables for a given pattern at one time. Args: patternnumber (integer): 0-7 Returns: A descriptive multiline string. """ _checkPatternNumber(patternnumber) outputstring = '' for stepnumber in range(8): outputstring += 'SP{0}: {1} Time{0}: {2}\n'.format(stepnumber, \ self.get_pattern_step_setpoint( patternnumber, stepnumber), \ self.get_pattern_step_time( patternnumber, stepnumber) ) outputstring += 'Actual step: {0}\n'.format(self.get_pattern_actual_step( patternnumber) ) outputstring += 'Additional cycles: {0}\n'.format(self.get_pattern_additional_cycles( patternnumber) ) outputstring += 'Linked pattern: {0}\n'.format(self.get_pattern_link_topattern( patternnumber) ) return outputstring
python
def get_all_pattern_variables(self, patternnumber): """Get all variables for a given pattern at one time. Args: patternnumber (integer): 0-7 Returns: A descriptive multiline string. """ _checkPatternNumber(patternnumber) outputstring = '' for stepnumber in range(8): outputstring += 'SP{0}: {1} Time{0}: {2}\n'.format(stepnumber, \ self.get_pattern_step_setpoint( patternnumber, stepnumber), \ self.get_pattern_step_time( patternnumber, stepnumber) ) outputstring += 'Actual step: {0}\n'.format(self.get_pattern_actual_step( patternnumber) ) outputstring += 'Additional cycles: {0}\n'.format(self.get_pattern_additional_cycles( patternnumber) ) outputstring += 'Linked pattern: {0}\n'.format(self.get_pattern_link_topattern( patternnumber) ) return outputstring
[ "def", "get_all_pattern_variables", "(", "self", ",", "patternnumber", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "outputstring", "=", "''", "for", "stepnumber", "in", "range", "(", "8", ")", ":", "outputstring", "+=", "'SP{0}: {1} Time{0}: {2}\\n'", ".", "format", "(", "stepnumber", ",", "self", ".", "get_pattern_step_setpoint", "(", "patternnumber", ",", "stepnumber", ")", ",", "self", ".", "get_pattern_step_time", "(", "patternnumber", ",", "stepnumber", ")", ")", "outputstring", "+=", "'Actual step: {0}\\n'", ".", "format", "(", "self", ".", "get_pattern_actual_step", "(", "patternnumber", ")", ")", "outputstring", "+=", "'Additional cycles: {0}\\n'", ".", "format", "(", "self", ".", "get_pattern_additional_cycles", "(", "patternnumber", ")", ")", "outputstring", "+=", "'Linked pattern: {0}\\n'", ".", "format", "(", "self", ".", "get_pattern_link_topattern", "(", "patternnumber", ")", ")", "return", "outputstring" ]
Get all variables for a given pattern at one time. Args: patternnumber (integer): 0-7 Returns: A descriptive multiline string.
[ "Get", "all", "variables", "for", "a", "given", "pattern", "at", "one", "time", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L376-L398
train
238,784
pyhys/minimalmodbus
omegacn7500.py
OmegaCN7500.set_all_pattern_variables
def set_all_pattern_variables(self, patternnumber, \ sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, \ actual_step, additional_cycles, link_pattern): """Set all variables for a given pattern at one time. Args: * patternnumber (integer): 0-7 * sp[*n*] (float): setpoint value for step *n* * ti[*n*] (integer??): step time for step *n*, 0-900 * actual_step (int): ? * additional_cycles(int): ? * link_pattern(int): ? """ _checkPatternNumber(patternnumber) self.set_pattern_step_setpoint(patternnumber, 0, sp0) self.set_pattern_step_setpoint(patternnumber, 1, sp1) self.set_pattern_step_setpoint(patternnumber, 2, sp2) self.set_pattern_step_setpoint(patternnumber, 3, sp3) self.set_pattern_step_setpoint(patternnumber, 4, sp4) self.set_pattern_step_setpoint(patternnumber, 5, sp5) self.set_pattern_step_setpoint(patternnumber, 6, sp6) self.set_pattern_step_setpoint(patternnumber, 7, sp7) self.set_pattern_step_time( patternnumber, 0, ti0) self.set_pattern_step_time( patternnumber, 1, ti1) self.set_pattern_step_time( patternnumber, 2, ti2) self.set_pattern_step_time( patternnumber, 3, ti3) self.set_pattern_step_time( patternnumber, 4, ti4) self.set_pattern_step_time( patternnumber, 5, ti5) self.set_pattern_step_time( patternnumber, 6, ti6) self.set_pattern_step_time( patternnumber, 7, ti7) self.set_pattern_additional_cycles(patternnumber, additional_cycles) self.set_pattern_link_topattern( patternnumber, link_pattern) self.set_pattern_actual_step( patternnumber, actual_step)
python
def set_all_pattern_variables(self, patternnumber, \ sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, \ actual_step, additional_cycles, link_pattern): """Set all variables for a given pattern at one time. Args: * patternnumber (integer): 0-7 * sp[*n*] (float): setpoint value for step *n* * ti[*n*] (integer??): step time for step *n*, 0-900 * actual_step (int): ? * additional_cycles(int): ? * link_pattern(int): ? """ _checkPatternNumber(patternnumber) self.set_pattern_step_setpoint(patternnumber, 0, sp0) self.set_pattern_step_setpoint(patternnumber, 1, sp1) self.set_pattern_step_setpoint(patternnumber, 2, sp2) self.set_pattern_step_setpoint(patternnumber, 3, sp3) self.set_pattern_step_setpoint(patternnumber, 4, sp4) self.set_pattern_step_setpoint(patternnumber, 5, sp5) self.set_pattern_step_setpoint(patternnumber, 6, sp6) self.set_pattern_step_setpoint(patternnumber, 7, sp7) self.set_pattern_step_time( patternnumber, 0, ti0) self.set_pattern_step_time( patternnumber, 1, ti1) self.set_pattern_step_time( patternnumber, 2, ti2) self.set_pattern_step_time( patternnumber, 3, ti3) self.set_pattern_step_time( patternnumber, 4, ti4) self.set_pattern_step_time( patternnumber, 5, ti5) self.set_pattern_step_time( patternnumber, 6, ti6) self.set_pattern_step_time( patternnumber, 7, ti7) self.set_pattern_additional_cycles(patternnumber, additional_cycles) self.set_pattern_link_topattern( patternnumber, link_pattern) self.set_pattern_actual_step( patternnumber, actual_step)
[ "def", "set_all_pattern_variables", "(", "self", ",", "patternnumber", ",", "sp0", ",", "ti0", ",", "sp1", ",", "ti1", ",", "sp2", ",", "ti2", ",", "sp3", ",", "ti3", ",", "sp4", ",", "ti4", ",", "sp5", ",", "ti5", ",", "sp6", ",", "ti6", ",", "sp7", ",", "ti7", ",", "actual_step", ",", "additional_cycles", ",", "link_pattern", ")", ":", "_checkPatternNumber", "(", "patternnumber", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "0", ",", "sp0", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "1", ",", "sp1", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "2", ",", "sp2", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "3", ",", "sp3", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "4", ",", "sp4", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "5", ",", "sp5", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "6", ",", "sp6", ")", "self", ".", "set_pattern_step_setpoint", "(", "patternnumber", ",", "7", ",", "sp7", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "0", ",", "ti0", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "1", ",", "ti1", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "2", ",", "ti2", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "3", ",", "ti3", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "4", ",", "ti4", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "5", ",", "ti5", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "6", ",", "ti6", ")", "self", ".", "set_pattern_step_time", "(", "patternnumber", ",", "7", ",", "ti7", ")", "self", ".", "set_pattern_additional_cycles", "(", "patternnumber", ",", "additional_cycles", ")", "self", ".", "set_pattern_link_topattern", "(", "patternnumber", ",", "link_pattern", ")", "self", ".", "set_pattern_actual_step", "(", "patternnumber", ",", "actual_step", ")" ]
Set all variables for a given pattern at one time. Args: * patternnumber (integer): 0-7 * sp[*n*] (float): setpoint value for step *n* * ti[*n*] (integer??): step time for step *n*, 0-900 * actual_step (int): ? * additional_cycles(int): ? * link_pattern(int): ?
[ "Set", "all", "variables", "for", "a", "given", "pattern", "at", "one", "time", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/omegacn7500.py#L401-L435
train
238,785
pyhys/minimalmodbus
dummy_serial.py
Serial.close
def close(self): """Close a port on dummy_serial.""" if VERBOSE: _print_out('\nDummy_serial: Closing port\n') if not self._isOpen: raise IOError('Dummy_serial: The port is already closed') self._isOpen = False self.port = None
python
def close(self): """Close a port on dummy_serial.""" if VERBOSE: _print_out('\nDummy_serial: Closing port\n') if not self._isOpen: raise IOError('Dummy_serial: The port is already closed') self._isOpen = False self.port = None
[ "def", "close", "(", "self", ")", ":", "if", "VERBOSE", ":", "_print_out", "(", "'\\nDummy_serial: Closing port\\n'", ")", "if", "not", "self", ".", "_isOpen", ":", "raise", "IOError", "(", "'Dummy_serial: The port is already closed'", ")", "self", ".", "_isOpen", "=", "False", "self", ".", "port", "=", "None" ]
Close a port on dummy_serial.
[ "Close", "a", "port", "on", "dummy_serial", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/dummy_serial.py#L129-L138
train
238,786
pyhys/minimalmodbus
dummy_serial.py
Serial.write
def write(self, inputdata): """Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**. """ if VERBOSE: _print_out('\nDummy_serial: Writing to port. Given:' + repr(inputdata) + '\n') if sys.version_info[0] > 2: if not type(inputdata) == bytes: raise TypeError('The input must be type bytes. Given:' + repr(inputdata)) inputstring = str(inputdata, encoding='latin1') else: inputstring = inputdata if not self._isOpen: raise IOError('Dummy_serial: Trying to write, but the port is not open. Given:' + repr(inputdata)) # Look up which data that should be waiting for subsequent read commands try: response = RESPONSES[inputstring] except: response = DEFAULT_RESPONSE self._waiting_data = response
python
def write(self, inputdata): """Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**. """ if VERBOSE: _print_out('\nDummy_serial: Writing to port. Given:' + repr(inputdata) + '\n') if sys.version_info[0] > 2: if not type(inputdata) == bytes: raise TypeError('The input must be type bytes. Given:' + repr(inputdata)) inputstring = str(inputdata, encoding='latin1') else: inputstring = inputdata if not self._isOpen: raise IOError('Dummy_serial: Trying to write, but the port is not open. Given:' + repr(inputdata)) # Look up which data that should be waiting for subsequent read commands try: response = RESPONSES[inputstring] except: response = DEFAULT_RESPONSE self._waiting_data = response
[ "def", "write", "(", "self", ",", "inputdata", ")", ":", "if", "VERBOSE", ":", "_print_out", "(", "'\\nDummy_serial: Writing to port. Given:'", "+", "repr", "(", "inputdata", ")", "+", "'\\n'", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "if", "not", "type", "(", "inputdata", ")", "==", "bytes", ":", "raise", "TypeError", "(", "'The input must be type bytes. Given:'", "+", "repr", "(", "inputdata", ")", ")", "inputstring", "=", "str", "(", "inputdata", ",", "encoding", "=", "'latin1'", ")", "else", ":", "inputstring", "=", "inputdata", "if", "not", "self", ".", "_isOpen", ":", "raise", "IOError", "(", "'Dummy_serial: Trying to write, but the port is not open. Given:'", "+", "repr", "(", "inputdata", ")", ")", "# Look up which data that should be waiting for subsequent read commands", "try", ":", "response", "=", "RESPONSES", "[", "inputstring", "]", "except", ":", "response", "=", "DEFAULT_RESPONSE", "self", ".", "_waiting_data", "=", "response" ]
Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**.
[ "Write", "to", "a", "port", "on", "dummy_serial", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/dummy_serial.py#L141-L169
train
238,787
pyhys/minimalmodbus
dummy_serial.py
Serial.read
def read(self, numberOfBytes): """Read from a port on dummy_serial. The response is dependent on what was written last to the port on dummy_serial, and what is defined in the :data:`RESPONSES` dictionary. Args: numberOfBytes (int): For compability with the real function. Returns a **string** for Python2 and **bytes** for Python3. If the response is shorter than numberOfBytes, it will sleep for timeout. If the response is longer than numberOfBytes, it will return only numberOfBytes bytes. """ if VERBOSE: _print_out('\nDummy_serial: Reading from port (max length {!r} bytes)'.format(numberOfBytes)) if numberOfBytes < 0: raise IOError('Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}'.format(numberOfBytes)) if not self._isOpen: raise IOError('Dummy_serial: Trying to read, but the port is not open.') # Do the actual reading from the waiting data, and simulate the influence of numberOfBytes if self._waiting_data == DEFAULT_RESPONSE: returnstring = self._waiting_data elif numberOfBytes == len(self._waiting_data): returnstring = self._waiting_data self._waiting_data = NO_DATA_PRESENT elif numberOfBytes < len(self._waiting_data): if VERBOSE: _print_out('Dummy_serial: The numberOfBytes to read is smaller than the available data. ' + \ 'Some bytes will be kept for later. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \ self._waiting_data, len(self._waiting_data), numberOfBytes)) returnstring = self._waiting_data[:numberOfBytes] self._waiting_data = self._waiting_data[numberOfBytes:] else: # Wait for timeout, as we have asked for more data than available if VERBOSE: _print_out('Dummy_serial: The numberOfBytes to read is larger than the available data. ' + \ 'Will sleep until timeout. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \ self._waiting_data, len(self._waiting_data), numberOfBytes)) time.sleep(self.timeout) returnstring = self._waiting_data self._waiting_data = NO_DATA_PRESENT # TODO Adapt the behavior to better mimic the Windows behavior if VERBOSE: _print_out('Dummy_serial read return data: {!r} (has length {})\n'.format(returnstring, len(returnstring))) if sys.version_info[0] > 2: # Convert types to make it python3 compatible return bytes(returnstring, encoding='latin1') else: return returnstring
python
def read(self, numberOfBytes): """Read from a port on dummy_serial. The response is dependent on what was written last to the port on dummy_serial, and what is defined in the :data:`RESPONSES` dictionary. Args: numberOfBytes (int): For compability with the real function. Returns a **string** for Python2 and **bytes** for Python3. If the response is shorter than numberOfBytes, it will sleep for timeout. If the response is longer than numberOfBytes, it will return only numberOfBytes bytes. """ if VERBOSE: _print_out('\nDummy_serial: Reading from port (max length {!r} bytes)'.format(numberOfBytes)) if numberOfBytes < 0: raise IOError('Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}'.format(numberOfBytes)) if not self._isOpen: raise IOError('Dummy_serial: Trying to read, but the port is not open.') # Do the actual reading from the waiting data, and simulate the influence of numberOfBytes if self._waiting_data == DEFAULT_RESPONSE: returnstring = self._waiting_data elif numberOfBytes == len(self._waiting_data): returnstring = self._waiting_data self._waiting_data = NO_DATA_PRESENT elif numberOfBytes < len(self._waiting_data): if VERBOSE: _print_out('Dummy_serial: The numberOfBytes to read is smaller than the available data. ' + \ 'Some bytes will be kept for later. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \ self._waiting_data, len(self._waiting_data), numberOfBytes)) returnstring = self._waiting_data[:numberOfBytes] self._waiting_data = self._waiting_data[numberOfBytes:] else: # Wait for timeout, as we have asked for more data than available if VERBOSE: _print_out('Dummy_serial: The numberOfBytes to read is larger than the available data. ' + \ 'Will sleep until timeout. Available data: {!r} (length = {}), numberOfBytes: {}'.format( \ self._waiting_data, len(self._waiting_data), numberOfBytes)) time.sleep(self.timeout) returnstring = self._waiting_data self._waiting_data = NO_DATA_PRESENT # TODO Adapt the behavior to better mimic the Windows behavior if VERBOSE: _print_out('Dummy_serial read return data: {!r} (has length {})\n'.format(returnstring, len(returnstring))) if sys.version_info[0] > 2: # Convert types to make it python3 compatible return bytes(returnstring, encoding='latin1') else: return returnstring
[ "def", "read", "(", "self", ",", "numberOfBytes", ")", ":", "if", "VERBOSE", ":", "_print_out", "(", "'\\nDummy_serial: Reading from port (max length {!r} bytes)'", ".", "format", "(", "numberOfBytes", ")", ")", "if", "numberOfBytes", "<", "0", ":", "raise", "IOError", "(", "'Dummy_serial: The numberOfBytes to read must not be negative. Given: {!r}'", ".", "format", "(", "numberOfBytes", ")", ")", "if", "not", "self", ".", "_isOpen", ":", "raise", "IOError", "(", "'Dummy_serial: Trying to read, but the port is not open.'", ")", "# Do the actual reading from the waiting data, and simulate the influence of numberOfBytes", "if", "self", ".", "_waiting_data", "==", "DEFAULT_RESPONSE", ":", "returnstring", "=", "self", ".", "_waiting_data", "elif", "numberOfBytes", "==", "len", "(", "self", ".", "_waiting_data", ")", ":", "returnstring", "=", "self", ".", "_waiting_data", "self", ".", "_waiting_data", "=", "NO_DATA_PRESENT", "elif", "numberOfBytes", "<", "len", "(", "self", ".", "_waiting_data", ")", ":", "if", "VERBOSE", ":", "_print_out", "(", "'Dummy_serial: The numberOfBytes to read is smaller than the available data. '", "+", "'Some bytes will be kept for later. Available data: {!r} (length = {}), numberOfBytes: {}'", ".", "format", "(", "self", ".", "_waiting_data", ",", "len", "(", "self", ".", "_waiting_data", ")", ",", "numberOfBytes", ")", ")", "returnstring", "=", "self", ".", "_waiting_data", "[", ":", "numberOfBytes", "]", "self", ".", "_waiting_data", "=", "self", ".", "_waiting_data", "[", "numberOfBytes", ":", "]", "else", ":", "# Wait for timeout, as we have asked for more data than available", "if", "VERBOSE", ":", "_print_out", "(", "'Dummy_serial: The numberOfBytes to read is larger than the available data. '", "+", "'Will sleep until timeout. Available data: {!r} (length = {}), numberOfBytes: {}'", ".", "format", "(", "self", ".", "_waiting_data", ",", "len", "(", "self", ".", "_waiting_data", ")", ",", "numberOfBytes", ")", ")", "time", ".", "sleep", "(", "self", ".", "timeout", ")", "returnstring", "=", "self", ".", "_waiting_data", "self", ".", "_waiting_data", "=", "NO_DATA_PRESENT", "# TODO Adapt the behavior to better mimic the Windows behavior", "if", "VERBOSE", ":", "_print_out", "(", "'Dummy_serial read return data: {!r} (has length {})\\n'", ".", "format", "(", "returnstring", ",", "len", "(", "returnstring", ")", ")", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "# Convert types to make it python3 compatible", "return", "bytes", "(", "returnstring", ",", "encoding", "=", "'latin1'", ")", "else", ":", "return", "returnstring" ]
Read from a port on dummy_serial. The response is dependent on what was written last to the port on dummy_serial, and what is defined in the :data:`RESPONSES` dictionary. Args: numberOfBytes (int): For compability with the real function. Returns a **string** for Python2 and **bytes** for Python3. If the response is shorter than numberOfBytes, it will sleep for timeout. If the response is longer than numberOfBytes, it will return only numberOfBytes bytes.
[ "Read", "from", "a", "port", "on", "dummy_serial", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/dummy_serial.py#L172-L227
train
238,788
pyhys/minimalmodbus
minimalmodbus.py
_embedPayload
def _embedPayload(slaveaddress, mode, functioncode, payloaddata): """Build a request from the slaveaddress, the function code and the payload data. Args: * slaveaddress (int): The address of the slave. * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register). * payloaddata (str): The byte string to be sent to the slave. Returns: The built (raw) request string for sending to the slave (including CRC etc). Raises: ValueError, TypeError. The resulting request has the format: * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes). * ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF) The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata. The header, LRC/CRC, and footer are excluded from the calculation. """ _checkSlaveaddress(slaveaddress) _checkMode(mode) _checkFunctioncode(functioncode, None) _checkString(payloaddata, description='payload') firstPart = _numToOneByteString(slaveaddress) + _numToOneByteString(functioncode) + payloaddata if mode == MODE_ASCII: request = _ASCII_HEADER + \ _hexencode(firstPart) + \ _hexencode(_calculateLrcString(firstPart)) + \ _ASCII_FOOTER else: request = firstPart + _calculateCrcString(firstPart) return request
python
def _embedPayload(slaveaddress, mode, functioncode, payloaddata): """Build a request from the slaveaddress, the function code and the payload data. Args: * slaveaddress (int): The address of the slave. * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register). * payloaddata (str): The byte string to be sent to the slave. Returns: The built (raw) request string for sending to the slave (including CRC etc). Raises: ValueError, TypeError. The resulting request has the format: * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes). * ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF) The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata. The header, LRC/CRC, and footer are excluded from the calculation. """ _checkSlaveaddress(slaveaddress) _checkMode(mode) _checkFunctioncode(functioncode, None) _checkString(payloaddata, description='payload') firstPart = _numToOneByteString(slaveaddress) + _numToOneByteString(functioncode) + payloaddata if mode == MODE_ASCII: request = _ASCII_HEADER + \ _hexencode(firstPart) + \ _hexencode(_calculateLrcString(firstPart)) + \ _ASCII_FOOTER else: request = firstPart + _calculateCrcString(firstPart) return request
[ "def", "_embedPayload", "(", "slaveaddress", ",", "mode", ",", "functioncode", ",", "payloaddata", ")", ":", "_checkSlaveaddress", "(", "slaveaddress", ")", "_checkMode", "(", "mode", ")", "_checkFunctioncode", "(", "functioncode", ",", "None", ")", "_checkString", "(", "payloaddata", ",", "description", "=", "'payload'", ")", "firstPart", "=", "_numToOneByteString", "(", "slaveaddress", ")", "+", "_numToOneByteString", "(", "functioncode", ")", "+", "payloaddata", "if", "mode", "==", "MODE_ASCII", ":", "request", "=", "_ASCII_HEADER", "+", "_hexencode", "(", "firstPart", ")", "+", "_hexencode", "(", "_calculateLrcString", "(", "firstPart", ")", ")", "+", "_ASCII_FOOTER", "else", ":", "request", "=", "firstPart", "+", "_calculateCrcString", "(", "firstPart", ")", "return", "request" ]
Build a request from the slaveaddress, the function code and the payload data. Args: * slaveaddress (int): The address of the slave. * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register). * payloaddata (str): The byte string to be sent to the slave. Returns: The built (raw) request string for sending to the slave (including CRC etc). Raises: ValueError, TypeError. The resulting request has the format: * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes). * ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF) The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata. The header, LRC/CRC, and footer are excluded from the calculation.
[ "Build", "a", "request", "from", "the", "slaveaddress", "the", "function", "code", "and", "the", "payload", "data", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L939-L977
train
238,789
pyhys/minimalmodbus
minimalmodbus.py
_extractPayload
def _extractPayload(response, slaveaddress, mode, functioncode): """Extract the payload data part from the slave's response. Args: * response (str): The raw response byte string from the slave. * slaveaddress (int): The adress of the slave. Used here for error checking only. * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Used here for error checking only. Returns: The payload part of the *response* string. Raises: ValueError, TypeError. Raises an exception if there is any problem with the received address, the functioncode or the CRC. The received response should have the format: * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes) * ASCII Mode: header (:) + slaveaddress byte + functioncode byte + payloaddata + LRC (which is two characters) + footer (CRLF) For development purposes, this function can also be used to extract the payload from the request sent TO the slave. """ BYTEPOSITION_FOR_ASCII_HEADER = 0 # Relative to plain response BYTEPOSITION_FOR_SLAVEADDRESS = 0 # Relative to (stripped) response BYTEPOSITION_FOR_FUNCTIONCODE = 1 NUMBER_OF_RESPONSE_STARTBYTES = 2 # Number of bytes before the response payload (in stripped response) NUMBER_OF_CRC_BYTES = 2 NUMBER_OF_LRC_BYTES = 1 BITNUMBER_FUNCTIONCODE_ERRORINDICATION = 7 MINIMAL_RESPONSE_LENGTH_RTU = NUMBER_OF_RESPONSE_STARTBYTES + NUMBER_OF_CRC_BYTES MINIMAL_RESPONSE_LENGTH_ASCII = 9 # Argument validity testing _checkString(response, description='response') _checkSlaveaddress(slaveaddress) _checkMode(mode) _checkFunctioncode(functioncode, None) plainresponse = response # Validate response length if mode == MODE_ASCII: if len(response) < MINIMAL_RESPONSE_LENGTH_ASCII: raise ValueError('Too short Modbus ASCII response (minimum length {} bytes). Response: {!r}'.format( \ MINIMAL_RESPONSE_LENGTH_ASCII, response)) elif len(response) < MINIMAL_RESPONSE_LENGTH_RTU: raise ValueError('Too short Modbus RTU response (minimum length {} bytes). Response: {!r}'.format( \ MINIMAL_RESPONSE_LENGTH_RTU, response)) # Validate the ASCII header and footer. if mode == MODE_ASCII: if response[BYTEPOSITION_FOR_ASCII_HEADER] != _ASCII_HEADER: raise ValueError('Did not find header ({!r}) as start of ASCII response. The plain response is: {!r}'.format( \ _ASCII_HEADER, response)) elif response[-len(_ASCII_FOOTER):] != _ASCII_FOOTER: raise ValueError('Did not find footer ({!r}) as end of ASCII response. The plain response is: {!r}'.format( \ _ASCII_FOOTER, response)) # Strip ASCII header and footer response = response[1:-2] if len(response) % 2 != 0: template = 'Stripped ASCII frames should have an even number of bytes, but is {} bytes. ' + \ 'The stripped response is: {!r} (plain response: {!r})' raise ValueError(template.format(len(response), response, plainresponse)) # Convert the ASCII (stripped) response string to RTU-like response string response = _hexdecode(response) # Validate response checksum if mode == MODE_ASCII: calculateChecksum = _calculateLrcString numberOfChecksumBytes = NUMBER_OF_LRC_BYTES else: calculateChecksum = _calculateCrcString numberOfChecksumBytes = NUMBER_OF_CRC_BYTES receivedChecksum = response[-numberOfChecksumBytes:] responseWithoutChecksum = response[0 : len(response) - numberOfChecksumBytes] calculatedChecksum = calculateChecksum(responseWithoutChecksum) if receivedChecksum != calculatedChecksum: template = 'Checksum error in {} mode: {!r} instead of {!r} . The response is: {!r} (plain response: {!r})' text = template.format( mode, receivedChecksum, calculatedChecksum, response, plainresponse) raise ValueError(text) # Check slave address responseaddress = ord(response[BYTEPOSITION_FOR_SLAVEADDRESS]) if responseaddress != slaveaddress: raise ValueError('Wrong return slave address: {} instead of {}. The response is: {!r}'.format( \ responseaddress, slaveaddress, response)) # Check function code receivedFunctioncode = ord(response[BYTEPOSITION_FOR_FUNCTIONCODE]) if receivedFunctioncode == _setBitOn(functioncode, BITNUMBER_FUNCTIONCODE_ERRORINDICATION): raise ValueError('The slave is indicating an error. The response is: {!r}'.format(response)) elif receivedFunctioncode != functioncode: raise ValueError('Wrong functioncode: {} instead of {}. The response is: {!r}'.format( \ receivedFunctioncode, functioncode, response)) # Read data payload firstDatabyteNumber = NUMBER_OF_RESPONSE_STARTBYTES if mode == MODE_ASCII: lastDatabyteNumber = len(response) - NUMBER_OF_LRC_BYTES else: lastDatabyteNumber = len(response) - NUMBER_OF_CRC_BYTES payload = response[firstDatabyteNumber:lastDatabyteNumber] return payload
python
def _extractPayload(response, slaveaddress, mode, functioncode): """Extract the payload data part from the slave's response. Args: * response (str): The raw response byte string from the slave. * slaveaddress (int): The adress of the slave. Used here for error checking only. * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Used here for error checking only. Returns: The payload part of the *response* string. Raises: ValueError, TypeError. Raises an exception if there is any problem with the received address, the functioncode or the CRC. The received response should have the format: * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes) * ASCII Mode: header (:) + slaveaddress byte + functioncode byte + payloaddata + LRC (which is two characters) + footer (CRLF) For development purposes, this function can also be used to extract the payload from the request sent TO the slave. """ BYTEPOSITION_FOR_ASCII_HEADER = 0 # Relative to plain response BYTEPOSITION_FOR_SLAVEADDRESS = 0 # Relative to (stripped) response BYTEPOSITION_FOR_FUNCTIONCODE = 1 NUMBER_OF_RESPONSE_STARTBYTES = 2 # Number of bytes before the response payload (in stripped response) NUMBER_OF_CRC_BYTES = 2 NUMBER_OF_LRC_BYTES = 1 BITNUMBER_FUNCTIONCODE_ERRORINDICATION = 7 MINIMAL_RESPONSE_LENGTH_RTU = NUMBER_OF_RESPONSE_STARTBYTES + NUMBER_OF_CRC_BYTES MINIMAL_RESPONSE_LENGTH_ASCII = 9 # Argument validity testing _checkString(response, description='response') _checkSlaveaddress(slaveaddress) _checkMode(mode) _checkFunctioncode(functioncode, None) plainresponse = response # Validate response length if mode == MODE_ASCII: if len(response) < MINIMAL_RESPONSE_LENGTH_ASCII: raise ValueError('Too short Modbus ASCII response (minimum length {} bytes). Response: {!r}'.format( \ MINIMAL_RESPONSE_LENGTH_ASCII, response)) elif len(response) < MINIMAL_RESPONSE_LENGTH_RTU: raise ValueError('Too short Modbus RTU response (minimum length {} bytes). Response: {!r}'.format( \ MINIMAL_RESPONSE_LENGTH_RTU, response)) # Validate the ASCII header and footer. if mode == MODE_ASCII: if response[BYTEPOSITION_FOR_ASCII_HEADER] != _ASCII_HEADER: raise ValueError('Did not find header ({!r}) as start of ASCII response. The plain response is: {!r}'.format( \ _ASCII_HEADER, response)) elif response[-len(_ASCII_FOOTER):] != _ASCII_FOOTER: raise ValueError('Did not find footer ({!r}) as end of ASCII response. The plain response is: {!r}'.format( \ _ASCII_FOOTER, response)) # Strip ASCII header and footer response = response[1:-2] if len(response) % 2 != 0: template = 'Stripped ASCII frames should have an even number of bytes, but is {} bytes. ' + \ 'The stripped response is: {!r} (plain response: {!r})' raise ValueError(template.format(len(response), response, plainresponse)) # Convert the ASCII (stripped) response string to RTU-like response string response = _hexdecode(response) # Validate response checksum if mode == MODE_ASCII: calculateChecksum = _calculateLrcString numberOfChecksumBytes = NUMBER_OF_LRC_BYTES else: calculateChecksum = _calculateCrcString numberOfChecksumBytes = NUMBER_OF_CRC_BYTES receivedChecksum = response[-numberOfChecksumBytes:] responseWithoutChecksum = response[0 : len(response) - numberOfChecksumBytes] calculatedChecksum = calculateChecksum(responseWithoutChecksum) if receivedChecksum != calculatedChecksum: template = 'Checksum error in {} mode: {!r} instead of {!r} . The response is: {!r} (plain response: {!r})' text = template.format( mode, receivedChecksum, calculatedChecksum, response, plainresponse) raise ValueError(text) # Check slave address responseaddress = ord(response[BYTEPOSITION_FOR_SLAVEADDRESS]) if responseaddress != slaveaddress: raise ValueError('Wrong return slave address: {} instead of {}. The response is: {!r}'.format( \ responseaddress, slaveaddress, response)) # Check function code receivedFunctioncode = ord(response[BYTEPOSITION_FOR_FUNCTIONCODE]) if receivedFunctioncode == _setBitOn(functioncode, BITNUMBER_FUNCTIONCODE_ERRORINDICATION): raise ValueError('The slave is indicating an error. The response is: {!r}'.format(response)) elif receivedFunctioncode != functioncode: raise ValueError('Wrong functioncode: {} instead of {}. The response is: {!r}'.format( \ receivedFunctioncode, functioncode, response)) # Read data payload firstDatabyteNumber = NUMBER_OF_RESPONSE_STARTBYTES if mode == MODE_ASCII: lastDatabyteNumber = len(response) - NUMBER_OF_LRC_BYTES else: lastDatabyteNumber = len(response) - NUMBER_OF_CRC_BYTES payload = response[firstDatabyteNumber:lastDatabyteNumber] return payload
[ "def", "_extractPayload", "(", "response", ",", "slaveaddress", ",", "mode", ",", "functioncode", ")", ":", "BYTEPOSITION_FOR_ASCII_HEADER", "=", "0", "# Relative to plain response", "BYTEPOSITION_FOR_SLAVEADDRESS", "=", "0", "# Relative to (stripped) response", "BYTEPOSITION_FOR_FUNCTIONCODE", "=", "1", "NUMBER_OF_RESPONSE_STARTBYTES", "=", "2", "# Number of bytes before the response payload (in stripped response)", "NUMBER_OF_CRC_BYTES", "=", "2", "NUMBER_OF_LRC_BYTES", "=", "1", "BITNUMBER_FUNCTIONCODE_ERRORINDICATION", "=", "7", "MINIMAL_RESPONSE_LENGTH_RTU", "=", "NUMBER_OF_RESPONSE_STARTBYTES", "+", "NUMBER_OF_CRC_BYTES", "MINIMAL_RESPONSE_LENGTH_ASCII", "=", "9", "# Argument validity testing", "_checkString", "(", "response", ",", "description", "=", "'response'", ")", "_checkSlaveaddress", "(", "slaveaddress", ")", "_checkMode", "(", "mode", ")", "_checkFunctioncode", "(", "functioncode", ",", "None", ")", "plainresponse", "=", "response", "# Validate response length", "if", "mode", "==", "MODE_ASCII", ":", "if", "len", "(", "response", ")", "<", "MINIMAL_RESPONSE_LENGTH_ASCII", ":", "raise", "ValueError", "(", "'Too short Modbus ASCII response (minimum length {} bytes). Response: {!r}'", ".", "format", "(", "MINIMAL_RESPONSE_LENGTH_ASCII", ",", "response", ")", ")", "elif", "len", "(", "response", ")", "<", "MINIMAL_RESPONSE_LENGTH_RTU", ":", "raise", "ValueError", "(", "'Too short Modbus RTU response (minimum length {} bytes). Response: {!r}'", ".", "format", "(", "MINIMAL_RESPONSE_LENGTH_RTU", ",", "response", ")", ")", "# Validate the ASCII header and footer.", "if", "mode", "==", "MODE_ASCII", ":", "if", "response", "[", "BYTEPOSITION_FOR_ASCII_HEADER", "]", "!=", "_ASCII_HEADER", ":", "raise", "ValueError", "(", "'Did not find header ({!r}) as start of ASCII response. The plain response is: {!r}'", ".", "format", "(", "_ASCII_HEADER", ",", "response", ")", ")", "elif", "response", "[", "-", "len", "(", "_ASCII_FOOTER", ")", ":", "]", "!=", "_ASCII_FOOTER", ":", "raise", "ValueError", "(", "'Did not find footer ({!r}) as end of ASCII response. The plain response is: {!r}'", ".", "format", "(", "_ASCII_FOOTER", ",", "response", ")", ")", "# Strip ASCII header and footer", "response", "=", "response", "[", "1", ":", "-", "2", "]", "if", "len", "(", "response", ")", "%", "2", "!=", "0", ":", "template", "=", "'Stripped ASCII frames should have an even number of bytes, but is {} bytes. '", "+", "'The stripped response is: {!r} (plain response: {!r})'", "raise", "ValueError", "(", "template", ".", "format", "(", "len", "(", "response", ")", ",", "response", ",", "plainresponse", ")", ")", "# Convert the ASCII (stripped) response string to RTU-like response string", "response", "=", "_hexdecode", "(", "response", ")", "# Validate response checksum", "if", "mode", "==", "MODE_ASCII", ":", "calculateChecksum", "=", "_calculateLrcString", "numberOfChecksumBytes", "=", "NUMBER_OF_LRC_BYTES", "else", ":", "calculateChecksum", "=", "_calculateCrcString", "numberOfChecksumBytes", "=", "NUMBER_OF_CRC_BYTES", "receivedChecksum", "=", "response", "[", "-", "numberOfChecksumBytes", ":", "]", "responseWithoutChecksum", "=", "response", "[", "0", ":", "len", "(", "response", ")", "-", "numberOfChecksumBytes", "]", "calculatedChecksum", "=", "calculateChecksum", "(", "responseWithoutChecksum", ")", "if", "receivedChecksum", "!=", "calculatedChecksum", ":", "template", "=", "'Checksum error in {} mode: {!r} instead of {!r} . The response is: {!r} (plain response: {!r})'", "text", "=", "template", ".", "format", "(", "mode", ",", "receivedChecksum", ",", "calculatedChecksum", ",", "response", ",", "plainresponse", ")", "raise", "ValueError", "(", "text", ")", "# Check slave address", "responseaddress", "=", "ord", "(", "response", "[", "BYTEPOSITION_FOR_SLAVEADDRESS", "]", ")", "if", "responseaddress", "!=", "slaveaddress", ":", "raise", "ValueError", "(", "'Wrong return slave address: {} instead of {}. The response is: {!r}'", ".", "format", "(", "responseaddress", ",", "slaveaddress", ",", "response", ")", ")", "# Check function code", "receivedFunctioncode", "=", "ord", "(", "response", "[", "BYTEPOSITION_FOR_FUNCTIONCODE", "]", ")", "if", "receivedFunctioncode", "==", "_setBitOn", "(", "functioncode", ",", "BITNUMBER_FUNCTIONCODE_ERRORINDICATION", ")", ":", "raise", "ValueError", "(", "'The slave is indicating an error. The response is: {!r}'", ".", "format", "(", "response", ")", ")", "elif", "receivedFunctioncode", "!=", "functioncode", ":", "raise", "ValueError", "(", "'Wrong functioncode: {} instead of {}. The response is: {!r}'", ".", "format", "(", "receivedFunctioncode", ",", "functioncode", ",", "response", ")", ")", "# Read data payload", "firstDatabyteNumber", "=", "NUMBER_OF_RESPONSE_STARTBYTES", "if", "mode", "==", "MODE_ASCII", ":", "lastDatabyteNumber", "=", "len", "(", "response", ")", "-", "NUMBER_OF_LRC_BYTES", "else", ":", "lastDatabyteNumber", "=", "len", "(", "response", ")", "-", "NUMBER_OF_CRC_BYTES", "payload", "=", "response", "[", "firstDatabyteNumber", ":", "lastDatabyteNumber", "]", "return", "payload" ]
Extract the payload data part from the slave's response. Args: * response (str): The raw response byte string from the slave. * slaveaddress (int): The adress of the slave. Used here for error checking only. * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Used here for error checking only. Returns: The payload part of the *response* string. Raises: ValueError, TypeError. Raises an exception if there is any problem with the received address, the functioncode or the CRC. The received response should have the format: * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes) * ASCII Mode: header (:) + slaveaddress byte + functioncode byte + payloaddata + LRC (which is two characters) + footer (CRLF) For development purposes, this function can also be used to extract the payload from the request sent TO the slave.
[ "Extract", "the", "payload", "data", "part", "from", "the", "slave", "s", "response", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L980-L1103
train
238,790
pyhys/minimalmodbus
minimalmodbus.py
_predictResponseSize
def _predictResponseSize(mode, functioncode, payloadToSlave): """Calculate the number of bytes that should be received from the slave. Args: * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Modbus function code. * payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string) Returns: The preducted number of bytes (int) in the response. Raises: ValueError, TypeError. """ MIN_PAYLOAD_LENGTH = 4 # For implemented functioncodes here BYTERANGE_FOR_GIVEN_SIZE = slice(2, 4) # Within the payload NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION = 4 NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD = 1 RTU_TO_ASCII_PAYLOAD_FACTOR = 2 NUMBER_OF_RTU_RESPONSE_STARTBYTES = 2 NUMBER_OF_RTU_RESPONSE_ENDBYTES = 2 NUMBER_OF_ASCII_RESPONSE_STARTBYTES = 5 NUMBER_OF_ASCII_RESPONSE_ENDBYTES = 4 # Argument validity testing _checkMode(mode) _checkFunctioncode(functioncode, None) _checkString(payloadToSlave, description='payload', minlength=MIN_PAYLOAD_LENGTH) # Calculate payload size if functioncode in [5, 6, 15, 16]: response_payload_size = NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION elif functioncode in [1, 2, 3, 4]: given_size = _twoByteStringToNum(payloadToSlave[BYTERANGE_FOR_GIVEN_SIZE]) if functioncode == 1 or functioncode == 2: # Algorithm from MODBUS APPLICATION PROTOCOL SPECIFICATION V1.1b number_of_inputs = given_size response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \ number_of_inputs // 8 + (1 if number_of_inputs % 8 else 0) elif functioncode == 3 or functioncode == 4: number_of_registers = given_size response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \ number_of_registers * _NUMBER_OF_BYTES_PER_REGISTER else: raise ValueError('Wrong functioncode: {}. The payload is: {!r}'.format( \ functioncode, payloadToSlave)) # Calculate number of bytes to read if mode == MODE_ASCII: return NUMBER_OF_ASCII_RESPONSE_STARTBYTES + \ response_payload_size * RTU_TO_ASCII_PAYLOAD_FACTOR + \ NUMBER_OF_ASCII_RESPONSE_ENDBYTES else: return NUMBER_OF_RTU_RESPONSE_STARTBYTES + \ response_payload_size + \ NUMBER_OF_RTU_RESPONSE_ENDBYTES
python
def _predictResponseSize(mode, functioncode, payloadToSlave): """Calculate the number of bytes that should be received from the slave. Args: * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Modbus function code. * payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string) Returns: The preducted number of bytes (int) in the response. Raises: ValueError, TypeError. """ MIN_PAYLOAD_LENGTH = 4 # For implemented functioncodes here BYTERANGE_FOR_GIVEN_SIZE = slice(2, 4) # Within the payload NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION = 4 NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD = 1 RTU_TO_ASCII_PAYLOAD_FACTOR = 2 NUMBER_OF_RTU_RESPONSE_STARTBYTES = 2 NUMBER_OF_RTU_RESPONSE_ENDBYTES = 2 NUMBER_OF_ASCII_RESPONSE_STARTBYTES = 5 NUMBER_OF_ASCII_RESPONSE_ENDBYTES = 4 # Argument validity testing _checkMode(mode) _checkFunctioncode(functioncode, None) _checkString(payloadToSlave, description='payload', minlength=MIN_PAYLOAD_LENGTH) # Calculate payload size if functioncode in [5, 6, 15, 16]: response_payload_size = NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION elif functioncode in [1, 2, 3, 4]: given_size = _twoByteStringToNum(payloadToSlave[BYTERANGE_FOR_GIVEN_SIZE]) if functioncode == 1 or functioncode == 2: # Algorithm from MODBUS APPLICATION PROTOCOL SPECIFICATION V1.1b number_of_inputs = given_size response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \ number_of_inputs // 8 + (1 if number_of_inputs % 8 else 0) elif functioncode == 3 or functioncode == 4: number_of_registers = given_size response_payload_size = NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD + \ number_of_registers * _NUMBER_OF_BYTES_PER_REGISTER else: raise ValueError('Wrong functioncode: {}. The payload is: {!r}'.format( \ functioncode, payloadToSlave)) # Calculate number of bytes to read if mode == MODE_ASCII: return NUMBER_OF_ASCII_RESPONSE_STARTBYTES + \ response_payload_size * RTU_TO_ASCII_PAYLOAD_FACTOR + \ NUMBER_OF_ASCII_RESPONSE_ENDBYTES else: return NUMBER_OF_RTU_RESPONSE_STARTBYTES + \ response_payload_size + \ NUMBER_OF_RTU_RESPONSE_ENDBYTES
[ "def", "_predictResponseSize", "(", "mode", ",", "functioncode", ",", "payloadToSlave", ")", ":", "MIN_PAYLOAD_LENGTH", "=", "4", "# For implemented functioncodes here", "BYTERANGE_FOR_GIVEN_SIZE", "=", "slice", "(", "2", ",", "4", ")", "# Within the payload", "NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION", "=", "4", "NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD", "=", "1", "RTU_TO_ASCII_PAYLOAD_FACTOR", "=", "2", "NUMBER_OF_RTU_RESPONSE_STARTBYTES", "=", "2", "NUMBER_OF_RTU_RESPONSE_ENDBYTES", "=", "2", "NUMBER_OF_ASCII_RESPONSE_STARTBYTES", "=", "5", "NUMBER_OF_ASCII_RESPONSE_ENDBYTES", "=", "4", "# Argument validity testing", "_checkMode", "(", "mode", ")", "_checkFunctioncode", "(", "functioncode", ",", "None", ")", "_checkString", "(", "payloadToSlave", ",", "description", "=", "'payload'", ",", "minlength", "=", "MIN_PAYLOAD_LENGTH", ")", "# Calculate payload size", "if", "functioncode", "in", "[", "5", ",", "6", ",", "15", ",", "16", "]", ":", "response_payload_size", "=", "NUMBER_OF_PAYLOAD_BYTES_IN_WRITE_CONFIRMATION", "elif", "functioncode", "in", "[", "1", ",", "2", ",", "3", ",", "4", "]", ":", "given_size", "=", "_twoByteStringToNum", "(", "payloadToSlave", "[", "BYTERANGE_FOR_GIVEN_SIZE", "]", ")", "if", "functioncode", "==", "1", "or", "functioncode", "==", "2", ":", "# Algorithm from MODBUS APPLICATION PROTOCOL SPECIFICATION V1.1b", "number_of_inputs", "=", "given_size", "response_payload_size", "=", "NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD", "+", "number_of_inputs", "//", "8", "+", "(", "1", "if", "number_of_inputs", "%", "8", "else", "0", ")", "elif", "functioncode", "==", "3", "or", "functioncode", "==", "4", ":", "number_of_registers", "=", "given_size", "response_payload_size", "=", "NUMBER_OF_PAYLOAD_BYTES_FOR_BYTECOUNTFIELD", "+", "number_of_registers", "*", "_NUMBER_OF_BYTES_PER_REGISTER", "else", ":", "raise", "ValueError", "(", "'Wrong functioncode: {}. The payload is: {!r}'", ".", "format", "(", "functioncode", ",", "payloadToSlave", ")", ")", "# Calculate number of bytes to read", "if", "mode", "==", "MODE_ASCII", ":", "return", "NUMBER_OF_ASCII_RESPONSE_STARTBYTES", "+", "response_payload_size", "*", "RTU_TO_ASCII_PAYLOAD_FACTOR", "+", "NUMBER_OF_ASCII_RESPONSE_ENDBYTES", "else", ":", "return", "NUMBER_OF_RTU_RESPONSE_STARTBYTES", "+", "response_payload_size", "+", "NUMBER_OF_RTU_RESPONSE_ENDBYTES" ]
Calculate the number of bytes that should be received from the slave. Args: * mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII) * functioncode (int): Modbus function code. * payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string) Returns: The preducted number of bytes (int) in the response. Raises: ValueError, TypeError.
[ "Calculate", "the", "number", "of", "bytes", "that", "should", "be", "received", "from", "the", "slave", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1110-L1172
train
238,791
pyhys/minimalmodbus
minimalmodbus.py
_calculate_minimum_silent_period
def _calculate_minimum_silent_period(baudrate): """Calculate the silent period length to comply with the 3.5 character silence between messages. Args: baudrate (numerical): The baudrate for the serial port Returns: The number of seconds (float) that should pass between each message on the bus. Raises: ValueError, TypeError. """ _checkNumerical(baudrate, minvalue=1, description='baudrate') # Avoid division by zero BITTIMES_PER_CHARACTERTIME = 11 MINIMUM_SILENT_CHARACTERTIMES = 3.5 bittime = 1 / float(baudrate) return bittime * BITTIMES_PER_CHARACTERTIME * MINIMUM_SILENT_CHARACTERTIMES
python
def _calculate_minimum_silent_period(baudrate): """Calculate the silent period length to comply with the 3.5 character silence between messages. Args: baudrate (numerical): The baudrate for the serial port Returns: The number of seconds (float) that should pass between each message on the bus. Raises: ValueError, TypeError. """ _checkNumerical(baudrate, minvalue=1, description='baudrate') # Avoid division by zero BITTIMES_PER_CHARACTERTIME = 11 MINIMUM_SILENT_CHARACTERTIMES = 3.5 bittime = 1 / float(baudrate) return bittime * BITTIMES_PER_CHARACTERTIME * MINIMUM_SILENT_CHARACTERTIMES
[ "def", "_calculate_minimum_silent_period", "(", "baudrate", ")", ":", "_checkNumerical", "(", "baudrate", ",", "minvalue", "=", "1", ",", "description", "=", "'baudrate'", ")", "# Avoid division by zero", "BITTIMES_PER_CHARACTERTIME", "=", "11", "MINIMUM_SILENT_CHARACTERTIMES", "=", "3.5", "bittime", "=", "1", "/", "float", "(", "baudrate", ")", "return", "bittime", "*", "BITTIMES_PER_CHARACTERTIME", "*", "MINIMUM_SILENT_CHARACTERTIMES" ]
Calculate the silent period length to comply with the 3.5 character silence between messages. Args: baudrate (numerical): The baudrate for the serial port Returns: The number of seconds (float) that should pass between each message on the bus. Raises: ValueError, TypeError.
[ "Calculate", "the", "silent", "period", "length", "to", "comply", "with", "the", "3", ".", "5", "character", "silence", "between", "messages", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1175-L1194
train
238,792
pyhys/minimalmodbus
minimalmodbus.py
_numToTwoByteString
def _numToTwoByteString(value, numberOfDecimals=0, LsbFirst=False, signed=False): """Convert a numerical value to a two-byte string, possibly scaling it. Args: * value (float or int): The numerical value to be converted. * numberOfDecimals (int): Number of decimals, 0 or more, for scaling. * LsbFirst (bol): Whether the least significant byte should be first in the resulting string. * signed (bol): Whether negative values should be accepted. Returns: A two-byte string. Raises: TypeError, ValueError. Gives DeprecationWarning instead of ValueError for some values in Python 2.6. Use ``numberOfDecimals=1`` to multiply ``value`` by 10 before sending it to the slave register. Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register. Use the parameter ``signed=True`` if making a bytestring that can hold negative values. Then negative input will be automatically converted into upper range data (two's complement). The byte order is controlled by the ``LsbFirst`` parameter, as seen here: ====================== ============= ==================================== ``LsbFirst`` parameter Endianness Description ====================== ============= ==================================== False (default) Big-endian Most significant byte is sent first True Little-endian Least significant byte is sent first ====================== ============= ==================================== For example: To store for example value=77.0, use ``numberOfDecimals = 1`` if the register will hold it as 770 internally. The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the least significant byte is 02 (hex). With ``LsbFirst = False``, the most significant byte is given first why the resulting string is ``\\x03\\x02``, which has the length 2. """ _checkNumerical(value, description='inputvalue') _checkInt(numberOfDecimals, minvalue=0, description='number of decimals') _checkBool(LsbFirst, description='LsbFirst') _checkBool(signed, description='signed parameter') multiplier = 10 ** numberOfDecimals integer = int(float(value) * multiplier) if LsbFirst: formatcode = '<' # Little-endian else: formatcode = '>' # Big-endian if signed: formatcode += 'h' # (Signed) short (2 bytes) else: formatcode += 'H' # Unsigned short (2 bytes) outstring = _pack(formatcode, integer) assert len(outstring) == 2 return outstring
python
def _numToTwoByteString(value, numberOfDecimals=0, LsbFirst=False, signed=False): """Convert a numerical value to a two-byte string, possibly scaling it. Args: * value (float or int): The numerical value to be converted. * numberOfDecimals (int): Number of decimals, 0 or more, for scaling. * LsbFirst (bol): Whether the least significant byte should be first in the resulting string. * signed (bol): Whether negative values should be accepted. Returns: A two-byte string. Raises: TypeError, ValueError. Gives DeprecationWarning instead of ValueError for some values in Python 2.6. Use ``numberOfDecimals=1`` to multiply ``value`` by 10 before sending it to the slave register. Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register. Use the parameter ``signed=True`` if making a bytestring that can hold negative values. Then negative input will be automatically converted into upper range data (two's complement). The byte order is controlled by the ``LsbFirst`` parameter, as seen here: ====================== ============= ==================================== ``LsbFirst`` parameter Endianness Description ====================== ============= ==================================== False (default) Big-endian Most significant byte is sent first True Little-endian Least significant byte is sent first ====================== ============= ==================================== For example: To store for example value=77.0, use ``numberOfDecimals = 1`` if the register will hold it as 770 internally. The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the least significant byte is 02 (hex). With ``LsbFirst = False``, the most significant byte is given first why the resulting string is ``\\x03\\x02``, which has the length 2. """ _checkNumerical(value, description='inputvalue') _checkInt(numberOfDecimals, minvalue=0, description='number of decimals') _checkBool(LsbFirst, description='LsbFirst') _checkBool(signed, description='signed parameter') multiplier = 10 ** numberOfDecimals integer = int(float(value) * multiplier) if LsbFirst: formatcode = '<' # Little-endian else: formatcode = '>' # Big-endian if signed: formatcode += 'h' # (Signed) short (2 bytes) else: formatcode += 'H' # Unsigned short (2 bytes) outstring = _pack(formatcode, integer) assert len(outstring) == 2 return outstring
[ "def", "_numToTwoByteString", "(", "value", ",", "numberOfDecimals", "=", "0", ",", "LsbFirst", "=", "False", ",", "signed", "=", "False", ")", ":", "_checkNumerical", "(", "value", ",", "description", "=", "'inputvalue'", ")", "_checkInt", "(", "numberOfDecimals", ",", "minvalue", "=", "0", ",", "description", "=", "'number of decimals'", ")", "_checkBool", "(", "LsbFirst", ",", "description", "=", "'LsbFirst'", ")", "_checkBool", "(", "signed", ",", "description", "=", "'signed parameter'", ")", "multiplier", "=", "10", "**", "numberOfDecimals", "integer", "=", "int", "(", "float", "(", "value", ")", "*", "multiplier", ")", "if", "LsbFirst", ":", "formatcode", "=", "'<'", "# Little-endian", "else", ":", "formatcode", "=", "'>'", "# Big-endian", "if", "signed", ":", "formatcode", "+=", "'h'", "# (Signed) short (2 bytes)", "else", ":", "formatcode", "+=", "'H'", "# Unsigned short (2 bytes)", "outstring", "=", "_pack", "(", "formatcode", ",", "integer", ")", "assert", "len", "(", "outstring", ")", "==", "2", "return", "outstring" ]
Convert a numerical value to a two-byte string, possibly scaling it. Args: * value (float or int): The numerical value to be converted. * numberOfDecimals (int): Number of decimals, 0 or more, for scaling. * LsbFirst (bol): Whether the least significant byte should be first in the resulting string. * signed (bol): Whether negative values should be accepted. Returns: A two-byte string. Raises: TypeError, ValueError. Gives DeprecationWarning instead of ValueError for some values in Python 2.6. Use ``numberOfDecimals=1`` to multiply ``value`` by 10 before sending it to the slave register. Similarly ``numberOfDecimals=2`` will multiply ``value`` by 100 before sending it to the slave register. Use the parameter ``signed=True`` if making a bytestring that can hold negative values. Then negative input will be automatically converted into upper range data (two's complement). The byte order is controlled by the ``LsbFirst`` parameter, as seen here: ====================== ============= ==================================== ``LsbFirst`` parameter Endianness Description ====================== ============= ==================================== False (default) Big-endian Most significant byte is sent first True Little-endian Least significant byte is sent first ====================== ============= ==================================== For example: To store for example value=77.0, use ``numberOfDecimals = 1`` if the register will hold it as 770 internally. The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the least significant byte is 02 (hex). With ``LsbFirst = False``, the most significant byte is given first why the resulting string is ``\\x03\\x02``, which has the length 2.
[ "Convert", "a", "numerical", "value", "to", "a", "two", "-", "byte", "string", "possibly", "scaling", "it", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1219-L1277
train
238,793
pyhys/minimalmodbus
minimalmodbus.py
_twoByteStringToNum
def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False): """Convert a two-byte string to a numerical value, possibly scaling it. Args: * bytestring (str): A string of length 2. * numberOfDecimals (int): The number of decimals. Defaults to 0. * signed (bol): Whether large positive values should be interpreted as negative values. Returns: The numerical value (int or float) calculated from the ``bytestring``. Raises: TypeError, ValueError Use the parameter ``signed=True`` if converting a bytestring that can hold negative values. Then upper range data will be automatically converted into negative return values (two's complement). Use ``numberOfDecimals=1`` to divide the received data by 10 before returning the value. Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value. The byte order is big-endian, meaning that the most significant byte is sent first. For example: A string ``\\x03\\x02`` (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If ``numberOfDecimals = 1``, then this is converted to 77.0 (float). """ _checkString(bytestring, minlength=2, maxlength=2, description='bytestring') _checkInt(numberOfDecimals, minvalue=0, description='number of decimals') _checkBool(signed, description='signed parameter') formatcode = '>' # Big-endian if signed: formatcode += 'h' # (Signed) short (2 bytes) else: formatcode += 'H' # Unsigned short (2 bytes) fullregister = _unpack(formatcode, bytestring) if numberOfDecimals == 0: return fullregister divisor = 10 ** numberOfDecimals return fullregister / float(divisor)
python
def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False): """Convert a two-byte string to a numerical value, possibly scaling it. Args: * bytestring (str): A string of length 2. * numberOfDecimals (int): The number of decimals. Defaults to 0. * signed (bol): Whether large positive values should be interpreted as negative values. Returns: The numerical value (int or float) calculated from the ``bytestring``. Raises: TypeError, ValueError Use the parameter ``signed=True`` if converting a bytestring that can hold negative values. Then upper range data will be automatically converted into negative return values (two's complement). Use ``numberOfDecimals=1`` to divide the received data by 10 before returning the value. Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value. The byte order is big-endian, meaning that the most significant byte is sent first. For example: A string ``\\x03\\x02`` (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If ``numberOfDecimals = 1``, then this is converted to 77.0 (float). """ _checkString(bytestring, minlength=2, maxlength=2, description='bytestring') _checkInt(numberOfDecimals, minvalue=0, description='number of decimals') _checkBool(signed, description='signed parameter') formatcode = '>' # Big-endian if signed: formatcode += 'h' # (Signed) short (2 bytes) else: formatcode += 'H' # Unsigned short (2 bytes) fullregister = _unpack(formatcode, bytestring) if numberOfDecimals == 0: return fullregister divisor = 10 ** numberOfDecimals return fullregister / float(divisor)
[ "def", "_twoByteStringToNum", "(", "bytestring", ",", "numberOfDecimals", "=", "0", ",", "signed", "=", "False", ")", ":", "_checkString", "(", "bytestring", ",", "minlength", "=", "2", ",", "maxlength", "=", "2", ",", "description", "=", "'bytestring'", ")", "_checkInt", "(", "numberOfDecimals", ",", "minvalue", "=", "0", ",", "description", "=", "'number of decimals'", ")", "_checkBool", "(", "signed", ",", "description", "=", "'signed parameter'", ")", "formatcode", "=", "'>'", "# Big-endian", "if", "signed", ":", "formatcode", "+=", "'h'", "# (Signed) short (2 bytes)", "else", ":", "formatcode", "+=", "'H'", "# Unsigned short (2 bytes)", "fullregister", "=", "_unpack", "(", "formatcode", ",", "bytestring", ")", "if", "numberOfDecimals", "==", "0", ":", "return", "fullregister", "divisor", "=", "10", "**", "numberOfDecimals", "return", "fullregister", "/", "float", "(", "divisor", ")" ]
Convert a two-byte string to a numerical value, possibly scaling it. Args: * bytestring (str): A string of length 2. * numberOfDecimals (int): The number of decimals. Defaults to 0. * signed (bol): Whether large positive values should be interpreted as negative values. Returns: The numerical value (int or float) calculated from the ``bytestring``. Raises: TypeError, ValueError Use the parameter ``signed=True`` if converting a bytestring that can hold negative values. Then upper range data will be automatically converted into negative return values (two's complement). Use ``numberOfDecimals=1`` to divide the received data by 10 before returning the value. Similarly ``numberOfDecimals=2`` will divide the received data by 100 before returning the value. The byte order is big-endian, meaning that the most significant byte is sent first. For example: A string ``\\x03\\x02`` (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If ``numberOfDecimals = 1``, then this is converted to 77.0 (float).
[ "Convert", "a", "two", "-", "byte", "string", "to", "a", "numerical", "value", "possibly", "scaling", "it", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1280-L1323
train
238,794
pyhys/minimalmodbus
minimalmodbus.py
_pack
def _pack(formatstring, value): """Pack a value into a bytestring. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * value (depends on formatstring): The value to be packed Returns: A bytestring (str). Raises: ValueError Note that the :mod:`struct` module produces byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically. """ _checkString(formatstring, description='formatstring', minlength=1) try: result = struct.pack(formatstring, value) except: errortext = 'The value to send is probably out of range, as the num-to-bytestring conversion failed.' errortext += ' Value: {0!r} Struct format code is: {1}' raise ValueError(errortext.format(value, formatstring)) if sys.version_info[0] > 2: return str(result, encoding='latin1') # Convert types to make it Python3 compatible return result
python
def _pack(formatstring, value): """Pack a value into a bytestring. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * value (depends on formatstring): The value to be packed Returns: A bytestring (str). Raises: ValueError Note that the :mod:`struct` module produces byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically. """ _checkString(formatstring, description='formatstring', minlength=1) try: result = struct.pack(formatstring, value) except: errortext = 'The value to send is probably out of range, as the num-to-bytestring conversion failed.' errortext += ' Value: {0!r} Struct format code is: {1}' raise ValueError(errortext.format(value, formatstring)) if sys.version_info[0] > 2: return str(result, encoding='latin1') # Convert types to make it Python3 compatible return result
[ "def", "_pack", "(", "formatstring", ",", "value", ")", ":", "_checkString", "(", "formatstring", ",", "description", "=", "'formatstring'", ",", "minlength", "=", "1", ")", "try", ":", "result", "=", "struct", ".", "pack", "(", "formatstring", ",", "value", ")", "except", ":", "errortext", "=", "'The value to send is probably out of range, as the num-to-bytestring conversion failed.'", "errortext", "+=", "' Value: {0!r} Struct format code is: {1}'", "raise", "ValueError", "(", "errortext", ".", "format", "(", "value", ",", "formatstring", ")", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "return", "str", "(", "result", ",", "encoding", "=", "'latin1'", ")", "# Convert types to make it Python3 compatible", "return", "result" ]
Pack a value into a bytestring. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * value (depends on formatstring): The value to be packed Returns: A bytestring (str). Raises: ValueError Note that the :mod:`struct` module produces byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically.
[ "Pack", "a", "value", "into", "a", "bytestring", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1597-L1627
train
238,795
pyhys/minimalmodbus
minimalmodbus.py
_unpack
def _unpack(formatstring, packed): """Unpack a bytestring into a value. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * packed (str): The bytestring to be unpacked. Returns: A value. The type depends on the formatstring. Raises: ValueError Note that the :mod:`struct` module wants byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically. """ _checkString(formatstring, description='formatstring', minlength=1) _checkString(packed, description='packed string', minlength=1) if sys.version_info[0] > 2: packed = bytes(packed, encoding='latin1') # Convert types to make it Python3 compatible try: value = struct.unpack(formatstring, packed)[0] except: errortext = 'The received bytestring is probably wrong, as the bytestring-to-num conversion failed.' errortext += ' Bytestring: {0!r} Struct format code is: {1}' raise ValueError(errortext.format(packed, formatstring)) return value
python
def _unpack(formatstring, packed): """Unpack a bytestring into a value. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * packed (str): The bytestring to be unpacked. Returns: A value. The type depends on the formatstring. Raises: ValueError Note that the :mod:`struct` module wants byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically. """ _checkString(formatstring, description='formatstring', minlength=1) _checkString(packed, description='packed string', minlength=1) if sys.version_info[0] > 2: packed = bytes(packed, encoding='latin1') # Convert types to make it Python3 compatible try: value = struct.unpack(formatstring, packed)[0] except: errortext = 'The received bytestring is probably wrong, as the bytestring-to-num conversion failed.' errortext += ' Bytestring: {0!r} Struct format code is: {1}' raise ValueError(errortext.format(packed, formatstring)) return value
[ "def", "_unpack", "(", "formatstring", ",", "packed", ")", ":", "_checkString", "(", "formatstring", ",", "description", "=", "'formatstring'", ",", "minlength", "=", "1", ")", "_checkString", "(", "packed", ",", "description", "=", "'packed string'", ",", "minlength", "=", "1", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "packed", "=", "bytes", "(", "packed", ",", "encoding", "=", "'latin1'", ")", "# Convert types to make it Python3 compatible", "try", ":", "value", "=", "struct", ".", "unpack", "(", "formatstring", ",", "packed", ")", "[", "0", "]", "except", ":", "errortext", "=", "'The received bytestring is probably wrong, as the bytestring-to-num conversion failed.'", "errortext", "+=", "' Bytestring: {0!r} Struct format code is: {1}'", "raise", "ValueError", "(", "errortext", ".", "format", "(", "packed", ",", "formatstring", ")", ")", "return", "value" ]
Unpack a bytestring into a value. Uses the built-in :mod:`struct` Python module. Args: * formatstring (str): String for the packing. See the :mod:`struct` module for details. * packed (str): The bytestring to be unpacked. Returns: A value. The type depends on the formatstring. Raises: ValueError Note that the :mod:`struct` module wants byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically.
[ "Unpack", "a", "bytestring", "into", "a", "value", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1630-L1662
train
238,796
pyhys/minimalmodbus
minimalmodbus.py
_hexencode
def _hexencode(bytestring, insert_spaces = False): """Convert a byte string to a hex encoded string. For example 'J' will return '4A', and ``'\\x04'`` will return '04'. Args: bytestring (str): Can be for example ``'A\\x01B\\x45'``. insert_spaces (bool): Insert space characters between pair of characters to increase readability. Returns: A string of twice the length, with characters in the range '0' to '9' and 'A' to 'F'. The string will be longer if spaces are inserted. Raises: TypeError, ValueError """ _checkString(bytestring, description='byte string') separator = '' if not insert_spaces else ' ' # Use plain string formatting instead of binhex.hexlify, # in order to have it Python 2.x and 3.x compatible byte_representions = [] for c in bytestring: byte_representions.append( '{0:02X}'.format(ord(c)) ) return separator.join(byte_representions).strip()
python
def _hexencode(bytestring, insert_spaces = False): """Convert a byte string to a hex encoded string. For example 'J' will return '4A', and ``'\\x04'`` will return '04'. Args: bytestring (str): Can be for example ``'A\\x01B\\x45'``. insert_spaces (bool): Insert space characters between pair of characters to increase readability. Returns: A string of twice the length, with characters in the range '0' to '9' and 'A' to 'F'. The string will be longer if spaces are inserted. Raises: TypeError, ValueError """ _checkString(bytestring, description='byte string') separator = '' if not insert_spaces else ' ' # Use plain string formatting instead of binhex.hexlify, # in order to have it Python 2.x and 3.x compatible byte_representions = [] for c in bytestring: byte_representions.append( '{0:02X}'.format(ord(c)) ) return separator.join(byte_representions).strip()
[ "def", "_hexencode", "(", "bytestring", ",", "insert_spaces", "=", "False", ")", ":", "_checkString", "(", "bytestring", ",", "description", "=", "'byte string'", ")", "separator", "=", "''", "if", "not", "insert_spaces", "else", "' '", "# Use plain string formatting instead of binhex.hexlify,", "# in order to have it Python 2.x and 3.x compatible", "byte_representions", "=", "[", "]", "for", "c", "in", "bytestring", ":", "byte_representions", ".", "append", "(", "'{0:02X}'", ".", "format", "(", "ord", "(", "c", ")", ")", ")", "return", "separator", ".", "join", "(", "byte_representions", ")", ".", "strip", "(", ")" ]
Convert a byte string to a hex encoded string. For example 'J' will return '4A', and ``'\\x04'`` will return '04'. Args: bytestring (str): Can be for example ``'A\\x01B\\x45'``. insert_spaces (bool): Insert space characters between pair of characters to increase readability. Returns: A string of twice the length, with characters in the range '0' to '9' and 'A' to 'F'. The string will be longer if spaces are inserted. Raises: TypeError, ValueError
[ "Convert", "a", "byte", "string", "to", "a", "hex", "encoded", "string", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1665-L1692
train
238,797
pyhys/minimalmodbus
minimalmodbus.py
_hexdecode
def _hexdecode(hexstring): """Convert a hex encoded string to a byte string. For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1). Args: hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length. Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space). Returns: A string of half the length, with characters corresponding to all 0-255 values for each byte. Raises: TypeError, ValueError """ # Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err # but the Python2 interpreter will indicate SyntaxError. # Thus we need to live with this warning in Python3: # 'During handling of the above exception, another exception occurred' _checkString(hexstring, description='hexstring') if len(hexstring) % 2 != 0: raise ValueError('The input hexstring must be of even length. Given: {!r}'.format(hexstring)) if sys.version_info[0] > 2: by = bytes(hexstring, 'latin1') try: return str(binascii.unhexlify(by), encoding='latin1') except binascii.Error as err: new_error_message = 'Hexdecode reported an error: {!s}. Input hexstring: {}'.format(err.args[0], hexstring) raise TypeError(new_error_message) else: try: return hexstring.decode('hex') except TypeError as err: raise TypeError('Hexdecode reported an error: {}. Input hexstring: {}'.format(err.message, hexstring))
python
def _hexdecode(hexstring): """Convert a hex encoded string to a byte string. For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1). Args: hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length. Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space). Returns: A string of half the length, with characters corresponding to all 0-255 values for each byte. Raises: TypeError, ValueError """ # Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err # but the Python2 interpreter will indicate SyntaxError. # Thus we need to live with this warning in Python3: # 'During handling of the above exception, another exception occurred' _checkString(hexstring, description='hexstring') if len(hexstring) % 2 != 0: raise ValueError('The input hexstring must be of even length. Given: {!r}'.format(hexstring)) if sys.version_info[0] > 2: by = bytes(hexstring, 'latin1') try: return str(binascii.unhexlify(by), encoding='latin1') except binascii.Error as err: new_error_message = 'Hexdecode reported an error: {!s}. Input hexstring: {}'.format(err.args[0], hexstring) raise TypeError(new_error_message) else: try: return hexstring.decode('hex') except TypeError as err: raise TypeError('Hexdecode reported an error: {}. Input hexstring: {}'.format(err.message, hexstring))
[ "def", "_hexdecode", "(", "hexstring", ")", ":", "# Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err", "# but the Python2 interpreter will indicate SyntaxError.", "# Thus we need to live with this warning in Python3:", "# 'During handling of the above exception, another exception occurred'", "_checkString", "(", "hexstring", ",", "description", "=", "'hexstring'", ")", "if", "len", "(", "hexstring", ")", "%", "2", "!=", "0", ":", "raise", "ValueError", "(", "'The input hexstring must be of even length. Given: {!r}'", ".", "format", "(", "hexstring", ")", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "by", "=", "bytes", "(", "hexstring", ",", "'latin1'", ")", "try", ":", "return", "str", "(", "binascii", ".", "unhexlify", "(", "by", ")", ",", "encoding", "=", "'latin1'", ")", "except", "binascii", ".", "Error", "as", "err", ":", "new_error_message", "=", "'Hexdecode reported an error: {!s}. Input hexstring: {}'", ".", "format", "(", "err", ".", "args", "[", "0", "]", ",", "hexstring", ")", "raise", "TypeError", "(", "new_error_message", ")", "else", ":", "try", ":", "return", "hexstring", ".", "decode", "(", "'hex'", ")", "except", "TypeError", "as", "err", ":", "raise", "TypeError", "(", "'Hexdecode reported an error: {}. Input hexstring: {}'", ".", "format", "(", "err", ".", "message", ",", "hexstring", ")", ")" ]
Convert a hex encoded string to a byte string. For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1). Args: hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length. Allowed characters are '0' to '9', 'a' to 'f' and 'A' to 'F' (not space). Returns: A string of half the length, with characters corresponding to all 0-255 values for each byte. Raises: TypeError, ValueError
[ "Convert", "a", "hex", "encoded", "string", "to", "a", "byte", "string", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1695-L1733
train
238,798
pyhys/minimalmodbus
minimalmodbus.py
_bitResponseToValue
def _bitResponseToValue(bytestring): """Convert a response string to a numerical value. Args: bytestring (str): A string of length 1. Can be for example ``\\x01``. Returns: The converted value (int). Raises: TypeError, ValueError """ _checkString(bytestring, description='bytestring', minlength=1, maxlength=1) RESPONSE_ON = '\x01' RESPONSE_OFF = '\x00' if bytestring == RESPONSE_ON: return 1 elif bytestring == RESPONSE_OFF: return 0 else: raise ValueError('Could not convert bit response to a value. Input: {0!r}'.format(bytestring))
python
def _bitResponseToValue(bytestring): """Convert a response string to a numerical value. Args: bytestring (str): A string of length 1. Can be for example ``\\x01``. Returns: The converted value (int). Raises: TypeError, ValueError """ _checkString(bytestring, description='bytestring', minlength=1, maxlength=1) RESPONSE_ON = '\x01' RESPONSE_OFF = '\x00' if bytestring == RESPONSE_ON: return 1 elif bytestring == RESPONSE_OFF: return 0 else: raise ValueError('Could not convert bit response to a value. Input: {0!r}'.format(bytestring))
[ "def", "_bitResponseToValue", "(", "bytestring", ")", ":", "_checkString", "(", "bytestring", ",", "description", "=", "'bytestring'", ",", "minlength", "=", "1", ",", "maxlength", "=", "1", ")", "RESPONSE_ON", "=", "'\\x01'", "RESPONSE_OFF", "=", "'\\x00'", "if", "bytestring", "==", "RESPONSE_ON", ":", "return", "1", "elif", "bytestring", "==", "RESPONSE_OFF", ":", "return", "0", "else", ":", "raise", "ValueError", "(", "'Could not convert bit response to a value. Input: {0!r}'", ".", "format", "(", "bytestring", ")", ")" ]
Convert a response string to a numerical value. Args: bytestring (str): A string of length 1. Can be for example ``\\x01``. Returns: The converted value (int). Raises: TypeError, ValueError
[ "Convert", "a", "response", "string", "to", "a", "numerical", "value", "." ]
e99f4d74c83258c6039073082955ac9bed3f2155
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L1747-L1770
train
238,799