partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
Roster.get_items_by_group
Return a list of items within a given group. :Parameters: - `name`: name to look-up - `case_sensitive`: if `False` the matching will be case insensitive. :Types: - `name`: `unicode` - `case_sensitive`: `bool` :Returntype: `list` of `RosterItem`
pyxmpp2/roster.py
def get_items_by_group(self, group, case_sensitive = True): """ Return a list of items within a given group. :Parameters: - `name`: name to look-up - `case_sensitive`: if `False` the matching will be case insensitive. :Types: - `name`: `unicode` - `case_sensitive`: `bool` :Returntype: `list` of `RosterItem` """ result = [] if not group: for item in self._items: if not item.groups: result.append(item) return result if not case_sensitive: group = group.lower() for item in self._items: if group in item.groups: result.append(item) elif not case_sensitive and group in [g.lower() for g in item.groups]: result.append(item) return result
def get_items_by_group(self, group, case_sensitive = True): """ Return a list of items within a given group. :Parameters: - `name`: name to look-up - `case_sensitive`: if `False` the matching will be case insensitive. :Types: - `name`: `unicode` - `case_sensitive`: `bool` :Returntype: `list` of `RosterItem` """ result = [] if not group: for item in self._items: if not item.groups: result.append(item) return result if not case_sensitive: group = group.lower() for item in self._items: if group in item.groups: result.append(item) elif not case_sensitive and group in [g.lower() for g in item.groups]: result.append(item) return result
[ "Return", "a", "list", "of", "items", "within", "a", "given", "group", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L576-L604
[ "def", "get_items_by_group", "(", "self", ",", "group", ",", "case_sensitive", "=", "True", ")", ":", "result", "=", "[", "]", "if", "not", "group", ":", "for", "item", "in", "self", ".", "_items", ":", "if", "not", "item", ".", "groups", ":", "result", ".", "append", "(", "item", ")", "return", "result", "if", "not", "case_sensitive", ":", "group", "=", "group", ".", "lower", "(", ")", "for", "item", "in", "self", ".", "_items", ":", "if", "group", "in", "item", ".", "groups", ":", "result", ".", "append", "(", "item", ")", "elif", "not", "case_sensitive", "and", "group", "in", "[", "g", ".", "lower", "(", ")", "for", "g", "in", "item", ".", "groups", "]", ":", "result", ".", "append", "(", "item", ")", "return", "result" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Roster.add_item
Add an item to the roster. This will not automatically update the roster on the server. :Parameters: - `item`: the item to add - `replace`: if `True` then existing item will be replaced, otherwise a `ValueError` will be raised on conflict :Types: - `item`: `RosterItem` - `replace`: `bool`
pyxmpp2/roster.py
def add_item(self, item, replace = False): """ Add an item to the roster. This will not automatically update the roster on the server. :Parameters: - `item`: the item to add - `replace`: if `True` then existing item will be replaced, otherwise a `ValueError` will be raised on conflict :Types: - `item`: `RosterItem` - `replace`: `bool` """ if item.jid in self._jids: if replace: self.remove_item(item.jid) else: raise ValueError("JID already in the roster") index = len(self._items) self._items.append(item) self._jids[item.jid] = index
def add_item(self, item, replace = False): """ Add an item to the roster. This will not automatically update the roster on the server. :Parameters: - `item`: the item to add - `replace`: if `True` then existing item will be replaced, otherwise a `ValueError` will be raised on conflict :Types: - `item`: `RosterItem` - `replace`: `bool` """ if item.jid in self._jids: if replace: self.remove_item(item.jid) else: raise ValueError("JID already in the roster") index = len(self._items) self._items.append(item) self._jids[item.jid] = index
[ "Add", "an", "item", "to", "the", "roster", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L606-L627
[ "def", "add_item", "(", "self", ",", "item", ",", "replace", "=", "False", ")", ":", "if", "item", ".", "jid", "in", "self", ".", "_jids", ":", "if", "replace", ":", "self", ".", "remove_item", "(", "item", ".", "jid", ")", "else", ":", "raise", "ValueError", "(", "\"JID already in the roster\"", ")", "index", "=", "len", "(", "self", ".", "_items", ")", "self", ".", "_items", ".", "append", "(", "item", ")", "self", ".", "_jids", "[", "item", ".", "jid", "]", "=", "index" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Roster.remove_item
Remove item from the roster. :Parameters: - `jid`: JID of the item to remove :Types: - `jid`: `JID`
pyxmpp2/roster.py
def remove_item(self, jid): """Remove item from the roster. :Parameters: - `jid`: JID of the item to remove :Types: - `jid`: `JID` """ if jid not in self._jids: raise KeyError(jid) index = self._jids[jid] for i in range(index, len(self._jids)): self._jids[self._items[i].jid] -= 1 del self._jids[jid] del self._items[index]
def remove_item(self, jid): """Remove item from the roster. :Parameters: - `jid`: JID of the item to remove :Types: - `jid`: `JID` """ if jid not in self._jids: raise KeyError(jid) index = self._jids[jid] for i in range(index, len(self._jids)): self._jids[self._items[i].jid] -= 1 del self._jids[jid] del self._items[index]
[ "Remove", "item", "from", "the", "roster", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L629-L643
[ "def", "remove_item", "(", "self", ",", "jid", ")", ":", "if", "jid", "not", "in", "self", ".", "_jids", ":", "raise", "KeyError", "(", "jid", ")", "index", "=", "self", ".", "_jids", "[", "jid", "]", "for", "i", "in", "range", "(", "index", ",", "len", "(", "self", ".", "_jids", ")", ")", ":", "self", ".", "_jids", "[", "self", ".", "_items", "[", "i", "]", ".", "jid", "]", "-=", "1", "del", "self", ".", "_jids", "[", "jid", "]", "del", "self", ".", "_items", "[", "index", "]" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.load_roster
Load roster from an XML file. Can be used before the connection is started to load saved roster copy, for efficient retrieval of versioned roster. :Parameters: - `source`: file name or a file object :Types: - `source`: `str` or file-like object
pyxmpp2/roster.py
def load_roster(self, source): """Load roster from an XML file. Can be used before the connection is started to load saved roster copy, for efficient retrieval of versioned roster. :Parameters: - `source`: file name or a file object :Types: - `source`: `str` or file-like object """ try: tree = ElementTree.parse(source) except ElementTree.ParseError, err: raise ValueError("Invalid roster format: {0}".format(err)) roster = Roster.from_xml(tree.getroot()) for item in roster: item.verify_roster_result(True) self.roster = roster
def load_roster(self, source): """Load roster from an XML file. Can be used before the connection is started to load saved roster copy, for efficient retrieval of versioned roster. :Parameters: - `source`: file name or a file object :Types: - `source`: `str` or file-like object """ try: tree = ElementTree.parse(source) except ElementTree.ParseError, err: raise ValueError("Invalid roster format: {0}".format(err)) roster = Roster.from_xml(tree.getroot()) for item in roster: item.verify_roster_result(True) self.roster = roster
[ "Load", "roster", "from", "an", "XML", "file", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L670-L688
[ "def", "load_roster", "(", "self", ",", "source", ")", ":", "try", ":", "tree", "=", "ElementTree", ".", "parse", "(", "source", ")", "except", "ElementTree", ".", "ParseError", ",", "err", ":", "raise", "ValueError", "(", "\"Invalid roster format: {0}\"", ".", "format", "(", "err", ")", ")", "roster", "=", "Roster", ".", "from_xml", "(", "tree", ".", "getroot", "(", ")", ")", "for", "item", "in", "roster", ":", "item", ".", "verify_roster_result", "(", "True", ")", "self", ".", "roster", "=", "roster" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.save_roster
Save the roster to an XML file. Can be used to save the last know roster copy for faster loading of a verisoned roster (if server supports that). :Parameters: - `dest`: file name or a file object - `pretty`: pretty-format the roster XML :Types: - `dest`: `str` or file-like object - `pretty`: `bool`
pyxmpp2/roster.py
def save_roster(self, dest, pretty = True): """Save the roster to an XML file. Can be used to save the last know roster copy for faster loading of a verisoned roster (if server supports that). :Parameters: - `dest`: file name or a file object - `pretty`: pretty-format the roster XML :Types: - `dest`: `str` or file-like object - `pretty`: `bool` """ if self.roster is None: raise ValueError("No roster") element = self.roster.as_xml() if pretty: if len(element): element.text = u'\n ' p_child = None for child in element: if p_child is not None: p_child.tail = u'\n ' if len(child): child.text = u'\n ' p_grand = None for grand in child: if p_grand is not None: p_grand.tail = u'\n ' p_grand = grand if p_grand is not None: p_grand.tail = u'\n ' p_child = child if p_child is not None: p_child.tail = u"\n" tree = ElementTree.ElementTree(element) tree.write(dest, "utf-8")
def save_roster(self, dest, pretty = True): """Save the roster to an XML file. Can be used to save the last know roster copy for faster loading of a verisoned roster (if server supports that). :Parameters: - `dest`: file name or a file object - `pretty`: pretty-format the roster XML :Types: - `dest`: `str` or file-like object - `pretty`: `bool` """ if self.roster is None: raise ValueError("No roster") element = self.roster.as_xml() if pretty: if len(element): element.text = u'\n ' p_child = None for child in element: if p_child is not None: p_child.tail = u'\n ' if len(child): child.text = u'\n ' p_grand = None for grand in child: if p_grand is not None: p_grand.tail = u'\n ' p_grand = grand if p_grand is not None: p_grand.tail = u'\n ' p_child = child if p_child is not None: p_child.tail = u"\n" tree = ElementTree.ElementTree(element) tree.write(dest, "utf-8")
[ "Save", "the", "roster", "to", "an", "XML", "file", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L690-L726
[ "def", "save_roster", "(", "self", ",", "dest", ",", "pretty", "=", "True", ")", ":", "if", "self", ".", "roster", "is", "None", ":", "raise", "ValueError", "(", "\"No roster\"", ")", "element", "=", "self", ".", "roster", ".", "as_xml", "(", ")", "if", "pretty", ":", "if", "len", "(", "element", ")", ":", "element", ".", "text", "=", "u'\\n '", "p_child", "=", "None", "for", "child", "in", "element", ":", "if", "p_child", "is", "not", "None", ":", "p_child", ".", "tail", "=", "u'\\n '", "if", "len", "(", "child", ")", ":", "child", ".", "text", "=", "u'\\n '", "p_grand", "=", "None", "for", "grand", "in", "child", ":", "if", "p_grand", "is", "not", "None", ":", "p_grand", ".", "tail", "=", "u'\\n '", "p_grand", "=", "grand", "if", "p_grand", "is", "not", "None", ":", "p_grand", ".", "tail", "=", "u'\\n '", "p_child", "=", "child", "if", "p_child", "is", "not", "None", ":", "p_child", ".", "tail", "=", "u\"\\n\"", "tree", "=", "ElementTree", ".", "ElementTree", "(", "element", ")", "tree", ".", "write", "(", "dest", ",", "\"utf-8\"", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.handle_got_features_event
Check for roster related features in the stream features received and set `server_features` accordingly.
pyxmpp2/roster.py
def handle_got_features_event(self, event): """Check for roster related features in the stream features received and set `server_features` accordingly. """ server_features = set() logger.debug("Checking roster-related features") if event.features.find(FEATURE_ROSTERVER) is not None: logger.debug(" Roster versioning available") server_features.add("versioning") if event.features.find(FEATURE_APPROVALS) is not None: logger.debug(" Subscription pre-approvals available") server_features.add("pre-approvals") self.server_features = server_features
def handle_got_features_event(self, event): """Check for roster related features in the stream features received and set `server_features` accordingly. """ server_features = set() logger.debug("Checking roster-related features") if event.features.find(FEATURE_ROSTERVER) is not None: logger.debug(" Roster versioning available") server_features.add("versioning") if event.features.find(FEATURE_APPROVALS) is not None: logger.debug(" Subscription pre-approvals available") server_features.add("pre-approvals") self.server_features = server_features
[ "Check", "for", "roster", "related", "features", "in", "the", "stream", "features", "received", "and", "set", "server_features", "accordingly", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L729-L741
[ "def", "handle_got_features_event", "(", "self", ",", "event", ")", ":", "server_features", "=", "set", "(", ")", "logger", ".", "debug", "(", "\"Checking roster-related features\"", ")", "if", "event", ".", "features", ".", "find", "(", "FEATURE_ROSTERVER", ")", "is", "not", "None", ":", "logger", ".", "debug", "(", "\" Roster versioning available\"", ")", "server_features", ".", "add", "(", "\"versioning\"", ")", "if", "event", ".", "features", ".", "find", "(", "FEATURE_APPROVALS", ")", "is", "not", "None", ":", "logger", ".", "debug", "(", "\" Subscription pre-approvals available\"", ")", "server_features", ".", "add", "(", "\"pre-approvals\"", ")", "self", ".", "server_features", "=", "server_features" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.handle_authorized_event
Request roster upon login.
pyxmpp2/roster.py
def handle_authorized_event(self, event): """Request roster upon login.""" self.server = event.authorized_jid.bare() if "versioning" in self.server_features: if self.roster is not None and self.roster.version is not None: version = self.roster.version else: version = u"" else: version = None self.request_roster(version)
def handle_authorized_event(self, event): """Request roster upon login.""" self.server = event.authorized_jid.bare() if "versioning" in self.server_features: if self.roster is not None and self.roster.version is not None: version = self.roster.version else: version = u"" else: version = None self.request_roster(version)
[ "Request", "roster", "upon", "login", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L744-L754
[ "def", "handle_authorized_event", "(", "self", ",", "event", ")", ":", "self", ".", "server", "=", "event", ".", "authorized_jid", ".", "bare", "(", ")", "if", "\"versioning\"", "in", "self", ".", "server_features", ":", "if", "self", ".", "roster", "is", "not", "None", "and", "self", ".", "roster", ".", "version", "is", "not", "None", ":", "version", "=", "self", ".", "roster", ".", "version", "else", ":", "version", "=", "u\"\"", "else", ":", "version", "=", "None", "self", ".", "request_roster", "(", "version", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.request_roster
Request roster from server. :Parameters: - `version`: if not `None` versioned roster will be requested for given local version. Use "" to request full roster. :Types: - `version`: `unicode`
pyxmpp2/roster.py
def request_roster(self, version = None): """Request roster from server. :Parameters: - `version`: if not `None` versioned roster will be requested for given local version. Use "" to request full roster. :Types: - `version`: `unicode` """ processor = self.stanza_processor request = Iq(stanza_type = "get") request.set_payload(RosterPayload(version = version)) processor.set_response_handlers(request, self._get_success, self._get_error) processor.send(request)
def request_roster(self, version = None): """Request roster from server. :Parameters: - `version`: if not `None` versioned roster will be requested for given local version. Use "" to request full roster. :Types: - `version`: `unicode` """ processor = self.stanza_processor request = Iq(stanza_type = "get") request.set_payload(RosterPayload(version = version)) processor.set_response_handlers(request, self._get_success, self._get_error) processor.send(request)
[ "Request", "roster", "from", "server", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L756-L770
[ "def", "request_roster", "(", "self", ",", "version", "=", "None", ")", ":", "processor", "=", "self", ".", "stanza_processor", "request", "=", "Iq", "(", "stanza_type", "=", "\"get\"", ")", "request", ".", "set_payload", "(", "RosterPayload", "(", "version", "=", "version", ")", ")", "processor", ".", "set_response_handlers", "(", "request", ",", "self", ".", "_get_success", ",", "self", ".", "_get_error", ")", "processor", ".", "send", "(", "request", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient._get_success
Handle successful response to the roster request.
pyxmpp2/roster.py
def _get_success(self, stanza): """Handle successful response to the roster request. """ payload = stanza.get_payload(RosterPayload) if payload is None: if "versioning" in self.server_features and self.roster: logger.debug("Server will send roster delta in pushes") else: logger.warning("Bad roster response (no payload)") self._event_queue.put(RosterNotReceivedEvent(self, stanza)) return else: items = list(payload) for item in items: item.verify_roster_result(True) self.roster = Roster(items, payload.version) self._event_queue.put(RosterReceivedEvent(self, self.roster))
def _get_success(self, stanza): """Handle successful response to the roster request. """ payload = stanza.get_payload(RosterPayload) if payload is None: if "versioning" in self.server_features and self.roster: logger.debug("Server will send roster delta in pushes") else: logger.warning("Bad roster response (no payload)") self._event_queue.put(RosterNotReceivedEvent(self, stanza)) return else: items = list(payload) for item in items: item.verify_roster_result(True) self.roster = Roster(items, payload.version) self._event_queue.put(RosterReceivedEvent(self, self.roster))
[ "Handle", "successful", "response", "to", "the", "roster", "request", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L772-L788
[ "def", "_get_success", "(", "self", ",", "stanza", ")", ":", "payload", "=", "stanza", ".", "get_payload", "(", "RosterPayload", ")", "if", "payload", "is", "None", ":", "if", "\"versioning\"", "in", "self", ".", "server_features", "and", "self", ".", "roster", ":", "logger", ".", "debug", "(", "\"Server will send roster delta in pushes\"", ")", "else", ":", "logger", ".", "warning", "(", "\"Bad roster response (no payload)\"", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterNotReceivedEvent", "(", "self", ",", "stanza", ")", ")", "return", "else", ":", "items", "=", "list", "(", "payload", ")", "for", "item", "in", "items", ":", "item", ".", "verify_roster_result", "(", "True", ")", "self", ".", "roster", "=", "Roster", "(", "items", ",", "payload", ".", "version", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterReceivedEvent", "(", "self", ",", "self", ".", "roster", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient._get_error
Handle failure of the roster request.
pyxmpp2/roster.py
def _get_error(self, stanza): """Handle failure of the roster request. """ if stanza: logger.debug(u"Roster request failed: {0}".format( stanza.error.condition_name)) else: logger.debug(u"Roster request failed: timeout") self._event_queue.put(RosterNotReceivedEvent(self, stanza))
def _get_error(self, stanza): """Handle failure of the roster request. """ if stanza: logger.debug(u"Roster request failed: {0}".format( stanza.error.condition_name)) else: logger.debug(u"Roster request failed: timeout") self._event_queue.put(RosterNotReceivedEvent(self, stanza))
[ "Handle", "failure", "of", "the", "roster", "request", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L790-L798
[ "def", "_get_error", "(", "self", ",", "stanza", ")", ":", "if", "stanza", ":", "logger", ".", "debug", "(", "u\"Roster request failed: {0}\"", ".", "format", "(", "stanza", ".", "error", ".", "condition_name", ")", ")", "else", ":", "logger", ".", "debug", "(", "u\"Roster request failed: timeout\"", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterNotReceivedEvent", "(", "self", ",", "stanza", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.handle_roster_push
Handle a roster push received from server.
pyxmpp2/roster.py
def handle_roster_push(self, stanza): """Handle a roster push received from server. """ if self.server is None and stanza.from_jid: logger.debug(u"Server address not known, cannot verify roster push" " from {0}".format(stanza.from_jid)) return stanza.make_error_response(u"service-unavailable") if self.server and stanza.from_jid and stanza.from_jid != self.server: logger.debug(u"Roster push from invalid source: {0}".format( stanza.from_jid)) return stanza.make_error_response(u"service-unavailable") payload = stanza.get_payload(RosterPayload) if len(payload) != 1: logger.warning("Bad roster push received ({0} items)" .format(len(payload))) return stanza.make_error_response(u"bad-request") if self.roster is None: logger.debug("Dropping roster push - no roster here") return True item = payload[0] item.verify_roster_push(True) old_item = self.roster.get(item.jid) if item.subscription == "remove": if old_item: self.roster.remove_item(item.jid) else: self.roster.add_item(item, replace = True) self._event_queue.put(RosterUpdatedEvent(self, old_item, item)) return stanza.make_result_response()
def handle_roster_push(self, stanza): """Handle a roster push received from server. """ if self.server is None and stanza.from_jid: logger.debug(u"Server address not known, cannot verify roster push" " from {0}".format(stanza.from_jid)) return stanza.make_error_response(u"service-unavailable") if self.server and stanza.from_jid and stanza.from_jid != self.server: logger.debug(u"Roster push from invalid source: {0}".format( stanza.from_jid)) return stanza.make_error_response(u"service-unavailable") payload = stanza.get_payload(RosterPayload) if len(payload) != 1: logger.warning("Bad roster push received ({0} items)" .format(len(payload))) return stanza.make_error_response(u"bad-request") if self.roster is None: logger.debug("Dropping roster push - no roster here") return True item = payload[0] item.verify_roster_push(True) old_item = self.roster.get(item.jid) if item.subscription == "remove": if old_item: self.roster.remove_item(item.jid) else: self.roster.add_item(item, replace = True) self._event_queue.put(RosterUpdatedEvent(self, old_item, item)) return stanza.make_result_response()
[ "Handle", "a", "roster", "push", "received", "from", "server", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L801-L829
[ "def", "handle_roster_push", "(", "self", ",", "stanza", ")", ":", "if", "self", ".", "server", "is", "None", "and", "stanza", ".", "from_jid", ":", "logger", ".", "debug", "(", "u\"Server address not known, cannot verify roster push\"", "\" from {0}\"", ".", "format", "(", "stanza", ".", "from_jid", ")", ")", "return", "stanza", ".", "make_error_response", "(", "u\"service-unavailable\"", ")", "if", "self", ".", "server", "and", "stanza", ".", "from_jid", "and", "stanza", ".", "from_jid", "!=", "self", ".", "server", ":", "logger", ".", "debug", "(", "u\"Roster push from invalid source: {0}\"", ".", "format", "(", "stanza", ".", "from_jid", ")", ")", "return", "stanza", ".", "make_error_response", "(", "u\"service-unavailable\"", ")", "payload", "=", "stanza", ".", "get_payload", "(", "RosterPayload", ")", "if", "len", "(", "payload", ")", "!=", "1", ":", "logger", ".", "warning", "(", "\"Bad roster push received ({0} items)\"", ".", "format", "(", "len", "(", "payload", ")", ")", ")", "return", "stanza", ".", "make_error_response", "(", "u\"bad-request\"", ")", "if", "self", ".", "roster", "is", "None", ":", "logger", ".", "debug", "(", "\"Dropping roster push - no roster here\"", ")", "return", "True", "item", "=", "payload", "[", "0", "]", "item", ".", "verify_roster_push", "(", "True", ")", "old_item", "=", "self", ".", "roster", ".", "get", "(", "item", ".", "jid", ")", "if", "item", ".", "subscription", "==", "\"remove\"", ":", "if", "old_item", ":", "self", ".", "roster", ".", "remove_item", "(", "item", ".", "jid", ")", "else", ":", "self", ".", "roster", ".", "add_item", "(", "item", ",", "replace", "=", "True", ")", "self", ".", "_event_queue", ".", "put", "(", "RosterUpdatedEvent", "(", "self", ",", "old_item", ",", "item", ")", ")", "return", "stanza", ".", "make_result_response", "(", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.add_item
Add a contact to the roster. :Parameters: - `jid`: contact's jid - `name`: name for the contact - `groups`: sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` - `name`: `unicode` - `groups`: sequence of `unicode`
pyxmpp2/roster.py
def add_item(self, jid, name = None, groups = None, callback = None, error_callback = None): """Add a contact to the roster. :Parameters: - `jid`: contact's jid - `name`: name for the contact - `groups`: sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` - `name`: `unicode` - `groups`: sequence of `unicode` """ # pylint: disable=R0913 if jid in self.roster: raise ValueError("{0!r} already in the roster".format(jid)) item = RosterItem(jid, name, groups) self._roster_set(item, callback, error_callback)
def add_item(self, jid, name = None, groups = None, callback = None, error_callback = None): """Add a contact to the roster. :Parameters: - `jid`: contact's jid - `name`: name for the contact - `groups`: sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` - `name`: `unicode` - `groups`: sequence of `unicode` """ # pylint: disable=R0913 if jid in self.roster: raise ValueError("{0!r} already in the roster".format(jid)) item = RosterItem(jid, name, groups) self._roster_set(item, callback, error_callback)
[ "Add", "a", "contact", "to", "the", "roster", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L831-L854
[ "def", "add_item", "(", "self", ",", "jid", ",", "name", "=", "None", ",", "groups", "=", "None", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "# pylint: disable=R0913", "if", "jid", "in", "self", ".", "roster", ":", "raise", "ValueError", "(", "\"{0!r} already in the roster\"", ".", "format", "(", "jid", ")", ")", "item", "=", "RosterItem", "(", "jid", ",", "name", ",", "groups", ")", "self", ".", "_roster_set", "(", "item", ",", "callback", ",", "error_callback", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.update_item
Modify a contact in the roster. :Parameters: - `jid`: contact's jid - `name`: a new name for the contact - `groups`: a sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` - `name`: `unicode` - `groups`: sequence of `unicode`
pyxmpp2/roster.py
def update_item(self, jid, name = NO_CHANGE, groups = NO_CHANGE, callback = None, error_callback = None): """Modify a contact in the roster. :Parameters: - `jid`: contact's jid - `name`: a new name for the contact - `groups`: a sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` - `name`: `unicode` - `groups`: sequence of `unicode` """ # pylint: disable=R0913 item = self.roster[jid] if name is NO_CHANGE and groups is NO_CHANGE: return if name is NO_CHANGE: name = item.name if groups is NO_CHANGE: groups = item.groups item = RosterItem(jid, name, groups) self._roster_set(item, callback, error_callback)
def update_item(self, jid, name = NO_CHANGE, groups = NO_CHANGE, callback = None, error_callback = None): """Modify a contact in the roster. :Parameters: - `jid`: contact's jid - `name`: a new name for the contact - `groups`: a sequence of group names the contact should belong to - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` - `name`: `unicode` - `groups`: sequence of `unicode` """ # pylint: disable=R0913 item = self.roster[jid] if name is NO_CHANGE and groups is NO_CHANGE: return if name is NO_CHANGE: name = item.name if groups is NO_CHANGE: groups = item.groups item = RosterItem(jid, name, groups) self._roster_set(item, callback, error_callback)
[ "Modify", "a", "contact", "in", "the", "roster", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L856-L884
[ "def", "update_item", "(", "self", ",", "jid", ",", "name", "=", "NO_CHANGE", ",", "groups", "=", "NO_CHANGE", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "# pylint: disable=R0913", "item", "=", "self", ".", "roster", "[", "jid", "]", "if", "name", "is", "NO_CHANGE", "and", "groups", "is", "NO_CHANGE", ":", "return", "if", "name", "is", "NO_CHANGE", ":", "name", "=", "item", ".", "name", "if", "groups", "is", "NO_CHANGE", ":", "groups", "=", "item", ".", "groups", "item", "=", "RosterItem", "(", "jid", ",", "name", ",", "groups", ")", "self", ".", "_roster_set", "(", "item", ",", "callback", ",", "error_callback", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient.remove_item
Remove a contact from the roster. :Parameters: - `jid`: contact's jid - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID`
pyxmpp2/roster.py
def remove_item(self, jid, callback = None, error_callback = None): """Remove a contact from the roster. :Parameters: - `jid`: contact's jid - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` """ item = self.roster[jid] if jid not in self.roster: raise KeyError(jid) item = RosterItem(jid, subscription = "remove") self._roster_set(item, callback, error_callback)
def remove_item(self, jid, callback = None, error_callback = None): """Remove a contact from the roster. :Parameters: - `jid`: contact's jid - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to call when the request fails. It should accept a single argument - an error stanza received (`None` in case of timeout) :Types: - `jid`: `JID` """ item = self.roster[jid] if jid not in self.roster: raise KeyError(jid) item = RosterItem(jid, subscription = "remove") self._roster_set(item, callback, error_callback)
[ "Remove", "a", "contact", "from", "the", "roster", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L886-L904
[ "def", "remove_item", "(", "self", ",", "jid", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "item", "=", "self", ".", "roster", "[", "jid", "]", "if", "jid", "not", "in", "self", ".", "roster", ":", "raise", "KeyError", "(", "jid", ")", "item", "=", "RosterItem", "(", "jid", ",", "subscription", "=", "\"remove\"", ")", "self", ".", "_roster_set", "(", "item", ",", "callback", ",", "error_callback", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
RosterClient._roster_set
Send a 'roster set' to the server. :Parameters: - `item`: the requested change :Types: - `item`: `RosterItem`
pyxmpp2/roster.py
def _roster_set(self, item, callback, error_callback): """Send a 'roster set' to the server. :Parameters: - `item`: the requested change :Types: - `item`: `RosterItem` """ stanza = Iq(to_jid = self.server, stanza_type = "set") payload = RosterPayload([item]) stanza.set_payload(payload) def success_cb(result_stanza): """Success callback for roster set.""" if callback: callback(item) def error_cb(error_stanza): """Error callback for roster set.""" if error_callback: error_callback(error_stanza) else: logger.error("Roster change of '{0}' failed".format(item.jid)) processor = self.stanza_processor processor.set_response_handlers(stanza, success_cb, error_cb) processor.send(stanza)
def _roster_set(self, item, callback, error_callback): """Send a 'roster set' to the server. :Parameters: - `item`: the requested change :Types: - `item`: `RosterItem` """ stanza = Iq(to_jid = self.server, stanza_type = "set") payload = RosterPayload([item]) stanza.set_payload(payload) def success_cb(result_stanza): """Success callback for roster set.""" if callback: callback(item) def error_cb(error_stanza): """Error callback for roster set.""" if error_callback: error_callback(error_stanza) else: logger.error("Roster change of '{0}' failed".format(item.jid)) processor = self.stanza_processor processor.set_response_handlers(stanza, success_cb, error_cb) processor.send(stanza)
[ "Send", "a", "roster", "set", "to", "the", "server", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L906-L930
[ "def", "_roster_set", "(", "self", ",", "item", ",", "callback", ",", "error_callback", ")", ":", "stanza", "=", "Iq", "(", "to_jid", "=", "self", ".", "server", ",", "stanza_type", "=", "\"set\"", ")", "payload", "=", "RosterPayload", "(", "[", "item", "]", ")", "stanza", ".", "set_payload", "(", "payload", ")", "def", "success_cb", "(", "result_stanza", ")", ":", "\"\"\"Success callback for roster set.\"\"\"", "if", "callback", ":", "callback", "(", "item", ")", "def", "error_cb", "(", "error_stanza", ")", ":", "\"\"\"Error callback for roster set.\"\"\"", "if", "error_callback", ":", "error_callback", "(", "error_stanza", ")", "else", ":", "logger", ".", "error", "(", "\"Roster change of '{0}' failed\"", ".", "format", "(", "item", ".", "jid", ")", ")", "processor", "=", "self", ".", "stanza_processor", "processor", ".", "set_response_handlers", "(", "stanza", ",", "success_cb", ",", "error_cb", ")", "processor", ".", "send", "(", "stanza", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucXBase.free
Unlink and free the XML node owned by `self`.
pyxmpp2/ext/muc/muccore.py
def free(self): """ Unlink and free the XML node owned by `self`. """ if not self.borrowed: self.xmlnode.unlinkNode() self.xmlnode.freeNode() self.xmlnode=None
def free(self): """ Unlink and free the XML node owned by `self`. """ if not self.borrowed: self.xmlnode.unlinkNode() self.xmlnode.freeNode() self.xmlnode=None
[ "Unlink", "and", "free", "the", "XML", "node", "owned", "by", "self", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L105-L112
[ "def", "free", "(", "self", ")", ":", "if", "not", "self", ".", "borrowed", ":", "self", ".", "xmlnode", ".", "unlinkNode", "(", ")", "self", ".", "xmlnode", ".", "freeNode", "(", ")", "self", ".", "xmlnode", "=", "None" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucXBase.xpath_eval
Evaluate XPath expression in context of `self.xmlnode`. :Parameters: - `expr`: the XPath expression :Types: - `expr`: `unicode` :return: the result of the expression evaluation. :returntype: list of `libxml2.xmlNode`
pyxmpp2/ext/muc/muccore.py
def xpath_eval(self,expr): """ Evaluate XPath expression in context of `self.xmlnode`. :Parameters: - `expr`: the XPath expression :Types: - `expr`: `unicode` :return: the result of the expression evaluation. :returntype: list of `libxml2.xmlNode` """ ctxt = common_doc.xpathNewContext() ctxt.setContextNode(self.xmlnode) ctxt.xpathRegisterNs("muc",self.ns.getContent()) ret=ctxt.xpathEval(to_utf8(expr)) ctxt.xpathFreeContext() return ret
def xpath_eval(self,expr): """ Evaluate XPath expression in context of `self.xmlnode`. :Parameters: - `expr`: the XPath expression :Types: - `expr`: `unicode` :return: the result of the expression evaluation. :returntype: list of `libxml2.xmlNode` """ ctxt = common_doc.xpathNewContext() ctxt.setContextNode(self.xmlnode) ctxt.xpathRegisterNs("muc",self.ns.getContent()) ret=ctxt.xpathEval(to_utf8(expr)) ctxt.xpathFreeContext() return ret
[ "Evaluate", "XPath", "expression", "in", "context", "of", "self", ".", "xmlnode", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L120-L137
[ "def", "xpath_eval", "(", "self", ",", "expr", ")", ":", "ctxt", "=", "common_doc", ".", "xpathNewContext", "(", ")", "ctxt", ".", "setContextNode", "(", "self", ".", "xmlnode", ")", "ctxt", ".", "xpathRegisterNs", "(", "\"muc\"", ",", "self", ".", "ns", ".", "getContent", "(", ")", ")", "ret", "=", "ctxt", ".", "xpathEval", "(", "to_utf8", "(", "expr", ")", ")", "ctxt", ".", "xpathFreeContext", "(", ")", "return", "ret" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucX.set_history
Set history parameters. Types: - `parameters`: `HistoryParameters`
pyxmpp2/ext/muc/muccore.py
def set_history(self, parameters): """ Set history parameters. Types: - `parameters`: `HistoryParameters` """ for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": child.unlinkNode() child.freeNode() break if parameters.maxchars and parameters.maxchars < 0: raise ValueError("History parameter maxchars must be positive") if parameters.maxstanzas and parameters.maxstanzas < 0: raise ValueError("History parameter maxstanzas must be positive") if parameters.maxseconds and parameters.maxseconds < 0: raise ValueError("History parameter maxseconds must be positive") hnode=self.xmlnode.newChild(self.xmlnode.ns(), "history", None) if parameters.maxchars is not None: hnode.setProp("maxchars", str(parameters.maxchars)) if parameters.maxstanzas is not None: hnode.setProp("maxstanzas", str(parameters.maxstanzas)) if parameters.maxseconds is not None: hnode.setProp("maxseconds", str(parameters.maxseconds)) if parameters.since is not None: hnode.setProp("since", parameters.since.strftime("%Y-%m-%dT%H:%M:%SZ"))
def set_history(self, parameters): """ Set history parameters. Types: - `parameters`: `HistoryParameters` """ for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": child.unlinkNode() child.freeNode() break if parameters.maxchars and parameters.maxchars < 0: raise ValueError("History parameter maxchars must be positive") if parameters.maxstanzas and parameters.maxstanzas < 0: raise ValueError("History parameter maxstanzas must be positive") if parameters.maxseconds and parameters.maxseconds < 0: raise ValueError("History parameter maxseconds must be positive") hnode=self.xmlnode.newChild(self.xmlnode.ns(), "history", None) if parameters.maxchars is not None: hnode.setProp("maxchars", str(parameters.maxchars)) if parameters.maxstanzas is not None: hnode.setProp("maxstanzas", str(parameters.maxstanzas)) if parameters.maxseconds is not None: hnode.setProp("maxseconds", str(parameters.maxseconds)) if parameters.since is not None: hnode.setProp("since", parameters.since.strftime("%Y-%m-%dT%H:%M:%SZ"))
[ "Set", "history", "parameters", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L157-L186
[ "def", "set_history", "(", "self", ",", "parameters", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"history\"", ":", "child", ".", "unlinkNode", "(", ")", "child", ".", "freeNode", "(", ")", "break", "if", "parameters", ".", "maxchars", "and", "parameters", ".", "maxchars", "<", "0", ":", "raise", "ValueError", "(", "\"History parameter maxchars must be positive\"", ")", "if", "parameters", ".", "maxstanzas", "and", "parameters", ".", "maxstanzas", "<", "0", ":", "raise", "ValueError", "(", "\"History parameter maxstanzas must be positive\"", ")", "if", "parameters", ".", "maxseconds", "and", "parameters", ".", "maxseconds", "<", "0", ":", "raise", "ValueError", "(", "\"History parameter maxseconds must be positive\"", ")", "hnode", "=", "self", ".", "xmlnode", ".", "newChild", "(", "self", ".", "xmlnode", ".", "ns", "(", ")", ",", "\"history\"", ",", "None", ")", "if", "parameters", ".", "maxchars", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"maxchars\"", ",", "str", "(", "parameters", ".", "maxchars", ")", ")", "if", "parameters", ".", "maxstanzas", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"maxstanzas\"", ",", "str", "(", "parameters", ".", "maxstanzas", ")", ")", "if", "parameters", ".", "maxseconds", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"maxseconds\"", ",", "str", "(", "parameters", ".", "maxseconds", ")", ")", "if", "parameters", ".", "since", "is", "not", "None", ":", "hnode", ".", "setProp", "(", "\"since\"", ",", "parameters", ".", "since", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucX.get_history
Return history parameters carried by the stanza. :returntype: `HistoryParameters`
pyxmpp2/ext/muc/muccore.py
def get_history(self): """Return history parameters carried by the stanza. :returntype: `HistoryParameters`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": maxchars = from_utf8(child.prop("maxchars")) if maxchars is not None: maxchars = int(maxchars) maxstanzas = from_utf8(child.prop("maxstanzas")) if maxstanzas is not None: maxstanzas = int(maxstanzas) maxseconds = from_utf8(child.prop("maxseconds")) if maxseconds is not None: maxseconds = int(maxseconds) # TODO: since -- requires parsing of Jabber dateTime profile since = None return HistoryParameters(maxchars, maxstanzas, maxseconds, since)
def get_history(self): """Return history parameters carried by the stanza. :returntype: `HistoryParameters`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": maxchars = from_utf8(child.prop("maxchars")) if maxchars is not None: maxchars = int(maxchars) maxstanzas = from_utf8(child.prop("maxstanzas")) if maxstanzas is not None: maxstanzas = int(maxstanzas) maxseconds = from_utf8(child.prop("maxseconds")) if maxseconds is not None: maxseconds = int(maxseconds) # TODO: since -- requires parsing of Jabber dateTime profile since = None return HistoryParameters(maxchars, maxstanzas, maxseconds, since)
[ "Return", "history", "parameters", "carried", "by", "the", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L188-L205
[ "def", "get_history", "(", "self", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"history\"", ":", "maxchars", "=", "from_utf8", "(", "child", ".", "prop", "(", "\"maxchars\"", ")", ")", "if", "maxchars", "is", "not", "None", ":", "maxchars", "=", "int", "(", "maxchars", ")", "maxstanzas", "=", "from_utf8", "(", "child", ".", "prop", "(", "\"maxstanzas\"", ")", ")", "if", "maxstanzas", "is", "not", "None", ":", "maxstanzas", "=", "int", "(", "maxstanzas", ")", "maxseconds", "=", "from_utf8", "(", "child", ".", "prop", "(", "\"maxseconds\"", ")", ")", "if", "maxseconds", "is", "not", "None", ":", "maxseconds", "=", "int", "(", "maxseconds", ")", "# TODO: since -- requires parsing of Jabber dateTime profile", "since", "=", "None", "return", "HistoryParameters", "(", "maxchars", ",", "maxstanzas", ",", "maxseconds", ",", "since", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucX.set_password
Set password for the MUC request. :Parameters: - `password`: password :Types: - `password`: `unicode`
pyxmpp2/ext/muc/muccore.py
def set_password(self, password): """Set password for the MUC request. :Parameters: - `password`: password :Types: - `password`: `unicode`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "password": child.unlinkNode() child.freeNode() break if password is not None: self.xmlnode.newTextChild(self.xmlnode.ns(), "password", to_utf8(password))
def set_password(self, password): """Set password for the MUC request. :Parameters: - `password`: password :Types: - `password`: `unicode`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "password": child.unlinkNode() child.freeNode() break if password is not None: self.xmlnode.newTextChild(self.xmlnode.ns(), "password", to_utf8(password))
[ "Set", "password", "for", "the", "MUC", "request", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L207-L221
[ "def", "set_password", "(", "self", ",", "password", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"password\"", ":", "child", ".", "unlinkNode", "(", ")", "child", ".", "freeNode", "(", ")", "break", "if", "password", "is", "not", "None", ":", "self", ".", "xmlnode", ".", "newTextChild", "(", "self", ".", "xmlnode", ".", "ns", "(", ")", ",", "\"password\"", ",", "to_utf8", "(", "password", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucX.get_password
Get password from the MUC request. :returntype: `unicode`
pyxmpp2/ext/muc/muccore.py
def get_password(self): """Get password from the MUC request. :returntype: `unicode` """ for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "password": return from_utf8(child.getContent()) return None
def get_password(self): """Get password from the MUC request. :returntype: `unicode` """ for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "password": return from_utf8(child.getContent()) return None
[ "Get", "password", "from", "the", "MUC", "request", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L223-L231
[ "def", "get_password", "(", "self", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"password\"", ":", "return", "from_utf8", "(", "child", ".", "getContent", "(", ")", ")", "return", "None" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucItem.__init
Initialize a `MucItem` object from a set of attributes. :Parameters: - `affiliation`: affiliation of the user. - `role`: role of the user. - `jid`: JID of the user. - `nick`: nickname of the user. - `actor`: actor modyfying the user data. - `reason`: reason of change of the user data. :Types: - `affiliation`: `str` - `role`: `str` - `jid`: `JID` - `nick`: `unicode` - `actor`: `JID` - `reason`: `unicode`
pyxmpp2/ext/muc/muccore.py
def __init(self,affiliation,role,jid=None,nick=None,actor=None,reason=None): """Initialize a `MucItem` object from a set of attributes. :Parameters: - `affiliation`: affiliation of the user. - `role`: role of the user. - `jid`: JID of the user. - `nick`: nickname of the user. - `actor`: actor modyfying the user data. - `reason`: reason of change of the user data. :Types: - `affiliation`: `str` - `role`: `str` - `jid`: `JID` - `nick`: `unicode` - `actor`: `JID` - `reason`: `unicode` """ if not affiliation: affiliation=None elif affiliation not in affiliations: raise ValueError("Bad affiliation") self.affiliation=affiliation if not role: role=None elif role not in roles: raise ValueError("Bad role") self.role=role if jid: self.jid=JID(jid) else: self.jid=None if actor: self.actor=JID(actor) else: self.actor=None self.nick=nick self.reason=reason
def __init(self,affiliation,role,jid=None,nick=None,actor=None,reason=None): """Initialize a `MucItem` object from a set of attributes. :Parameters: - `affiliation`: affiliation of the user. - `role`: role of the user. - `jid`: JID of the user. - `nick`: nickname of the user. - `actor`: actor modyfying the user data. - `reason`: reason of change of the user data. :Types: - `affiliation`: `str` - `role`: `str` - `jid`: `JID` - `nick`: `unicode` - `actor`: `JID` - `reason`: `unicode` """ if not affiliation: affiliation=None elif affiliation not in affiliations: raise ValueError("Bad affiliation") self.affiliation=affiliation if not role: role=None elif role not in roles: raise ValueError("Bad role") self.role=role if jid: self.jid=JID(jid) else: self.jid=None if actor: self.actor=JID(actor) else: self.actor=None self.nick=nick self.reason=reason
[ "Initialize", "a", "MucItem", "object", "from", "a", "set", "of", "attributes", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L322-L359
[ "def", "__init", "(", "self", ",", "affiliation", ",", "role", ",", "jid", "=", "None", ",", "nick", "=", "None", ",", "actor", "=", "None", ",", "reason", "=", "None", ")", ":", "if", "not", "affiliation", ":", "affiliation", "=", "None", "elif", "affiliation", "not", "in", "affiliations", ":", "raise", "ValueError", "(", "\"Bad affiliation\"", ")", "self", ".", "affiliation", "=", "affiliation", "if", "not", "role", ":", "role", "=", "None", "elif", "role", "not", "in", "roles", ":", "raise", "ValueError", "(", "\"Bad role\"", ")", "self", ".", "role", "=", "role", "if", "jid", ":", "self", ".", "jid", "=", "JID", "(", "jid", ")", "else", ":", "self", ".", "jid", "=", "None", "if", "actor", ":", "self", ".", "actor", "=", "JID", "(", "actor", ")", "else", ":", "self", ".", "actor", "=", "None", "self", ".", "nick", "=", "nick", "self", ".", "reason", "=", "reason" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucItem.__from_xmlnode
Initialize a `MucItem` object from an XML node. :Parameters: - `xmlnode`: the XML node. :Types: - `xmlnode`: `libxml2.xmlNode`
pyxmpp2/ext/muc/muccore.py
def __from_xmlnode(self, xmlnode): """Initialize a `MucItem` object from an XML node. :Parameters: - `xmlnode`: the XML node. :Types: - `xmlnode`: `libxml2.xmlNode` """ actor=None reason=None n=xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: continue if n.name=="actor": actor=n.getContent() if n.name=="reason": reason=n.getContent() n=n.next self.__init( from_utf8(xmlnode.prop("affiliation")), from_utf8(xmlnode.prop("role")), from_utf8(xmlnode.prop("jid")), from_utf8(xmlnode.prop("nick")), from_utf8(actor), from_utf8(reason), );
def __from_xmlnode(self, xmlnode): """Initialize a `MucItem` object from an XML node. :Parameters: - `xmlnode`: the XML node. :Types: - `xmlnode`: `libxml2.xmlNode` """ actor=None reason=None n=xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: continue if n.name=="actor": actor=n.getContent() if n.name=="reason": reason=n.getContent() n=n.next self.__init( from_utf8(xmlnode.prop("affiliation")), from_utf8(xmlnode.prop("role")), from_utf8(xmlnode.prop("jid")), from_utf8(xmlnode.prop("nick")), from_utf8(actor), from_utf8(reason), );
[ "Initialize", "a", "MucItem", "object", "from", "an", "XML", "node", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L361-L388
[ "def", "__from_xmlnode", "(", "self", ",", "xmlnode", ")", ":", "actor", "=", "None", "reason", "=", "None", "n", "=", "xmlnode", ".", "children", "while", "n", ":", "ns", "=", "n", ".", "ns", "(", ")", "if", "ns", "and", "ns", ".", "getContent", "(", ")", "!=", "MUC_USER_NS", ":", "continue", "if", "n", ".", "name", "==", "\"actor\"", ":", "actor", "=", "n", ".", "getContent", "(", ")", "if", "n", ".", "name", "==", "\"reason\"", ":", "reason", "=", "n", ".", "getContent", "(", ")", "n", "=", "n", ".", "next", "self", ".", "__init", "(", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"affiliation\"", ")", ")", ",", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"role\"", ")", ")", ",", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"jid\"", ")", ")", ",", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"nick\"", ")", ")", ",", "from_utf8", "(", "actor", ")", ",", "from_utf8", "(", "reason", ")", ",", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucItem.as_xml
Create XML representation of `self`. :Parameters: - `parent`: the element to which the created node should be linked to. :Types: - `parent`: `libxml2.xmlNode` :return: an XML node. :returntype: `libxml2.xmlNode`
pyxmpp2/ext/muc/muccore.py
def as_xml(self,parent): """ Create XML representation of `self`. :Parameters: - `parent`: the element to which the created node should be linked to. :Types: - `parent`: `libxml2.xmlNode` :return: an XML node. :returntype: `libxml2.xmlNode` """ n=parent.newChild(None,"item",None) if self.actor: n.newTextChild(None,"actor",to_utf8(self.actor)) if self.reason: n.newTextChild(None,"reason",to_utf8(self.reason)) n.setProp("affiliation",to_utf8(self.affiliation)) if self.role: n.setProp("role",to_utf8(self.role)) if self.jid: n.setProp("jid",to_utf8(self.jid.as_unicode())) if self.nick: n.setProp("nick",to_utf8(self.nick)) return n
def as_xml(self,parent): """ Create XML representation of `self`. :Parameters: - `parent`: the element to which the created node should be linked to. :Types: - `parent`: `libxml2.xmlNode` :return: an XML node. :returntype: `libxml2.xmlNode` """ n=parent.newChild(None,"item",None) if self.actor: n.newTextChild(None,"actor",to_utf8(self.actor)) if self.reason: n.newTextChild(None,"reason",to_utf8(self.reason)) n.setProp("affiliation",to_utf8(self.affiliation)) if self.role: n.setProp("role",to_utf8(self.role)) if self.jid: n.setProp("jid",to_utf8(self.jid.as_unicode())) if self.nick: n.setProp("nick",to_utf8(self.nick)) return n
[ "Create", "XML", "representation", "of", "self", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L390-L414
[ "def", "as_xml", "(", "self", ",", "parent", ")", ":", "n", "=", "parent", ".", "newChild", "(", "None", ",", "\"item\"", ",", "None", ")", "if", "self", ".", "actor", ":", "n", ".", "newTextChild", "(", "None", ",", "\"actor\"", ",", "to_utf8", "(", "self", ".", "actor", ")", ")", "if", "self", ".", "reason", ":", "n", ".", "newTextChild", "(", "None", ",", "\"reason\"", ",", "to_utf8", "(", "self", ".", "reason", ")", ")", "n", ".", "setProp", "(", "\"affiliation\"", ",", "to_utf8", "(", "self", ".", "affiliation", ")", ")", "if", "self", ".", "role", ":", "n", ".", "setProp", "(", "\"role\"", ",", "to_utf8", "(", "self", ".", "role", ")", ")", "if", "self", ".", "jid", ":", "n", ".", "setProp", "(", "\"jid\"", ",", "to_utf8", "(", "self", ".", "jid", ".", "as_unicode", "(", ")", ")", ")", "if", "self", ".", "nick", ":", "n", ".", "setProp", "(", "\"nick\"", ",", "to_utf8", "(", "self", ".", "nick", ")", ")", "return", "n" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucStatus.__init
Initialize a `MucStatus` element from a status code. :Parameters: - `code`: the status code. :Types: - `code`: `int`
pyxmpp2/ext/muc/muccore.py
def __init(self,code): """Initialize a `MucStatus` element from a status code. :Parameters: - `code`: the status code. :Types: - `code`: `int` """ code=int(code) if code<0 or code>999: raise ValueError("Bad status code") self.code=code
def __init(self,code): """Initialize a `MucStatus` element from a status code. :Parameters: - `code`: the status code. :Types: - `code`: `int` """ code=int(code) if code<0 or code>999: raise ValueError("Bad status code") self.code=code
[ "Initialize", "a", "MucStatus", "element", "from", "a", "status", "code", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L440-L451
[ "def", "__init", "(", "self", ",", "code", ")", ":", "code", "=", "int", "(", "code", ")", "if", "code", "<", "0", "or", "code", ">", "999", ":", "raise", "ValueError", "(", "\"Bad status code\"", ")", "self", ".", "code", "=", "code" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucStatus.as_xml
Create XML representation of `self`. :Parameters: - `parent`: the element to which the created node should be linked to. :Types: - `parent`: `libxml2.xmlNode` :return: an XML node. :returntype: `libxml2.xmlNode`
pyxmpp2/ext/muc/muccore.py
def as_xml(self,parent): """ Create XML representation of `self`. :Parameters: - `parent`: the element to which the created node should be linked to. :Types: - `parent`: `libxml2.xmlNode` :return: an XML node. :returntype: `libxml2.xmlNode` """ n=parent.newChild(None,"status",None) n.setProp("code","%03i" % (self.code,)) return n
def as_xml(self,parent): """ Create XML representation of `self`. :Parameters: - `parent`: the element to which the created node should be linked to. :Types: - `parent`: `libxml2.xmlNode` :return: an XML node. :returntype: `libxml2.xmlNode` """ n=parent.newChild(None,"status",None) n.setProp("code","%03i" % (self.code,)) return n
[ "Create", "XML", "representation", "of", "self", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L463-L477
[ "def", "as_xml", "(", "self", ",", "parent", ")", ":", "n", "=", "parent", ".", "newChild", "(", "None", ",", "\"status\"", ",", "None", ")", "n", ".", "setProp", "(", "\"code\"", ",", "\"%03i\"", "%", "(", "self", ".", "code", ",", ")", ")", "return", "n" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucUserX.get_items
Get a list of objects describing the content of `self`. :return: the list of objects. :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`)
pyxmpp2/ext/muc/muccore.py
def get_items(self): """Get a list of objects describing the content of `self`. :return: the list of objects. :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`) """ if not self.xmlnode.children: return [] ret=[] n=self.xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=self.ns: pass elif n.name=="item": ret.append(MucItem(n)) elif n.name=="status": ret.append(MucStatus(n)) # FIXME: alt,decline,invite,password n=n.next return ret
def get_items(self): """Get a list of objects describing the content of `self`. :return: the list of objects. :returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`) """ if not self.xmlnode.children: return [] ret=[] n=self.xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=self.ns: pass elif n.name=="item": ret.append(MucItem(n)) elif n.name=="status": ret.append(MucStatus(n)) # FIXME: alt,decline,invite,password n=n.next return ret
[ "Get", "a", "list", "of", "objects", "describing", "the", "content", "of", "self", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L491-L511
[ "def", "get_items", "(", "self", ")", ":", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "[", "]", "ret", "=", "[", "]", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "ns", "=", "n", ".", "ns", "(", ")", "if", "ns", "and", "ns", ".", "getContent", "(", ")", "!=", "self", ".", "ns", ":", "pass", "elif", "n", ".", "name", "==", "\"item\"", ":", "ret", ".", "append", "(", "MucItem", "(", "n", ")", ")", "elif", "n", ".", "name", "==", "\"status\"", ":", "ret", ".", "append", "(", "MucStatus", "(", "n", ")", ")", "# FIXME: alt,decline,invite,password", "n", "=", "n", ".", "next", "return", "ret" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucUserX.clear
Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc.
pyxmpp2/ext/muc/muccore.py
def clear(self): """ Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc. """ if not self.xmlnode.children: return n=self.xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: pass else: n.unlinkNode() n.freeNode() n=n.next
def clear(self): """ Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc. """ if not self.xmlnode.children: return n=self.xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: pass else: n.unlinkNode() n.freeNode() n=n.next
[ "Clear", "the", "content", "of", "self", ".", "xmlnode", "removing", "all", "<item", "/", ">", "<status", "/", ">", "etc", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L512-L526
[ "def", "clear", "(", "self", ")", ":", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "ns", "=", "n", ".", "ns", "(", ")", "if", "ns", "and", "ns", ".", "getContent", "(", ")", "!=", "MUC_USER_NS", ":", "pass", "else", ":", "n", ".", "unlinkNode", "(", ")", "n", ".", "freeNode", "(", ")", "n", "=", "n", ".", "next" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucUserX.add_item
Add an item to `self`. :Parameters: - `item`: the item to add. :Types: - `item`: `MucItemBase`
pyxmpp2/ext/muc/muccore.py
def add_item(self,item): """Add an item to `self`. :Parameters: - `item`: the item to add. :Types: - `item`: `MucItemBase` """ if not isinstance(item,MucItemBase): raise TypeError("Bad item type for muc#user") item.as_xml(self.xmlnode)
def add_item(self,item): """Add an item to `self`. :Parameters: - `item`: the item to add. :Types: - `item`: `MucItemBase` """ if not isinstance(item,MucItemBase): raise TypeError("Bad item type for muc#user") item.as_xml(self.xmlnode)
[ "Add", "an", "item", "to", "self", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L527-L537
[ "def", "add_item", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "MucItemBase", ")", ":", "raise", "TypeError", "(", "\"Bad item type for muc#user\"", ")", "item", ".", "as_xml", "(", "self", ".", "xmlnode", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucStanzaExt.get_muc_child
Get the MUC specific payload element. :return: the object describing the stanza payload in MUC namespace. :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX`
pyxmpp2/ext/muc/muccore.py
def get_muc_child(self): """ Get the MUC specific payload element. :return: the object describing the stanza payload in MUC namespace. :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX` """ if self.muc_child: return self.muc_child if not self.xmlnode.children: return None n=self.xmlnode.children while n: if n.name not in ("x","query"): n=n.next continue ns=n.ns() if not ns: n=n.next continue ns_uri=ns.getContent() if (n.name,ns_uri)==("x",MUC_NS): self.muc_child=MucX(n) return self.muc_child if (n.name,ns_uri)==("x",MUC_USER_NS): self.muc_child=MucUserX(n) return self.muc_child if (n.name,ns_uri)==("query",MUC_ADMIN_NS): self.muc_child=MucAdminQuery(n) return self.muc_child if (n.name,ns_uri)==("query",MUC_OWNER_NS): self.muc_child=MucOwnerX(n) return self.muc_child n=n.next
def get_muc_child(self): """ Get the MUC specific payload element. :return: the object describing the stanza payload in MUC namespace. :returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX` """ if self.muc_child: return self.muc_child if not self.xmlnode.children: return None n=self.xmlnode.children while n: if n.name not in ("x","query"): n=n.next continue ns=n.ns() if not ns: n=n.next continue ns_uri=ns.getContent() if (n.name,ns_uri)==("x",MUC_NS): self.muc_child=MucX(n) return self.muc_child if (n.name,ns_uri)==("x",MUC_USER_NS): self.muc_child=MucUserX(n) return self.muc_child if (n.name,ns_uri)==("query",MUC_ADMIN_NS): self.muc_child=MucAdminQuery(n) return self.muc_child if (n.name,ns_uri)==("query",MUC_OWNER_NS): self.muc_child=MucOwnerX(n) return self.muc_child n=n.next
[ "Get", "the", "MUC", "specific", "payload", "element", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L576-L609
[ "def", "get_muc_child", "(", "self", ")", ":", "if", "self", ".", "muc_child", ":", "return", "self", ".", "muc_child", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "None", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "if", "n", ".", "name", "not", "in", "(", "\"x\"", ",", "\"query\"", ")", ":", "n", "=", "n", ".", "next", "continue", "ns", "=", "n", ".", "ns", "(", ")", "if", "not", "ns", ":", "n", "=", "n", ".", "next", "continue", "ns_uri", "=", "ns", ".", "getContent", "(", ")", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"x\"", ",", "MUC_NS", ")", ":", "self", ".", "muc_child", "=", "MucX", "(", "n", ")", "return", "self", ".", "muc_child", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"x\"", ",", "MUC_USER_NS", ")", ":", "self", ".", "muc_child", "=", "MucUserX", "(", "n", ")", "return", "self", ".", "muc_child", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"query\"", ",", "MUC_ADMIN_NS", ")", ":", "self", ".", "muc_child", "=", "MucAdminQuery", "(", "n", ")", "return", "self", ".", "muc_child", "if", "(", "n", ".", "name", ",", "ns_uri", ")", "==", "(", "\"query\"", ",", "MUC_OWNER_NS", ")", ":", "self", ".", "muc_child", "=", "MucOwnerX", "(", "n", ")", "return", "self", ".", "muc_child", "n", "=", "n", ".", "next" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucStanzaExt.clear_muc_child
Remove the MUC specific stanza payload element.
pyxmpp2/ext/muc/muccore.py
def clear_muc_child(self): """ Remove the MUC specific stanza payload element. """ if self.muc_child: self.muc_child.free_borrowed() self.muc_child=None if not self.xmlnode.children: return n=self.xmlnode.children while n: if n.name not in ("x","query"): n=n.next continue ns=n.ns() if not ns: n=n.next continue ns_uri=ns.getContent() if ns_uri in (MUC_NS,MUC_USER_NS,MUC_ADMIN_NS,MUC_OWNER_NS): n.unlinkNode() n.freeNode() n=n.next
def clear_muc_child(self): """ Remove the MUC specific stanza payload element. """ if self.muc_child: self.muc_child.free_borrowed() self.muc_child=None if not self.xmlnode.children: return n=self.xmlnode.children while n: if n.name not in ("x","query"): n=n.next continue ns=n.ns() if not ns: n=n.next continue ns_uri=ns.getContent() if ns_uri in (MUC_NS,MUC_USER_NS,MUC_ADMIN_NS,MUC_OWNER_NS): n.unlinkNode() n.freeNode() n=n.next
[ "Remove", "the", "MUC", "specific", "stanza", "payload", "element", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L611-L633
[ "def", "clear_muc_child", "(", "self", ")", ":", "if", "self", ".", "muc_child", ":", "self", ".", "muc_child", ".", "free_borrowed", "(", ")", "self", ".", "muc_child", "=", "None", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "if", "n", ".", "name", "not", "in", "(", "\"x\"", ",", "\"query\"", ")", ":", "n", "=", "n", ".", "next", "continue", "ns", "=", "n", ".", "ns", "(", ")", "if", "not", "ns", ":", "n", "=", "n", ".", "next", "continue", "ns_uri", "=", "ns", ".", "getContent", "(", ")", "if", "ns_uri", "in", "(", "MUC_NS", ",", "MUC_USER_NS", ",", "MUC_ADMIN_NS", ",", "MUC_OWNER_NS", ")", ":", "n", ".", "unlinkNode", "(", ")", "n", ".", "freeNode", "(", ")", "n", "=", "n", ".", "next" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucStanzaExt.make_muc_userinfo
Create <x xmlns="...muc#user"/> element in the stanza. :return: the element created. :returntype: `MucUserX`
pyxmpp2/ext/muc/muccore.py
def make_muc_userinfo(self): """ Create <x xmlns="...muc#user"/> element in the stanza. :return: the element created. :returntype: `MucUserX` """ self.clear_muc_child() self.muc_child=MucUserX(parent=self.xmlnode) return self.muc_child
def make_muc_userinfo(self): """ Create <x xmlns="...muc#user"/> element in the stanza. :return: the element created. :returntype: `MucUserX` """ self.clear_muc_child() self.muc_child=MucUserX(parent=self.xmlnode) return self.muc_child
[ "Create", "<x", "xmlns", "=", "...", "muc#user", "/", ">", "element", "in", "the", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L635-L644
[ "def", "make_muc_userinfo", "(", "self", ")", ":", "self", ".", "clear_muc_child", "(", ")", "self", ".", "muc_child", "=", "MucUserX", "(", "parent", "=", "self", ".", "xmlnode", ")", "return", "self", ".", "muc_child" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucStanzaExt.make_muc_admin_quey
Create <query xmlns="...muc#admin"/> element in the stanza. :return: the element created. :returntype: `MucAdminQuery`
pyxmpp2/ext/muc/muccore.py
def make_muc_admin_quey(self): """ Create <query xmlns="...muc#admin"/> element in the stanza. :return: the element created. :returntype: `MucAdminQuery` """ self.clear_muc_child() self.muc_child=MucAdminQuery(parent=self.xmlnode) return self.muc_child
def make_muc_admin_quey(self): """ Create <query xmlns="...muc#admin"/> element in the stanza. :return: the element created. :returntype: `MucAdminQuery` """ self.clear_muc_child() self.muc_child=MucAdminQuery(parent=self.xmlnode) return self.muc_child
[ "Create", "<query", "xmlns", "=", "...", "muc#admin", "/", ">", "element", "in", "the", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L646-L655
[ "def", "make_muc_admin_quey", "(", "self", ")", ":", "self", ".", "clear_muc_child", "(", ")", "self", ".", "muc_child", "=", "MucAdminQuery", "(", "parent", "=", "self", ".", "xmlnode", ")", "return", "self", ".", "muc_child" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucPresence.make_join_request
Make the presence stanza a MUC room join request. :Parameters: - `password`: password to the room. - `history_maxchars`: limit of the total number of characters in history. - `history_maxstanzas`: limit of the total number of messages in history. - `history_seconds`: send only messages received in the last `seconds` seconds. - `history_since`: Send only the messages received since the dateTime specified (UTC). :Types: - `password`: `unicode` - `history_maxchars`: `int` - `history_maxstanzas`: `int` - `history_seconds`: `int` - `history_since`: `datetime.datetime`
pyxmpp2/ext/muc/muccore.py
def make_join_request(self, password = None, history_maxchars = None, history_maxstanzas = None, history_seconds = None, history_since = None): """ Make the presence stanza a MUC room join request. :Parameters: - `password`: password to the room. - `history_maxchars`: limit of the total number of characters in history. - `history_maxstanzas`: limit of the total number of messages in history. - `history_seconds`: send only messages received in the last `seconds` seconds. - `history_since`: Send only the messages received since the dateTime specified (UTC). :Types: - `password`: `unicode` - `history_maxchars`: `int` - `history_maxstanzas`: `int` - `history_seconds`: `int` - `history_since`: `datetime.datetime` """ self.clear_muc_child() self.muc_child=MucX(parent=self.xmlnode) if (history_maxchars is not None or history_maxstanzas is not None or history_seconds is not None or history_since is not None): history = HistoryParameters(history_maxchars, history_maxstanzas, history_seconds, history_since) self.muc_child.set_history(history) if password is not None: self.muc_child.set_password(password)
def make_join_request(self, password = None, history_maxchars = None, history_maxstanzas = None, history_seconds = None, history_since = None): """ Make the presence stanza a MUC room join request. :Parameters: - `password`: password to the room. - `history_maxchars`: limit of the total number of characters in history. - `history_maxstanzas`: limit of the total number of messages in history. - `history_seconds`: send only messages received in the last `seconds` seconds. - `history_since`: Send only the messages received since the dateTime specified (UTC). :Types: - `password`: `unicode` - `history_maxchars`: `int` - `history_maxstanzas`: `int` - `history_seconds`: `int` - `history_since`: `datetime.datetime` """ self.clear_muc_child() self.muc_child=MucX(parent=self.xmlnode) if (history_maxchars is not None or history_maxstanzas is not None or history_seconds is not None or history_since is not None): history = HistoryParameters(history_maxchars, history_maxstanzas, history_seconds, history_since) self.muc_child.set_history(history) if password is not None: self.muc_child.set_password(password)
[ "Make", "the", "presence", "stanza", "a", "MUC", "room", "join", "request", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L709-L740
[ "def", "make_join_request", "(", "self", ",", "password", "=", "None", ",", "history_maxchars", "=", "None", ",", "history_maxstanzas", "=", "None", ",", "history_seconds", "=", "None", ",", "history_since", "=", "None", ")", ":", "self", ".", "clear_muc_child", "(", ")", "self", ".", "muc_child", "=", "MucX", "(", "parent", "=", "self", ".", "xmlnode", ")", "if", "(", "history_maxchars", "is", "not", "None", "or", "history_maxstanzas", "is", "not", "None", "or", "history_seconds", "is", "not", "None", "or", "history_since", "is", "not", "None", ")", ":", "history", "=", "HistoryParameters", "(", "history_maxchars", ",", "history_maxstanzas", ",", "history_seconds", ",", "history_since", ")", "self", ".", "muc_child", ".", "set_history", "(", "history", ")", "if", "password", "is", "not", "None", ":", "self", ".", "muc_child", ".", "set_password", "(", "password", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucPresence.get_join_info
If `self` is a MUC room join request return the information contained. :return: the join request details or `None`. :returntype: `MucX`
pyxmpp2/ext/muc/muccore.py
def get_join_info(self): """If `self` is a MUC room join request return the information contained. :return: the join request details or `None`. :returntype: `MucX` """ x=self.get_muc_child() if not x: return None if not isinstance(x,MucX): return None return x
def get_join_info(self): """If `self` is a MUC room join request return the information contained. :return: the join request details or `None`. :returntype: `MucX` """ x=self.get_muc_child() if not x: return None if not isinstance(x,MucX): return None return x
[ "If", "self", "is", "a", "MUC", "room", "join", "request", "return", "the", "information", "contained", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L742-L753
[ "def", "get_join_info", "(", "self", ")", ":", "x", "=", "self", ".", "get_muc_child", "(", ")", "if", "not", "x", ":", "return", "None", "if", "not", "isinstance", "(", "x", ",", "MucX", ")", ":", "return", "None", "return", "x" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MucIq.make_kick_request
Make the iq stanza a MUC room participant kick request. :Parameters: - `nick`: nickname of user to kick. - `reason`: reason of the kick. :Types: - `nick`: `unicode` - `reason`: `unicode` :return: object describing the kick request details. :returntype: `MucItem`
pyxmpp2/ext/muc/muccore.py
def make_kick_request(self,nick,reason): """ Make the iq stanza a MUC room participant kick request. :Parameters: - `nick`: nickname of user to kick. - `reason`: reason of the kick. :Types: - `nick`: `unicode` - `reason`: `unicode` :return: object describing the kick request details. :returntype: `MucItem` """ self.clear_muc_child() self.muc_child=MucAdminQuery(parent=self.xmlnode) item=MucItem("none","none",nick=nick,reason=reason) self.muc_child.add_item(item) return self.muc_child
def make_kick_request(self,nick,reason): """ Make the iq stanza a MUC room participant kick request. :Parameters: - `nick`: nickname of user to kick. - `reason`: reason of the kick. :Types: - `nick`: `unicode` - `reason`: `unicode` :return: object describing the kick request details. :returntype: `MucItem` """ self.clear_muc_child() self.muc_child=MucAdminQuery(parent=self.xmlnode) item=MucItem("none","none",nick=nick,reason=reason) self.muc_child.add_item(item) return self.muc_child
[ "Make", "the", "iq", "stanza", "a", "MUC", "room", "participant", "kick", "request", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L794-L812
[ "def", "make_kick_request", "(", "self", ",", "nick", ",", "reason", ")", ":", "self", ".", "clear_muc_child", "(", ")", "self", ".", "muc_child", "=", "MucAdminQuery", "(", "parent", "=", "self", ".", "xmlnode", ")", "item", "=", "MucItem", "(", "\"none\"", ",", "\"none\"", ",", "nick", "=", "nick", ",", "reason", "=", "reason", ")", "self", ".", "muc_child", ".", "add_item", "(", "item", ")", "return", "self", ".", "muc_child" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
nfkc
Do NFKC normalization of Unicode data. :Parameters: - `data`: list of Unicode characters or Unicode string. :return: normalized Unicode string.
pyxmpp2/xmppstringprep.py
def nfkc(data): """Do NFKC normalization of Unicode data. :Parameters: - `data`: list of Unicode characters or Unicode string. :return: normalized Unicode string.""" if isinstance(data, list): data = u"".join(data) return unicodedata.normalize("NFKC", data)
def nfkc(data): """Do NFKC normalization of Unicode data. :Parameters: - `data`: list of Unicode characters or Unicode string. :return: normalized Unicode string.""" if isinstance(data, list): data = u"".join(data) return unicodedata.normalize("NFKC", data)
[ "Do", "NFKC", "normalization", "of", "Unicode", "data", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L61-L70
[ "def", "nfkc", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "data", "=", "u\"\"", ".", "join", "(", "data", ")", "return", "unicodedata", ".", "normalize", "(", "\"NFKC\"", ",", "data", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
set_stringprep_cache_size
Modify stringprep cache size. :Parameters: - `size`: new cache size
pyxmpp2/xmppstringprep.py
def set_stringprep_cache_size(size): """Modify stringprep cache size. :Parameters: - `size`: new cache size """ # pylint: disable-msg=W0603 global _stringprep_cache_size _stringprep_cache_size = size if len(Profile.cache_items) > size: remove = Profile.cache_items[:-size] for profile, key in remove: try: del profile.cache[key] except KeyError: pass Profile.cache_items = Profile.cache_items[-size:]
def set_stringprep_cache_size(size): """Modify stringprep cache size. :Parameters: - `size`: new cache size """ # pylint: disable-msg=W0603 global _stringprep_cache_size _stringprep_cache_size = size if len(Profile.cache_items) > size: remove = Profile.cache_items[:-size] for profile, key in remove: try: del profile.cache[key] except KeyError: pass Profile.cache_items = Profile.cache_items[-size:]
[ "Modify", "stringprep", "cache", "size", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L237-L253
[ "def", "set_stringprep_cache_size", "(", "size", ")", ":", "# pylint: disable-msg=W0603", "global", "_stringprep_cache_size", "_stringprep_cache_size", "=", "size", "if", "len", "(", "Profile", ".", "cache_items", ")", ">", "size", ":", "remove", "=", "Profile", ".", "cache_items", "[", ":", "-", "size", "]", "for", "profile", ",", "key", "in", "remove", ":", "try", ":", "del", "profile", ".", "cache", "[", "key", "]", "except", "KeyError", ":", "pass", "Profile", ".", "cache_items", "=", "Profile", ".", "cache_items", "[", "-", "size", ":", "]" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Profile.prepare
Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails
pyxmpp2/xmppstringprep.py
def prepare(self, data): """Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails """ ret = self.cache.get(data) if ret is not None: return ret result = self.map(data) if self.normalization: result = self.normalization(result) result = self.prohibit(result) result = self.check_unassigned(result) if self.bidi: result = self.check_bidi(result) if isinstance(result, list): result = u"".join() if len(self.cache_items) >= _stringprep_cache_size: remove = self.cache_items[: -_stringprep_cache_size // 2] for profile, key in remove: try: del profile.cache[key] except KeyError: pass self.cache_items[:] = self.cache_items[ -_stringprep_cache_size // 2 :] self.cache_items.append((self, data)) self.cache[data] = result return result
def prepare(self, data): """Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails """ ret = self.cache.get(data) if ret is not None: return ret result = self.map(data) if self.normalization: result = self.normalization(result) result = self.prohibit(result) result = self.check_unassigned(result) if self.bidi: result = self.check_bidi(result) if isinstance(result, list): result = u"".join() if len(self.cache_items) >= _stringprep_cache_size: remove = self.cache_items[: -_stringprep_cache_size // 2] for profile, key in remove: try: del profile.cache[key] except KeyError: pass self.cache_items[:] = self.cache_items[ -_stringprep_cache_size // 2 :] self.cache_items.append((self, data)) self.cache[data] = result return result
[ "Complete", "string", "preparation", "procedure", "for", "stored", "strings", ".", "(", "includes", "checks", "for", "unassigned", "codes", ")" ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L101-L135
[ "def", "prepare", "(", "self", ",", "data", ")", ":", "ret", "=", "self", ".", "cache", ".", "get", "(", "data", ")", "if", "ret", "is", "not", "None", ":", "return", "ret", "result", "=", "self", ".", "map", "(", "data", ")", "if", "self", ".", "normalization", ":", "result", "=", "self", ".", "normalization", "(", "result", ")", "result", "=", "self", ".", "prohibit", "(", "result", ")", "result", "=", "self", ".", "check_unassigned", "(", "result", ")", "if", "self", ".", "bidi", ":", "result", "=", "self", ".", "check_bidi", "(", "result", ")", "if", "isinstance", "(", "result", ",", "list", ")", ":", "result", "=", "u\"\"", ".", "join", "(", ")", "if", "len", "(", "self", ".", "cache_items", ")", ">=", "_stringprep_cache_size", ":", "remove", "=", "self", ".", "cache_items", "[", ":", "-", "_stringprep_cache_size", "//", "2", "]", "for", "profile", ",", "key", "in", "remove", ":", "try", ":", "del", "profile", ".", "cache", "[", "key", "]", "except", "KeyError", ":", "pass", "self", ".", "cache_items", "[", ":", "]", "=", "self", ".", "cache_items", "[", "-", "_stringprep_cache_size", "//", "2", ":", "]", "self", ".", "cache_items", ".", "append", "(", "(", "self", ",", "data", ")", ")", "self", ".", "cache", "[", "data", "]", "=", "result", "return", "result" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Profile.prepare_query
Complete string preparation procedure for 'query' strings. (without checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails
pyxmpp2/xmppstringprep.py
def prepare_query(self, data): """Complete string preparation procedure for 'query' strings. (without checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails """ data = self.map(data) if self.normalization: data = self.normalization(data) data = self.prohibit(data) if self.bidi: data = self.check_bidi(data) if isinstance(data, list): data = u"".join(data) return data
def prepare_query(self, data): """Complete string preparation procedure for 'query' strings. (without checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails """ data = self.map(data) if self.normalization: data = self.normalization(data) data = self.prohibit(data) if self.bidi: data = self.check_bidi(data) if isinstance(data, list): data = u"".join(data) return data
[ "Complete", "string", "preparation", "procedure", "for", "query", "strings", ".", "(", "without", "checks", "for", "unassigned", "codes", ")" ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L137-L156
[ "def", "prepare_query", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "map", "(", "data", ")", "if", "self", ".", "normalization", ":", "data", "=", "self", ".", "normalization", "(", "data", ")", "data", "=", "self", ".", "prohibit", "(", "data", ")", "if", "self", ".", "bidi", ":", "data", "=", "self", ".", "check_bidi", "(", "data", ")", "if", "isinstance", "(", "data", ",", "list", ")", ":", "data", "=", "u\"\"", ".", "join", "(", "data", ")", "return", "data" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Profile.map
Mapping part of string preparation.
pyxmpp2/xmppstringprep.py
def map(self, data): """Mapping part of string preparation.""" result = [] for char in data: ret = None for lookup in self.mapping: ret = lookup(char) if ret is not None: break if ret is not None: result.append(ret) else: result.append(char) return result
def map(self, data): """Mapping part of string preparation.""" result = [] for char in data: ret = None for lookup in self.mapping: ret = lookup(char) if ret is not None: break if ret is not None: result.append(ret) else: result.append(char) return result
[ "Mapping", "part", "of", "string", "preparation", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L158-L171
[ "def", "map", "(", "self", ",", "data", ")", ":", "result", "=", "[", "]", "for", "char", "in", "data", ":", "ret", "=", "None", "for", "lookup", "in", "self", ".", "mapping", ":", "ret", "=", "lookup", "(", "char", ")", "if", "ret", "is", "not", "None", ":", "break", "if", "ret", "is", "not", "None", ":", "result", ".", "append", "(", "ret", ")", "else", ":", "result", ".", "append", "(", "char", ")", "return", "result" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Profile.prohibit
Checks for prohibited characters.
pyxmpp2/xmppstringprep.py
def prohibit(self, data): """Checks for prohibited characters.""" for char in data: for lookup in self.prohibited: if lookup(char): raise StringprepError("Prohibited character: {0!r}" .format(char)) return data
def prohibit(self, data): """Checks for prohibited characters.""" for char in data: for lookup in self.prohibited: if lookup(char): raise StringprepError("Prohibited character: {0!r}" .format(char)) return data
[ "Checks", "for", "prohibited", "characters", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L173-L180
[ "def", "prohibit", "(", "self", ",", "data", ")", ":", "for", "char", "in", "data", ":", "for", "lookup", "in", "self", ".", "prohibited", ":", "if", "lookup", "(", "char", ")", ":", "raise", "StringprepError", "(", "\"Prohibited character: {0!r}\"", ".", "format", "(", "char", ")", ")", "return", "data" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Profile.check_unassigned
Checks for unassigned character codes.
pyxmpp2/xmppstringprep.py
def check_unassigned(self, data): """Checks for unassigned character codes.""" for char in data: for lookup in self.unassigned: if lookup(char): raise StringprepError("Unassigned character: {0!r}" .format(char)) return data
def check_unassigned(self, data): """Checks for unassigned character codes.""" for char in data: for lookup in self.unassigned: if lookup(char): raise StringprepError("Unassigned character: {0!r}" .format(char)) return data
[ "Checks", "for", "unassigned", "character", "codes", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L182-L189
[ "def", "check_unassigned", "(", "self", ",", "data", ")", ":", "for", "char", "in", "data", ":", "for", "lookup", "in", "self", ".", "unassigned", ":", "if", "lookup", "(", "char", ")", ":", "raise", "StringprepError", "(", "\"Unassigned character: {0!r}\"", ".", "format", "(", "char", ")", ")", "return", "data" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Profile.check_bidi
Checks if sting is valid for bidirectional printing.
pyxmpp2/xmppstringprep.py
def check_bidi(data): """Checks if sting is valid for bidirectional printing.""" has_l = False has_ral = False for char in data: if stringprep.in_table_d1(char): has_ral = True elif stringprep.in_table_d2(char): has_l = True if has_l and has_ral: raise StringprepError("Both RandALCat and LCat characters present") if has_ral and (not stringprep.in_table_d1(data[0]) or not stringprep.in_table_d1(data[-1])): raise StringprepError("The first and the last character must" " be RandALCat") return data
def check_bidi(data): """Checks if sting is valid for bidirectional printing.""" has_l = False has_ral = False for char in data: if stringprep.in_table_d1(char): has_ral = True elif stringprep.in_table_d2(char): has_l = True if has_l and has_ral: raise StringprepError("Both RandALCat and LCat characters present") if has_ral and (not stringprep.in_table_d1(data[0]) or not stringprep.in_table_d1(data[-1])): raise StringprepError("The first and the last character must" " be RandALCat") return data
[ "Checks", "if", "sting", "is", "valid", "for", "bidirectional", "printing", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppstringprep.py#L192-L207
[ "def", "check_bidi", "(", "data", ")", ":", "has_l", "=", "False", "has_ral", "=", "False", "for", "char", "in", "data", ":", "if", "stringprep", ".", "in_table_d1", "(", "char", ")", ":", "has_ral", "=", "True", "elif", "stringprep", ".", "in_table_d2", "(", "char", ")", ":", "has_l", "=", "True", "if", "has_l", "and", "has_ral", ":", "raise", "StringprepError", "(", "\"Both RandALCat and LCat characters present\"", ")", "if", "has_ral", "and", "(", "not", "stringprep", ".", "in_table_d1", "(", "data", "[", "0", "]", ")", "or", "not", "stringprep", ".", "in_table_d1", "(", "data", "[", "-", "1", "]", ")", ")", ":", "raise", "StringprepError", "(", "\"The first and the last character must\"", "\" be RandALCat\"", ")", "return", "data" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
hold_exception
Decorator for glib callback methods of GLibMainLoop used to store the exception raised.
pyxmpp2/mainloop/glib.py
def hold_exception(method): """Decorator for glib callback methods of GLibMainLoop used to store the exception raised.""" @functools.wraps(method) def wrapper(self, *args, **kwargs): """Wrapper for methods decorated with `hold_exception`.""" # pylint: disable=W0703,W0212 try: return method(self, *args, **kwargs) except Exception: if self.exc_info: raise if not self._stack: logger.debug('@hold_exception wrapped method {0!r} called' ' from outside of the main loop'.format(method)) raise self.exc_info = sys.exc_info() logger.debug(u"exception in glib main loop callback:", exc_info = self.exc_info) # pylint: disable=W0212 main_loop = self._stack[-1] if main_loop is not None: main_loop.quit() return False return wrapper
def hold_exception(method): """Decorator for glib callback methods of GLibMainLoop used to store the exception raised.""" @functools.wraps(method) def wrapper(self, *args, **kwargs): """Wrapper for methods decorated with `hold_exception`.""" # pylint: disable=W0703,W0212 try: return method(self, *args, **kwargs) except Exception: if self.exc_info: raise if not self._stack: logger.debug('@hold_exception wrapped method {0!r} called' ' from outside of the main loop'.format(method)) raise self.exc_info = sys.exc_info() logger.debug(u"exception in glib main loop callback:", exc_info = self.exc_info) # pylint: disable=W0212 main_loop = self._stack[-1] if main_loop is not None: main_loop.quit() return False return wrapper
[ "Decorator", "for", "glib", "callback", "methods", "of", "GLibMainLoop", "used", "to", "store", "the", "exception", "raised", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L36-L60
[ "def", "hold_exception", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper for methods decorated with `hold_exception`.\"\"\"", "# pylint: disable=W0703,W0212", "try", ":", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "if", "self", ".", "exc_info", ":", "raise", "if", "not", "self", ".", "_stack", ":", "logger", ".", "debug", "(", "'@hold_exception wrapped method {0!r} called'", "' from outside of the main loop'", ".", "format", "(", "method", ")", ")", "raise", "self", ".", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "logger", ".", "debug", "(", "u\"exception in glib main loop callback:\"", ",", "exc_info", "=", "self", ".", "exc_info", ")", "# pylint: disable=W0212", "main_loop", "=", "self", ".", "_stack", "[", "-", "1", "]", "if", "main_loop", "is", "not", "None", ":", "main_loop", ".", "quit", "(", ")", "return", "False", "return", "wrapper" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._configure_io_handler
Register an io-handler with the glib main loop.
pyxmpp2/mainloop/glib.py
def _configure_io_handler(self, handler): """Register an io-handler with the glib main loop.""" if self.check_events(): return if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] prepared = self._prepare_io_handler(handler) else: old_fileno = None prepared = True fileno = handler.fileno() if old_fileno is not None and fileno != old_fileno: tag = self._io_sources.pop(handler, None) if tag is not None: glib.source_remove(tag) if not prepared: self._unprepared_handlers[handler] = fileno if fileno is None: logger.debug(" {0!r}.fileno() is None, not polling" .format(handler)) return events = 0 if handler.is_readable(): logger.debug(" {0!r} readable".format(handler)) events |= glib.IO_IN | glib.IO_ERR if handler.is_writable(): logger.debug(" {0!r} writable".format(handler)) events |= glib.IO_OUT | glib.IO_HUP | glib.IO_ERR if events: logger.debug(" registering {0!r} handler fileno {1} for" " events {2}".format(handler, fileno, events)) glib.io_add_watch(fileno, events, self._io_callback, handler)
def _configure_io_handler(self, handler): """Register an io-handler with the glib main loop.""" if self.check_events(): return if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] prepared = self._prepare_io_handler(handler) else: old_fileno = None prepared = True fileno = handler.fileno() if old_fileno is not None and fileno != old_fileno: tag = self._io_sources.pop(handler, None) if tag is not None: glib.source_remove(tag) if not prepared: self._unprepared_handlers[handler] = fileno if fileno is None: logger.debug(" {0!r}.fileno() is None, not polling" .format(handler)) return events = 0 if handler.is_readable(): logger.debug(" {0!r} readable".format(handler)) events |= glib.IO_IN | glib.IO_ERR if handler.is_writable(): logger.debug(" {0!r} writable".format(handler)) events |= glib.IO_OUT | glib.IO_HUP | glib.IO_ERR if events: logger.debug(" registering {0!r} handler fileno {1} for" " events {2}".format(handler, fileno, events)) glib.io_add_watch(fileno, events, self._io_callback, handler)
[ "Register", "an", "io", "-", "handler", "with", "the", "glib", "main", "loop", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L90-L121
[ "def", "_configure_io_handler", "(", "self", ",", "handler", ")", ":", "if", "self", ".", "check_events", "(", ")", ":", "return", "if", "handler", "in", "self", ".", "_unprepared_handlers", ":", "old_fileno", "=", "self", ".", "_unprepared_handlers", "[", "handler", "]", "prepared", "=", "self", ".", "_prepare_io_handler", "(", "handler", ")", "else", ":", "old_fileno", "=", "None", "prepared", "=", "True", "fileno", "=", "handler", ".", "fileno", "(", ")", "if", "old_fileno", "is", "not", "None", "and", "fileno", "!=", "old_fileno", ":", "tag", "=", "self", ".", "_io_sources", ".", "pop", "(", "handler", ",", "None", ")", "if", "tag", "is", "not", "None", ":", "glib", ".", "source_remove", "(", "tag", ")", "if", "not", "prepared", ":", "self", ".", "_unprepared_handlers", "[", "handler", "]", "=", "fileno", "if", "fileno", "is", "None", ":", "logger", ".", "debug", "(", "\" {0!r}.fileno() is None, not polling\"", ".", "format", "(", "handler", ")", ")", "return", "events", "=", "0", "if", "handler", ".", "is_readable", "(", ")", ":", "logger", ".", "debug", "(", "\" {0!r} readable\"", ".", "format", "(", "handler", ")", ")", "events", "|=", "glib", ".", "IO_IN", "|", "glib", ".", "IO_ERR", "if", "handler", ".", "is_writable", "(", ")", ":", "logger", ".", "debug", "(", "\" {0!r} writable\"", ".", "format", "(", "handler", ")", ")", "events", "|=", "glib", ".", "IO_OUT", "|", "glib", ".", "IO_HUP", "|", "glib", ".", "IO_ERR", "if", "events", ":", "logger", ".", "debug", "(", "\" registering {0!r} handler fileno {1} for\"", "\" events {2}\"", ".", "format", "(", "handler", ",", "fileno", ",", "events", ")", ")", "glib", ".", "io_add_watch", "(", "fileno", ",", "events", ",", "self", ".", "_io_callback", ",", "handler", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._io_callback
Called by glib on I/O event.
pyxmpp2/mainloop/glib.py
def _io_callback(self, fileno, condition, handler): """Called by glib on I/O event.""" # pylint: disable=W0613 self._anything_done = True logger.debug("_io_callback called for {0!r}, cond: {1}".format(handler, condition)) try: if condition & glib.IO_HUP: handler.handle_hup() if condition & glib.IO_IN: handler.handle_read() elif condition & glib.IO_ERR: handler.handle_err() if condition & glib.IO_OUT: handler.handle_write() if self.check_events(): return False finally: self._io_sources.pop(handler, None) self._configure_io_handler(handler) self._prepare_pending() return False
def _io_callback(self, fileno, condition, handler): """Called by glib on I/O event.""" # pylint: disable=W0613 self._anything_done = True logger.debug("_io_callback called for {0!r}, cond: {1}".format(handler, condition)) try: if condition & glib.IO_HUP: handler.handle_hup() if condition & glib.IO_IN: handler.handle_read() elif condition & glib.IO_ERR: handler.handle_err() if condition & glib.IO_OUT: handler.handle_write() if self.check_events(): return False finally: self._io_sources.pop(handler, None) self._configure_io_handler(handler) self._prepare_pending() return False
[ "Called", "by", "glib", "on", "I", "/", "O", "event", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L124-L145
[ "def", "_io_callback", "(", "self", ",", "fileno", ",", "condition", ",", "handler", ")", ":", "# pylint: disable=W0613", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_io_callback called for {0!r}, cond: {1}\"", ".", "format", "(", "handler", ",", "condition", ")", ")", "try", ":", "if", "condition", "&", "glib", ".", "IO_HUP", ":", "handler", ".", "handle_hup", "(", ")", "if", "condition", "&", "glib", ".", "IO_IN", ":", "handler", ".", "handle_read", "(", ")", "elif", "condition", "&", "glib", ".", "IO_ERR", ":", "handler", ".", "handle_err", "(", ")", "if", "condition", "&", "glib", ".", "IO_OUT", ":", "handler", ".", "handle_write", "(", ")", "if", "self", ".", "check_events", "(", ")", ":", "return", "False", "finally", ":", "self", ".", "_io_sources", ".", "pop", "(", "handler", ",", "None", ")", "self", ".", "_configure_io_handler", "(", "handler", ")", "self", ".", "_prepare_pending", "(", ")", "return", "False" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._prepare_io_handler
Call the `interfaces.IOHandler.prepare` method and remove the handler from unprepared handler list when done.
pyxmpp2/mainloop/glib.py
def _prepare_io_handler(self, handler): """Call the `interfaces.IOHandler.prepare` method and remove the handler from unprepared handler list when done. """ logger.debug(" preparing handler: {0!r}".format(handler)) self._unprepared_pending.discard(handler) ret = handler.prepare() logger.debug(" prepare result: {0!r}".format(ret)) if isinstance(ret, HandlerReady): del self._unprepared_handlers[handler] prepared = True elif isinstance(ret, PrepareAgain): if ret.timeout == 0: tag = glib.idle_add(self._prepare_io_handler_cb, handler) self._prepare_sources[handler] = tag elif ret.timeout is not None: timeout = ret.timeout timeout = int(timeout * 1000) if not timeout: timeout = 1 tag = glib.timeout_add(timeout, self._prepare_io_handler_cb, handler) self._prepare_sources[handler] = tag else: self._unprepared_pending.add(handler) prepared = False else: raise TypeError("Unexpected result type from prepare()") return prepared
def _prepare_io_handler(self, handler): """Call the `interfaces.IOHandler.prepare` method and remove the handler from unprepared handler list when done. """ logger.debug(" preparing handler: {0!r}".format(handler)) self._unprepared_pending.discard(handler) ret = handler.prepare() logger.debug(" prepare result: {0!r}".format(ret)) if isinstance(ret, HandlerReady): del self._unprepared_handlers[handler] prepared = True elif isinstance(ret, PrepareAgain): if ret.timeout == 0: tag = glib.idle_add(self._prepare_io_handler_cb, handler) self._prepare_sources[handler] = tag elif ret.timeout is not None: timeout = ret.timeout timeout = int(timeout * 1000) if not timeout: timeout = 1 tag = glib.timeout_add(timeout, self._prepare_io_handler_cb, handler) self._prepare_sources[handler] = tag else: self._unprepared_pending.add(handler) prepared = False else: raise TypeError("Unexpected result type from prepare()") return prepared
[ "Call", "the", "interfaces", ".", "IOHandler", ".", "prepare", "method", "and", "remove", "the", "handler", "from", "unprepared", "handler", "list", "when", "done", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L147-L175
[ "def", "_prepare_io_handler", "(", "self", ",", "handler", ")", ":", "logger", ".", "debug", "(", "\" preparing handler: {0!r}\"", ".", "format", "(", "handler", ")", ")", "self", ".", "_unprepared_pending", ".", "discard", "(", "handler", ")", "ret", "=", "handler", ".", "prepare", "(", ")", "logger", ".", "debug", "(", "\" prepare result: {0!r}\"", ".", "format", "(", "ret", ")", ")", "if", "isinstance", "(", "ret", ",", "HandlerReady", ")", ":", "del", "self", ".", "_unprepared_handlers", "[", "handler", "]", "prepared", "=", "True", "elif", "isinstance", "(", "ret", ",", "PrepareAgain", ")", ":", "if", "ret", ".", "timeout", "==", "0", ":", "tag", "=", "glib", ".", "idle_add", "(", "self", ".", "_prepare_io_handler_cb", ",", "handler", ")", "self", ".", "_prepare_sources", "[", "handler", "]", "=", "tag", "elif", "ret", ".", "timeout", "is", "not", "None", ":", "timeout", "=", "ret", ".", "timeout", "timeout", "=", "int", "(", "timeout", "*", "1000", ")", "if", "not", "timeout", ":", "timeout", "=", "1", "tag", "=", "glib", ".", "timeout_add", "(", "timeout", ",", "self", ".", "_prepare_io_handler_cb", ",", "handler", ")", "self", ".", "_prepare_sources", "[", "handler", "]", "=", "tag", "else", ":", "self", ".", "_unprepared_pending", ".", "add", "(", "handler", ")", "prepared", "=", "False", "else", ":", "raise", "TypeError", "(", "\"Unexpected result type from prepare()\"", ")", "return", "prepared" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._prepare_pending
Prepare pending handlers.
pyxmpp2/mainloop/glib.py
def _prepare_pending(self): """Prepare pending handlers. """ if not self._unprepared_pending: return for handler in list(self._unprepared_pending): self._configure_io_handler(handler) self.check_events()
def _prepare_pending(self): """Prepare pending handlers. """ if not self._unprepared_pending: return for handler in list(self._unprepared_pending): self._configure_io_handler(handler) self.check_events()
[ "Prepare", "pending", "handlers", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L177-L184
[ "def", "_prepare_pending", "(", "self", ")", ":", "if", "not", "self", ".", "_unprepared_pending", ":", "return", "for", "handler", "in", "list", "(", "self", ".", "_unprepared_pending", ")", ":", "self", ".", "_configure_io_handler", "(", "handler", ")", "self", ".", "check_events", "(", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._prepare_io_handler_cb
Timeout callback called to try prepare an IOHandler again.
pyxmpp2/mainloop/glib.py
def _prepare_io_handler_cb(self, handler): """Timeout callback called to try prepare an IOHandler again.""" self._anything_done = True logger.debug("_prepar_io_handler_cb called for {0!r}".format(handler)) self._configure_io_handler(handler) self._prepare_sources.pop(handler, None) return False
def _prepare_io_handler_cb(self, handler): """Timeout callback called to try prepare an IOHandler again.""" self._anything_done = True logger.debug("_prepar_io_handler_cb called for {0!r}".format(handler)) self._configure_io_handler(handler) self._prepare_sources.pop(handler, None) return False
[ "Timeout", "callback", "called", "to", "try", "prepare", "an", "IOHandler", "again", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L187-L193
[ "def", "_prepare_io_handler_cb", "(", "self", ",", "handler", ")", ":", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_prepar_io_handler_cb called for {0!r}\"", ".", "format", "(", "handler", ")", ")", "self", ".", "_configure_io_handler", "(", "handler", ")", "self", ".", "_prepare_sources", ".", "pop", "(", "handler", ",", "None", ")", "return", "False" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._remove_io_handler
Remove an i/o-handler.
pyxmpp2/mainloop/glib.py
def _remove_io_handler(self, handler): """Remove an i/o-handler.""" if handler in self._unprepared_handlers: del self._unprepared_handlers[handler] tag = self._prepare_sources.pop(handler, None) if tag is not None: glib.source_remove(tag) tag = self._io_sources.pop(handler, None) if tag is not None: glib.source_remove(tag)
def _remove_io_handler(self, handler): """Remove an i/o-handler.""" if handler in self._unprepared_handlers: del self._unprepared_handlers[handler] tag = self._prepare_sources.pop(handler, None) if tag is not None: glib.source_remove(tag) tag = self._io_sources.pop(handler, None) if tag is not None: glib.source_remove(tag)
[ "Remove", "an", "i", "/", "o", "-", "handler", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L195-L204
[ "def", "_remove_io_handler", "(", "self", ",", "handler", ")", ":", "if", "handler", "in", "self", ".", "_unprepared_handlers", ":", "del", "self", ".", "_unprepared_handlers", "[", "handler", "]", "tag", "=", "self", ".", "_prepare_sources", ".", "pop", "(", "handler", ",", "None", ")", "if", "tag", "is", "not", "None", ":", "glib", ".", "source_remove", "(", "tag", ")", "tag", "=", "self", ".", "_io_sources", ".", "pop", "(", "handler", ",", "None", ")", "if", "tag", "is", "not", "None", ":", "glib", ".", "source_remove", "(", "tag", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._add_timeout_handler
Add a `TimeoutHandler` to the main loop.
pyxmpp2/mainloop/glib.py
def _add_timeout_handler(self, handler): """Add a `TimeoutHandler` to the main loop.""" # pylint: disable=W0212 for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue tag = glib.timeout_add(int(method._pyxmpp_timeout * 1000), self._timeout_cb, method) self._timer_sources[method] = tag
def _add_timeout_handler(self, handler): """Add a `TimeoutHandler` to the main loop.""" # pylint: disable=W0212 for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue tag = glib.timeout_add(int(method._pyxmpp_timeout * 1000), self._timeout_cb, method) self._timer_sources[method] = tag
[ "Add", "a", "TimeoutHandler", "to", "the", "main", "loop", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L206-L214
[ "def", "_add_timeout_handler", "(", "self", ",", "handler", ")", ":", "# pylint: disable=W0212", "for", "dummy", ",", "method", "in", "inspect", ".", "getmembers", "(", "handler", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "method", ",", "\"_pyxmpp_timeout\"", ")", ":", "continue", "tag", "=", "glib", ".", "timeout_add", "(", "int", "(", "method", ".", "_pyxmpp_timeout", "*", "1000", ")", ",", "self", ".", "_timeout_cb", ",", "method", ")", "self", ".", "_timer_sources", "[", "method", "]", "=", "tag" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._remove_timeout_handler
Remove `TimeoutHandler` from the main loop.
pyxmpp2/mainloop/glib.py
def _remove_timeout_handler(self, handler): """Remove `TimeoutHandler` from the main loop.""" for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue tag = self._timer_sources.pop(method, None) if tag is not None: glib.source_remove(tag)
def _remove_timeout_handler(self, handler): """Remove `TimeoutHandler` from the main loop.""" for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue tag = self._timer_sources.pop(method, None) if tag is not None: glib.source_remove(tag)
[ "Remove", "TimeoutHandler", "from", "the", "main", "loop", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L216-L223
[ "def", "_remove_timeout_handler", "(", "self", ",", "handler", ")", ":", "for", "dummy", ",", "method", "in", "inspect", ".", "getmembers", "(", "handler", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "method", ",", "\"_pyxmpp_timeout\"", ")", ":", "continue", "tag", "=", "self", ".", "_timer_sources", ".", "pop", "(", "method", ",", "None", ")", "if", "tag", "is", "not", "None", ":", "glib", ".", "source_remove", "(", "tag", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._timeout_cb
Call the timeout handler due.
pyxmpp2/mainloop/glib.py
def _timeout_cb(self, method): """Call the timeout handler due. """ self._anything_done = True logger.debug("_timeout_cb() called for: {0!r}".format(method)) result = method() # pylint: disable=W0212 rec = method._pyxmpp_recurring if rec: self._prepare_pending() return True if rec is None and result is not None: logger.debug(" auto-recurring, restarting in {0} s" .format(result)) tag = glib.timeout_add(int(result * 1000), self._timeout_cb, method) self._timer_sources[method] = tag else: self._timer_sources.pop(method, None) self._prepare_pending() return False
def _timeout_cb(self, method): """Call the timeout handler due. """ self._anything_done = True logger.debug("_timeout_cb() called for: {0!r}".format(method)) result = method() # pylint: disable=W0212 rec = method._pyxmpp_recurring if rec: self._prepare_pending() return True if rec is None and result is not None: logger.debug(" auto-recurring, restarting in {0} s" .format(result)) tag = glib.timeout_add(int(result * 1000), self._timeout_cb, method) self._timer_sources[method] = tag else: self._timer_sources.pop(method, None) self._prepare_pending() return False
[ "Call", "the", "timeout", "handler", "due", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L226-L246
[ "def", "_timeout_cb", "(", "self", ",", "method", ")", ":", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_timeout_cb() called for: {0!r}\"", ".", "format", "(", "method", ")", ")", "result", "=", "method", "(", ")", "# pylint: disable=W0212", "rec", "=", "method", ".", "_pyxmpp_recurring", "if", "rec", ":", "self", ".", "_prepare_pending", "(", ")", "return", "True", "if", "rec", "is", "None", "and", "result", "is", "not", "None", ":", "logger", ".", "debug", "(", "\" auto-recurring, restarting in {0} s\"", ".", "format", "(", "result", ")", ")", "tag", "=", "glib", ".", "timeout_add", "(", "int", "(", "result", "*", "1000", ")", ",", "self", ".", "_timeout_cb", ",", "method", ")", "self", ".", "_timer_sources", "[", "method", "]", "=", "tag", "else", ":", "self", ".", "_timer_sources", ".", "pop", "(", "method", ",", "None", ")", "self", ".", "_prepare_pending", "(", ")", "return", "False" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
GLibMainLoop._loop_timeout_cb
Stops the loop after the time specified in the `loop` call.
pyxmpp2/mainloop/glib.py
def _loop_timeout_cb(self, main_loop): """Stops the loop after the time specified in the `loop` call. """ self._anything_done = True logger.debug("_loop_timeout_cb() called") main_loop.quit()
def _loop_timeout_cb(self, main_loop): """Stops the loop after the time specified in the `loop` call. """ self._anything_done = True logger.debug("_loop_timeout_cb() called") main_loop.quit()
[ "Stops", "the", "loop", "after", "the", "time", "specified", "in", "the", "loop", "call", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L301-L306
[ "def", "_loop_timeout_cb", "(", "self", ",", "main_loop", ")", ":", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_loop_timeout_cb() called\"", ")", "main_loop", ".", "quit", "(", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
stanza_factory
Creates Iq, Message or Presence object for XML stanza `element` :Parameters: - `element`: the stanza XML element - `return_path`: object through which responses to this stanza should be sent (will be weakly referenced by the stanza object). - `language`: default language for the stanza :Types: - `element`: :etree:`ElementTree.Element` - `return_path`: `StanzaRoute` - `language`: `unicode`
pyxmpp2/stanzaprocessor.py
def stanza_factory(element, return_path = None, language = None): """Creates Iq, Message or Presence object for XML stanza `element` :Parameters: - `element`: the stanza XML element - `return_path`: object through which responses to this stanza should be sent (will be weakly referenced by the stanza object). - `language`: default language for the stanza :Types: - `element`: :etree:`ElementTree.Element` - `return_path`: `StanzaRoute` - `language`: `unicode` """ tag = element.tag if tag.endswith("}iq") or tag == "iq": return Iq(element, return_path = return_path, language = language) if tag.endswith("}message") or tag == "message": return Message(element, return_path = return_path, language = language) if tag.endswith("}presence") or tag == "presence": return Presence(element, return_path = return_path, language = language) else: return Stanza(element, return_path = return_path, language = language)
def stanza_factory(element, return_path = None, language = None): """Creates Iq, Message or Presence object for XML stanza `element` :Parameters: - `element`: the stanza XML element - `return_path`: object through which responses to this stanza should be sent (will be weakly referenced by the stanza object). - `language`: default language for the stanza :Types: - `element`: :etree:`ElementTree.Element` - `return_path`: `StanzaRoute` - `language`: `unicode` """ tag = element.tag if tag.endswith("}iq") or tag == "iq": return Iq(element, return_path = return_path, language = language) if tag.endswith("}message") or tag == "message": return Message(element, return_path = return_path, language = language) if tag.endswith("}presence") or tag == "presence": return Presence(element, return_path = return_path, language = language) else: return Stanza(element, return_path = return_path, language = language)
[ "Creates", "Iq", "Message", "or", "Presence", "object", "for", "XML", "stanza", "element" ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L46-L67
[ "def", "stanza_factory", "(", "element", ",", "return_path", "=", "None", ",", "language", "=", "None", ")", ":", "tag", "=", "element", ".", "tag", "if", "tag", ".", "endswith", "(", "\"}iq\"", ")", "or", "tag", "==", "\"iq\"", ":", "return", "Iq", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")", "if", "tag", ".", "endswith", "(", "\"}message\"", ")", "or", "tag", "==", "\"message\"", ":", "return", "Message", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")", "if", "tag", ".", "endswith", "(", "\"}presence\"", ")", "or", "tag", "==", "\"presence\"", ":", "return", "Presence", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")", "else", ":", "return", "Stanza", "(", "element", ",", "return_path", "=", "return_path", ",", "language", "=", "language", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor._process_handler_result
Examines out the response returned by a stanza handler and sends all stanzas provided. :Parameters: - `response`: the response to process. `None` or `False` means 'not handled'. `True` means 'handled'. Stanza or stanza list means handled with the stanzas to send back :Types: - `response`: `bool` or `Stanza` or iterable of `Stanza` :Returns: - `True`: if `response` is `Stanza`, iterable or `True` (meaning the stanza was processed). - `False`: when `response` is `False` or `None` :returntype: `bool`
pyxmpp2/stanzaprocessor.py
def _process_handler_result(self, response): """Examines out the response returned by a stanza handler and sends all stanzas provided. :Parameters: - `response`: the response to process. `None` or `False` means 'not handled'. `True` means 'handled'. Stanza or stanza list means handled with the stanzas to send back :Types: - `response`: `bool` or `Stanza` or iterable of `Stanza` :Returns: - `True`: if `response` is `Stanza`, iterable or `True` (meaning the stanza was processed). - `False`: when `response` is `False` or `None` :returntype: `bool` """ if response is None or response is False: return False if isinstance(response, Stanza): self.send(response) return True try: response = iter(response) except TypeError: return bool(response) for stanza in response: if isinstance(stanza, Stanza): self.send(stanza) else: logger.warning(u"Unexpected object in stanza handler result:" u" {0!r}".format(stanza)) return True
def _process_handler_result(self, response): """Examines out the response returned by a stanza handler and sends all stanzas provided. :Parameters: - `response`: the response to process. `None` or `False` means 'not handled'. `True` means 'handled'. Stanza or stanza list means handled with the stanzas to send back :Types: - `response`: `bool` or `Stanza` or iterable of `Stanza` :Returns: - `True`: if `response` is `Stanza`, iterable or `True` (meaning the stanza was processed). - `False`: when `response` is `False` or `None` :returntype: `bool` """ if response is None or response is False: return False if isinstance(response, Stanza): self.send(response) return True try: response = iter(response) except TypeError: return bool(response) for stanza in response: if isinstance(stanza, Stanza): self.send(stanza) else: logger.warning(u"Unexpected object in stanza handler result:" u" {0!r}".format(stanza)) return True
[ "Examines", "out", "the", "response", "returned", "by", "a", "stanza", "handler", "and", "sends", "all", "stanzas", "provided", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L106-L143
[ "def", "_process_handler_result", "(", "self", ",", "response", ")", ":", "if", "response", "is", "None", "or", "response", "is", "False", ":", "return", "False", "if", "isinstance", "(", "response", ",", "Stanza", ")", ":", "self", ".", "send", "(", "response", ")", "return", "True", "try", ":", "response", "=", "iter", "(", "response", ")", "except", "TypeError", ":", "return", "bool", "(", "response", ")", "for", "stanza", "in", "response", ":", "if", "isinstance", "(", "stanza", ",", "Stanza", ")", ":", "self", ".", "send", "(", "stanza", ")", "else", ":", "logger", ".", "warning", "(", "u\"Unexpected object in stanza handler result:\"", "u\" {0!r}\"", ".", "format", "(", "stanza", ")", ")", "return", "True" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor._process_iq_response
Process IQ stanza of type 'response' or 'error'. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set".
pyxmpp2/stanzaprocessor.py
def _process_iq_response(self, stanza): """Process IQ stanza of type 'response' or 'error'. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set". """ stanza_id = stanza.stanza_id from_jid = stanza.from_jid if from_jid: ufrom = from_jid.as_unicode() else: ufrom = None res_handler = err_handler = None try: res_handler, err_handler = self._iq_response_handlers.pop( (stanza_id, ufrom)) except KeyError: logger.debug("No response handler for id={0!r} from={1!r}" .format(stanza_id, ufrom)) logger.debug(" from_jid: {0!r} peer: {1!r} me: {2!r}" .format(from_jid, self.peer, self.me)) if ( (from_jid == self.peer or from_jid == self.me or self.me and from_jid == self.me.bare()) ): try: logger.debug(" trying id={0!r} from=None" .format(stanza_id)) res_handler, err_handler = \ self._iq_response_handlers.pop( (stanza_id, None)) except KeyError: pass if stanza.stanza_type == "result": if res_handler: response = res_handler(stanza) else: return False else: if err_handler: response = err_handler(stanza) else: return False self._process_handler_result(response) return True
def _process_iq_response(self, stanza): """Process IQ stanza of type 'response' or 'error'. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set". """ stanza_id = stanza.stanza_id from_jid = stanza.from_jid if from_jid: ufrom = from_jid.as_unicode() else: ufrom = None res_handler = err_handler = None try: res_handler, err_handler = self._iq_response_handlers.pop( (stanza_id, ufrom)) except KeyError: logger.debug("No response handler for id={0!r} from={1!r}" .format(stanza_id, ufrom)) logger.debug(" from_jid: {0!r} peer: {1!r} me: {2!r}" .format(from_jid, self.peer, self.me)) if ( (from_jid == self.peer or from_jid == self.me or self.me and from_jid == self.me.bare()) ): try: logger.debug(" trying id={0!r} from=None" .format(stanza_id)) res_handler, err_handler = \ self._iq_response_handlers.pop( (stanza_id, None)) except KeyError: pass if stanza.stanza_type == "result": if res_handler: response = res_handler(stanza) else: return False else: if err_handler: response = err_handler(stanza) else: return False self._process_handler_result(response) return True
[ "Process", "IQ", "stanza", "of", "type", "response", "or", "error", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L145-L193
[ "def", "_process_iq_response", "(", "self", ",", "stanza", ")", ":", "stanza_id", "=", "stanza", ".", "stanza_id", "from_jid", "=", "stanza", ".", "from_jid", "if", "from_jid", ":", "ufrom", "=", "from_jid", ".", "as_unicode", "(", ")", "else", ":", "ufrom", "=", "None", "res_handler", "=", "err_handler", "=", "None", "try", ":", "res_handler", ",", "err_handler", "=", "self", ".", "_iq_response_handlers", ".", "pop", "(", "(", "stanza_id", ",", "ufrom", ")", ")", "except", "KeyError", ":", "logger", ".", "debug", "(", "\"No response handler for id={0!r} from={1!r}\"", ".", "format", "(", "stanza_id", ",", "ufrom", ")", ")", "logger", ".", "debug", "(", "\" from_jid: {0!r} peer: {1!r} me: {2!r}\"", ".", "format", "(", "from_jid", ",", "self", ".", "peer", ",", "self", ".", "me", ")", ")", "if", "(", "(", "from_jid", "==", "self", ".", "peer", "or", "from_jid", "==", "self", ".", "me", "or", "self", ".", "me", "and", "from_jid", "==", "self", ".", "me", ".", "bare", "(", ")", ")", ")", ":", "try", ":", "logger", ".", "debug", "(", "\" trying id={0!r} from=None\"", ".", "format", "(", "stanza_id", ")", ")", "res_handler", ",", "err_handler", "=", "self", ".", "_iq_response_handlers", ".", "pop", "(", "(", "stanza_id", ",", "None", ")", ")", "except", "KeyError", ":", "pass", "if", "stanza", ".", "stanza_type", "==", "\"result\"", ":", "if", "res_handler", ":", "response", "=", "res_handler", "(", "stanza", ")", "else", ":", "return", "False", "else", ":", "if", "err_handler", ":", "response", "=", "err_handler", "(", "stanza", ")", "else", ":", "return", "False", "self", ".", "_process_handler_result", "(", "response", ")", "return", "True" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.process_iq
Process IQ stanza received. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set".
pyxmpp2/stanzaprocessor.py
def process_iq(self, stanza): """Process IQ stanza received. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set".""" typ = stanza.stanza_type if typ in ("result", "error"): return self._process_iq_response(stanza) if typ not in ("get", "set"): raise BadRequestProtocolError("Bad <iq/> type") logger.debug("Handling <iq type='{0}'> stanza: {1!r}".format( stanza, typ)) payload = stanza.get_payload(None) logger.debug(" payload: {0!r}".format(payload)) if not payload: raise BadRequestProtocolError("<iq/> stanza with no child element") handler = self._get_iq_handler(typ, payload) if not handler: payload = stanza.get_payload(None, specialize = True) logger.debug(" specialized payload: {0!r}".format(payload)) if not isinstance(payload, XMLPayload): handler = self._get_iq_handler(typ, payload) if handler: response = handler(stanza) self._process_handler_result(response) return True else: raise ServiceUnavailableProtocolError("Not implemented")
def process_iq(self, stanza): """Process IQ stanza received. :Parameters: - `stanza`: the stanza received :Types: - `stanza`: `Iq` If a matching handler is available pass the stanza to it. Otherwise ignore it if it is "error" or "result" stanza or return "feature-not-implemented" error if it is "get" or "set".""" typ = stanza.stanza_type if typ in ("result", "error"): return self._process_iq_response(stanza) if typ not in ("get", "set"): raise BadRequestProtocolError("Bad <iq/> type") logger.debug("Handling <iq type='{0}'> stanza: {1!r}".format( stanza, typ)) payload = stanza.get_payload(None) logger.debug(" payload: {0!r}".format(payload)) if not payload: raise BadRequestProtocolError("<iq/> stanza with no child element") handler = self._get_iq_handler(typ, payload) if not handler: payload = stanza.get_payload(None, specialize = True) logger.debug(" specialized payload: {0!r}".format(payload)) if not isinstance(payload, XMLPayload): handler = self._get_iq_handler(typ, payload) if handler: response = handler(stanza) self._process_handler_result(response) return True else: raise ServiceUnavailableProtocolError("Not implemented")
[ "Process", "IQ", "stanza", "received", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L195-L229
[ "def", "process_iq", "(", "self", ",", "stanza", ")", ":", "typ", "=", "stanza", ".", "stanza_type", "if", "typ", "in", "(", "\"result\"", ",", "\"error\"", ")", ":", "return", "self", ".", "_process_iq_response", "(", "stanza", ")", "if", "typ", "not", "in", "(", "\"get\"", ",", "\"set\"", ")", ":", "raise", "BadRequestProtocolError", "(", "\"Bad <iq/> type\"", ")", "logger", ".", "debug", "(", "\"Handling <iq type='{0}'> stanza: {1!r}\"", ".", "format", "(", "stanza", ",", "typ", ")", ")", "payload", "=", "stanza", ".", "get_payload", "(", "None", ")", "logger", ".", "debug", "(", "\" payload: {0!r}\"", ".", "format", "(", "payload", ")", ")", "if", "not", "payload", ":", "raise", "BadRequestProtocolError", "(", "\"<iq/> stanza with no child element\"", ")", "handler", "=", "self", ".", "_get_iq_handler", "(", "typ", ",", "payload", ")", "if", "not", "handler", ":", "payload", "=", "stanza", ".", "get_payload", "(", "None", ",", "specialize", "=", "True", ")", "logger", ".", "debug", "(", "\" specialized payload: {0!r}\"", ".", "format", "(", "payload", ")", ")", "if", "not", "isinstance", "(", "payload", ",", "XMLPayload", ")", ":", "handler", "=", "self", ".", "_get_iq_handler", "(", "typ", ",", "payload", ")", "if", "handler", ":", "response", "=", "handler", "(", "stanza", ")", "self", ".", "_process_handler_result", "(", "response", ")", "return", "True", "else", ":", "raise", "ServiceUnavailableProtocolError", "(", "\"Not implemented\"", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor._get_iq_handler
Get an <iq/> handler for given iq type and payload.
pyxmpp2/stanzaprocessor.py
def _get_iq_handler(self, iq_type, payload): """Get an <iq/> handler for given iq type and payload.""" key = (payload.__class__, payload.handler_key) logger.debug("looking up iq {0} handler for {1!r}, key: {2!r}" .format(iq_type, payload, key)) logger.debug("handlers: {0!r}".format(self._iq_handlers)) handler = self._iq_handlers[iq_type].get(key) return handler
def _get_iq_handler(self, iq_type, payload): """Get an <iq/> handler for given iq type and payload.""" key = (payload.__class__, payload.handler_key) logger.debug("looking up iq {0} handler for {1!r}, key: {2!r}" .format(iq_type, payload, key)) logger.debug("handlers: {0!r}".format(self._iq_handlers)) handler = self._iq_handlers[iq_type].get(key) return handler
[ "Get", "an", "<iq", "/", ">", "handler", "for", "given", "iq", "type", "and", "payload", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L231-L238
[ "def", "_get_iq_handler", "(", "self", ",", "iq_type", ",", "payload", ")", ":", "key", "=", "(", "payload", ".", "__class__", ",", "payload", ".", "handler_key", ")", "logger", ".", "debug", "(", "\"looking up iq {0} handler for {1!r}, key: {2!r}\"", ".", "format", "(", "iq_type", ",", "payload", ",", "key", ")", ")", "logger", ".", "debug", "(", "\"handlers: {0!r}\"", ".", "format", "(", "self", ".", "_iq_handlers", ")", ")", "handler", "=", "self", ".", "_iq_handlers", "[", "iq_type", "]", ".", "get", "(", "key", ")", "return", "handler" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.__try_handlers
Search the handler list for handlers matching given stanza type and payload namespace. Run the handlers found ordering them by priority until the first one which returns `True`. :Parameters: - `handler_list`: list of available handlers - `stanza`: the stanza to handle - `stanza_type`: stanza type override (value of its "type" attribute) :return: result of the last handler or `False` if no handler was found.
pyxmpp2/stanzaprocessor.py
def __try_handlers(self, handler_list, stanza, stanza_type = None): """ Search the handler list for handlers matching given stanza type and payload namespace. Run the handlers found ordering them by priority until the first one which returns `True`. :Parameters: - `handler_list`: list of available handlers - `stanza`: the stanza to handle - `stanza_type`: stanza type override (value of its "type" attribute) :return: result of the last handler or `False` if no handler was found. """ # pylint: disable=W0212 if stanza_type is None: stanza_type = stanza.stanza_type payload = stanza.get_all_payload() classes = [p.__class__ for p in payload] keys = [(p.__class__, p.handler_key) for p in payload] for handler in handler_list: type_filter = handler._pyxmpp_stanza_handled[1] class_filter = handler._pyxmpp_payload_class_handled extra_filter = handler._pyxmpp_payload_key if type_filter != stanza_type: continue if class_filter: if extra_filter is None and class_filter not in classes: continue if extra_filter and (class_filter, extra_filter) not in keys: continue response = handler(stanza) if self._process_handler_result(response): return True return False
def __try_handlers(self, handler_list, stanza, stanza_type = None): """ Search the handler list for handlers matching given stanza type and payload namespace. Run the handlers found ordering them by priority until the first one which returns `True`. :Parameters: - `handler_list`: list of available handlers - `stanza`: the stanza to handle - `stanza_type`: stanza type override (value of its "type" attribute) :return: result of the last handler or `False` if no handler was found. """ # pylint: disable=W0212 if stanza_type is None: stanza_type = stanza.stanza_type payload = stanza.get_all_payload() classes = [p.__class__ for p in payload] keys = [(p.__class__, p.handler_key) for p in payload] for handler in handler_list: type_filter = handler._pyxmpp_stanza_handled[1] class_filter = handler._pyxmpp_payload_class_handled extra_filter = handler._pyxmpp_payload_key if type_filter != stanza_type: continue if class_filter: if extra_filter is None and class_filter not in classes: continue if extra_filter and (class_filter, extra_filter) not in keys: continue response = handler(stanza) if self._process_handler_result(response): return True return False
[ "Search", "the", "handler", "list", "for", "handlers", "matching", "given", "stanza", "type", "and", "payload", "namespace", ".", "Run", "the", "handlers", "found", "ordering", "them", "by", "priority", "until", "the", "first", "one", "which", "returns", "True", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L240-L275
[ "def", "__try_handlers", "(", "self", ",", "handler_list", ",", "stanza", ",", "stanza_type", "=", "None", ")", ":", "# pylint: disable=W0212", "if", "stanza_type", "is", "None", ":", "stanza_type", "=", "stanza", ".", "stanza_type", "payload", "=", "stanza", ".", "get_all_payload", "(", ")", "classes", "=", "[", "p", ".", "__class__", "for", "p", "in", "payload", "]", "keys", "=", "[", "(", "p", ".", "__class__", ",", "p", ".", "handler_key", ")", "for", "p", "in", "payload", "]", "for", "handler", "in", "handler_list", ":", "type_filter", "=", "handler", ".", "_pyxmpp_stanza_handled", "[", "1", "]", "class_filter", "=", "handler", ".", "_pyxmpp_payload_class_handled", "extra_filter", "=", "handler", ".", "_pyxmpp_payload_key", "if", "type_filter", "!=", "stanza_type", ":", "continue", "if", "class_filter", ":", "if", "extra_filter", "is", "None", "and", "class_filter", "not", "in", "classes", ":", "continue", "if", "extra_filter", "and", "(", "class_filter", ",", "extra_filter", ")", "not", "in", "keys", ":", "continue", "response", "=", "handler", "(", "stanza", ")", "if", "self", ".", "_process_handler_result", "(", "response", ")", ":", "return", "True", "return", "False" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.process_message
Process message stanza. Pass it to a handler of the stanza's type and payload namespace. If no handler for the actual stanza type succeeds then hadlers for type "normal" are used. :Parameters: - `stanza`: message stanza to be handled
pyxmpp2/stanzaprocessor.py
def process_message(self, stanza): """Process message stanza. Pass it to a handler of the stanza's type and payload namespace. If no handler for the actual stanza type succeeds then hadlers for type "normal" are used. :Parameters: - `stanza`: message stanza to be handled """ stanza_type = stanza.stanza_type if stanza_type is None: stanza_type = "normal" if self.__try_handlers(self._message_handlers, stanza, stanza_type = stanza_type): return True if stanza_type not in ("error", "normal"): # try 'normal' handler additionaly to the regular handler return self.__try_handlers(self._message_handlers, stanza, stanza_type = "normal") return False
def process_message(self, stanza): """Process message stanza. Pass it to a handler of the stanza's type and payload namespace. If no handler for the actual stanza type succeeds then hadlers for type "normal" are used. :Parameters: - `stanza`: message stanza to be handled """ stanza_type = stanza.stanza_type if stanza_type is None: stanza_type = "normal" if self.__try_handlers(self._message_handlers, stanza, stanza_type = stanza_type): return True if stanza_type not in ("error", "normal"): # try 'normal' handler additionaly to the regular handler return self.__try_handlers(self._message_handlers, stanza, stanza_type = "normal") return False
[ "Process", "message", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L277-L300
[ "def", "process_message", "(", "self", ",", "stanza", ")", ":", "stanza_type", "=", "stanza", ".", "stanza_type", "if", "stanza_type", "is", "None", ":", "stanza_type", "=", "\"normal\"", "if", "self", ".", "__try_handlers", "(", "self", ".", "_message_handlers", ",", "stanza", ",", "stanza_type", "=", "stanza_type", ")", ":", "return", "True", "if", "stanza_type", "not", "in", "(", "\"error\"", ",", "\"normal\"", ")", ":", "# try 'normal' handler additionaly to the regular handler", "return", "self", ".", "__try_handlers", "(", "self", ".", "_message_handlers", ",", "stanza", ",", "stanza_type", "=", "\"normal\"", ")", "return", "False" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.process_presence
Process presence stanza. Pass it to a handler of the stanza's type and payload namespace. :Parameters: - `stanza`: presence stanza to be handled
pyxmpp2/stanzaprocessor.py
def process_presence(self, stanza): """Process presence stanza. Pass it to a handler of the stanza's type and payload namespace. :Parameters: - `stanza`: presence stanza to be handled """ stanza_type = stanza.stanza_type return self.__try_handlers(self._presence_handlers, stanza, stanza_type)
def process_presence(self, stanza): """Process presence stanza. Pass it to a handler of the stanza's type and payload namespace. :Parameters: - `stanza`: presence stanza to be handled """ stanza_type = stanza.stanza_type return self.__try_handlers(self._presence_handlers, stanza, stanza_type)
[ "Process", "presence", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L302-L312
[ "def", "process_presence", "(", "self", ",", "stanza", ")", ":", "stanza_type", "=", "stanza", ".", "stanza_type", "return", "self", ".", "__try_handlers", "(", "self", ".", "_presence_handlers", ",", "stanza", ",", "stanza_type", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.route_stanza
Process stanza not addressed to us. Return "recipient-unavailable" return if it is not "error" nor "result" stanza. This method should be overriden in derived classes if they are supposed to handle stanzas not addressed directly to local stream endpoint. :Parameters: - `stanza`: presence stanza to be processed
pyxmpp2/stanzaprocessor.py
def route_stanza(self, stanza): """Process stanza not addressed to us. Return "recipient-unavailable" return if it is not "error" nor "result" stanza. This method should be overriden in derived classes if they are supposed to handle stanzas not addressed directly to local stream endpoint. :Parameters: - `stanza`: presence stanza to be processed """ if stanza.stanza_type not in ("error", "result"): response = stanza.make_error_response(u"recipient-unavailable") self.send(response) return True
def route_stanza(self, stanza): """Process stanza not addressed to us. Return "recipient-unavailable" return if it is not "error" nor "result" stanza. This method should be overriden in derived classes if they are supposed to handle stanzas not addressed directly to local stream endpoint. :Parameters: - `stanza`: presence stanza to be processed """ if stanza.stanza_type not in ("error", "result"): response = stanza.make_error_response(u"recipient-unavailable") self.send(response) return True
[ "Process", "stanza", "not", "addressed", "to", "us", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L314-L330
[ "def", "route_stanza", "(", "self", ",", "stanza", ")", ":", "if", "stanza", ".", "stanza_type", "not", "in", "(", "\"error\"", ",", "\"result\"", ")", ":", "response", "=", "stanza", ".", "make_error_response", "(", "u\"recipient-unavailable\"", ")", "self", ".", "send", "(", "response", ")", "return", "True" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.process_stanza
Process stanza received from the stream. First "fix" the stanza with `self.fix_in_stanza()`, then pass it to `self.route_stanza()` if it is not directed to `self.me` and `self.process_all_stanzas` is not True. Otherwise stanza is passwd to `self.process_iq()`, `self.process_message()` or `self.process_presence()` appropriately. :Parameters: - `stanza`: the stanza received. :returns: `True` when stanza was handled
pyxmpp2/stanzaprocessor.py
def process_stanza(self, stanza): """Process stanza received from the stream. First "fix" the stanza with `self.fix_in_stanza()`, then pass it to `self.route_stanza()` if it is not directed to `self.me` and `self.process_all_stanzas` is not True. Otherwise stanza is passwd to `self.process_iq()`, `self.process_message()` or `self.process_presence()` appropriately. :Parameters: - `stanza`: the stanza received. :returns: `True` when stanza was handled """ self.fix_in_stanza(stanza) to_jid = stanza.to_jid if not self.process_all_stanzas and to_jid and ( to_jid != self.me and to_jid.bare() != self.me.bare()): return self.route_stanza(stanza) try: if isinstance(stanza, Iq): if self.process_iq(stanza): return True elif isinstance(stanza, Message): if self.process_message(stanza): return True elif isinstance(stanza, Presence): if self.process_presence(stanza): return True except ProtocolError, err: typ = stanza.stanza_type if typ != 'error' and (typ != 'result' or stanza.stanza_type != 'iq'): response = stanza.make_error_response(err.xmpp_name) self.send(response) err.log_reported() else: err.log_ignored() return logger.debug("Unhandled %r stanza: %r" % (stanza.stanza_type, stanza.serialize())) return False
def process_stanza(self, stanza): """Process stanza received from the stream. First "fix" the stanza with `self.fix_in_stanza()`, then pass it to `self.route_stanza()` if it is not directed to `self.me` and `self.process_all_stanzas` is not True. Otherwise stanza is passwd to `self.process_iq()`, `self.process_message()` or `self.process_presence()` appropriately. :Parameters: - `stanza`: the stanza received. :returns: `True` when stanza was handled """ self.fix_in_stanza(stanza) to_jid = stanza.to_jid if not self.process_all_stanzas and to_jid and ( to_jid != self.me and to_jid.bare() != self.me.bare()): return self.route_stanza(stanza) try: if isinstance(stanza, Iq): if self.process_iq(stanza): return True elif isinstance(stanza, Message): if self.process_message(stanza): return True elif isinstance(stanza, Presence): if self.process_presence(stanza): return True except ProtocolError, err: typ = stanza.stanza_type if typ != 'error' and (typ != 'result' or stanza.stanza_type != 'iq'): response = stanza.make_error_response(err.xmpp_name) self.send(response) err.log_reported() else: err.log_ignored() return logger.debug("Unhandled %r stanza: %r" % (stanza.stanza_type, stanza.serialize())) return False
[ "Process", "stanza", "received", "from", "the", "stream", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L332-L376
[ "def", "process_stanza", "(", "self", ",", "stanza", ")", ":", "self", ".", "fix_in_stanza", "(", "stanza", ")", "to_jid", "=", "stanza", ".", "to_jid", "if", "not", "self", ".", "process_all_stanzas", "and", "to_jid", "and", "(", "to_jid", "!=", "self", ".", "me", "and", "to_jid", ".", "bare", "(", ")", "!=", "self", ".", "me", ".", "bare", "(", ")", ")", ":", "return", "self", ".", "route_stanza", "(", "stanza", ")", "try", ":", "if", "isinstance", "(", "stanza", ",", "Iq", ")", ":", "if", "self", ".", "process_iq", "(", "stanza", ")", ":", "return", "True", "elif", "isinstance", "(", "stanza", ",", "Message", ")", ":", "if", "self", ".", "process_message", "(", "stanza", ")", ":", "return", "True", "elif", "isinstance", "(", "stanza", ",", "Presence", ")", ":", "if", "self", ".", "process_presence", "(", "stanza", ")", ":", "return", "True", "except", "ProtocolError", ",", "err", ":", "typ", "=", "stanza", ".", "stanza_type", "if", "typ", "!=", "'error'", "and", "(", "typ", "!=", "'result'", "or", "stanza", ".", "stanza_type", "!=", "'iq'", ")", ":", "response", "=", "stanza", ".", "make_error_response", "(", "err", ".", "xmpp_name", ")", "self", ".", "send", "(", "response", ")", "err", ".", "log_reported", "(", ")", "else", ":", "err", ".", "log_ignored", "(", ")", "return", "logger", ".", "debug", "(", "\"Unhandled %r stanza: %r\"", "%", "(", "stanza", ".", "stanza_type", ",", "stanza", ".", "serialize", "(", ")", ")", ")", "return", "False" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.set_response_handlers
Set response handler for an IQ "get" or "set" stanza. This should be called before the stanza is sent. :Parameters: - `stanza`: an IQ stanza - `res_handler`: result handler for the stanza. Will be called when matching <iq type="result"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response. - `err_handler`: error handler for the stanza. Will be called when matching <iq type="error"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response but this feature should rather not be used (it is better not to respond to 'error' stanzas). - `timeout_handler`: timeout handler for the stanza. Will be called (with no arguments) when no matching <iq type="result"/> or <iq type="error"/> is received in next `timeout` seconds. - `timeout`: timeout value for the stanza. After that time if no matching <iq type="result"/> nor <iq type="error"/> stanza is received, then timeout_handler (if given) will be called.
pyxmpp2/stanzaprocessor.py
def set_response_handlers(self, stanza, res_handler, err_handler, timeout_handler = None, timeout = None): """Set response handler for an IQ "get" or "set" stanza. This should be called before the stanza is sent. :Parameters: - `stanza`: an IQ stanza - `res_handler`: result handler for the stanza. Will be called when matching <iq type="result"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response. - `err_handler`: error handler for the stanza. Will be called when matching <iq type="error"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response but this feature should rather not be used (it is better not to respond to 'error' stanzas). - `timeout_handler`: timeout handler for the stanza. Will be called (with no arguments) when no matching <iq type="result"/> or <iq type="error"/> is received in next `timeout` seconds. - `timeout`: timeout value for the stanza. After that time if no matching <iq type="result"/> nor <iq type="error"/> stanza is received, then timeout_handler (if given) will be called. """ # pylint: disable-msg=R0913 self.lock.acquire() try: self._set_response_handlers(stanza, res_handler, err_handler, timeout_handler, timeout) finally: self.lock.release()
def set_response_handlers(self, stanza, res_handler, err_handler, timeout_handler = None, timeout = None): """Set response handler for an IQ "get" or "set" stanza. This should be called before the stanza is sent. :Parameters: - `stanza`: an IQ stanza - `res_handler`: result handler for the stanza. Will be called when matching <iq type="result"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response. - `err_handler`: error handler for the stanza. Will be called when matching <iq type="error"/> is received. Its only argument will be the stanza received. The handler may return a stanza or list of stanzas which should be sent in response but this feature should rather not be used (it is better not to respond to 'error' stanzas). - `timeout_handler`: timeout handler for the stanza. Will be called (with no arguments) when no matching <iq type="result"/> or <iq type="error"/> is received in next `timeout` seconds. - `timeout`: timeout value for the stanza. After that time if no matching <iq type="result"/> nor <iq type="error"/> stanza is received, then timeout_handler (if given) will be called. """ # pylint: disable-msg=R0913 self.lock.acquire() try: self._set_response_handlers(stanza, res_handler, err_handler, timeout_handler, timeout) finally: self.lock.release()
[ "Set", "response", "handler", "for", "an", "IQ", "get", "or", "set", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L389-L420
[ "def", "set_response_handlers", "(", "self", ",", "stanza", ",", "res_handler", ",", "err_handler", ",", "timeout_handler", "=", "None", ",", "timeout", "=", "None", ")", ":", "# pylint: disable-msg=R0913", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_set_response_handlers", "(", "stanza", ",", "res_handler", ",", "err_handler", ",", "timeout_handler", ",", "timeout", ")", "finally", ":", "self", ".", "lock", ".", "release", "(", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor._set_response_handlers
Same as `set_response_handlers` but assume `self.lock` is acquired.
pyxmpp2/stanzaprocessor.py
def _set_response_handlers(self, stanza, res_handler, err_handler, timeout_handler = None, timeout = None): """Same as `set_response_handlers` but assume `self.lock` is acquired.""" # pylint: disable-msg=R0913 self.fix_out_stanza(stanza) to_jid = stanza.to_jid if to_jid: to_jid = unicode(to_jid) if timeout_handler: def callback(dummy1, dummy2): """Wrapper for the timeout handler to make it compatible with the `ExpiringDictionary` """ timeout_handler() self._iq_response_handlers.set_item( (stanza.stanza_id, to_jid), (res_handler,err_handler), timeout, callback) else: self._iq_response_handlers.set_item( (stanza.stanza_id, to_jid), (res_handler, err_handler), timeout)
def _set_response_handlers(self, stanza, res_handler, err_handler, timeout_handler = None, timeout = None): """Same as `set_response_handlers` but assume `self.lock` is acquired.""" # pylint: disable-msg=R0913 self.fix_out_stanza(stanza) to_jid = stanza.to_jid if to_jid: to_jid = unicode(to_jid) if timeout_handler: def callback(dummy1, dummy2): """Wrapper for the timeout handler to make it compatible with the `ExpiringDictionary` """ timeout_handler() self._iq_response_handlers.set_item( (stanza.stanza_id, to_jid), (res_handler,err_handler), timeout, callback) else: self._iq_response_handlers.set_item( (stanza.stanza_id, to_jid), (res_handler, err_handler), timeout)
[ "Same", "as", "set_response_handlers", "but", "assume", "self", ".", "lock", "is", "acquired", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L422-L444
[ "def", "_set_response_handlers", "(", "self", ",", "stanza", ",", "res_handler", ",", "err_handler", ",", "timeout_handler", "=", "None", ",", "timeout", "=", "None", ")", ":", "# pylint: disable-msg=R0913", "self", ".", "fix_out_stanza", "(", "stanza", ")", "to_jid", "=", "stanza", ".", "to_jid", "if", "to_jid", ":", "to_jid", "=", "unicode", "(", "to_jid", ")", "if", "timeout_handler", ":", "def", "callback", "(", "dummy1", ",", "dummy2", ")", ":", "\"\"\"Wrapper for the timeout handler to make it compatible\n with the `ExpiringDictionary` \"\"\"", "timeout_handler", "(", ")", "self", ".", "_iq_response_handlers", ".", "set_item", "(", "(", "stanza", ".", "stanza_id", ",", "to_jid", ")", ",", "(", "res_handler", ",", "err_handler", ")", ",", "timeout", ",", "callback", ")", "else", ":", "self", ".", "_iq_response_handlers", ".", "set_item", "(", "(", "stanza", ".", "stanza_id", ",", "to_jid", ")", ",", "(", "res_handler", ",", "err_handler", ")", ",", "timeout", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.setup_stanza_handlers
Install stanza handlers provided by `handler_objects`
pyxmpp2/stanzaprocessor.py
def setup_stanza_handlers(self, handler_objects, usage_restriction): """Install stanza handlers provided by `handler_objects`""" # pylint: disable=W0212 iq_handlers = {"get": {}, "set": {}} message_handlers = [] presence_handlers = [] for obj in handler_objects: if not isinstance(obj, XMPPFeatureHandler): continue obj.stanza_processor = self for dummy, handler in inspect.getmembers(obj, callable): if not hasattr(handler, "_pyxmpp_stanza_handled"): continue element_name, stanza_type = handler._pyxmpp_stanza_handled restr = handler._pyxmpp_usage_restriction if restr and restr != usage_restriction: continue if element_name == "iq": payload_class = handler._pyxmpp_payload_class_handled payload_key = handler._pyxmpp_payload_key if (payload_class, payload_key) in iq_handlers[stanza_type]: continue iq_handlers[stanza_type][(payload_class, payload_key)] = \ handler continue elif element_name == "message": handler_list = message_handlers elif element_name == "presence": handler_list = presence_handlers else: raise ValueError, "Bad handler decoration" handler_list.append(handler) with self.lock: self._iq_handlers = iq_handlers self._presence_handlers = presence_handlers self._message_handlers = message_handlers
def setup_stanza_handlers(self, handler_objects, usage_restriction): """Install stanza handlers provided by `handler_objects`""" # pylint: disable=W0212 iq_handlers = {"get": {}, "set": {}} message_handlers = [] presence_handlers = [] for obj in handler_objects: if not isinstance(obj, XMPPFeatureHandler): continue obj.stanza_processor = self for dummy, handler in inspect.getmembers(obj, callable): if not hasattr(handler, "_pyxmpp_stanza_handled"): continue element_name, stanza_type = handler._pyxmpp_stanza_handled restr = handler._pyxmpp_usage_restriction if restr and restr != usage_restriction: continue if element_name == "iq": payload_class = handler._pyxmpp_payload_class_handled payload_key = handler._pyxmpp_payload_key if (payload_class, payload_key) in iq_handlers[stanza_type]: continue iq_handlers[stanza_type][(payload_class, payload_key)] = \ handler continue elif element_name == "message": handler_list = message_handlers elif element_name == "presence": handler_list = presence_handlers else: raise ValueError, "Bad handler decoration" handler_list.append(handler) with self.lock: self._iq_handlers = iq_handlers self._presence_handlers = presence_handlers self._message_handlers = message_handlers
[ "Install", "stanza", "handlers", "provided", "by", "handler_objects" ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L450-L485
[ "def", "setup_stanza_handlers", "(", "self", ",", "handler_objects", ",", "usage_restriction", ")", ":", "# pylint: disable=W0212", "iq_handlers", "=", "{", "\"get\"", ":", "{", "}", ",", "\"set\"", ":", "{", "}", "}", "message_handlers", "=", "[", "]", "presence_handlers", "=", "[", "]", "for", "obj", "in", "handler_objects", ":", "if", "not", "isinstance", "(", "obj", ",", "XMPPFeatureHandler", ")", ":", "continue", "obj", ".", "stanza_processor", "=", "self", "for", "dummy", ",", "handler", "in", "inspect", ".", "getmembers", "(", "obj", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "handler", ",", "\"_pyxmpp_stanza_handled\"", ")", ":", "continue", "element_name", ",", "stanza_type", "=", "handler", ".", "_pyxmpp_stanza_handled", "restr", "=", "handler", ".", "_pyxmpp_usage_restriction", "if", "restr", "and", "restr", "!=", "usage_restriction", ":", "continue", "if", "element_name", "==", "\"iq\"", ":", "payload_class", "=", "handler", ".", "_pyxmpp_payload_class_handled", "payload_key", "=", "handler", ".", "_pyxmpp_payload_key", "if", "(", "payload_class", ",", "payload_key", ")", "in", "iq_handlers", "[", "stanza_type", "]", ":", "continue", "iq_handlers", "[", "stanza_type", "]", "[", "(", "payload_class", ",", "payload_key", ")", "]", "=", "handler", "continue", "elif", "element_name", "==", "\"message\"", ":", "handler_list", "=", "message_handlers", "elif", "element_name", "==", "\"presence\"", ":", "handler_list", "=", "presence_handlers", "else", ":", "raise", "ValueError", ",", "\"Bad handler decoration\"", "handler_list", ".", "append", "(", "handler", ")", "with", "self", ".", "lock", ":", "self", ".", "_iq_handlers", "=", "iq_handlers", "self", ".", "_presence_handlers", "=", "presence_handlers", "self", ".", "_message_handlers", "=", "message_handlers" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
StanzaProcessor.send
Send a stanza somwhere. The default implementation sends it via the `uplink` if it is defined or raises the `NoRouteError`. :Parameters: - `stanza`: the stanza to send. :Types: - `stanza`: `pyxmpp.stanza.Stanza`
pyxmpp2/stanzaprocessor.py
def send(self, stanza): """Send a stanza somwhere. The default implementation sends it via the `uplink` if it is defined or raises the `NoRouteError`. :Parameters: - `stanza`: the stanza to send. :Types: - `stanza`: `pyxmpp.stanza.Stanza`""" if self.uplink: self.uplink.send(stanza) else: raise NoRouteError("No route for stanza")
def send(self, stanza): """Send a stanza somwhere. The default implementation sends it via the `uplink` if it is defined or raises the `NoRouteError`. :Parameters: - `stanza`: the stanza to send. :Types: - `stanza`: `pyxmpp.stanza.Stanza`""" if self.uplink: self.uplink.send(stanza) else: raise NoRouteError("No route for stanza")
[ "Send", "a", "stanza", "somwhere", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzaprocessor.py#L504-L517
[ "def", "send", "(", "self", ",", "stanza", ")", ":", "if", "self", ".", "uplink", ":", "self", ".", "uplink", ".", "send", "(", "stanza", ")", "else", ":", "raise", "NoRouteError", "(", "\"No route for stanza\"", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MainLoopBase.check_events
Call the event dispatcher. Quit the main loop when the `QUIT` event is reached. :Return: `True` if `QUIT` was reached.
pyxmpp2/mainloop/base.py
def check_events(self): """Call the event dispatcher. Quit the main loop when the `QUIT` event is reached. :Return: `True` if `QUIT` was reached. """ if self.event_dispatcher.flush() is QUIT: self._quit = True return True return False
def check_events(self): """Call the event dispatcher. Quit the main loop when the `QUIT` event is reached. :Return: `True` if `QUIT` was reached. """ if self.event_dispatcher.flush() is QUIT: self._quit = True return True return False
[ "Call", "the", "event", "dispatcher", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/base.py#L95-L105
[ "def", "check_events", "(", "self", ")", ":", "if", "self", ".", "event_dispatcher", ".", "flush", "(", ")", "is", "QUIT", ":", "self", ".", "_quit", "=", "True", "return", "True", "return", "False" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MainLoopBase._add_timeout_handler
Add a `TimeoutHandler` to the main loop.
pyxmpp2/mainloop/base.py
def _add_timeout_handler(self, handler): """Add a `TimeoutHandler` to the main loop.""" # pylint: disable-msg=W0212 now = time.time() for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue self._timeout_handlers.append((now + method._pyxmpp_timeout, method)) self._timeout_handlers.sort(key = lambda x: x[0])
def _add_timeout_handler(self, handler): """Add a `TimeoutHandler` to the main loop.""" # pylint: disable-msg=W0212 now = time.time() for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue self._timeout_handlers.append((now + method._pyxmpp_timeout, method)) self._timeout_handlers.sort(key = lambda x: x[0])
[ "Add", "a", "TimeoutHandler", "to", "the", "main", "loop", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/base.py#L107-L116
[ "def", "_add_timeout_handler", "(", "self", ",", "handler", ")", ":", "# pylint: disable-msg=W0212", "now", "=", "time", ".", "time", "(", ")", "for", "dummy", ",", "method", "in", "inspect", ".", "getmembers", "(", "handler", ",", "callable", ")", ":", "if", "not", "hasattr", "(", "method", ",", "\"_pyxmpp_timeout\"", ")", ":", "continue", "self", ".", "_timeout_handlers", ".", "append", "(", "(", "now", "+", "method", ".", "_pyxmpp_timeout", ",", "method", ")", ")", "self", ".", "_timeout_handlers", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MainLoopBase._remove_timeout_handler
Remove `TimeoutHandler` from the main loop.
pyxmpp2/mainloop/base.py
def _remove_timeout_handler(self, handler): """Remove `TimeoutHandler` from the main loop.""" self._timeout_handlers = [(t, h) for (t, h) in self._timeout_handlers if h.im_self != handler]
def _remove_timeout_handler(self, handler): """Remove `TimeoutHandler` from the main loop.""" self._timeout_handlers = [(t, h) for (t, h) in self._timeout_handlers if h.im_self != handler]
[ "Remove", "TimeoutHandler", "from", "the", "main", "loop", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/base.py#L118-L122
[ "def", "_remove_timeout_handler", "(", "self", ",", "handler", ")", ":", "self", ".", "_timeout_handlers", "=", "[", "(", "t", ",", "h", ")", "for", "(", "t", ",", "h", ")", "in", "self", ".", "_timeout_handlers", "if", "h", ".", "im_self", "!=", "handler", "]" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
MainLoopBase._call_timeout_handlers
Call the timeout handlers due. :Return: (next_event_timeout, sources_handled) tuple. next_event_timeout is number of seconds until the next timeout event, sources_handled is number of handlers called.
pyxmpp2/mainloop/base.py
def _call_timeout_handlers(self): """Call the timeout handlers due. :Return: (next_event_timeout, sources_handled) tuple. next_event_timeout is number of seconds until the next timeout event, sources_handled is number of handlers called. """ sources_handled = 0 now = time.time() schedule = None while self._timeout_handlers: schedule, handler = self._timeout_handlers[0] if schedule <= now: # pylint: disable-msg=W0212 logger.debug("About to call a timeout handler: {0!r}" .format(handler)) self._timeout_handlers = self._timeout_handlers[1:] result = handler() logger.debug(" handler result: {0!r}".format(result)) rec = handler._pyxmpp_recurring if rec: logger.debug(" recurring, restarting in {0} s" .format(handler._pyxmpp_timeout)) self._timeout_handlers.append( (now + handler._pyxmpp_timeout, handler)) self._timeout_handlers.sort(key = lambda x: x[0]) elif rec is None and result is not None: logger.debug(" auto-recurring, restarting in {0} s" .format(result)) self._timeout_handlers.append((now + result, handler)) self._timeout_handlers.sort(key = lambda x: x[0]) sources_handled += 1 else: break if self.check_events(): return 0, sources_handled if self._timeout_handlers and schedule: timeout = schedule - now else: timeout = None return timeout, sources_handled
def _call_timeout_handlers(self): """Call the timeout handlers due. :Return: (next_event_timeout, sources_handled) tuple. next_event_timeout is number of seconds until the next timeout event, sources_handled is number of handlers called. """ sources_handled = 0 now = time.time() schedule = None while self._timeout_handlers: schedule, handler = self._timeout_handlers[0] if schedule <= now: # pylint: disable-msg=W0212 logger.debug("About to call a timeout handler: {0!r}" .format(handler)) self._timeout_handlers = self._timeout_handlers[1:] result = handler() logger.debug(" handler result: {0!r}".format(result)) rec = handler._pyxmpp_recurring if rec: logger.debug(" recurring, restarting in {0} s" .format(handler._pyxmpp_timeout)) self._timeout_handlers.append( (now + handler._pyxmpp_timeout, handler)) self._timeout_handlers.sort(key = lambda x: x[0]) elif rec is None and result is not None: logger.debug(" auto-recurring, restarting in {0} s" .format(result)) self._timeout_handlers.append((now + result, handler)) self._timeout_handlers.sort(key = lambda x: x[0]) sources_handled += 1 else: break if self.check_events(): return 0, sources_handled if self._timeout_handlers and schedule: timeout = schedule - now else: timeout = None return timeout, sources_handled
[ "Call", "the", "timeout", "handlers", "due", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/base.py#L124-L164
[ "def", "_call_timeout_handlers", "(", "self", ")", ":", "sources_handled", "=", "0", "now", "=", "time", ".", "time", "(", ")", "schedule", "=", "None", "while", "self", ".", "_timeout_handlers", ":", "schedule", ",", "handler", "=", "self", ".", "_timeout_handlers", "[", "0", "]", "if", "schedule", "<=", "now", ":", "# pylint: disable-msg=W0212", "logger", ".", "debug", "(", "\"About to call a timeout handler: {0!r}\"", ".", "format", "(", "handler", ")", ")", "self", ".", "_timeout_handlers", "=", "self", ".", "_timeout_handlers", "[", "1", ":", "]", "result", "=", "handler", "(", ")", "logger", ".", "debug", "(", "\" handler result: {0!r}\"", ".", "format", "(", "result", ")", ")", "rec", "=", "handler", ".", "_pyxmpp_recurring", "if", "rec", ":", "logger", ".", "debug", "(", "\" recurring, restarting in {0} s\"", ".", "format", "(", "handler", ".", "_pyxmpp_timeout", ")", ")", "self", ".", "_timeout_handlers", ".", "append", "(", "(", "now", "+", "handler", ".", "_pyxmpp_timeout", ",", "handler", ")", ")", "self", ".", "_timeout_handlers", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "elif", "rec", "is", "None", "and", "result", "is", "not", "None", ":", "logger", ".", "debug", "(", "\" auto-recurring, restarting in {0} s\"", ".", "format", "(", "result", ")", ")", "self", ".", "_timeout_handlers", ".", "append", "(", "(", "now", "+", "result", ",", "handler", ")", ")", "self", ".", "_timeout_handlers", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "sources_handled", "+=", "1", "else", ":", "break", "if", "self", ".", "check_events", "(", ")", ":", "return", "0", ",", "sources_handled", "if", "self", ".", "_timeout_handlers", "and", "schedule", ":", "timeout", "=", "schedule", "-", "now", "else", ":", "timeout", "=", "None", "return", "timeout", ",", "sources_handled" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
xml_elements_equal
Check if two XML elements are equal. :Parameters: - `element1`: the first element to compare - `element2`: the other element to compare - `ignore_level1_cdata`: if direct text children of the elements should be ignored for the comparision :Types: - `element1`: :etree:`ElementTree.Element` - `element2`: :etree:`ElementTree.Element` - `ignore_level1_cdata`: `bool` :Returntype: `bool`
pyxmpp2/utils.py
def xml_elements_equal(element1, element2, ignore_level1_cdata = False): """Check if two XML elements are equal. :Parameters: - `element1`: the first element to compare - `element2`: the other element to compare - `ignore_level1_cdata`: if direct text children of the elements should be ignored for the comparision :Types: - `element1`: :etree:`ElementTree.Element` - `element2`: :etree:`ElementTree.Element` - `ignore_level1_cdata`: `bool` :Returntype: `bool` """ # pylint: disable-msg=R0911 if None in (element1, element2) or element1.tag != element2.tag: return False attrs1 = element1.items() attrs1.sort() attrs2 = element2.items() attrs2.sort() if not ignore_level1_cdata: if element1.text != element2.text: return False if attrs1 != attrs2: return False if len(element1) != len(element2): return False for child1, child2 in zip(element1, element2): if child1.tag != child2.tag: return False if not ignore_level1_cdata: if element1.text != element2.text: return False if not xml_elements_equal(child1, child2): return False return True
def xml_elements_equal(element1, element2, ignore_level1_cdata = False): """Check if two XML elements are equal. :Parameters: - `element1`: the first element to compare - `element2`: the other element to compare - `ignore_level1_cdata`: if direct text children of the elements should be ignored for the comparision :Types: - `element1`: :etree:`ElementTree.Element` - `element2`: :etree:`ElementTree.Element` - `ignore_level1_cdata`: `bool` :Returntype: `bool` """ # pylint: disable-msg=R0911 if None in (element1, element2) or element1.tag != element2.tag: return False attrs1 = element1.items() attrs1.sort() attrs2 = element2.items() attrs2.sort() if not ignore_level1_cdata: if element1.text != element2.text: return False if attrs1 != attrs2: return False if len(element1) != len(element2): return False for child1, child2 in zip(element1, element2): if child1.tag != child2.tag: return False if not ignore_level1_cdata: if element1.text != element2.text: return False if not xml_elements_equal(child1, child2): return False return True
[ "Check", "if", "two", "XML", "elements", "are", "equal", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/utils.py#L24-L64
[ "def", "xml_elements_equal", "(", "element1", ",", "element2", ",", "ignore_level1_cdata", "=", "False", ")", ":", "# pylint: disable-msg=R0911", "if", "None", "in", "(", "element1", ",", "element2", ")", "or", "element1", ".", "tag", "!=", "element2", ".", "tag", ":", "return", "False", "attrs1", "=", "element1", ".", "items", "(", ")", "attrs1", ".", "sort", "(", ")", "attrs2", "=", "element2", ".", "items", "(", ")", "attrs2", ".", "sort", "(", ")", "if", "not", "ignore_level1_cdata", ":", "if", "element1", ".", "text", "!=", "element2", ".", "text", ":", "return", "False", "if", "attrs1", "!=", "attrs2", ":", "return", "False", "if", "len", "(", "element1", ")", "!=", "len", "(", "element2", ")", ":", "return", "False", "for", "child1", ",", "child2", "in", "zip", "(", "element1", ",", "element2", ")", ":", "if", "child1", ".", "tag", "!=", "child2", ".", "tag", ":", "return", "False", "if", "not", "ignore_level1_cdata", ":", "if", "element1", ".", "text", "!=", "element2", ".", "text", ":", "return", "False", "if", "not", "xml_elements_equal", "(", "child1", ",", "child2", ")", ":", "return", "False", "return", "True" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
datetime_utc_to_local
An ugly hack to convert naive :std:`datetime.datetime` object containing UTC time to a naive :std:`datetime.datetime` object with local time. It seems standard Python 2.3 library doesn't provide any better way to do that.
pyxmpp2/utils.py
def datetime_utc_to_local(utc): """ An ugly hack to convert naive :std:`datetime.datetime` object containing UTC time to a naive :std:`datetime.datetime` object with local time. It seems standard Python 2.3 library doesn't provide any better way to do that. """ # pylint: disable-msg=C0103 ts = time.time() cur = datetime.datetime.fromtimestamp(ts) cur_utc = datetime.datetime.utcfromtimestamp(ts) offset = cur - cur_utc t = utc d = datetime.timedelta(hours = 2) while d > _MINUTE: local = t + offset tm = local.timetuple() tm = tm[0:8] + (0, ) ts = time.mktime(tm) u = datetime.datetime.utcfromtimestamp(ts) diff = u - utc if diff < _MINUTE and diff > -_MINUTE: break if diff > _NULLDELTA: offset -= d else: offset += d d //= 2 return local
def datetime_utc_to_local(utc): """ An ugly hack to convert naive :std:`datetime.datetime` object containing UTC time to a naive :std:`datetime.datetime` object with local time. It seems standard Python 2.3 library doesn't provide any better way to do that. """ # pylint: disable-msg=C0103 ts = time.time() cur = datetime.datetime.fromtimestamp(ts) cur_utc = datetime.datetime.utcfromtimestamp(ts) offset = cur - cur_utc t = utc d = datetime.timedelta(hours = 2) while d > _MINUTE: local = t + offset tm = local.timetuple() tm = tm[0:8] + (0, ) ts = time.mktime(tm) u = datetime.datetime.utcfromtimestamp(ts) diff = u - utc if diff < _MINUTE and diff > -_MINUTE: break if diff > _NULLDELTA: offset -= d else: offset += d d //= 2 return local
[ "An", "ugly", "hack", "to", "convert", "naive", ":", "std", ":", "datetime", ".", "datetime", "object", "containing", "UTC", "time", "to", "a", "naive", ":", "std", ":", "datetime", ".", "datetime", "object", "with", "local", "time", ".", "It", "seems", "standard", "Python", "2", ".", "3", "library", "doesn", "t", "provide", "any", "better", "way", "to", "do", "that", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/utils.py#L72-L102
[ "def", "datetime_utc_to_local", "(", "utc", ")", ":", "# pylint: disable-msg=C0103", "ts", "=", "time", ".", "time", "(", ")", "cur", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "ts", ")", "cur_utc", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "ts", ")", "offset", "=", "cur", "-", "cur_utc", "t", "=", "utc", "d", "=", "datetime", ".", "timedelta", "(", "hours", "=", "2", ")", "while", "d", ">", "_MINUTE", ":", "local", "=", "t", "+", "offset", "tm", "=", "local", ".", "timetuple", "(", ")", "tm", "=", "tm", "[", "0", ":", "8", "]", "+", "(", "0", ",", ")", "ts", "=", "time", ".", "mktime", "(", "tm", ")", "u", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "ts", ")", "diff", "=", "u", "-", "utc", "if", "diff", "<", "_MINUTE", "and", "diff", ">", "-", "_MINUTE", ":", "break", "if", "diff", ">", "_NULLDELTA", ":", "offset", "-=", "d", "else", ":", "offset", "+=", "d", "d", "//=", "2", "return", "local" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
datetime_local_to_utc
Simple function to convert naive :std:`datetime.datetime` object containing local time to a naive :std:`datetime.datetime` object with UTC time.
pyxmpp2/utils.py
def datetime_local_to_utc(local): """ Simple function to convert naive :std:`datetime.datetime` object containing local time to a naive :std:`datetime.datetime` object with UTC time. """ timestamp = time.mktime(local.timetuple()) return datetime.datetime.utcfromtimestamp(timestamp)
def datetime_local_to_utc(local): """ Simple function to convert naive :std:`datetime.datetime` object containing local time to a naive :std:`datetime.datetime` object with UTC time. """ timestamp = time.mktime(local.timetuple()) return datetime.datetime.utcfromtimestamp(timestamp)
[ "Simple", "function", "to", "convert", "naive", ":", "std", ":", "datetime", ".", "datetime", "object", "containing", "local", "time", "to", "a", "naive", ":", "std", ":", "datetime", ".", "datetime", "object", "with", "UTC", "time", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/utils.py#L104-L110
[ "def", "datetime_local_to_utc", "(", "local", ")", ":", "timestamp", "=", "time", ".", "mktime", "(", "local", ".", "timetuple", "(", ")", ")", "return", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "timestamp", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Message._decode_subelements
Decode the stanza subelements.
pyxmpp2/message.py
def _decode_subelements(self): """Decode the stanza subelements.""" for child in self._element: if child.tag == self._subject_tag: self._subject = child.text elif child.tag == self._body_tag: self._body = child.text elif child.tag == self._thread_tag: self._thread = child.text
def _decode_subelements(self): """Decode the stanza subelements.""" for child in self._element: if child.tag == self._subject_tag: self._subject = child.text elif child.tag == self._body_tag: self._body = child.text elif child.tag == self._thread_tag: self._thread = child.text
[ "Decode", "the", "stanza", "subelements", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/message.py#L103-L111
[ "def", "_decode_subelements", "(", "self", ")", ":", "for", "child", "in", "self", ".", "_element", ":", "if", "child", ".", "tag", "==", "self", ".", "_subject_tag", ":", "self", ".", "_subject", "=", "child", ".", "text", "elif", "child", ".", "tag", "==", "self", ".", "_body_tag", ":", "self", ".", "_body", "=", "child", ".", "text", "elif", "child", ".", "tag", "==", "self", ".", "_thread_tag", ":", "self", ".", "_thread", "=", "child", ".", "text" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Message.as_xml
Return the XML stanza representation. Always return an independent copy of the stanza XML representation, which can be freely modified without affecting the stanza. :returntype: :etree:`ElementTree.Element`
pyxmpp2/message.py
def as_xml(self): """Return the XML stanza representation. Always return an independent copy of the stanza XML representation, which can be freely modified without affecting the stanza. :returntype: :etree:`ElementTree.Element`""" result = Stanza.as_xml(self) if self._subject: child = ElementTree.SubElement(result, self._subject_tag) child.text = self._subject if self._body: child = ElementTree.SubElement(result, self._body_tag) child.text = self._body if self._thread: child = ElementTree.SubElement(result, self._thread_tag) child.text = self._thread return result
def as_xml(self): """Return the XML stanza representation. Always return an independent copy of the stanza XML representation, which can be freely modified without affecting the stanza. :returntype: :etree:`ElementTree.Element`""" result = Stanza.as_xml(self) if self._subject: child = ElementTree.SubElement(result, self._subject_tag) child.text = self._subject if self._body: child = ElementTree.SubElement(result, self._body_tag) child.text = self._body if self._thread: child = ElementTree.SubElement(result, self._thread_tag) child.text = self._thread return result
[ "Return", "the", "XML", "stanza", "representation", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/message.py#L113-L130
[ "def", "as_xml", "(", "self", ")", ":", "result", "=", "Stanza", ".", "as_xml", "(", "self", ")", "if", "self", ".", "_subject", ":", "child", "=", "ElementTree", ".", "SubElement", "(", "result", ",", "self", ".", "_subject_tag", ")", "child", ".", "text", "=", "self", ".", "_subject", "if", "self", ".", "_body", ":", "child", "=", "ElementTree", ".", "SubElement", "(", "result", ",", "self", ".", "_body_tag", ")", "child", ".", "text", "=", "self", ".", "_body", "if", "self", ".", "_thread", ":", "child", "=", "ElementTree", ".", "SubElement", "(", "result", ",", "self", ".", "_thread_tag", ")", "child", ".", "text", "=", "self", ".", "_thread", "return", "result" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Message.copy
Create a deep copy of the stanza. :returntype: `Message`
pyxmpp2/message.py
def copy(self): """Create a deep copy of the stanza. :returntype: `Message`""" result = Message(None, self.from_jid, self.to_jid, self.stanza_type, self.stanza_id, self.error, self._return_path(), self._subject, self._body, self._thread) for payload in self._payload: result.add_payload(payload.copy()) return result
def copy(self): """Create a deep copy of the stanza. :returntype: `Message`""" result = Message(None, self.from_jid, self.to_jid, self.stanza_type, self.stanza_id, self.error, self._return_path(), self._subject, self._body, self._thread) for payload in self._payload: result.add_payload(payload.copy()) return result
[ "Create", "a", "deep", "copy", "of", "the", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/message.py#L132-L142
[ "def", "copy", "(", "self", ")", ":", "result", "=", "Message", "(", "None", ",", "self", ".", "from_jid", ",", "self", ".", "to_jid", ",", "self", ".", "stanza_type", ",", "self", ".", "stanza_id", ",", "self", ".", "error", ",", "self", ".", "_return_path", "(", ")", ",", "self", ".", "_subject", ",", "self", ".", "_body", ",", "self", ".", "_thread", ")", "for", "payload", "in", "self", ".", "_payload", ":", "result", ".", "add_payload", "(", "payload", ".", "copy", "(", ")", ")", "return", "result" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Message.make_error_response
Create error response for any non-error message stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :return: new message stanza with the same "id" as self, "from" and "to" attributes swapped, type="error" and containing <error /> element plus payload of `self`. :returntype: `Message`
pyxmpp2/message.py
def make_error_response(self, cond): """Create error response for any non-error message stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :return: new message stanza with the same "id" as self, "from" and "to" attributes swapped, type="error" and containing <error /> element plus payload of `self`. :returntype: `Message`""" if self.stanza_type == "error": raise ValueError("Errors may not be generated in response" " to errors") msg = Message(stanza_type = "error", from_jid = self.to_jid, to_jid = self.from_jid, stanza_id = self.stanza_id, error_cond = cond, subject = self._subject, body = self._body, thread = self._thread) if self._payload is None: self.decode_payload() for payload in self._payload: msg.add_payload(payload.copy()) return msg
def make_error_response(self, cond): """Create error response for any non-error message stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :return: new message stanza with the same "id" as self, "from" and "to" attributes swapped, type="error" and containing <error /> element plus payload of `self`. :returntype: `Message`""" if self.stanza_type == "error": raise ValueError("Errors may not be generated in response" " to errors") msg = Message(stanza_type = "error", from_jid = self.to_jid, to_jid = self.from_jid, stanza_id = self.stanza_id, error_cond = cond, subject = self._subject, body = self._body, thread = self._thread) if self._payload is None: self.decode_payload() for payload in self._payload: msg.add_payload(payload.copy()) return msg
[ "Create", "error", "response", "for", "any", "non", "-", "error", "message", "stanza", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/message.py#L183-L209
[ "def", "make_error_response", "(", "self", ",", "cond", ")", ":", "if", "self", ".", "stanza_type", "==", "\"error\"", ":", "raise", "ValueError", "(", "\"Errors may not be generated in response\"", "\" to errors\"", ")", "msg", "=", "Message", "(", "stanza_type", "=", "\"error\"", ",", "from_jid", "=", "self", ".", "to_jid", ",", "to_jid", "=", "self", ".", "from_jid", ",", "stanza_id", "=", "self", ".", "stanza_id", ",", "error_cond", "=", "cond", ",", "subject", "=", "self", ".", "_subject", ",", "body", "=", "self", ".", "_body", ",", "thread", "=", "self", ".", "_thread", ")", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "decode_payload", "(", ")", "for", "payload", "in", "self", ".", "_payload", ":", "msg", ".", "add_payload", "(", "payload", ".", "copy", "(", ")", ")", "return", "msg" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
_move_session_handler
Find a SessionHandler instance in the list and move it to the beginning.
pyxmpp2/client.py
def _move_session_handler(handlers): """Find a SessionHandler instance in the list and move it to the beginning. """ index = 0 for i, handler in enumerate(handlers): if isinstance(handler, SessionHandler): index = i break if index: handlers[:index + 1] = [handlers[index]] + handlers[:index]
def _move_session_handler(handlers): """Find a SessionHandler instance in the list and move it to the beginning. """ index = 0 for i, handler in enumerate(handlers): if isinstance(handler, SessionHandler): index = i break if index: handlers[:index + 1] = [handlers[index]] + handlers[:index]
[ "Find", "a", "SessionHandler", "instance", "in", "the", "list", "and", "move", "it", "to", "the", "beginning", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L73-L82
[ "def", "_move_session_handler", "(", "handlers", ")", ":", "index", "=", "0", "for", "i", ",", "handler", "in", "enumerate", "(", "handlers", ")", ":", "if", "isinstance", "(", "handler", ",", "SessionHandler", ")", ":", "index", "=", "i", "break", "if", "index", ":", "handlers", "[", ":", "index", "+", "1", "]", "=", "[", "handlers", "[", "index", "]", "]", "+", "handlers", "[", ":", "index", "]" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client.connect
Schedule a new XMPP c2s connection.
pyxmpp2/client.py
def connect(self): """Schedule a new XMPP c2s connection. """ with self.lock: if self.stream: logger.debug("Closing the previously used stream.") self._close_stream() transport = TCPTransport(self.settings) addr = self.settings["server"] if addr: service = None else: addr = self.jid.domain service = self.settings["c2s_service"] transport.connect(addr, self.settings["c2s_port"], service) handlers = self._base_handlers[:] handlers += self.handlers + [self] self.clear_response_handlers() self.setup_stanza_handlers(handlers, "pre-auth") stream = ClientStream(self.jid, self, handlers, self.settings) stream.initiate(transport) self.main_loop.add_handler(transport) self.main_loop.add_handler(stream) self._ml_handlers += [transport, stream] self.stream = stream self.uplink = stream
def connect(self): """Schedule a new XMPP c2s connection. """ with self.lock: if self.stream: logger.debug("Closing the previously used stream.") self._close_stream() transport = TCPTransport(self.settings) addr = self.settings["server"] if addr: service = None else: addr = self.jid.domain service = self.settings["c2s_service"] transport.connect(addr, self.settings["c2s_port"], service) handlers = self._base_handlers[:] handlers += self.handlers + [self] self.clear_response_handlers() self.setup_stanza_handlers(handlers, "pre-auth") stream = ClientStream(self.jid, self, handlers, self.settings) stream.initiate(transport) self.main_loop.add_handler(transport) self.main_loop.add_handler(stream) self._ml_handlers += [transport, stream] self.stream = stream self.uplink = stream
[ "Schedule", "a", "new", "XMPP", "c2s", "connection", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L157-L185
[ "def", "connect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "stream", ":", "logger", ".", "debug", "(", "\"Closing the previously used stream.\"", ")", "self", ".", "_close_stream", "(", ")", "transport", "=", "TCPTransport", "(", "self", ".", "settings", ")", "addr", "=", "self", ".", "settings", "[", "\"server\"", "]", "if", "addr", ":", "service", "=", "None", "else", ":", "addr", "=", "self", ".", "jid", ".", "domain", "service", "=", "self", ".", "settings", "[", "\"c2s_service\"", "]", "transport", ".", "connect", "(", "addr", ",", "self", ".", "settings", "[", "\"c2s_port\"", "]", ",", "service", ")", "handlers", "=", "self", ".", "_base_handlers", "[", ":", "]", "handlers", "+=", "self", ".", "handlers", "+", "[", "self", "]", "self", ".", "clear_response_handlers", "(", ")", "self", ".", "setup_stanza_handlers", "(", "handlers", ",", "\"pre-auth\"", ")", "stream", "=", "ClientStream", "(", "self", ".", "jid", ",", "self", ",", "handlers", ",", "self", ".", "settings", ")", "stream", ".", "initiate", "(", "transport", ")", "self", ".", "main_loop", ".", "add_handler", "(", "transport", ")", "self", ".", "main_loop", ".", "add_handler", "(", "stream", ")", "self", ".", "_ml_handlers", "+=", "[", "transport", ",", "stream", "]", "self", ".", "stream", "=", "stream", "self", ".", "uplink", "=", "stream" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client.disconnect
Gracefully disconnect from the server.
pyxmpp2/client.py
def disconnect(self): """Gracefully disconnect from the server.""" with self.lock: if self.stream: if self.settings[u"initial_presence"]: self.send(Presence(stanza_type = "unavailable")) self.stream.disconnect()
def disconnect(self): """Gracefully disconnect from the server.""" with self.lock: if self.stream: if self.settings[u"initial_presence"]: self.send(Presence(stanza_type = "unavailable")) self.stream.disconnect()
[ "Gracefully", "disconnect", "from", "the", "server", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L187-L193
[ "def", "disconnect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "stream", ":", "if", "self", ".", "settings", "[", "u\"initial_presence\"", "]", ":", "self", ".", "send", "(", "Presence", "(", "stanza_type", "=", "\"unavailable\"", ")", ")", "self", ".", "stream", ".", "disconnect", "(", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client._close_stream
Same as `close_stream` but with the `lock` acquired.
pyxmpp2/client.py
def _close_stream(self): """Same as `close_stream` but with the `lock` acquired. """ self.stream.close() if self.stream.transport in self._ml_handlers: self._ml_handlers.remove(self.stream.transport) self.main_loop.remove_handler(self.stream.transport) self.stream = None self.uplink = None
def _close_stream(self): """Same as `close_stream` but with the `lock` acquired. """ self.stream.close() if self.stream.transport in self._ml_handlers: self._ml_handlers.remove(self.stream.transport) self.main_loop.remove_handler(self.stream.transport) self.stream = None self.uplink = None
[ "Same", "as", "close_stream", "but", "with", "the", "lock", "acquired", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L201-L209
[ "def", "_close_stream", "(", "self", ")", ":", "self", ".", "stream", ".", "close", "(", ")", "if", "self", ".", "stream", ".", "transport", "in", "self", ".", "_ml_handlers", ":", "self", ".", "_ml_handlers", ".", "remove", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "main_loop", ".", "remove_handler", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "stream", "=", "None", "self", ".", "uplink", "=", "None" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client._stream_authenticated
Handle the `AuthenticatedEvent`.
pyxmpp2/client.py
def _stream_authenticated(self, event): """Handle the `AuthenticatedEvent`. """ with self.lock: if event.stream != self.stream: return self.me = event.stream.me self.peer = event.stream.peer handlers = self._base_handlers[:] handlers += self.handlers + [self] self.setup_stanza_handlers(handlers, "post-auth")
def _stream_authenticated(self, event): """Handle the `AuthenticatedEvent`. """ with self.lock: if event.stream != self.stream: return self.me = event.stream.me self.peer = event.stream.peer handlers = self._base_handlers[:] handlers += self.handlers + [self] self.setup_stanza_handlers(handlers, "post-auth")
[ "Handle", "the", "AuthenticatedEvent", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L219-L229
[ "def", "_stream_authenticated", "(", "self", ",", "event", ")", ":", "with", "self", ".", "lock", ":", "if", "event", ".", "stream", "!=", "self", ".", "stream", ":", "return", "self", ".", "me", "=", "event", ".", "stream", ".", "me", "self", ".", "peer", "=", "event", ".", "stream", ".", "peer", "handlers", "=", "self", ".", "_base_handlers", "[", ":", "]", "handlers", "+=", "self", ".", "handlers", "+", "[", "self", "]", "self", ".", "setup_stanza_handlers", "(", "handlers", ",", "\"post-auth\"", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client._stream_authorized
Handle the `AuthorizedEvent`.
pyxmpp2/client.py
def _stream_authorized(self, event): """Handle the `AuthorizedEvent`. """ with self.lock: if event.stream != self.stream: return self.me = event.stream.me self.peer = event.stream.peer presence = self.settings[u"initial_presence"] if presence: self.send(presence)
def _stream_authorized(self, event): """Handle the `AuthorizedEvent`. """ with self.lock: if event.stream != self.stream: return self.me = event.stream.me self.peer = event.stream.peer presence = self.settings[u"initial_presence"] if presence: self.send(presence)
[ "Handle", "the", "AuthorizedEvent", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L232-L242
[ "def", "_stream_authorized", "(", "self", ",", "event", ")", ":", "with", "self", ".", "lock", ":", "if", "event", ".", "stream", "!=", "self", ".", "stream", ":", "return", "self", ".", "me", "=", "event", ".", "stream", ".", "me", "self", ".", "peer", "=", "event", ".", "stream", ".", "peer", "presence", "=", "self", ".", "settings", "[", "u\"initial_presence\"", "]", "if", "presence", ":", "self", ".", "send", "(", "presence", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client._stream_disconnected
Handle stream disconnection event.
pyxmpp2/client.py
def _stream_disconnected(self, event): """Handle stream disconnection event. """ with self.lock: if event.stream != self.stream: return if self.stream is not None and event.stream == self.stream: if self.stream.transport in self._ml_handlers: self._ml_handlers.remove(self.stream.transport) self.main_loop.remove_handler(self.stream.transport) self.stream = None self.uplink = None
def _stream_disconnected(self, event): """Handle stream disconnection event. """ with self.lock: if event.stream != self.stream: return if self.stream is not None and event.stream == self.stream: if self.stream.transport in self._ml_handlers: self._ml_handlers.remove(self.stream.transport) self.main_loop.remove_handler(self.stream.transport) self.stream = None self.uplink = None
[ "Handle", "stream", "disconnection", "event", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L245-L256
[ "def", "_stream_disconnected", "(", "self", ",", "event", ")", ":", "with", "self", ".", "lock", ":", "if", "event", ".", "stream", "!=", "self", ".", "stream", ":", "return", "if", "self", ".", "stream", "is", "not", "None", "and", "event", ".", "stream", "==", "self", ".", "stream", ":", "if", "self", ".", "stream", ".", "transport", "in", "self", ".", "_ml_handlers", ":", "self", ".", "_ml_handlers", ".", "remove", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "main_loop", ".", "remove_handler", "(", "self", ".", "stream", ".", "transport", ")", "self", ".", "stream", "=", "None", "self", ".", "uplink", "=", "None" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client.regular_tasks
Do some housekeeping (cache expiration, timeout handling). This method should be called periodically from the application's main loop. :Return: suggested delay (in seconds) before the next call to this method. :Returntype: `int`
pyxmpp2/client.py
def regular_tasks(self): """Do some housekeeping (cache expiration, timeout handling). This method should be called periodically from the application's main loop. :Return: suggested delay (in seconds) before the next call to this method. :Returntype: `int` """ with self.lock: ret = self._iq_response_handlers.expire() if ret is None: return 1 else: return min(1, ret)
def regular_tasks(self): """Do some housekeeping (cache expiration, timeout handling). This method should be called periodically from the application's main loop. :Return: suggested delay (in seconds) before the next call to this method. :Returntype: `int` """ with self.lock: ret = self._iq_response_handlers.expire() if ret is None: return 1 else: return min(1, ret)
[ "Do", "some", "housekeeping", "(", "cache", "expiration", "timeout", "handling", ")", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L259-L274
[ "def", "regular_tasks", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "ret", "=", "self", ".", "_iq_response_handlers", ".", "expire", "(", ")", "if", "ret", "is", "None", ":", "return", "1", "else", ":", "return", "min", "(", "1", ",", "ret", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
Client.base_handlers_factory
Default base client handlers factory. Subclasses can provide different behaviour by overriding this. :Return: list of handlers
pyxmpp2/client.py
def base_handlers_factory(self): """Default base client handlers factory. Subclasses can provide different behaviour by overriding this. :Return: list of handlers """ tls_handler = StreamTLSHandler(self.settings) sasl_handler = StreamSASLHandler(self.settings) session_handler = SessionHandler() binding_handler = ResourceBindingHandler(self.settings) return [tls_handler, sasl_handler, binding_handler, session_handler]
def base_handlers_factory(self): """Default base client handlers factory. Subclasses can provide different behaviour by overriding this. :Return: list of handlers """ tls_handler = StreamTLSHandler(self.settings) sasl_handler = StreamSASLHandler(self.settings) session_handler = SessionHandler() binding_handler = ResourceBindingHandler(self.settings) return [tls_handler, sasl_handler, binding_handler, session_handler]
[ "Default", "base", "client", "handlers", "factory", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/client.py#L276-L287
[ "def", "base_handlers_factory", "(", "self", ")", ":", "tls_handler", "=", "StreamTLSHandler", "(", "self", ".", "settings", ")", "sasl_handler", "=", "StreamSASLHandler", "(", "self", ".", "settings", ")", "session_handler", "=", "SessionHandler", "(", ")", "binding_handler", "=", "ResourceBindingHandler", "(", "self", ".", "settings", ")", "return", "[", "tls_handler", ",", "sasl_handler", ",", "binding_handler", ",", "session_handler", "]" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
payload_class_for_element_name
Return a payload class for given element name.
pyxmpp2/stanzapayload.py
def payload_class_for_element_name(element_name): """Return a payload class for given element name.""" logger.debug(" looking up payload class for element: {0!r}".format( element_name)) logger.debug(" known: {0!r}".format(STANZA_PAYLOAD_CLASSES)) if element_name in STANZA_PAYLOAD_CLASSES: return STANZA_PAYLOAD_CLASSES[element_name] else: return XMLPayload
def payload_class_for_element_name(element_name): """Return a payload class for given element name.""" logger.debug(" looking up payload class for element: {0!r}".format( element_name)) logger.debug(" known: {0!r}".format(STANZA_PAYLOAD_CLASSES)) if element_name in STANZA_PAYLOAD_CLASSES: return STANZA_PAYLOAD_CLASSES[element_name] else: return XMLPayload
[ "Return", "a", "payload", "class", "for", "given", "element", "name", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/stanzapayload.py#L66-L74
[ "def", "payload_class_for_element_name", "(", "element_name", ")", ":", "logger", ".", "debug", "(", "\" looking up payload class for element: {0!r}\"", ".", "format", "(", "element_name", ")", ")", "logger", ".", "debug", "(", "\" known: {0!r}\"", ".", "format", "(", "STANZA_PAYLOAD_CLASSES", ")", ")", "if", "element_name", "in", "STANZA_PAYLOAD_CLASSES", ":", "return", "STANZA_PAYLOAD_CLASSES", "[", "element_name", "]", "else", ":", "return", "XMLPayload" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
_unquote
Unquote quoted value from DIGEST-MD5 challenge or response. If `data` doesn't start or doesn't end with '"' then return it unchanged, remove the quotes and escape backslashes otherwise. :Parameters: - `data`: a quoted string. :Types: - `data`: `bytes` :return: the unquoted string. :returntype: `bytes`
pyxmpp2/sasl/digest_md5.py
def _unquote(data): """Unquote quoted value from DIGEST-MD5 challenge or response. If `data` doesn't start or doesn't end with '"' then return it unchanged, remove the quotes and escape backslashes otherwise. :Parameters: - `data`: a quoted string. :Types: - `data`: `bytes` :return: the unquoted string. :returntype: `bytes` """ if not data.startswith(b'"') or not data.endswith(b'"'): return data return QUOTE_RE.sub(b"\\1", data[1:-1])
def _unquote(data): """Unquote quoted value from DIGEST-MD5 challenge or response. If `data` doesn't start or doesn't end with '"' then return it unchanged, remove the quotes and escape backslashes otherwise. :Parameters: - `data`: a quoted string. :Types: - `data`: `bytes` :return: the unquoted string. :returntype: `bytes` """ if not data.startswith(b'"') or not data.endswith(b'"'): return data return QUOTE_RE.sub(b"\\1", data[1:-1])
[ "Unquote", "quoted", "value", "from", "DIGEST", "-", "MD5", "challenge", "or", "response", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/digest_md5.py#L43-L59
[ "def", "_unquote", "(", "data", ")", ":", "if", "not", "data", ".", "startswith", "(", "b'\"'", ")", "or", "not", "data", ".", "endswith", "(", "b'\"'", ")", ":", "return", "data", "return", "QUOTE_RE", ".", "sub", "(", "b\"\\\\1\"", ",", "data", "[", "1", ":", "-", "1", "]", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
_quote
Prepare a string for quoting for DIGEST-MD5 challenge or response. Don't add the quotes, only escape '"' and "\\" with backslashes. :Parameters: - `data`: a raw string. :Types: - `data`: `bytes` :return: `data` with '"' and "\\" escaped using "\\". :returntype: `bytes`
pyxmpp2/sasl/digest_md5.py
def _quote(data): """Prepare a string for quoting for DIGEST-MD5 challenge or response. Don't add the quotes, only escape '"' and "\\" with backslashes. :Parameters: - `data`: a raw string. :Types: - `data`: `bytes` :return: `data` with '"' and "\\" escaped using "\\". :returntype: `bytes` """ data = data.replace(b'\\', b'\\\\') data = data.replace(b'"', b'\\"') return data
def _quote(data): """Prepare a string for quoting for DIGEST-MD5 challenge or response. Don't add the quotes, only escape '"' and "\\" with backslashes. :Parameters: - `data`: a raw string. :Types: - `data`: `bytes` :return: `data` with '"' and "\\" escaped using "\\". :returntype: `bytes` """ data = data.replace(b'\\', b'\\\\') data = data.replace(b'"', b'\\"') return data
[ "Prepare", "a", "string", "for", "quoting", "for", "DIGEST", "-", "MD5", "challenge", "or", "response", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/digest_md5.py#L61-L76
[ "def", "_quote", "(", "data", ")", ":", "data", "=", "data", ".", "replace", "(", "b'\\\\'", ",", "b'\\\\\\\\'", ")", "data", "=", "data", ".", "replace", "(", "b'\"'", ",", "b'\\\\\"'", ")", "return", "data" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
_make_urp_hash
Compute MD5 sum of username:realm:password. :Parameters: - `username`: a username. - `realm`: a realm. - `passwd`: a password. :Types: - `username`: `bytes` - `realm`: `bytes` - `passwd`: `bytes` :return: the MD5 sum of the parameters joined with ':'. :returntype: `bytes`
pyxmpp2/sasl/digest_md5.py
def _make_urp_hash(username, realm, passwd): """Compute MD5 sum of username:realm:password. :Parameters: - `username`: a username. - `realm`: a realm. - `passwd`: a password. :Types: - `username`: `bytes` - `realm`: `bytes` - `passwd`: `bytes` :return: the MD5 sum of the parameters joined with ':'. :returntype: `bytes`""" if realm is None: realm = b"" return _h_value(b":".join((username, realm, passwd)))
def _make_urp_hash(username, realm, passwd): """Compute MD5 sum of username:realm:password. :Parameters: - `username`: a username. - `realm`: a realm. - `passwd`: a password. :Types: - `username`: `bytes` - `realm`: `bytes` - `passwd`: `bytes` :return: the MD5 sum of the parameters joined with ':'. :returntype: `bytes`""" if realm is None: realm = b"" return _h_value(b":".join((username, realm, passwd)))
[ "Compute", "MD5", "sum", "of", "username", ":", "realm", ":", "password", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/digest_md5.py#L105-L121
[ "def", "_make_urp_hash", "(", "username", ",", "realm", ",", "passwd", ")", ":", "if", "realm", "is", "None", ":", "realm", "=", "b\"\"", "return", "_h_value", "(", "b\":\"", ".", "join", "(", "(", "username", ",", "realm", ",", "passwd", ")", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
_compute_response
Compute DIGEST-MD5 response value. :Parameters: - `urp_hash`: MD5 sum of username:realm:password. - `nonce`: nonce value from a server challenge. - `cnonce`: cnonce value from the client response. - `nonce_count`: nonce count value. - `authzid`: authorization id. - `digest_uri`: digest-uri value. :Types: - `urp_hash`: `bytes` - `nonce`: `bytes` - `nonce_count`: `int` - `authzid`: `bytes` - `digest_uri`: `bytes` :return: the computed response value. :returntype: `bytes`
pyxmpp2/sasl/digest_md5.py
def _compute_response(urp_hash, nonce, cnonce, nonce_count, authzid, digest_uri): """Compute DIGEST-MD5 response value. :Parameters: - `urp_hash`: MD5 sum of username:realm:password. - `nonce`: nonce value from a server challenge. - `cnonce`: cnonce value from the client response. - `nonce_count`: nonce count value. - `authzid`: authorization id. - `digest_uri`: digest-uri value. :Types: - `urp_hash`: `bytes` - `nonce`: `bytes` - `nonce_count`: `int` - `authzid`: `bytes` - `digest_uri`: `bytes` :return: the computed response value. :returntype: `bytes`""" # pylint: disable-msg=C0103,R0913 logger.debug("_compute_response{0!r}".format((urp_hash, nonce, cnonce, nonce_count, authzid,digest_uri))) if authzid: a1 = b":".join((urp_hash, nonce, cnonce, authzid)) else: a1 = b":".join((urp_hash, nonce, cnonce)) a2 = b"AUTHENTICATE:" + digest_uri return b2a_hex(_kd_value(b2a_hex(_h_value(a1)), b":".join(( nonce, nonce_count, cnonce, b"auth", b2a_hex(_h_value(a2))))))
def _compute_response(urp_hash, nonce, cnonce, nonce_count, authzid, digest_uri): """Compute DIGEST-MD5 response value. :Parameters: - `urp_hash`: MD5 sum of username:realm:password. - `nonce`: nonce value from a server challenge. - `cnonce`: cnonce value from the client response. - `nonce_count`: nonce count value. - `authzid`: authorization id. - `digest_uri`: digest-uri value. :Types: - `urp_hash`: `bytes` - `nonce`: `bytes` - `nonce_count`: `int` - `authzid`: `bytes` - `digest_uri`: `bytes` :return: the computed response value. :returntype: `bytes`""" # pylint: disable-msg=C0103,R0913 logger.debug("_compute_response{0!r}".format((urp_hash, nonce, cnonce, nonce_count, authzid,digest_uri))) if authzid: a1 = b":".join((urp_hash, nonce, cnonce, authzid)) else: a1 = b":".join((urp_hash, nonce, cnonce)) a2 = b"AUTHENTICATE:" + digest_uri return b2a_hex(_kd_value(b2a_hex(_h_value(a1)), b":".join(( nonce, nonce_count, cnonce, b"auth", b2a_hex(_h_value(a2))))))
[ "Compute", "DIGEST", "-", "MD5", "response", "value", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/digest_md5.py#L123-L152
[ "def", "_compute_response", "(", "urp_hash", ",", "nonce", ",", "cnonce", ",", "nonce_count", ",", "authzid", ",", "digest_uri", ")", ":", "# pylint: disable-msg=C0103,R0913", "logger", ".", "debug", "(", "\"_compute_response{0!r}\"", ".", "format", "(", "(", "urp_hash", ",", "nonce", ",", "cnonce", ",", "nonce_count", ",", "authzid", ",", "digest_uri", ")", ")", ")", "if", "authzid", ":", "a1", "=", "b\":\"", ".", "join", "(", "(", "urp_hash", ",", "nonce", ",", "cnonce", ",", "authzid", ")", ")", "else", ":", "a1", "=", "b\":\"", ".", "join", "(", "(", "urp_hash", ",", "nonce", ",", "cnonce", ")", ")", "a2", "=", "b\"AUTHENTICATE:\"", "+", "digest_uri", "return", "b2a_hex", "(", "_kd_value", "(", "b2a_hex", "(", "_h_value", "(", "a1", ")", ")", ",", "b\":\"", ".", "join", "(", "(", "nonce", ",", "nonce_count", ",", "cnonce", ",", "b\"auth\"", ",", "b2a_hex", "(", "_h_value", "(", "a2", ")", ")", ")", ")", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
rfc2425encode
Encodes a vCard field into an RFC2425 line. :Parameters: - `name`: field type name - `value`: field value - `parameters`: optional parameters - `charset`: encoding of the output and of the `value` (if not `unicode`) :Types: - `name`: `str` - `value`: `unicode` or `str` - `parameters`: `dict` of `str` -> `str` - `charset`: `str` :return: the encoded RFC2425 line (possibly folded) :returntype: `str`
pyxmpp2/ext/vcard.py
def rfc2425encode(name,value,parameters=None,charset="utf-8"): """Encodes a vCard field into an RFC2425 line. :Parameters: - `name`: field type name - `value`: field value - `parameters`: optional parameters - `charset`: encoding of the output and of the `value` (if not `unicode`) :Types: - `name`: `str` - `value`: `unicode` or `str` - `parameters`: `dict` of `str` -> `str` - `charset`: `str` :return: the encoded RFC2425 line (possibly folded) :returntype: `str`""" if not parameters: parameters={} if type(value) is unicode: value=value.replace(u"\r\n",u"\\n") value=value.replace(u"\n",u"\\n") value=value.replace(u"\r",u"\\n") value=value.encode(charset,"replace") elif type(value) is not str: raise TypeError("Bad type for rfc2425 value") elif not valid_string_re.match(value): parameters["encoding"]="b" value=binascii.b2a_base64(value) ret=str(name).lower() for k,v in parameters.items(): ret+=";%s=%s" % (str(k),str(v)) ret+=":" while(len(value)>70): ret+=value[:70]+"\r\n " value=value[70:] ret+=value+"\r\n" return ret
def rfc2425encode(name,value,parameters=None,charset="utf-8"): """Encodes a vCard field into an RFC2425 line. :Parameters: - `name`: field type name - `value`: field value - `parameters`: optional parameters - `charset`: encoding of the output and of the `value` (if not `unicode`) :Types: - `name`: `str` - `value`: `unicode` or `str` - `parameters`: `dict` of `str` -> `str` - `charset`: `str` :return: the encoded RFC2425 line (possibly folded) :returntype: `str`""" if not parameters: parameters={} if type(value) is unicode: value=value.replace(u"\r\n",u"\\n") value=value.replace(u"\n",u"\\n") value=value.replace(u"\r",u"\\n") value=value.encode(charset,"replace") elif type(value) is not str: raise TypeError("Bad type for rfc2425 value") elif not valid_string_re.match(value): parameters["encoding"]="b" value=binascii.b2a_base64(value) ret=str(name).lower() for k,v in parameters.items(): ret+=";%s=%s" % (str(k),str(v)) ret+=":" while(len(value)>70): ret+=value[:70]+"\r\n " value=value[70:] ret+=value+"\r\n" return ret
[ "Encodes", "a", "vCard", "field", "into", "an", "RFC2425", "line", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L60-L98
[ "def", "rfc2425encode", "(", "name", ",", "value", ",", "parameters", "=", "None", ",", "charset", "=", "\"utf-8\"", ")", ":", "if", "not", "parameters", ":", "parameters", "=", "{", "}", "if", "type", "(", "value", ")", "is", "unicode", ":", "value", "=", "value", ".", "replace", "(", "u\"\\r\\n\"", ",", "u\"\\\\n\"", ")", "value", "=", "value", ".", "replace", "(", "u\"\\n\"", ",", "u\"\\\\n\"", ")", "value", "=", "value", ".", "replace", "(", "u\"\\r\"", ",", "u\"\\\\n\"", ")", "value", "=", "value", ".", "encode", "(", "charset", ",", "\"replace\"", ")", "elif", "type", "(", "value", ")", "is", "not", "str", ":", "raise", "TypeError", "(", "\"Bad type for rfc2425 value\"", ")", "elif", "not", "valid_string_re", ".", "match", "(", "value", ")", ":", "parameters", "[", "\"encoding\"", "]", "=", "\"b\"", "value", "=", "binascii", ".", "b2a_base64", "(", "value", ")", "ret", "=", "str", "(", "name", ")", ".", "lower", "(", ")", "for", "k", ",", "v", "in", "parameters", ".", "items", "(", ")", ":", "ret", "+=", "\";%s=%s\"", "%", "(", "str", "(", "k", ")", ",", "str", "(", "v", ")", ")", "ret", "+=", "\":\"", "while", "(", "len", "(", "value", ")", ">", "70", ")", ":", "ret", "+=", "value", "[", ":", "70", "]", "+", "\"\\r\\n \"", "value", "=", "value", "[", "70", ":", "]", "ret", "+=", "value", "+", "\"\\r\\n\"", "return", "ret" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
VCardString.as_xml
Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`
pyxmpp2/ext/vcard.py
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" return parent.newTextChild(None, to_utf8(self.name.upper()), to_utf8(self.value))
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" return parent.newTextChild(None, to_utf8(self.name.upper()), to_utf8(self.value))
[ "Create", "vcard", "-", "tmp", "XML", "representation", "of", "the", "field", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L161-L171
[ "def", "as_xml", "(", "self", ",", "parent", ")", ":", "return", "parent", ".", "newTextChild", "(", "None", ",", "to_utf8", "(", "self", ".", "name", ".", "upper", "(", ")", ")", ",", "to_utf8", "(", "self", ".", "value", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
VCardJID.as_xml
Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`
pyxmpp2/ext/vcard.py
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" name=to_utf8(self.name.upper()) content=self.value.as_utf8() return parent.newTextChild(None, name, content)
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" name=to_utf8(self.name.upper()) content=self.value.as_utf8() return parent.newTextChild(None, name, content)
[ "Create", "vcard", "-", "tmp", "XML", "representation", "of", "the", "field", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L231-L243
[ "def", "as_xml", "(", "self", ",", "parent", ")", ":", "name", "=", "to_utf8", "(", "self", ".", "name", ".", "upper", "(", ")", ")", "content", "=", "self", ".", "value", ".", "as_utf8", "(", ")", "return", "parent", ".", "newTextChild", "(", "None", ",", "name", ",", "content", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
VCardName.rfc2426
RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`
pyxmpp2/ext/vcard.py
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" return rfc2425encode("n",u';'.join(quote_semicolon(val) for val in (self.family,self.given,self.middle,self.prefix,self.suffix)))
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" return rfc2425encode("n",u';'.join(quote_semicolon(val) for val in (self.family,self.given,self.middle,self.prefix,self.suffix)))
[ "RFC2426", "-", "encode", "the", "field", "content", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L316-L322
[ "def", "rfc2426", "(", "self", ")", ":", "return", "rfc2425encode", "(", "\"n\"", ",", "u';'", ".", "join", "(", "quote_semicolon", "(", "val", ")", "for", "val", "in", "(", "self", ".", "family", ",", "self", ".", "given", ",", "self", ".", "middle", ",", "self", ".", "prefix", ",", "self", ".", "suffix", ")", ")", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
VCardName.as_xml
Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`
pyxmpp2/ext/vcard.py
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=parent.newChild(None,"N",None) n.newTextChild(None,"FAMILY",to_utf8(self.family)) n.newTextChild(None,"GIVEN",to_utf8(self.given)) n.newTextChild(None,"MIDDLE",to_utf8(self.middle)) n.newTextChild(None,"PREFIX",to_utf8(self.prefix)) n.newTextChild(None,"SUFFIX",to_utf8(self.suffix)) return n
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=parent.newChild(None,"N",None) n.newTextChild(None,"FAMILY",to_utf8(self.family)) n.newTextChild(None,"GIVEN",to_utf8(self.given)) n.newTextChild(None,"MIDDLE",to_utf8(self.middle)) n.newTextChild(None,"PREFIX",to_utf8(self.prefix)) n.newTextChild(None,"SUFFIX",to_utf8(self.suffix)) return n
[ "Create", "vcard", "-", "tmp", "XML", "representation", "of", "the", "field", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L323-L339
[ "def", "as_xml", "(", "self", ",", "parent", ")", ":", "n", "=", "parent", ".", "newChild", "(", "None", ",", "\"N\"", ",", "None", ")", "n", ".", "newTextChild", "(", "None", ",", "\"FAMILY\"", ",", "to_utf8", "(", "self", ".", "family", ")", ")", "n", ".", "newTextChild", "(", "None", ",", "\"GIVEN\"", ",", "to_utf8", "(", "self", ".", "given", ")", ")", "n", ".", "newTextChild", "(", "None", ",", "\"MIDDLE\"", ",", "to_utf8", "(", "self", ".", "middle", ")", ")", "n", ".", "newTextChild", "(", "None", ",", "\"PREFIX\"", ",", "to_utf8", "(", "self", ".", "prefix", ")", ")", "n", ".", "newTextChild", "(", "None", ",", "\"SUFFIX\"", ",", "to_utf8", "(", "self", ".", "suffix", ")", ")", "return", "n" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18
valid
VCardImage.rfc2426
RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`
pyxmpp2/ext/vcard.py
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" if self.uri: return rfc2425encode(self.name,self.uri,{"value":"uri"}) elif self.image: if self.type: p={"type":self.type} else: p={} return rfc2425encode(self.name,self.image,p)
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" if self.uri: return rfc2425encode(self.name,self.uri,{"value":"uri"}) elif self.image: if self.type: p={"type":self.type} else: p={} return rfc2425encode(self.name,self.image,p)
[ "RFC2426", "-", "encode", "the", "field", "content", "." ]
Jajcus/pyxmpp2
python
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L411-L423
[ "def", "rfc2426", "(", "self", ")", ":", "if", "self", ".", "uri", ":", "return", "rfc2425encode", "(", "self", ".", "name", ",", "self", ".", "uri", ",", "{", "\"value\"", ":", "\"uri\"", "}", ")", "elif", "self", ".", "image", ":", "if", "self", ".", "type", ":", "p", "=", "{", "\"type\"", ":", "self", ".", "type", "}", "else", ":", "p", "=", "{", "}", "return", "rfc2425encode", "(", "self", ".", "name", ",", "self", ".", "image", ",", "p", ")" ]
14a40a3950910a9cd008b55f0d8905aa0186ce18