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
|
VCardImage.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,self.name.upper(),None)
if self.uri:
n.newTextChild(None,"EXTVAL",to_utf8(self.uri))
else:
if self.type:
n.newTextChild(None,"TYPE",self.type)
n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.image))
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,self.name.upper(),None)
if self.uri:
n.newTextChild(None,"EXTVAL",to_utf8(self.uri))
else:
if self.type:
n.newTextChild(None,"TYPE",self.type)
n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.image))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L424-L441
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"self",
".",
"name",
".",
"upper",
"(",
")",
",",
"None",
")",
"if",
"self",
".",
"uri",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"EXTVAL\"",
",",
"to_utf8",
"(",
"self",
".",
"uri",
")",
")",
"else",
":",
"if",
"self",
".",
"type",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"TYPE\"",
",",
"self",
".",
"type",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"BINVAL\"",
",",
"binascii",
".",
"b2a_base64",
"(",
"self",
".",
"image",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardAdr.__from_xml
|
Initialize a `VCardAdr` object from and XML element.
:Parameters:
- `value`: field value as an XML node
:Types:
- `value`: `libxml2.xmlNode`
|
pyxmpp2/ext/vcard.py
|
def __from_xml(self,value):
"""Initialize a `VCardAdr` object from and XML element.
:Parameters:
- `value`: field value as an XML node
:Types:
- `value`: `libxml2.xmlNode`"""
n=value.children
vns=get_node_ns(value)
while n:
if n.type!='element':
n=n.next
continue
ns=get_node_ns(n)
if (ns and vns and ns.getContent()!=vns.getContent()):
n=n.next
continue
if n.name=='POBOX':
self.pobox=unicode(n.getContent(),"utf-8","replace")
elif n.name in ('EXTADR', 'EXTADD'):
self.extadr=unicode(n.getContent(),"utf-8","replace")
elif n.name=='STREET':
self.street=unicode(n.getContent(),"utf-8","replace")
elif n.name=='LOCALITY':
self.locality=unicode(n.getContent(),"utf-8","replace")
elif n.name=='REGION':
self.region=unicode(n.getContent(),"utf-8","replace")
elif n.name=='PCODE':
self.pcode=unicode(n.getContent(),"utf-8","replace")
elif n.name=='CTRY':
self.ctry=unicode(n.getContent(),"utf-8","replace")
elif n.name in ("HOME","WORK","POSTAL","PARCEL","DOM","INTL",
"PREF"):
self.type.append(n.name.lower())
n=n.next
if self.type==[]:
self.type=["intl","postal","parcel","work"]
elif "dom" in self.type and "intl" in self.type:
raise ValueError("Both 'dom' and 'intl' specified in vcard ADR")
|
def __from_xml(self,value):
"""Initialize a `VCardAdr` object from and XML element.
:Parameters:
- `value`: field value as an XML node
:Types:
- `value`: `libxml2.xmlNode`"""
n=value.children
vns=get_node_ns(value)
while n:
if n.type!='element':
n=n.next
continue
ns=get_node_ns(n)
if (ns and vns and ns.getContent()!=vns.getContent()):
n=n.next
continue
if n.name=='POBOX':
self.pobox=unicode(n.getContent(),"utf-8","replace")
elif n.name in ('EXTADR', 'EXTADD'):
self.extadr=unicode(n.getContent(),"utf-8","replace")
elif n.name=='STREET':
self.street=unicode(n.getContent(),"utf-8","replace")
elif n.name=='LOCALITY':
self.locality=unicode(n.getContent(),"utf-8","replace")
elif n.name=='REGION':
self.region=unicode(n.getContent(),"utf-8","replace")
elif n.name=='PCODE':
self.pcode=unicode(n.getContent(),"utf-8","replace")
elif n.name=='CTRY':
self.ctry=unicode(n.getContent(),"utf-8","replace")
elif n.name in ("HOME","WORK","POSTAL","PARCEL","DOM","INTL",
"PREF"):
self.type.append(n.name.lower())
n=n.next
if self.type==[]:
self.type=["intl","postal","parcel","work"]
elif "dom" in self.type and "intl" in self.type:
raise ValueError("Both 'dom' and 'intl' specified in vcard ADR")
|
[
"Initialize",
"a",
"VCardAdr",
"object",
"from",
"and",
"XML",
"element",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L507-L545
|
[
"def",
"__from_xml",
"(",
"self",
",",
"value",
")",
":",
"n",
"=",
"value",
".",
"children",
"vns",
"=",
"get_node_ns",
"(",
"value",
")",
"while",
"n",
":",
"if",
"n",
".",
"type",
"!=",
"'element'",
":",
"n",
"=",
"n",
".",
"next",
"continue",
"ns",
"=",
"get_node_ns",
"(",
"n",
")",
"if",
"(",
"ns",
"and",
"vns",
"and",
"ns",
".",
"getContent",
"(",
")",
"!=",
"vns",
".",
"getContent",
"(",
")",
")",
":",
"n",
"=",
"n",
".",
"next",
"continue",
"if",
"n",
".",
"name",
"==",
"'POBOX'",
":",
"self",
".",
"pobox",
"=",
"unicode",
"(",
"n",
".",
"getContent",
"(",
")",
",",
"\"utf-8\"",
",",
"\"replace\"",
")",
"elif",
"n",
".",
"name",
"in",
"(",
"'EXTADR'",
",",
"'EXTADD'",
")",
":",
"self",
".",
"extadr",
"=",
"unicode",
"(",
"n",
".",
"getContent",
"(",
")",
",",
"\"utf-8\"",
",",
"\"replace\"",
")",
"elif",
"n",
".",
"name",
"==",
"'STREET'",
":",
"self",
".",
"street",
"=",
"unicode",
"(",
"n",
".",
"getContent",
"(",
")",
",",
"\"utf-8\"",
",",
"\"replace\"",
")",
"elif",
"n",
".",
"name",
"==",
"'LOCALITY'",
":",
"self",
".",
"locality",
"=",
"unicode",
"(",
"n",
".",
"getContent",
"(",
")",
",",
"\"utf-8\"",
",",
"\"replace\"",
")",
"elif",
"n",
".",
"name",
"==",
"'REGION'",
":",
"self",
".",
"region",
"=",
"unicode",
"(",
"n",
".",
"getContent",
"(",
")",
",",
"\"utf-8\"",
",",
"\"replace\"",
")",
"elif",
"n",
".",
"name",
"==",
"'PCODE'",
":",
"self",
".",
"pcode",
"=",
"unicode",
"(",
"n",
".",
"getContent",
"(",
")",
",",
"\"utf-8\"",
",",
"\"replace\"",
")",
"elif",
"n",
".",
"name",
"==",
"'CTRY'",
":",
"self",
".",
"ctry",
"=",
"unicode",
"(",
"n",
".",
"getContent",
"(",
")",
",",
"\"utf-8\"",
",",
"\"replace\"",
")",
"elif",
"n",
".",
"name",
"in",
"(",
"\"HOME\"",
",",
"\"WORK\"",
",",
"\"POSTAL\"",
",",
"\"PARCEL\"",
",",
"\"DOM\"",
",",
"\"INTL\"",
",",
"\"PREF\"",
")",
":",
"self",
".",
"type",
".",
"append",
"(",
"n",
".",
"name",
".",
"lower",
"(",
")",
")",
"n",
"=",
"n",
".",
"next",
"if",
"self",
".",
"type",
"==",
"[",
"]",
":",
"self",
".",
"type",
"=",
"[",
"\"intl\"",
",",
"\"postal\"",
",",
"\"parcel\"",
",",
"\"work\"",
"]",
"elif",
"\"dom\"",
"in",
"self",
".",
"type",
"and",
"\"intl\"",
"in",
"self",
".",
"type",
":",
"raise",
"ValueError",
"(",
"\"Both 'dom' and 'intl' specified in vcard ADR\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardAdr.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("adr",u';'.join(quote_semicolon(val) for val in
(self.pobox,self.extadr,self.street,self.locality,
self.region,self.pcode,self.ctry)),
{"type":",".join(self.type)})
|
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
return rfc2425encode("adr",u';'.join(quote_semicolon(val) for val in
(self.pobox,self.extadr,self.street,self.locality,
self.region,self.pcode,self.ctry)),
{"type":",".join(self.type)})
|
[
"RFC2426",
"-",
"encode",
"the",
"field",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L547-L555
|
[
"def",
"rfc2426",
"(",
"self",
")",
":",
"return",
"rfc2425encode",
"(",
"\"adr\"",
",",
"u';'",
".",
"join",
"(",
"quote_semicolon",
"(",
"val",
")",
"for",
"val",
"in",
"(",
"self",
".",
"pobox",
",",
"self",
".",
"extadr",
",",
"self",
".",
"street",
",",
"self",
".",
"locality",
",",
"self",
".",
"region",
",",
"self",
".",
"pcode",
",",
"self",
".",
"ctry",
")",
")",
",",
"{",
"\"type\"",
":",
"\",\"",
".",
"join",
"(",
"self",
".",
"type",
")",
"}",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardAdr.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,"ADR",None)
for t in ("home","work","postal","parcel","dom","intl","pref"):
if t in self.type:
n.newChild(None,t.upper(),None)
n.newTextChild(None,"POBOX",to_utf8(self.pobox))
n.newTextChild(None,"EXTADD",to_utf8(self.extadr))
n.newTextChild(None,"STREET",to_utf8(self.street))
n.newTextChild(None,"LOCALITY",to_utf8(self.locality))
n.newTextChild(None,"REGION",to_utf8(self.region))
n.newTextChild(None,"PCODE",to_utf8(self.pcode))
n.newTextChild(None,"CTRY",to_utf8(self.ctry))
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,"ADR",None)
for t in ("home","work","postal","parcel","dom","intl","pref"):
if t in self.type:
n.newChild(None,t.upper(),None)
n.newTextChild(None,"POBOX",to_utf8(self.pobox))
n.newTextChild(None,"EXTADD",to_utf8(self.extadr))
n.newTextChild(None,"STREET",to_utf8(self.street))
n.newTextChild(None,"LOCALITY",to_utf8(self.locality))
n.newTextChild(None,"REGION",to_utf8(self.region))
n.newTextChild(None,"PCODE",to_utf8(self.pcode))
n.newTextChild(None,"CTRY",to_utf8(self.ctry))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L557-L578
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"ADR\"",
",",
"None",
")",
"for",
"t",
"in",
"(",
"\"home\"",
",",
"\"work\"",
",",
"\"postal\"",
",",
"\"parcel\"",
",",
"\"dom\"",
",",
"\"intl\"",
",",
"\"pref\"",
")",
":",
"if",
"t",
"in",
"self",
".",
"type",
":",
"n",
".",
"newChild",
"(",
"None",
",",
"t",
".",
"upper",
"(",
")",
",",
"None",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"POBOX\"",
",",
"to_utf8",
"(",
"self",
".",
"pobox",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"EXTADD\"",
",",
"to_utf8",
"(",
"self",
".",
"extadr",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"STREET\"",
",",
"to_utf8",
"(",
"self",
".",
"street",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"LOCALITY\"",
",",
"to_utf8",
"(",
"self",
".",
"locality",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"REGION\"",
",",
"to_utf8",
"(",
"self",
".",
"region",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"PCODE\"",
",",
"to_utf8",
"(",
"self",
".",
"pcode",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"CTRY\"",
",",
"to_utf8",
"(",
"self",
".",
"ctry",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardLabel.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("label",u"\n".join(self.lines),
{"type":",".join(self.type)})
|
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
return rfc2425encode("label",u"\n".join(self.lines),
{"type":",".join(self.type)})
|
[
"RFC2426",
"-",
"encode",
"the",
"field",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L641-L647
|
[
"def",
"rfc2426",
"(",
"self",
")",
":",
"return",
"rfc2425encode",
"(",
"\"label\"",
",",
"u\"\\n\"",
".",
"join",
"(",
"self",
".",
"lines",
")",
",",
"{",
"\"type\"",
":",
"\",\"",
".",
"join",
"(",
"self",
".",
"type",
")",
"}",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardLabel.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,"ADR",None)
for t in ("home","work","postal","parcel","dom","intl","pref"):
if t in self.type:
n.newChild(None,t.upper(),None)
for l in self.lines:
n.newTextChild(None,"LINE",l)
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,"ADR",None)
for t in ("home","work","postal","parcel","dom","intl","pref"):
if t in self.type:
n.newChild(None,t.upper(),None)
for l in self.lines:
n.newTextChild(None,"LINE",l)
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L648-L664
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"ADR\"",
",",
"None",
")",
"for",
"t",
"in",
"(",
"\"home\"",
",",
"\"work\"",
",",
"\"postal\"",
",",
"\"parcel\"",
",",
"\"dom\"",
",",
"\"intl\"",
",",
"\"pref\"",
")",
":",
"if",
"t",
"in",
"self",
".",
"type",
":",
"n",
".",
"newChild",
"(",
"None",
",",
"t",
".",
"upper",
"(",
")",
",",
"None",
")",
"for",
"l",
"in",
"self",
".",
"lines",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"LINE\"",
",",
"l",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardTel.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,"TEL",None)
for t in ("home","work","voice","fax","pager","msg","cell","video",
"bbs","modem","isdn","pcs","pref"):
if t in self.type:
n.newChild(None,t.upper(),None)
n.newTextChild(None,"NUMBER",to_utf8(self.number))
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,"TEL",None)
for t in ("home","work","voice","fax","pager","msg","cell","video",
"bbs","modem","isdn","pcs","pref"):
if t in self.type:
n.newChild(None,t.upper(),None)
n.newTextChild(None,"NUMBER",to_utf8(self.number))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L729-L745
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"TEL\"",
",",
"None",
")",
"for",
"t",
"in",
"(",
"\"home\"",
",",
"\"work\"",
",",
"\"voice\"",
",",
"\"fax\"",
",",
"\"pager\"",
",",
"\"msg\"",
",",
"\"cell\"",
",",
"\"video\"",
",",
"\"bbs\"",
",",
"\"modem\"",
",",
"\"isdn\"",
",",
"\"pcs\"",
",",
"\"pref\"",
")",
":",
"if",
"t",
"in",
"self",
".",
"type",
":",
"n",
".",
"newChild",
"(",
"None",
",",
"t",
".",
"upper",
"(",
")",
",",
"None",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"NUMBER\"",
",",
"to_utf8",
"(",
"self",
".",
"number",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardGeo.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("geo",u';'.join(quote_semicolon(val) for val in
(self.lat,self.lon)))
|
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
return rfc2425encode("geo",u';'.join(quote_semicolon(val) for val in
(self.lat,self.lon)))
|
[
"RFC2426",
"-",
"encode",
"the",
"field",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L871-L877
|
[
"def",
"rfc2426",
"(",
"self",
")",
":",
"return",
"rfc2425encode",
"(",
"\"geo\"",
",",
"u';'",
".",
"join",
"(",
"quote_semicolon",
"(",
"val",
")",
"for",
"val",
"in",
"(",
"self",
".",
"lat",
",",
"self",
".",
"lon",
")",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardGeo.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,"GEO",None)
n.newTextChild(None,"LAT",to_utf8(self.lat))
n.newTextChild(None,"LON",to_utf8(self.lon))
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,"GEO",None)
n.newTextChild(None,"LAT",to_utf8(self.lat))
n.newTextChild(None,"LON",to_utf8(self.lon))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L878-L891
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"GEO\"",
",",
"None",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"LAT\"",
",",
"to_utf8",
"(",
"self",
".",
"lat",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"LON\"",
",",
"to_utf8",
"(",
"self",
".",
"lon",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardOrg.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.unit:
return rfc2425encode("org",u';'.join(quote_semicolon(val) for val in
(self.name,self.unit)))
else:
return rfc2425encode("org",unicode(quote_semicolon(self.name)))
|
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
if self.unit:
return rfc2425encode("org",u';'.join(quote_semicolon(val) for val in
(self.name,self.unit)))
else:
return rfc2425encode("org",unicode(quote_semicolon(self.name)))
|
[
"RFC2426",
"-",
"encode",
"the",
"field",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L944-L953
|
[
"def",
"rfc2426",
"(",
"self",
")",
":",
"if",
"self",
".",
"unit",
":",
"return",
"rfc2425encode",
"(",
"\"org\"",
",",
"u';'",
".",
"join",
"(",
"quote_semicolon",
"(",
"val",
")",
"for",
"val",
"in",
"(",
"self",
".",
"name",
",",
"self",
".",
"unit",
")",
")",
")",
"else",
":",
"return",
"rfc2425encode",
"(",
"\"org\"",
",",
"unicode",
"(",
"quote_semicolon",
"(",
"self",
".",
"name",
")",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardOrg.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,"ORG",None)
n.newTextChild(None,"ORGNAME",to_utf8(self.name))
n.newTextChild(None,"ORGUNIT",to_utf8(self.unit))
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,"ORG",None)
n.newTextChild(None,"ORGNAME",to_utf8(self.name))
n.newTextChild(None,"ORGUNIT",to_utf8(self.unit))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L954-L967
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"ORG\"",
",",
"None",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"ORGNAME\"",
",",
"to_utf8",
"(",
"self",
".",
"name",
")",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"ORGUNIT\"",
",",
"to_utf8",
"(",
"self",
".",
"unit",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardCategories.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,"CATEGORIES",None)
for k in self.keywords:
n.newTextChild(None,"KEYWORD",to_utf8(k))
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,"CATEGORIES",None)
for k in self.keywords:
n.newTextChild(None,"KEYWORD",to_utf8(k))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1018-L1031
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"\"CATEGORIES\"",
",",
"None",
")",
"for",
"k",
"in",
"self",
".",
"keywords",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"KEYWORD\"",
",",
"to_utf8",
"(",
"k",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardSound.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.sound:
return rfc2425encode(self.name,self.sound)
|
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.sound:
return rfc2425encode(self.name,self.sound)
|
[
"RFC2426",
"-",
"encode",
"the",
"field",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1094-L1102
|
[
"def",
"rfc2426",
"(",
"self",
")",
":",
"if",
"self",
".",
"uri",
":",
"return",
"rfc2425encode",
"(",
"self",
".",
"name",
",",
"self",
".",
"uri",
",",
"{",
"\"value\"",
":",
"\"uri\"",
"}",
")",
"elif",
"self",
".",
"sound",
":",
"return",
"rfc2425encode",
"(",
"self",
".",
"name",
",",
"self",
".",
"sound",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardSound.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,self.name.upper(),None)
if self.uri:
n.newTextChild(None,"EXTVAL",to_utf8(self.uri))
elif self.phonetic:
n.newTextChild(None,"PHONETIC",to_utf8(self.phonetic))
else:
n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.sound))
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,self.name.upper(),None)
if self.uri:
n.newTextChild(None,"EXTVAL",to_utf8(self.uri))
elif self.phonetic:
n.newTextChild(None,"PHONETIC",to_utf8(self.phonetic))
else:
n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.sound))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1103-L1120
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"self",
".",
"name",
".",
"upper",
"(",
")",
",",
"None",
")",
"if",
"self",
".",
"uri",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"EXTVAL\"",
",",
"to_utf8",
"(",
"self",
".",
"uri",
")",
")",
"elif",
"self",
".",
"phonetic",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"PHONETIC\"",
",",
"to_utf8",
"(",
"self",
".",
"phonetic",
")",
")",
"else",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"BINVAL\"",
",",
"binascii",
".",
"b2a_base64",
"(",
"self",
".",
"sound",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardPrivacy.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`"""
if self.value in ("public","private","confidental"):
n=parent.newChild(None,self.name.upper(),None)
n.newChild(None,self.value.upper(),None)
return n
return None
|
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`"""
if self.value in ("public","private","confidental"):
n=parent.newChild(None,self.name.upper(),None)
n.newChild(None,self.value.upper(),None)
return n
return None
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1172-L1186
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"value",
"in",
"(",
"\"public\"",
",",
"\"private\"",
",",
"\"confidental\"",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"self",
".",
"name",
".",
"upper",
"(",
")",
",",
"None",
")",
"n",
".",
"newChild",
"(",
"None",
",",
"self",
".",
"value",
".",
"upper",
"(",
")",
",",
"None",
")",
"return",
"n",
"return",
"None"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardKey.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.type:
p={"type":self.type}
else:
p={}
return rfc2425encode(self.name,self.cred,p)
|
def rfc2426(self):
"""RFC2426-encode the field content.
:return: the field in the RFC 2426 format.
:returntype: `str`"""
if self.type:
p={"type":self.type}
else:
p={}
return rfc2425encode(self.name,self.cred,p)
|
[
"RFC2426",
"-",
"encode",
"the",
"field",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1233-L1242
|
[
"def",
"rfc2426",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
":",
"p",
"=",
"{",
"\"type\"",
":",
"self",
".",
"type",
"}",
"else",
":",
"p",
"=",
"{",
"}",
"return",
"rfc2425encode",
"(",
"self",
".",
"name",
",",
"self",
".",
"cred",
",",
"p",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCardKey.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,self.name.upper(),None)
if self.type:
n.newTextChild(None,"TYPE",self.type)
n.newTextChild(None,"CRED",binascii.b2a_base64(self.cred))
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,self.name.upper(),None)
if self.type:
n.newTextChild(None,"TYPE",self.type)
n.newTextChild(None,"CRED",binascii.b2a_base64(self.cred))
return n
|
[
"Create",
"vcard",
"-",
"tmp",
"XML",
"representation",
"of",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1243-L1257
|
[
"def",
"as_xml",
"(",
"self",
",",
"parent",
")",
":",
"n",
"=",
"parent",
".",
"newChild",
"(",
"None",
",",
"self",
".",
"name",
".",
"upper",
"(",
")",
",",
"None",
")",
"if",
"self",
".",
"type",
":",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"TYPE\"",
",",
"self",
".",
"type",
")",
"n",
".",
"newTextChild",
"(",
"None",
",",
"\"CRED\"",
",",
"binascii",
".",
"b2a_base64",
"(",
"self",
".",
"cred",
")",
")",
"return",
"n"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCard.__make_fn
|
Initialize the mandatory `self.fn` from `self.n`.
This is a workaround for buggy clients which set only one of them.
|
pyxmpp2/ext/vcard.py
|
def __make_fn(self):
"""Initialize the mandatory `self.fn` from `self.n`.
This is a workaround for buggy clients which set only one of them."""
s=[]
if self.n.prefix:
s.append(self.n.prefix)
if self.n.given:
s.append(self.n.given)
if self.n.middle:
s.append(self.n.middle)
if self.n.family:
s.append(self.n.family)
if self.n.suffix:
s.append(self.n.suffix)
s=u" ".join(s)
self.content["FN"]=VCardString("FN", s, empty_ok = True)
|
def __make_fn(self):
"""Initialize the mandatory `self.fn` from `self.n`.
This is a workaround for buggy clients which set only one of them."""
s=[]
if self.n.prefix:
s.append(self.n.prefix)
if self.n.given:
s.append(self.n.given)
if self.n.middle:
s.append(self.n.middle)
if self.n.family:
s.append(self.n.family)
if self.n.suffix:
s.append(self.n.suffix)
s=u" ".join(s)
self.content["FN"]=VCardString("FN", s, empty_ok = True)
|
[
"Initialize",
"the",
"mandatory",
"self",
".",
"fn",
"from",
"self",
".",
"n",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1399-L1415
|
[
"def",
"__make_fn",
"(",
"self",
")",
":",
"s",
"=",
"[",
"]",
"if",
"self",
".",
"n",
".",
"prefix",
":",
"s",
".",
"append",
"(",
"self",
".",
"n",
".",
"prefix",
")",
"if",
"self",
".",
"n",
".",
"given",
":",
"s",
".",
"append",
"(",
"self",
".",
"n",
".",
"given",
")",
"if",
"self",
".",
"n",
".",
"middle",
":",
"s",
".",
"append",
"(",
"self",
".",
"n",
".",
"middle",
")",
"if",
"self",
".",
"n",
".",
"family",
":",
"s",
".",
"append",
"(",
"self",
".",
"n",
".",
"family",
")",
"if",
"self",
".",
"n",
".",
"suffix",
":",
"s",
".",
"append",
"(",
"self",
".",
"n",
".",
"suffix",
")",
"s",
"=",
"u\" \"",
".",
"join",
"(",
"s",
")",
"self",
".",
"content",
"[",
"\"FN\"",
"]",
"=",
"VCardString",
"(",
"\"FN\"",
",",
"s",
",",
"empty_ok",
"=",
"True",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCard.__from_xml
|
Initialize a VCard object from XML node.
:Parameters:
- `data`: vcard to parse.
:Types:
- `data`: `libxml2.xmlNode`
|
pyxmpp2/ext/vcard.py
|
def __from_xml(self,data):
"""Initialize a VCard object from XML node.
:Parameters:
- `data`: vcard to parse.
:Types:
- `data`: `libxml2.xmlNode`"""
ns=get_node_ns(data)
if ns and ns.getContent()!=VCARD_NS:
raise ValueError("Not in the %r namespace" % (VCARD_NS,))
if data.name!="vCard":
raise ValueError("Bad root element name: %r" % (data.name,))
n=data.children
dns=get_node_ns(data)
while n:
if n.type!='element':
n=n.next
continue
ns=get_node_ns(n)
if (ns and dns and ns.getContent()!=dns.getContent()):
n=n.next
continue
if not self.components.has_key(n.name):
n=n.next
continue
cl,tp=self.components[n.name]
if tp in ("required","optional"):
if self.content.has_key(n.name):
raise ValueError("Duplicate %s" % (n.name,))
try:
self.content[n.name]=cl(n.name,n)
except Empty:
pass
elif tp=="multi":
if not self.content.has_key(n.name):
self.content[n.name]=[]
try:
self.content[n.name].append(cl(n.name,n))
except Empty:
pass
n=n.next
|
def __from_xml(self,data):
"""Initialize a VCard object from XML node.
:Parameters:
- `data`: vcard to parse.
:Types:
- `data`: `libxml2.xmlNode`"""
ns=get_node_ns(data)
if ns and ns.getContent()!=VCARD_NS:
raise ValueError("Not in the %r namespace" % (VCARD_NS,))
if data.name!="vCard":
raise ValueError("Bad root element name: %r" % (data.name,))
n=data.children
dns=get_node_ns(data)
while n:
if n.type!='element':
n=n.next
continue
ns=get_node_ns(n)
if (ns and dns and ns.getContent()!=dns.getContent()):
n=n.next
continue
if not self.components.has_key(n.name):
n=n.next
continue
cl,tp=self.components[n.name]
if tp in ("required","optional"):
if self.content.has_key(n.name):
raise ValueError("Duplicate %s" % (n.name,))
try:
self.content[n.name]=cl(n.name,n)
except Empty:
pass
elif tp=="multi":
if not self.content.has_key(n.name):
self.content[n.name]=[]
try:
self.content[n.name].append(cl(n.name,n))
except Empty:
pass
n=n.next
|
[
"Initialize",
"a",
"VCard",
"object",
"from",
"XML",
"node",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1417-L1457
|
[
"def",
"__from_xml",
"(",
"self",
",",
"data",
")",
":",
"ns",
"=",
"get_node_ns",
"(",
"data",
")",
"if",
"ns",
"and",
"ns",
".",
"getContent",
"(",
")",
"!=",
"VCARD_NS",
":",
"raise",
"ValueError",
"(",
"\"Not in the %r namespace\"",
"%",
"(",
"VCARD_NS",
",",
")",
")",
"if",
"data",
".",
"name",
"!=",
"\"vCard\"",
":",
"raise",
"ValueError",
"(",
"\"Bad root element name: %r\"",
"%",
"(",
"data",
".",
"name",
",",
")",
")",
"n",
"=",
"data",
".",
"children",
"dns",
"=",
"get_node_ns",
"(",
"data",
")",
"while",
"n",
":",
"if",
"n",
".",
"type",
"!=",
"'element'",
":",
"n",
"=",
"n",
".",
"next",
"continue",
"ns",
"=",
"get_node_ns",
"(",
"n",
")",
"if",
"(",
"ns",
"and",
"dns",
"and",
"ns",
".",
"getContent",
"(",
")",
"!=",
"dns",
".",
"getContent",
"(",
")",
")",
":",
"n",
"=",
"n",
".",
"next",
"continue",
"if",
"not",
"self",
".",
"components",
".",
"has_key",
"(",
"n",
".",
"name",
")",
":",
"n",
"=",
"n",
".",
"next",
"continue",
"cl",
",",
"tp",
"=",
"self",
".",
"components",
"[",
"n",
".",
"name",
"]",
"if",
"tp",
"in",
"(",
"\"required\"",
",",
"\"optional\"",
")",
":",
"if",
"self",
".",
"content",
".",
"has_key",
"(",
"n",
".",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"Duplicate %s\"",
"%",
"(",
"n",
".",
"name",
",",
")",
")",
"try",
":",
"self",
".",
"content",
"[",
"n",
".",
"name",
"]",
"=",
"cl",
"(",
"n",
".",
"name",
",",
"n",
")",
"except",
"Empty",
":",
"pass",
"elif",
"tp",
"==",
"\"multi\"",
":",
"if",
"not",
"self",
".",
"content",
".",
"has_key",
"(",
"n",
".",
"name",
")",
":",
"self",
".",
"content",
"[",
"n",
".",
"name",
"]",
"=",
"[",
"]",
"try",
":",
"self",
".",
"content",
"[",
"n",
".",
"name",
"]",
".",
"append",
"(",
"cl",
"(",
"n",
".",
"name",
",",
"n",
")",
")",
"except",
"Empty",
":",
"pass",
"n",
"=",
"n",
".",
"next"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCard.__from_rfc2426
|
Initialize a VCard object from an RFC2426 string.
:Parameters:
- `data`: vcard to parse.
:Types:
- `data`: `libxml2.xmlNode`, `unicode` or `str`
|
pyxmpp2/ext/vcard.py
|
def __from_rfc2426(self,data):
"""Initialize a VCard object from an RFC2426 string.
:Parameters:
- `data`: vcard to parse.
:Types:
- `data`: `libxml2.xmlNode`, `unicode` or `str`"""
data=from_utf8(data)
lines=data.split("\n")
started=0
current=None
for l in lines:
if not l:
continue
if l[-1]=="\r":
l=l[:-1]
if not l:
continue
if l[0] in " \t":
if current is None:
continue
current+=l[1:]
continue
if not started and current and current.upper().strip()=="BEGIN:VCARD":
started=1
elif started and current.upper().strip()=="END:VCARD":
current=None
break
elif current and started:
self._process_rfc2425_record(current)
current=l
if started and current:
self._process_rfc2425_record(current)
|
def __from_rfc2426(self,data):
"""Initialize a VCard object from an RFC2426 string.
:Parameters:
- `data`: vcard to parse.
:Types:
- `data`: `libxml2.xmlNode`, `unicode` or `str`"""
data=from_utf8(data)
lines=data.split("\n")
started=0
current=None
for l in lines:
if not l:
continue
if l[-1]=="\r":
l=l[:-1]
if not l:
continue
if l[0] in " \t":
if current is None:
continue
current+=l[1:]
continue
if not started and current and current.upper().strip()=="BEGIN:VCARD":
started=1
elif started and current.upper().strip()=="END:VCARD":
current=None
break
elif current and started:
self._process_rfc2425_record(current)
current=l
if started and current:
self._process_rfc2425_record(current)
|
[
"Initialize",
"a",
"VCard",
"object",
"from",
"an",
"RFC2426",
"string",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1459-L1491
|
[
"def",
"__from_rfc2426",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"from_utf8",
"(",
"data",
")",
"lines",
"=",
"data",
".",
"split",
"(",
"\"\\n\"",
")",
"started",
"=",
"0",
"current",
"=",
"None",
"for",
"l",
"in",
"lines",
":",
"if",
"not",
"l",
":",
"continue",
"if",
"l",
"[",
"-",
"1",
"]",
"==",
"\"\\r\"",
":",
"l",
"=",
"l",
"[",
":",
"-",
"1",
"]",
"if",
"not",
"l",
":",
"continue",
"if",
"l",
"[",
"0",
"]",
"in",
"\" \\t\"",
":",
"if",
"current",
"is",
"None",
":",
"continue",
"current",
"+=",
"l",
"[",
"1",
":",
"]",
"continue",
"if",
"not",
"started",
"and",
"current",
"and",
"current",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"==",
"\"BEGIN:VCARD\"",
":",
"started",
"=",
"1",
"elif",
"started",
"and",
"current",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"==",
"\"END:VCARD\"",
":",
"current",
"=",
"None",
"break",
"elif",
"current",
"and",
"started",
":",
"self",
".",
"_process_rfc2425_record",
"(",
"current",
")",
"current",
"=",
"l",
"if",
"started",
"and",
"current",
":",
"self",
".",
"_process_rfc2425_record",
"(",
"current",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCard._process_rfc2425_record
|
Parse single RFC2425 record and update attributes of `self`.
:Parameters:
- `data`: the record (probably multiline)
:Types:
- `data`: `unicode`
|
pyxmpp2/ext/vcard.py
|
def _process_rfc2425_record(self,data):
"""Parse single RFC2425 record and update attributes of `self`.
:Parameters:
- `data`: the record (probably multiline)
:Types:
- `data`: `unicode`"""
label,value=data.split(":",1)
value=value.replace("\\n","\n").replace("\\N","\n")
psplit=label.lower().split(";")
name=psplit[0]
params=psplit[1:]
if u"." in name:
name=name.split(".",1)[1]
name=name.upper()
if name in (u"X-DESC",u"X-JABBERID"):
name=name[2:]
if not self.components.has_key(name):
return
if params:
params=dict([p.split("=",1) for p in params])
cl,tp=self.components[name]
if tp in ("required","optional"):
if self.content.has_key(name):
raise ValueError("Duplicate %s" % (name,))
try:
self.content[name]=cl(name,value,params)
except Empty:
pass
elif tp=="multi":
if not self.content.has_key(name):
self.content[name]=[]
try:
self.content[name].append(cl(name,value,params))
except Empty:
pass
else:
return
|
def _process_rfc2425_record(self,data):
"""Parse single RFC2425 record and update attributes of `self`.
:Parameters:
- `data`: the record (probably multiline)
:Types:
- `data`: `unicode`"""
label,value=data.split(":",1)
value=value.replace("\\n","\n").replace("\\N","\n")
psplit=label.lower().split(";")
name=psplit[0]
params=psplit[1:]
if u"." in name:
name=name.split(".",1)[1]
name=name.upper()
if name in (u"X-DESC",u"X-JABBERID"):
name=name[2:]
if not self.components.has_key(name):
return
if params:
params=dict([p.split("=",1) for p in params])
cl,tp=self.components[name]
if tp in ("required","optional"):
if self.content.has_key(name):
raise ValueError("Duplicate %s" % (name,))
try:
self.content[name]=cl(name,value,params)
except Empty:
pass
elif tp=="multi":
if not self.content.has_key(name):
self.content[name]=[]
try:
self.content[name].append(cl(name,value,params))
except Empty:
pass
else:
return
|
[
"Parse",
"single",
"RFC2425",
"record",
"and",
"update",
"attributes",
"of",
"self",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1493-L1530
|
[
"def",
"_process_rfc2425_record",
"(",
"self",
",",
"data",
")",
":",
"label",
",",
"value",
"=",
"data",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"value",
"=",
"value",
".",
"replace",
"(",
"\"\\\\n\"",
",",
"\"\\n\"",
")",
".",
"replace",
"(",
"\"\\\\N\"",
",",
"\"\\n\"",
")",
"psplit",
"=",
"label",
".",
"lower",
"(",
")",
".",
"split",
"(",
"\";\"",
")",
"name",
"=",
"psplit",
"[",
"0",
"]",
"params",
"=",
"psplit",
"[",
"1",
":",
"]",
"if",
"u\".\"",
"in",
"name",
":",
"name",
"=",
"name",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"1",
"]",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"if",
"name",
"in",
"(",
"u\"X-DESC\"",
",",
"u\"X-JABBERID\"",
")",
":",
"name",
"=",
"name",
"[",
"2",
":",
"]",
"if",
"not",
"self",
".",
"components",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"if",
"params",
":",
"params",
"=",
"dict",
"(",
"[",
"p",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"for",
"p",
"in",
"params",
"]",
")",
"cl",
",",
"tp",
"=",
"self",
".",
"components",
"[",
"name",
"]",
"if",
"tp",
"in",
"(",
"\"required\"",
",",
"\"optional\"",
")",
":",
"if",
"self",
".",
"content",
".",
"has_key",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"Duplicate %s\"",
"%",
"(",
"name",
",",
")",
")",
"try",
":",
"self",
".",
"content",
"[",
"name",
"]",
"=",
"cl",
"(",
"name",
",",
"value",
",",
"params",
")",
"except",
"Empty",
":",
"pass",
"elif",
"tp",
"==",
"\"multi\"",
":",
"if",
"not",
"self",
".",
"content",
".",
"has_key",
"(",
"name",
")",
":",
"self",
".",
"content",
"[",
"name",
"]",
"=",
"[",
"]",
"try",
":",
"self",
".",
"content",
"[",
"name",
"]",
".",
"append",
"(",
"cl",
"(",
"name",
",",
"value",
",",
"params",
")",
")",
"except",
"Empty",
":",
"pass",
"else",
":",
"return"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCard.rfc2426
|
Get the RFC2426 representation of `self`.
:return: the UTF-8 encoded RFC2426 representation.
:returntype: `str`
|
pyxmpp2/ext/vcard.py
|
def rfc2426(self):
"""Get the RFC2426 representation of `self`.
:return: the UTF-8 encoded RFC2426 representation.
:returntype: `str`"""
ret="begin:VCARD\r\n"
ret+="version:3.0\r\n"
for _unused, value in self.content.items():
if value is None:
continue
if type(value) is list:
for v in value:
ret+=v.rfc2426()
else:
v=value.rfc2426()
ret+=v
return ret+"end:VCARD\r\n"
|
def rfc2426(self):
"""Get the RFC2426 representation of `self`.
:return: the UTF-8 encoded RFC2426 representation.
:returntype: `str`"""
ret="begin:VCARD\r\n"
ret+="version:3.0\r\n"
for _unused, value in self.content.items():
if value is None:
continue
if type(value) is list:
for v in value:
ret+=v.rfc2426()
else:
v=value.rfc2426()
ret+=v
return ret+"end:VCARD\r\n"
|
[
"Get",
"the",
"RFC2426",
"representation",
"of",
"self",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1533-L1549
|
[
"def",
"rfc2426",
"(",
"self",
")",
":",
"ret",
"=",
"\"begin:VCARD\\r\\n\"",
"ret",
"+=",
"\"version:3.0\\r\\n\"",
"for",
"_unused",
",",
"value",
"in",
"self",
".",
"content",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"continue",
"if",
"type",
"(",
"value",
")",
"is",
"list",
":",
"for",
"v",
"in",
"value",
":",
"ret",
"+=",
"v",
".",
"rfc2426",
"(",
")",
"else",
":",
"v",
"=",
"value",
".",
"rfc2426",
"(",
")",
"ret",
"+=",
"v",
"return",
"ret",
"+",
"\"end:VCARD\\r\\n\""
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
VCard.complete_xml_element
|
Complete the XML node with `self` content.
Should be overriden in classes derived from `StanzaPayloadObject`.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `_unused`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `_unused`: `libxml2.xmlDoc`
|
pyxmpp2/ext/vcard.py
|
def complete_xml_element(self, xmlnode, _unused):
"""Complete the XML node with `self` content.
Should be overriden in classes derived from `StanzaPayloadObject`.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `_unused`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `_unused`: `libxml2.xmlDoc`"""
for _unused1, value in self.content.items():
if value is None:
continue
if type(value) is list:
for v in value:
v.as_xml(xmlnode)
else:
value.as_xml(xmlnode)
|
def complete_xml_element(self, xmlnode, _unused):
"""Complete the XML node with `self` content.
Should be overriden in classes derived from `StanzaPayloadObject`.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `_unused`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `_unused`: `libxml2.xmlDoc`"""
for _unused1, value in self.content.items():
if value is None:
continue
if type(value) is list:
for v in value:
v.as_xml(xmlnode)
else:
value.as_xml(xmlnode)
|
[
"Complete",
"the",
"XML",
"node",
"with",
"self",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/vcard.py#L1551-L1570
|
[
"def",
"complete_xml_element",
"(",
"self",
",",
"xmlnode",
",",
"_unused",
")",
":",
"for",
"_unused1",
",",
"value",
"in",
"self",
".",
"content",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"continue",
"if",
"type",
"(",
"value",
")",
"is",
"list",
":",
"for",
"v",
"in",
"value",
":",
"v",
".",
"as_xml",
"(",
"xmlnode",
")",
"else",
":",
"value",
".",
"as_xml",
"(",
"xmlnode",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheItem.update_state
|
Update current status of the item and compute time of the next
state change.
:return: the new state.
:returntype: :std:`datetime`
|
pyxmpp2/cache.py
|
def update_state(self):
"""Update current status of the item and compute time of the next
state change.
:return: the new state.
:returntype: :std:`datetime`"""
self._lock.acquire()
try:
now = datetime.utcnow()
if self.state == 'new':
self.state = 'fresh'
if self.state == 'fresh':
if now > self.freshness_time:
self.state = 'old'
if self.state == 'old':
if now > self.expire_time:
self.state = 'stale'
if self.state == 'stale':
if now > self.purge_time:
self.state = 'purged'
self.state_value = _state_values[self.state]
return self.state
finally:
self._lock.release()
|
def update_state(self):
"""Update current status of the item and compute time of the next
state change.
:return: the new state.
:returntype: :std:`datetime`"""
self._lock.acquire()
try:
now = datetime.utcnow()
if self.state == 'new':
self.state = 'fresh'
if self.state == 'fresh':
if now > self.freshness_time:
self.state = 'old'
if self.state == 'old':
if now > self.expire_time:
self.state = 'stale'
if self.state == 'stale':
if now > self.purge_time:
self.state = 'purged'
self.state_value = _state_values[self.state]
return self.state
finally:
self._lock.release()
|
[
"Update",
"current",
"status",
"of",
"the",
"item",
"and",
"compute",
"time",
"of",
"the",
"next",
"state",
"change",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L108-L131
|
[
"def",
"update_state",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"self",
".",
"state",
"==",
"'new'",
":",
"self",
".",
"state",
"=",
"'fresh'",
"if",
"self",
".",
"state",
"==",
"'fresh'",
":",
"if",
"now",
">",
"self",
".",
"freshness_time",
":",
"self",
".",
"state",
"=",
"'old'",
"if",
"self",
".",
"state",
"==",
"'old'",
":",
"if",
"now",
">",
"self",
".",
"expire_time",
":",
"self",
".",
"state",
"=",
"'stale'",
"if",
"self",
".",
"state",
"==",
"'stale'",
":",
"if",
"now",
">",
"self",
".",
"purge_time",
":",
"self",
".",
"state",
"=",
"'purged'",
"self",
".",
"state_value",
"=",
"_state_values",
"[",
"self",
".",
"state",
"]",
"return",
"self",
".",
"state",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheFetcher._deactivate
|
Remove the fetcher from cache and mark it not active.
|
pyxmpp2/cache.py
|
def _deactivate(self):
"""Remove the fetcher from cache and mark it not active."""
self.cache.remove_fetcher(self)
if self.active:
self._deactivated()
|
def _deactivate(self):
"""Remove the fetcher from cache and mark it not active."""
self.cache.remove_fetcher(self)
if self.active:
self._deactivated()
|
[
"Remove",
"the",
"fetcher",
"from",
"cache",
"and",
"mark",
"it",
"not",
"active",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L212-L216
|
[
"def",
"_deactivate",
"(",
"self",
")",
":",
"self",
".",
"cache",
".",
"remove_fetcher",
"(",
"self",
")",
"if",
"self",
".",
"active",
":",
"self",
".",
"_deactivated",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheFetcher.got_it
|
Handle a successfull retrieval and call apriopriate handler.
Should be called when retrieval succeeds.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `value`: fetched object.
- `state`: initial state of the object.
:Types:
- `value`: any
- `state`: `str`
|
pyxmpp2/cache.py
|
def got_it(self, value, state = "new"):
"""Handle a successfull retrieval and call apriopriate handler.
Should be called when retrieval succeeds.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `value`: fetched object.
- `state`: initial state of the object.
:Types:
- `value`: any
- `state`: `str`"""
if not self.active:
return
item = CacheItem(self.address, value, self._item_freshness_period,
self._item_expiration_period, self._item_purge_period, state)
self._object_handler(item.address, item.value, item.state)
self.cache.add_item(item)
self._deactivate()
|
def got_it(self, value, state = "new"):
"""Handle a successfull retrieval and call apriopriate handler.
Should be called when retrieval succeeds.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `value`: fetched object.
- `state`: initial state of the object.
:Types:
- `value`: any
- `state`: `str`"""
if not self.active:
return
item = CacheItem(self.address, value, self._item_freshness_period,
self._item_expiration_period, self._item_purge_period, state)
self._object_handler(item.address, item.value, item.state)
self.cache.add_item(item)
self._deactivate()
|
[
"Handle",
"a",
"successfull",
"retrieval",
"and",
"call",
"apriopriate",
"handler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L228-L248
|
[
"def",
"got_it",
"(",
"self",
",",
"value",
",",
"state",
"=",
"\"new\"",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"return",
"item",
"=",
"CacheItem",
"(",
"self",
".",
"address",
",",
"value",
",",
"self",
".",
"_item_freshness_period",
",",
"self",
".",
"_item_expiration_period",
",",
"self",
".",
"_item_purge_period",
",",
"state",
")",
"self",
".",
"_object_handler",
"(",
"item",
".",
"address",
",",
"item",
".",
"value",
",",
"item",
".",
"state",
")",
"self",
".",
"cache",
".",
"add_item",
"(",
"item",
")",
"self",
".",
"_deactivate",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheFetcher.error
|
Handle a retrieval error and call apriopriate handler.
Should be called when retrieval fails.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `error_data`: additional information about the error (e.g. `StanzaError` instance).
:Types:
- `error_data`: fetcher dependant
|
pyxmpp2/cache.py
|
def error(self, error_data):
"""Handle a retrieval error and call apriopriate handler.
Should be called when retrieval fails.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `error_data`: additional information about the error (e.g. `StanzaError` instance).
:Types:
- `error_data`: fetcher dependant
"""
if not self.active:
return
if not self._try_backup_item():
self._error_handler(self.address, error_data)
self.cache.invalidate_object(self.address)
self._deactivate()
|
def error(self, error_data):
"""Handle a retrieval error and call apriopriate handler.
Should be called when retrieval fails.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
:Parameters:
- `error_data`: additional information about the error (e.g. `StanzaError` instance).
:Types:
- `error_data`: fetcher dependant
"""
if not self.active:
return
if not self._try_backup_item():
self._error_handler(self.address, error_data)
self.cache.invalidate_object(self.address)
self._deactivate()
|
[
"Handle",
"a",
"retrieval",
"error",
"and",
"call",
"apriopriate",
"handler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L250-L268
|
[
"def",
"error",
"(",
"self",
",",
"error_data",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"return",
"if",
"not",
"self",
".",
"_try_backup_item",
"(",
")",
":",
"self",
".",
"_error_handler",
"(",
"self",
".",
"address",
",",
"error_data",
")",
"self",
".",
"cache",
".",
"invalidate_object",
"(",
"self",
".",
"address",
")",
"self",
".",
"_deactivate",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheFetcher.timeout
|
Handle fetcher timeout and call apriopriate handler.
Is called by the cache object and should _not_ be called by fetcher or
application.
Do nothing when the fetcher is not active any more (after
one of handlers was already called).
|
pyxmpp2/cache.py
|
def timeout(self):
"""Handle fetcher timeout and call apriopriate handler.
Is called by the cache object and should _not_ be called by fetcher or
application.
Do nothing when the fetcher is not active any more (after
one of handlers was already called)."""
if not self.active:
return
if not self._try_backup_item():
if self._timeout_handler:
self._timeout_handler(self.address)
else:
self._error_handler(self.address, None)
self.cache.invalidate_object(self.address)
self._deactivate()
|
def timeout(self):
"""Handle fetcher timeout and call apriopriate handler.
Is called by the cache object and should _not_ be called by fetcher or
application.
Do nothing when the fetcher is not active any more (after
one of handlers was already called)."""
if not self.active:
return
if not self._try_backup_item():
if self._timeout_handler:
self._timeout_handler(self.address)
else:
self._error_handler(self.address, None)
self.cache.invalidate_object(self.address)
self._deactivate()
|
[
"Handle",
"fetcher",
"timeout",
"and",
"call",
"apriopriate",
"handler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L270-L286
|
[
"def",
"timeout",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"return",
"if",
"not",
"self",
".",
"_try_backup_item",
"(",
")",
":",
"if",
"self",
".",
"_timeout_handler",
":",
"self",
".",
"_timeout_handler",
"(",
"self",
".",
"address",
")",
"else",
":",
"self",
".",
"_error_handler",
"(",
"self",
".",
"address",
",",
"None",
")",
"self",
".",
"cache",
".",
"invalidate_object",
"(",
"self",
".",
"address",
")",
"self",
".",
"_deactivate",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheFetcher._try_backup_item
|
Check if a backup item is available in cache and call
the item handler if it is.
:return: `True` if backup item was found.
:returntype: `bool`
|
pyxmpp2/cache.py
|
def _try_backup_item(self):
"""Check if a backup item is available in cache and call
the item handler if it is.
:return: `True` if backup item was found.
:returntype: `bool`"""
if not self._backup_state:
return False
item = self.cache.get_item(self.address, self._backup_state)
if item:
self._object_handler(item.address, item.value, item.state)
return True
else:
False
|
def _try_backup_item(self):
"""Check if a backup item is available in cache and call
the item handler if it is.
:return: `True` if backup item was found.
:returntype: `bool`"""
if not self._backup_state:
return False
item = self.cache.get_item(self.address, self._backup_state)
if item:
self._object_handler(item.address, item.value, item.state)
return True
else:
False
|
[
"Check",
"if",
"a",
"backup",
"item",
"is",
"available",
"in",
"cache",
"and",
"call",
"the",
"item",
"handler",
"if",
"it",
"is",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L288-L301
|
[
"def",
"_try_backup_item",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_backup_state",
":",
"return",
"False",
"item",
"=",
"self",
".",
"cache",
".",
"get_item",
"(",
"self",
".",
"address",
",",
"self",
".",
"_backup_state",
")",
"if",
"item",
":",
"self",
".",
"_object_handler",
"(",
"item",
".",
"address",
",",
"item",
".",
"value",
",",
"item",
".",
"state",
")",
"return",
"True",
"else",
":",
"False"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.request_object
|
Request an object with given address and state not worse than
`state`. The object will be taken from cache if available, and
created/fetched otherwise. The request is asynchronous -- this metod
doesn't return the object directly, but the `object_handler` is called
as soon as the object is available (this may be before `request_object`
returns and may happen in other thread). On error the `error_handler`
will be called, and on timeout -- the `timeout_handler`.
:Parameters:
- `address`: address of the object requested.
- `state`: the worst acceptable object state. When 'new' then always
a new object will be created/fetched. 'stale' will select any
item available in cache.
- `object_handler`: function to be called when object is available.
It will be called with the following arguments: address, object
and its state.
- `error_handler`: function to be called on object retrieval error.
It will be called with two arguments: requested address and
additional error information (fetcher-specific, may be
StanzaError for XMPP objects). If not given, then the object
handler will be called with object set to `None` and state
"error".
- `timeout_handler`: function to be called on object retrieval
timeout. It will be called with only one argument: the requested
address. If not given, then the `error_handler` will be called
instead, with error details set to `None`.
- `backup_state`: when set and object in state `state` is not
available in the cache and object retrieval failed then object
with this state will also be looked-up in the cache and provided
if available.
- `timeout`: time interval after which retrieval of the object
should be given up.
- `freshness_period`: time interval after which the item created
should become 'old'.
- `expiration_period`: time interval after which the item created
should become 'stale'.
- `purge_period`: time interval after which the item created
shuld be removed from the cache.
:Types:
- `address`: any hashable
- `state`: "new", "fresh", "old" or "stale"
- `object_handler`: callable(address, value, state)
- `error_handler`: callable(address, error_data)
- `timeout_handler`: callable(address)
- `backup_state`: "new", "fresh", "old" or "stale"
- `timeout`: `timedelta`
- `freshness_period`: `timedelta`
- `expiration_period`: `timedelta`
- `purge_period`: `timedelta`
|
pyxmpp2/cache.py
|
def request_object(self, address, state, object_handler,
error_handler = None, timeout_handler = None,
backup_state = None, timeout = timedelta(minutes=60),
freshness_period = None, expiration_period = None,
purge_period = None):
"""Request an object with given address and state not worse than
`state`. The object will be taken from cache if available, and
created/fetched otherwise. The request is asynchronous -- this metod
doesn't return the object directly, but the `object_handler` is called
as soon as the object is available (this may be before `request_object`
returns and may happen in other thread). On error the `error_handler`
will be called, and on timeout -- the `timeout_handler`.
:Parameters:
- `address`: address of the object requested.
- `state`: the worst acceptable object state. When 'new' then always
a new object will be created/fetched. 'stale' will select any
item available in cache.
- `object_handler`: function to be called when object is available.
It will be called with the following arguments: address, object
and its state.
- `error_handler`: function to be called on object retrieval error.
It will be called with two arguments: requested address and
additional error information (fetcher-specific, may be
StanzaError for XMPP objects). If not given, then the object
handler will be called with object set to `None` and state
"error".
- `timeout_handler`: function to be called on object retrieval
timeout. It will be called with only one argument: the requested
address. If not given, then the `error_handler` will be called
instead, with error details set to `None`.
- `backup_state`: when set and object in state `state` is not
available in the cache and object retrieval failed then object
with this state will also be looked-up in the cache and provided
if available.
- `timeout`: time interval after which retrieval of the object
should be given up.
- `freshness_period`: time interval after which the item created
should become 'old'.
- `expiration_period`: time interval after which the item created
should become 'stale'.
- `purge_period`: time interval after which the item created
shuld be removed from the cache.
:Types:
- `address`: any hashable
- `state`: "new", "fresh", "old" or "stale"
- `object_handler`: callable(address, value, state)
- `error_handler`: callable(address, error_data)
- `timeout_handler`: callable(address)
- `backup_state`: "new", "fresh", "old" or "stale"
- `timeout`: `timedelta`
- `freshness_period`: `timedelta`
- `expiration_period`: `timedelta`
- `purge_period`: `timedelta`
"""
self._lock.acquire()
try:
if state == 'stale':
state = 'purged'
item = self.get_item(address, state)
if item:
object_handler(item.address, item.value, item.state)
return
if not self._fetcher:
raise TypeError("No cache fetcher defined")
if not error_handler:
def default_error_handler(address, _unused):
"Default error handler."
return object_handler(address, None, 'error')
error_handler = default_error_handler
if not timeout_handler:
def default_timeout_handler(address):
"Default timeout handler."
return error_handler(address, None)
timeout_handler = default_timeout_handler
if freshness_period is None:
freshness_period = self.default_freshness_period
if expiration_period is None:
expiration_period = self.default_expiration_period
if purge_period is None:
purge_period = self.default_purge_period
fetcher = self._fetcher(self, address, freshness_period,
expiration_period, purge_period, object_handler, error_handler,
timeout_handler, timeout, backup_state)
fetcher.fetch()
self._active_fetchers.append((fetcher.timeout_time,fetcher))
self._active_fetchers.sort()
finally:
self._lock.release()
|
def request_object(self, address, state, object_handler,
error_handler = None, timeout_handler = None,
backup_state = None, timeout = timedelta(minutes=60),
freshness_period = None, expiration_period = None,
purge_period = None):
"""Request an object with given address and state not worse than
`state`. The object will be taken from cache if available, and
created/fetched otherwise. The request is asynchronous -- this metod
doesn't return the object directly, but the `object_handler` is called
as soon as the object is available (this may be before `request_object`
returns and may happen in other thread). On error the `error_handler`
will be called, and on timeout -- the `timeout_handler`.
:Parameters:
- `address`: address of the object requested.
- `state`: the worst acceptable object state. When 'new' then always
a new object will be created/fetched. 'stale' will select any
item available in cache.
- `object_handler`: function to be called when object is available.
It will be called with the following arguments: address, object
and its state.
- `error_handler`: function to be called on object retrieval error.
It will be called with two arguments: requested address and
additional error information (fetcher-specific, may be
StanzaError for XMPP objects). If not given, then the object
handler will be called with object set to `None` and state
"error".
- `timeout_handler`: function to be called on object retrieval
timeout. It will be called with only one argument: the requested
address. If not given, then the `error_handler` will be called
instead, with error details set to `None`.
- `backup_state`: when set and object in state `state` is not
available in the cache and object retrieval failed then object
with this state will also be looked-up in the cache and provided
if available.
- `timeout`: time interval after which retrieval of the object
should be given up.
- `freshness_period`: time interval after which the item created
should become 'old'.
- `expiration_period`: time interval after which the item created
should become 'stale'.
- `purge_period`: time interval after which the item created
shuld be removed from the cache.
:Types:
- `address`: any hashable
- `state`: "new", "fresh", "old" or "stale"
- `object_handler`: callable(address, value, state)
- `error_handler`: callable(address, error_data)
- `timeout_handler`: callable(address)
- `backup_state`: "new", "fresh", "old" or "stale"
- `timeout`: `timedelta`
- `freshness_period`: `timedelta`
- `expiration_period`: `timedelta`
- `purge_period`: `timedelta`
"""
self._lock.acquire()
try:
if state == 'stale':
state = 'purged'
item = self.get_item(address, state)
if item:
object_handler(item.address, item.value, item.state)
return
if not self._fetcher:
raise TypeError("No cache fetcher defined")
if not error_handler:
def default_error_handler(address, _unused):
"Default error handler."
return object_handler(address, None, 'error')
error_handler = default_error_handler
if not timeout_handler:
def default_timeout_handler(address):
"Default timeout handler."
return error_handler(address, None)
timeout_handler = default_timeout_handler
if freshness_period is None:
freshness_period = self.default_freshness_period
if expiration_period is None:
expiration_period = self.default_expiration_period
if purge_period is None:
purge_period = self.default_purge_period
fetcher = self._fetcher(self, address, freshness_period,
expiration_period, purge_period, object_handler, error_handler,
timeout_handler, timeout, backup_state)
fetcher.fetch()
self._active_fetchers.append((fetcher.timeout_time,fetcher))
self._active_fetchers.sort()
finally:
self._lock.release()
|
[
"Request",
"an",
"object",
"with",
"given",
"address",
"and",
"state",
"not",
"worse",
"than",
"state",
".",
"The",
"object",
"will",
"be",
"taken",
"from",
"cache",
"if",
"available",
"and",
"created",
"/",
"fetched",
"otherwise",
".",
"The",
"request",
"is",
"asynchronous",
"--",
"this",
"metod",
"doesn",
"t",
"return",
"the",
"object",
"directly",
"but",
"the",
"object_handler",
"is",
"called",
"as",
"soon",
"as",
"the",
"object",
"is",
"available",
"(",
"this",
"may",
"be",
"before",
"request_object",
"returns",
"and",
"may",
"happen",
"in",
"other",
"thread",
")",
".",
"On",
"error",
"the",
"error_handler",
"will",
"be",
"called",
"and",
"on",
"timeout",
"--",
"the",
"timeout_handler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L372-L461
|
[
"def",
"request_object",
"(",
"self",
",",
"address",
",",
"state",
",",
"object_handler",
",",
"error_handler",
"=",
"None",
",",
"timeout_handler",
"=",
"None",
",",
"backup_state",
"=",
"None",
",",
"timeout",
"=",
"timedelta",
"(",
"minutes",
"=",
"60",
")",
",",
"freshness_period",
"=",
"None",
",",
"expiration_period",
"=",
"None",
",",
"purge_period",
"=",
"None",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"state",
"==",
"'stale'",
":",
"state",
"=",
"'purged'",
"item",
"=",
"self",
".",
"get_item",
"(",
"address",
",",
"state",
")",
"if",
"item",
":",
"object_handler",
"(",
"item",
".",
"address",
",",
"item",
".",
"value",
",",
"item",
".",
"state",
")",
"return",
"if",
"not",
"self",
".",
"_fetcher",
":",
"raise",
"TypeError",
"(",
"\"No cache fetcher defined\"",
")",
"if",
"not",
"error_handler",
":",
"def",
"default_error_handler",
"(",
"address",
",",
"_unused",
")",
":",
"\"Default error handler.\"",
"return",
"object_handler",
"(",
"address",
",",
"None",
",",
"'error'",
")",
"error_handler",
"=",
"default_error_handler",
"if",
"not",
"timeout_handler",
":",
"def",
"default_timeout_handler",
"(",
"address",
")",
":",
"\"Default timeout handler.\"",
"return",
"error_handler",
"(",
"address",
",",
"None",
")",
"timeout_handler",
"=",
"default_timeout_handler",
"if",
"freshness_period",
"is",
"None",
":",
"freshness_period",
"=",
"self",
".",
"default_freshness_period",
"if",
"expiration_period",
"is",
"None",
":",
"expiration_period",
"=",
"self",
".",
"default_expiration_period",
"if",
"purge_period",
"is",
"None",
":",
"purge_period",
"=",
"self",
".",
"default_purge_period",
"fetcher",
"=",
"self",
".",
"_fetcher",
"(",
"self",
",",
"address",
",",
"freshness_period",
",",
"expiration_period",
",",
"purge_period",
",",
"object_handler",
",",
"error_handler",
",",
"timeout_handler",
",",
"timeout",
",",
"backup_state",
")",
"fetcher",
".",
"fetch",
"(",
")",
"self",
".",
"_active_fetchers",
".",
"append",
"(",
"(",
"fetcher",
".",
"timeout_time",
",",
"fetcher",
")",
")",
"self",
".",
"_active_fetchers",
".",
"sort",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.invalidate_object
|
Force cache item state change (to 'worse' state only).
:Parameters:
- `state`: the new state requested.
:Types:
- `state`: `str`
|
pyxmpp2/cache.py
|
def invalidate_object(self, address, state = 'stale'):
"""Force cache item state change (to 'worse' state only).
:Parameters:
- `state`: the new state requested.
:Types:
- `state`: `str`"""
self._lock.acquire()
try:
item = self.get_item(address)
if item and item.state_value<_state_values[state]:
item.state=state
item.update_state()
self._items_list.sort()
finally:
self._lock.release()
|
def invalidate_object(self, address, state = 'stale'):
"""Force cache item state change (to 'worse' state only).
:Parameters:
- `state`: the new state requested.
:Types:
- `state`: `str`"""
self._lock.acquire()
try:
item = self.get_item(address)
if item and item.state_value<_state_values[state]:
item.state=state
item.update_state()
self._items_list.sort()
finally:
self._lock.release()
|
[
"Force",
"cache",
"item",
"state",
"change",
"(",
"to",
"worse",
"state",
"only",
")",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L463-L478
|
[
"def",
"invalidate_object",
"(",
"self",
",",
"address",
",",
"state",
"=",
"'stale'",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"item",
"=",
"self",
".",
"get_item",
"(",
"address",
")",
"if",
"item",
"and",
"item",
".",
"state_value",
"<",
"_state_values",
"[",
"state",
"]",
":",
"item",
".",
"state",
"=",
"state",
"item",
".",
"update_state",
"(",
")",
"self",
".",
"_items_list",
".",
"sort",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.add_item
|
Add an item to the cache.
Item state is updated before adding it (it will not be 'new' any more).
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `CacheItem`
:return: state of the item after addition.
:returntype: `str`
|
pyxmpp2/cache.py
|
def add_item(self, item):
"""Add an item to the cache.
Item state is updated before adding it (it will not be 'new' any more).
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `CacheItem`
:return: state of the item after addition.
:returntype: `str`
"""
self._lock.acquire()
try:
state = item.update_state()
if state != 'purged':
if len(self._items_list) >= self.max_items:
self.purge_items()
self._items[item.address] = item
self._items_list.append(item)
self._items_list.sort()
return item.state
finally:
self._lock.release()
|
def add_item(self, item):
"""Add an item to the cache.
Item state is updated before adding it (it will not be 'new' any more).
:Parameters:
- `item`: the item to add.
:Types:
- `item`: `CacheItem`
:return: state of the item after addition.
:returntype: `str`
"""
self._lock.acquire()
try:
state = item.update_state()
if state != 'purged':
if len(self._items_list) >= self.max_items:
self.purge_items()
self._items[item.address] = item
self._items_list.append(item)
self._items_list.sort()
return item.state
finally:
self._lock.release()
|
[
"Add",
"an",
"item",
"to",
"the",
"cache",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L480-L504
|
[
"def",
"add_item",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"state",
"=",
"item",
".",
"update_state",
"(",
")",
"if",
"state",
"!=",
"'purged'",
":",
"if",
"len",
"(",
"self",
".",
"_items_list",
")",
">=",
"self",
".",
"max_items",
":",
"self",
".",
"purge_items",
"(",
")",
"self",
".",
"_items",
"[",
"item",
".",
"address",
"]",
"=",
"item",
"self",
".",
"_items_list",
".",
"append",
"(",
"item",
")",
"self",
".",
"_items_list",
".",
"sort",
"(",
")",
"return",
"item",
".",
"state",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.get_item
|
Get an item from the cache.
:Parameters:
- `address`: its address.
- `state`: the worst state that is acceptable.
:Types:
- `address`: any hashable
- `state`: `str`
:return: the item or `None` if it was not found.
:returntype: `CacheItem`
|
pyxmpp2/cache.py
|
def get_item(self, address, state = 'fresh'):
"""Get an item from the cache.
:Parameters:
- `address`: its address.
- `state`: the worst state that is acceptable.
:Types:
- `address`: any hashable
- `state`: `str`
:return: the item or `None` if it was not found.
:returntype: `CacheItem`"""
self._lock.acquire()
try:
item = self._items.get(address)
if not item:
return None
self.update_item(item)
if _state_values[state] >= item.state_value:
return item
return None
finally:
self._lock.release()
|
def get_item(self, address, state = 'fresh'):
"""Get an item from the cache.
:Parameters:
- `address`: its address.
- `state`: the worst state that is acceptable.
:Types:
- `address`: any hashable
- `state`: `str`
:return: the item or `None` if it was not found.
:returntype: `CacheItem`"""
self._lock.acquire()
try:
item = self._items.get(address)
if not item:
return None
self.update_item(item)
if _state_values[state] >= item.state_value:
return item
return None
finally:
self._lock.release()
|
[
"Get",
"an",
"item",
"from",
"the",
"cache",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L506-L528
|
[
"def",
"get_item",
"(",
"self",
",",
"address",
",",
"state",
"=",
"'fresh'",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"item",
"=",
"self",
".",
"_items",
".",
"get",
"(",
"address",
")",
"if",
"not",
"item",
":",
"return",
"None",
"self",
".",
"update_item",
"(",
"item",
")",
"if",
"_state_values",
"[",
"state",
"]",
">=",
"item",
".",
"state_value",
":",
"return",
"item",
"return",
"None",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.update_item
|
Update state of an item in the cache.
Update item's state and remove the item from the cache
if its new state is 'purged'
:Parameters:
- `item`: item to update.
:Types:
- `item`: `CacheItem`
:return: new state of the item.
:returntype: `str`
|
pyxmpp2/cache.py
|
def update_item(self, item):
"""Update state of an item in the cache.
Update item's state and remove the item from the cache
if its new state is 'purged'
:Parameters:
- `item`: item to update.
:Types:
- `item`: `CacheItem`
:return: new state of the item.
:returntype: `str`"""
self._lock.acquire()
try:
state = item.update_state()
self._items_list.sort()
if item.state == 'purged':
self._purged += 1
if self._purged > 0.25*self.max_items:
self.purge_items()
return state
finally:
self._lock.release()
|
def update_item(self, item):
"""Update state of an item in the cache.
Update item's state and remove the item from the cache
if its new state is 'purged'
:Parameters:
- `item`: item to update.
:Types:
- `item`: `CacheItem`
:return: new state of the item.
:returntype: `str`"""
self._lock.acquire()
try:
state = item.update_state()
self._items_list.sort()
if item.state == 'purged':
self._purged += 1
if self._purged > 0.25*self.max_items:
self.purge_items()
return state
finally:
self._lock.release()
|
[
"Update",
"state",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L530-L554
|
[
"def",
"update_item",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"state",
"=",
"item",
".",
"update_state",
"(",
")",
"self",
".",
"_items_list",
".",
"sort",
"(",
")",
"if",
"item",
".",
"state",
"==",
"'purged'",
":",
"self",
".",
"_purged",
"+=",
"1",
"if",
"self",
".",
"_purged",
">",
"0.25",
"*",
"self",
".",
"max_items",
":",
"self",
".",
"purge_items",
"(",
")",
"return",
"state",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.purge_items
|
Remove purged and overlimit items from the cache.
TODO: optimize somehow.
Leave no more than 75% of `self.max_items` items in the cache.
|
pyxmpp2/cache.py
|
def purge_items(self):
"""Remove purged and overlimit items from the cache.
TODO: optimize somehow.
Leave no more than 75% of `self.max_items` items in the cache."""
self._lock.acquire()
try:
il=self._items_list
num_items = len(il)
need_remove = num_items - int(0.75 * self.max_items)
for _unused in range(need_remove):
item=il.pop(0)
try:
del self._items[item.address]
except KeyError:
pass
while il and il[0].update_state()=="purged":
item=il.pop(0)
try:
del self._items[item.address]
except KeyError:
pass
finally:
self._lock.release()
|
def purge_items(self):
"""Remove purged and overlimit items from the cache.
TODO: optimize somehow.
Leave no more than 75% of `self.max_items` items in the cache."""
self._lock.acquire()
try:
il=self._items_list
num_items = len(il)
need_remove = num_items - int(0.75 * self.max_items)
for _unused in range(need_remove):
item=il.pop(0)
try:
del self._items[item.address]
except KeyError:
pass
while il and il[0].update_state()=="purged":
item=il.pop(0)
try:
del self._items[item.address]
except KeyError:
pass
finally:
self._lock.release()
|
[
"Remove",
"purged",
"and",
"overlimit",
"items",
"from",
"the",
"cache",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L563-L589
|
[
"def",
"purge_items",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"il",
"=",
"self",
".",
"_items_list",
"num_items",
"=",
"len",
"(",
"il",
")",
"need_remove",
"=",
"num_items",
"-",
"int",
"(",
"0.75",
"*",
"self",
".",
"max_items",
")",
"for",
"_unused",
"in",
"range",
"(",
"need_remove",
")",
":",
"item",
"=",
"il",
".",
"pop",
"(",
"0",
")",
"try",
":",
"del",
"self",
".",
"_items",
"[",
"item",
".",
"address",
"]",
"except",
"KeyError",
":",
"pass",
"while",
"il",
"and",
"il",
"[",
"0",
"]",
".",
"update_state",
"(",
")",
"==",
"\"purged\"",
":",
"item",
"=",
"il",
".",
"pop",
"(",
"0",
")",
"try",
":",
"del",
"self",
".",
"_items",
"[",
"item",
".",
"address",
"]",
"except",
"KeyError",
":",
"pass",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.tick
|
Do the regular cache maintenance.
Must be called from time to time for timeouts and cache old items
purging to work.
|
pyxmpp2/cache.py
|
def tick(self):
"""Do the regular cache maintenance.
Must be called from time to time for timeouts and cache old items
purging to work."""
self._lock.acquire()
try:
now = datetime.utcnow()
for t,f in list(self._active_fetchers):
if t > now:
break
f.timeout()
self.purge_items()
finally:
self._lock.release()
|
def tick(self):
"""Do the regular cache maintenance.
Must be called from time to time for timeouts and cache old items
purging to work."""
self._lock.acquire()
try:
now = datetime.utcnow()
for t,f in list(self._active_fetchers):
if t > now:
break
f.timeout()
self.purge_items()
finally:
self._lock.release()
|
[
"Do",
"the",
"regular",
"cache",
"maintenance",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L591-L605
|
[
"def",
"tick",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"for",
"t",
",",
"f",
"in",
"list",
"(",
"self",
".",
"_active_fetchers",
")",
":",
"if",
"t",
">",
"now",
":",
"break",
"f",
".",
"timeout",
"(",
")",
"self",
".",
"purge_items",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.remove_fetcher
|
Remove a running fetcher from the list of active fetchers.
:Parameters:
- `fetcher`: fetcher instance.
:Types:
- `fetcher`: `CacheFetcher`
|
pyxmpp2/cache.py
|
def remove_fetcher(self, fetcher):
"""Remove a running fetcher from the list of active fetchers.
:Parameters:
- `fetcher`: fetcher instance.
:Types:
- `fetcher`: `CacheFetcher`"""
self._lock.acquire()
try:
for t, f in list(self._active_fetchers):
if f is fetcher:
self._active_fetchers.remove((t, f))
f._deactivated()
return
finally:
self._lock.release()
|
def remove_fetcher(self, fetcher):
"""Remove a running fetcher from the list of active fetchers.
:Parameters:
- `fetcher`: fetcher instance.
:Types:
- `fetcher`: `CacheFetcher`"""
self._lock.acquire()
try:
for t, f in list(self._active_fetchers):
if f is fetcher:
self._active_fetchers.remove((t, f))
f._deactivated()
return
finally:
self._lock.release()
|
[
"Remove",
"a",
"running",
"fetcher",
"from",
"the",
"list",
"of",
"active",
"fetchers",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L607-L622
|
[
"def",
"remove_fetcher",
"(",
"self",
",",
"fetcher",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"for",
"t",
",",
"f",
"in",
"list",
"(",
"self",
".",
"_active_fetchers",
")",
":",
"if",
"f",
"is",
"fetcher",
":",
"self",
".",
"_active_fetchers",
".",
"remove",
"(",
"(",
"t",
",",
"f",
")",
")",
"f",
".",
"_deactivated",
"(",
")",
"return",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Cache.set_fetcher
|
Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class
|
pyxmpp2/cache.py
|
def set_fetcher(self, fetcher_class):
"""Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
self._fetcher = fetcher_class
finally:
self._lock.release()
|
def set_fetcher(self, fetcher_class):
"""Set the fetcher class.
:Parameters:
- `fetcher_class`: the fetcher class.
:Types:
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
self._fetcher = fetcher_class
finally:
self._lock.release()
|
[
"Set",
"the",
"fetcher",
"class",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L624-L636
|
[
"def",
"set_fetcher",
"(",
"self",
",",
"fetcher_class",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_fetcher",
"=",
"fetcher_class",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheSuite.request_object
|
Request an object of given class, with given address and state not
worse than `state`. The object will be taken from cache if available,
and created/fetched otherwise. The request is asynchronous -- this
metod doesn't return the object directly, but the `object_handler` is
called as soon as the object is available (this may be before
`request_object` returns and may happen in other thread). On error the
`error_handler` will be called, and on timeout -- the
`timeout_handler`.
:Parameters:
- `object_class`: class (type) of the object requested.
- `address`: address of the object requested.
- `state`: the worst acceptable object state. When 'new' then always
a new object will be created/fetched. 'stale' will select any
item available in cache.
- `object_handler`: function to be called when object is available.
It will be called with the following arguments: address, object
and its state.
- `error_handler`: function to be called on object retrieval error.
It will be called with two arguments: requested address and
additional error information (fetcher-specific, may be
StanzaError for XMPP objects). If not given, then the object
handler will be called with object set to `None` and state
"error".
- `timeout_handler`: function to be called on object retrieval
timeout. It will be called with only one argument: the requested
address. If not given, then the `error_handler` will be called
instead, with error details set to `None`.
- `backup_state`: when set and object in state `state` is not
available in the cache and object retrieval failed then object
with this state will also be looked-up in the cache and provided
if available.
- `timeout`: time interval after which retrieval of the object
should be given up.
- `freshness_period`: time interval after which the item created
should become 'old'.
- `expiration_period`: time interval after which the item created
should become 'stale'.
- `purge_period`: time interval after which the item created
shuld be removed from the cache.
:Types:
- `object_class`: `classobj`
- `address`: any hashable
- `state`: "new", "fresh", "old" or "stale"
- `object_handler`: callable(address, value, state)
- `error_handler`: callable(address, error_data)
- `timeout_handler`: callable(address)
- `backup_state`: "new", "fresh", "old" or "stale"
- `timeout`: `timedelta`
- `freshness_period`: `timedelta`
- `expiration_period`: `timedelta`
- `purge_period`: `timedelta`
|
pyxmpp2/cache.py
|
def request_object(self, object_class, address, state, object_handler,
error_handler = None, timeout_handler = None,
backup_state = None, timeout = None,
freshness_period = None, expiration_period = None, purge_period = None):
"""Request an object of given class, with given address and state not
worse than `state`. The object will be taken from cache if available,
and created/fetched otherwise. The request is asynchronous -- this
metod doesn't return the object directly, but the `object_handler` is
called as soon as the object is available (this may be before
`request_object` returns and may happen in other thread). On error the
`error_handler` will be called, and on timeout -- the
`timeout_handler`.
:Parameters:
- `object_class`: class (type) of the object requested.
- `address`: address of the object requested.
- `state`: the worst acceptable object state. When 'new' then always
a new object will be created/fetched. 'stale' will select any
item available in cache.
- `object_handler`: function to be called when object is available.
It will be called with the following arguments: address, object
and its state.
- `error_handler`: function to be called on object retrieval error.
It will be called with two arguments: requested address and
additional error information (fetcher-specific, may be
StanzaError for XMPP objects). If not given, then the object
handler will be called with object set to `None` and state
"error".
- `timeout_handler`: function to be called on object retrieval
timeout. It will be called with only one argument: the requested
address. If not given, then the `error_handler` will be called
instead, with error details set to `None`.
- `backup_state`: when set and object in state `state` is not
available in the cache and object retrieval failed then object
with this state will also be looked-up in the cache and provided
if available.
- `timeout`: time interval after which retrieval of the object
should be given up.
- `freshness_period`: time interval after which the item created
should become 'old'.
- `expiration_period`: time interval after which the item created
should become 'stale'.
- `purge_period`: time interval after which the item created
shuld be removed from the cache.
:Types:
- `object_class`: `classobj`
- `address`: any hashable
- `state`: "new", "fresh", "old" or "stale"
- `object_handler`: callable(address, value, state)
- `error_handler`: callable(address, error_data)
- `timeout_handler`: callable(address)
- `backup_state`: "new", "fresh", "old" or "stale"
- `timeout`: `timedelta`
- `freshness_period`: `timedelta`
- `expiration_period`: `timedelta`
- `purge_period`: `timedelta`
"""
self._lock.acquire()
try:
if object_class not in self._caches:
raise TypeError("No cache for %r" % (object_class,))
self._caches[object_class].request_object(address, state, object_handler,
error_handler, timeout_handler, backup_state, timeout,
freshness_period, expiration_period, purge_period)
finally:
self._lock.release()
|
def request_object(self, object_class, address, state, object_handler,
error_handler = None, timeout_handler = None,
backup_state = None, timeout = None,
freshness_period = None, expiration_period = None, purge_period = None):
"""Request an object of given class, with given address and state not
worse than `state`. The object will be taken from cache if available,
and created/fetched otherwise. The request is asynchronous -- this
metod doesn't return the object directly, but the `object_handler` is
called as soon as the object is available (this may be before
`request_object` returns and may happen in other thread). On error the
`error_handler` will be called, and on timeout -- the
`timeout_handler`.
:Parameters:
- `object_class`: class (type) of the object requested.
- `address`: address of the object requested.
- `state`: the worst acceptable object state. When 'new' then always
a new object will be created/fetched. 'stale' will select any
item available in cache.
- `object_handler`: function to be called when object is available.
It will be called with the following arguments: address, object
and its state.
- `error_handler`: function to be called on object retrieval error.
It will be called with two arguments: requested address and
additional error information (fetcher-specific, may be
StanzaError for XMPP objects). If not given, then the object
handler will be called with object set to `None` and state
"error".
- `timeout_handler`: function to be called on object retrieval
timeout. It will be called with only one argument: the requested
address. If not given, then the `error_handler` will be called
instead, with error details set to `None`.
- `backup_state`: when set and object in state `state` is not
available in the cache and object retrieval failed then object
with this state will also be looked-up in the cache and provided
if available.
- `timeout`: time interval after which retrieval of the object
should be given up.
- `freshness_period`: time interval after which the item created
should become 'old'.
- `expiration_period`: time interval after which the item created
should become 'stale'.
- `purge_period`: time interval after which the item created
shuld be removed from the cache.
:Types:
- `object_class`: `classobj`
- `address`: any hashable
- `state`: "new", "fresh", "old" or "stale"
- `object_handler`: callable(address, value, state)
- `error_handler`: callable(address, error_data)
- `timeout_handler`: callable(address)
- `backup_state`: "new", "fresh", "old" or "stale"
- `timeout`: `timedelta`
- `freshness_period`: `timedelta`
- `expiration_period`: `timedelta`
- `purge_period`: `timedelta`
"""
self._lock.acquire()
try:
if object_class not in self._caches:
raise TypeError("No cache for %r" % (object_class,))
self._caches[object_class].request_object(address, state, object_handler,
error_handler, timeout_handler, backup_state, timeout,
freshness_period, expiration_period, purge_period)
finally:
self._lock.release()
|
[
"Request",
"an",
"object",
"of",
"given",
"class",
"with",
"given",
"address",
"and",
"state",
"not",
"worse",
"than",
"state",
".",
"The",
"object",
"will",
"be",
"taken",
"from",
"cache",
"if",
"available",
"and",
"created",
"/",
"fetched",
"otherwise",
".",
"The",
"request",
"is",
"asynchronous",
"--",
"this",
"metod",
"doesn",
"t",
"return",
"the",
"object",
"directly",
"but",
"the",
"object_handler",
"is",
"called",
"as",
"soon",
"as",
"the",
"object",
"is",
"available",
"(",
"this",
"may",
"be",
"before",
"request_object",
"returns",
"and",
"may",
"happen",
"in",
"other",
"thread",
")",
".",
"On",
"error",
"the",
"error_handler",
"will",
"be",
"called",
"and",
"on",
"timeout",
"--",
"the",
"timeout_handler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L700-L767
|
[
"def",
"request_object",
"(",
"self",
",",
"object_class",
",",
"address",
",",
"state",
",",
"object_handler",
",",
"error_handler",
"=",
"None",
",",
"timeout_handler",
"=",
"None",
",",
"backup_state",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"freshness_period",
"=",
"None",
",",
"expiration_period",
"=",
"None",
",",
"purge_period",
"=",
"None",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"object_class",
"not",
"in",
"self",
".",
"_caches",
":",
"raise",
"TypeError",
"(",
"\"No cache for %r\"",
"%",
"(",
"object_class",
",",
")",
")",
"self",
".",
"_caches",
"[",
"object_class",
"]",
".",
"request_object",
"(",
"address",
",",
"state",
",",
"object_handler",
",",
"error_handler",
",",
"timeout_handler",
",",
"backup_state",
",",
"timeout",
",",
"freshness_period",
",",
"expiration_period",
",",
"purge_period",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheSuite.tick
|
Do the regular cache maintenance.
Must be called from time to time for timeouts and cache old items
purging to work.
|
pyxmpp2/cache.py
|
def tick(self):
"""Do the regular cache maintenance.
Must be called from time to time for timeouts and cache old items
purging to work."""
self._lock.acquire()
try:
for cache in self._caches.values():
cache.tick()
finally:
self._lock.release()
|
def tick(self):
"""Do the regular cache maintenance.
Must be called from time to time for timeouts and cache old items
purging to work."""
self._lock.acquire()
try:
for cache in self._caches.values():
cache.tick()
finally:
self._lock.release()
|
[
"Do",
"the",
"regular",
"cache",
"maintenance",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L769-L779
|
[
"def",
"tick",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"for",
"cache",
"in",
"self",
".",
"_caches",
".",
"values",
"(",
")",
":",
"cache",
".",
"tick",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheSuite.register_fetcher
|
Register a fetcher class for an object class.
:Parameters:
- `object_class`: class to be retrieved by the fetcher.
- `fetcher_class`: the fetcher class.
:Types:
- `object_class`: `classobj`
- `fetcher_class`: `CacheFetcher` based class
|
pyxmpp2/cache.py
|
def register_fetcher(self, object_class, fetcher_class):
"""Register a fetcher class for an object class.
:Parameters:
- `object_class`: class to be retrieved by the fetcher.
- `fetcher_class`: the fetcher class.
:Types:
- `object_class`: `classobj`
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
cache = self._caches.get(object_class)
if not cache:
cache = Cache(self.max_items, self.default_freshness_period,
self.default_expiration_period, self.default_purge_period)
self._caches[object_class] = cache
cache.set_fetcher(fetcher_class)
finally:
self._lock.release()
|
def register_fetcher(self, object_class, fetcher_class):
"""Register a fetcher class for an object class.
:Parameters:
- `object_class`: class to be retrieved by the fetcher.
- `fetcher_class`: the fetcher class.
:Types:
- `object_class`: `classobj`
- `fetcher_class`: `CacheFetcher` based class
"""
self._lock.acquire()
try:
cache = self._caches.get(object_class)
if not cache:
cache = Cache(self.max_items, self.default_freshness_period,
self.default_expiration_period, self.default_purge_period)
self._caches[object_class] = cache
cache.set_fetcher(fetcher_class)
finally:
self._lock.release()
|
[
"Register",
"a",
"fetcher",
"class",
"for",
"an",
"object",
"class",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L781-L800
|
[
"def",
"register_fetcher",
"(",
"self",
",",
"object_class",
",",
"fetcher_class",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"cache",
"=",
"self",
".",
"_caches",
".",
"get",
"(",
"object_class",
")",
"if",
"not",
"cache",
":",
"cache",
"=",
"Cache",
"(",
"self",
".",
"max_items",
",",
"self",
".",
"default_freshness_period",
",",
"self",
".",
"default_expiration_period",
",",
"self",
".",
"default_purge_period",
")",
"self",
".",
"_caches",
"[",
"object_class",
"]",
"=",
"cache",
"cache",
".",
"set_fetcher",
"(",
"fetcher_class",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CacheSuite.unregister_fetcher
|
Unregister a fetcher class for an object class.
:Parameters:
- `object_class`: class retrieved by the fetcher.
:Types:
- `object_class`: `classobj`
|
pyxmpp2/cache.py
|
def unregister_fetcher(self, object_class):
"""Unregister a fetcher class for an object class.
:Parameters:
- `object_class`: class retrieved by the fetcher.
:Types:
- `object_class`: `classobj`
"""
self._lock.acquire()
try:
cache = self._caches.get(object_class)
if not cache:
return
cache.set_fetcher(None)
finally:
self._lock.release()
|
def unregister_fetcher(self, object_class):
"""Unregister a fetcher class for an object class.
:Parameters:
- `object_class`: class retrieved by the fetcher.
:Types:
- `object_class`: `classobj`
"""
self._lock.acquire()
try:
cache = self._caches.get(object_class)
if not cache:
return
cache.set_fetcher(None)
finally:
self._lock.release()
|
[
"Unregister",
"a",
"fetcher",
"class",
"for",
"an",
"object",
"class",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cache.py#L802-L817
|
[
"def",
"unregister_fetcher",
"(",
"self",
",",
"object_class",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"cache",
"=",
"self",
".",
"_caches",
".",
"get",
"(",
"object_class",
")",
"if",
"not",
"cache",
":",
"return",
"cache",
".",
"set_fetcher",
"(",
"None",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
_register_client_authenticator
|
Add a client authenticator class to `CLIENT_MECHANISMS_D`,
`CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`
|
pyxmpp2/sasl/core.py
|
def _register_client_authenticator(klass, name):
"""Add a client authenticator class to `CLIENT_MECHANISMS_D`,
`CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`
"""
# pylint: disable-msg=W0212
CLIENT_MECHANISMS_D[name] = klass
items = sorted(CLIENT_MECHANISMS_D.items(), key = _key_func, reverse = True)
CLIENT_MECHANISMS[:] = [k for (k, v) in items ]
SECURE_CLIENT_MECHANISMS[:] = [k for (k, v) in items
if v._pyxmpp_sasl_secure]
|
def _register_client_authenticator(klass, name):
"""Add a client authenticator class to `CLIENT_MECHANISMS_D`,
`CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS`
"""
# pylint: disable-msg=W0212
CLIENT_MECHANISMS_D[name] = klass
items = sorted(CLIENT_MECHANISMS_D.items(), key = _key_func, reverse = True)
CLIENT_MECHANISMS[:] = [k for (k, v) in items ]
SECURE_CLIENT_MECHANISMS[:] = [k for (k, v) in items
if v._pyxmpp_sasl_secure]
|
[
"Add",
"a",
"client",
"authenticator",
"class",
"to",
"CLIENT_MECHANISMS_D",
"CLIENT_MECHANISMS",
"and",
"optionally",
"to",
"SECURE_CLIENT_MECHANISMS"
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L444-L453
|
[
"def",
"_register_client_authenticator",
"(",
"klass",
",",
"name",
")",
":",
"# pylint: disable-msg=W0212",
"CLIENT_MECHANISMS_D",
"[",
"name",
"]",
"=",
"klass",
"items",
"=",
"sorted",
"(",
"CLIENT_MECHANISMS_D",
".",
"items",
"(",
")",
",",
"key",
"=",
"_key_func",
",",
"reverse",
"=",
"True",
")",
"CLIENT_MECHANISMS",
"[",
":",
"]",
"=",
"[",
"k",
"for",
"(",
"k",
",",
"v",
")",
"in",
"items",
"]",
"SECURE_CLIENT_MECHANISMS",
"[",
":",
"]",
"=",
"[",
"k",
"for",
"(",
"k",
",",
"v",
")",
"in",
"items",
"if",
"v",
".",
"_pyxmpp_sasl_secure",
"]"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
_register_server_authenticator
|
Add a client authenticator class to `SERVER_MECHANISMS_D`,
`SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`
|
pyxmpp2/sasl/core.py
|
def _register_server_authenticator(klass, name):
"""Add a client authenticator class to `SERVER_MECHANISMS_D`,
`SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`
"""
# pylint: disable-msg=W0212
SERVER_MECHANISMS_D[name] = klass
items = sorted(SERVER_MECHANISMS_D.items(), key = _key_func, reverse = True)
SERVER_MECHANISMS[:] = [k for (k, v) in items ]
SECURE_SERVER_MECHANISMS[:] = [k for (k, v) in items
if v._pyxmpp_sasl_secure]
|
def _register_server_authenticator(klass, name):
"""Add a client authenticator class to `SERVER_MECHANISMS_D`,
`SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS`
"""
# pylint: disable-msg=W0212
SERVER_MECHANISMS_D[name] = klass
items = sorted(SERVER_MECHANISMS_D.items(), key = _key_func, reverse = True)
SERVER_MECHANISMS[:] = [k for (k, v) in items ]
SECURE_SERVER_MECHANISMS[:] = [k for (k, v) in items
if v._pyxmpp_sasl_secure]
|
[
"Add",
"a",
"client",
"authenticator",
"class",
"to",
"SERVER_MECHANISMS_D",
"SERVER_MECHANISMS",
"and",
"optionally",
"to",
"SECURE_SERVER_MECHANISMS"
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L455-L464
|
[
"def",
"_register_server_authenticator",
"(",
"klass",
",",
"name",
")",
":",
"# pylint: disable-msg=W0212",
"SERVER_MECHANISMS_D",
"[",
"name",
"]",
"=",
"klass",
"items",
"=",
"sorted",
"(",
"SERVER_MECHANISMS_D",
".",
"items",
"(",
")",
",",
"key",
"=",
"_key_func",
",",
"reverse",
"=",
"True",
")",
"SERVER_MECHANISMS",
"[",
":",
"]",
"=",
"[",
"k",
"for",
"(",
"k",
",",
"v",
")",
"in",
"items",
"]",
"SECURE_SERVER_MECHANISMS",
"[",
":",
"]",
"=",
"[",
"k",
"for",
"(",
"k",
",",
"v",
")",
"in",
"items",
"if",
"v",
".",
"_pyxmpp_sasl_secure",
"]"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
sasl_mechanism
|
Class decorator generator for `ClientAuthenticator` or
`ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
mechanism registry.
:Parameters:
- `name`: SASL mechanism name
- `secure`: if the mechanims can be considered secure - `True`
if it can be used over plain-text channel
- `preference`: mechanism preference level (the higher the better)
:Types:
- `name`: `unicode`
- `secure`: `bool`
- `preference`: `int`
|
pyxmpp2/sasl/core.py
|
def sasl_mechanism(name, secure, preference = 50):
"""Class decorator generator for `ClientAuthenticator` or
`ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
mechanism registry.
:Parameters:
- `name`: SASL mechanism name
- `secure`: if the mechanims can be considered secure - `True`
if it can be used over plain-text channel
- `preference`: mechanism preference level (the higher the better)
:Types:
- `name`: `unicode`
- `secure`: `bool`
- `preference`: `int`
"""
# pylint: disable-msg=W0212
def decorator(klass):
"""The decorator."""
klass._pyxmpp_sasl_secure = secure
klass._pyxmpp_sasl_preference = preference
if issubclass(klass, ClientAuthenticator):
_register_client_authenticator(klass, name)
elif issubclass(klass, ServerAuthenticator):
_register_server_authenticator(klass, name)
else:
raise TypeError("Not a ClientAuthenticator"
" or ServerAuthenticator class")
return klass
return decorator
|
def sasl_mechanism(name, secure, preference = 50):
"""Class decorator generator for `ClientAuthenticator` or
`ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl
mechanism registry.
:Parameters:
- `name`: SASL mechanism name
- `secure`: if the mechanims can be considered secure - `True`
if it can be used over plain-text channel
- `preference`: mechanism preference level (the higher the better)
:Types:
- `name`: `unicode`
- `secure`: `bool`
- `preference`: `int`
"""
# pylint: disable-msg=W0212
def decorator(klass):
"""The decorator."""
klass._pyxmpp_sasl_secure = secure
klass._pyxmpp_sasl_preference = preference
if issubclass(klass, ClientAuthenticator):
_register_client_authenticator(klass, name)
elif issubclass(klass, ServerAuthenticator):
_register_server_authenticator(klass, name)
else:
raise TypeError("Not a ClientAuthenticator"
" or ServerAuthenticator class")
return klass
return decorator
|
[
"Class",
"decorator",
"generator",
"for",
"ClientAuthenticator",
"or",
"ServerAuthenticator",
"subclasses",
".",
"Adds",
"the",
"class",
"to",
"the",
"pyxmpp",
".",
"sasl",
"mechanism",
"registry",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L466-L494
|
[
"def",
"sasl_mechanism",
"(",
"name",
",",
"secure",
",",
"preference",
"=",
"50",
")",
":",
"# pylint: disable-msg=W0212",
"def",
"decorator",
"(",
"klass",
")",
":",
"\"\"\"The decorator.\"\"\"",
"klass",
".",
"_pyxmpp_sasl_secure",
"=",
"secure",
"klass",
".",
"_pyxmpp_sasl_preference",
"=",
"preference",
"if",
"issubclass",
"(",
"klass",
",",
"ClientAuthenticator",
")",
":",
"_register_client_authenticator",
"(",
"klass",
",",
"name",
")",
"elif",
"issubclass",
"(",
"klass",
",",
"ServerAuthenticator",
")",
":",
"_register_server_authenticator",
"(",
"klass",
",",
"name",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Not a ClientAuthenticator\"",
"\" or ServerAuthenticator class\"",
")",
"return",
"klass",
"return",
"decorator"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
PasswordDatabase.check_password
|
Check the password validity.
Used by plain-text authentication mechanisms.
Default implementation: retrieve a "plain" password for the `username`
and `realm` using `self.get_password` and compare it with the password
provided.
May be overridden e.g. to check the password against some external
authentication mechanism (PAM, LDAP, etc.).
:Parameters:
- `username`: the username for which the password verification is
requested.
- `password`: the password to verify.
- `properties`: mapping with authentication properties (those
provided to the authenticator's ``start()`` method plus some
already obtained via the mechanism).
:Types:
- `username`: `unicode`
- `password`: `unicode`
- `properties`: mapping
:return: `True` if the password is valid.
:returntype: `bool`
|
pyxmpp2/sasl/core.py
|
def check_password(self, username, password, properties):
"""Check the password validity.
Used by plain-text authentication mechanisms.
Default implementation: retrieve a "plain" password for the `username`
and `realm` using `self.get_password` and compare it with the password
provided.
May be overridden e.g. to check the password against some external
authentication mechanism (PAM, LDAP, etc.).
:Parameters:
- `username`: the username for which the password verification is
requested.
- `password`: the password to verify.
- `properties`: mapping with authentication properties (those
provided to the authenticator's ``start()`` method plus some
already obtained via the mechanism).
:Types:
- `username`: `unicode`
- `password`: `unicode`
- `properties`: mapping
:return: `True` if the password is valid.
:returntype: `bool`
"""
logger.debug("check_password{0!r}".format(
(username, password, properties)))
pwd, pwd_format = self.get_password(username,
(u"plain", u"md5:user:realm:password"), properties)
if pwd_format == u"plain":
logger.debug("got plain password: {0!r}".format(pwd))
return pwd is not None and password == pwd
elif pwd_format in (u"md5:user:realm:password"):
logger.debug("got md5:user:realm:password password: {0!r}"
.format(pwd))
realm = properties.get("realm")
if realm is None:
realm = ""
else:
realm = realm.encode("utf-8")
username = username.encode("utf-8")
password = password.encode("utf-8")
# pylint: disable-msg=E1101
urp_hash = hashlib.md5(b"%s:%s:%s").hexdigest()
return urp_hash == pwd
logger.debug("got password in unknown format: {0!r}".format(pwd_format))
return False
|
def check_password(self, username, password, properties):
"""Check the password validity.
Used by plain-text authentication mechanisms.
Default implementation: retrieve a "plain" password for the `username`
and `realm` using `self.get_password` and compare it with the password
provided.
May be overridden e.g. to check the password against some external
authentication mechanism (PAM, LDAP, etc.).
:Parameters:
- `username`: the username for which the password verification is
requested.
- `password`: the password to verify.
- `properties`: mapping with authentication properties (those
provided to the authenticator's ``start()`` method plus some
already obtained via the mechanism).
:Types:
- `username`: `unicode`
- `password`: `unicode`
- `properties`: mapping
:return: `True` if the password is valid.
:returntype: `bool`
"""
logger.debug("check_password{0!r}".format(
(username, password, properties)))
pwd, pwd_format = self.get_password(username,
(u"plain", u"md5:user:realm:password"), properties)
if pwd_format == u"plain":
logger.debug("got plain password: {0!r}".format(pwd))
return pwd is not None and password == pwd
elif pwd_format in (u"md5:user:realm:password"):
logger.debug("got md5:user:realm:password password: {0!r}"
.format(pwd))
realm = properties.get("realm")
if realm is None:
realm = ""
else:
realm = realm.encode("utf-8")
username = username.encode("utf-8")
password = password.encode("utf-8")
# pylint: disable-msg=E1101
urp_hash = hashlib.md5(b"%s:%s:%s").hexdigest()
return urp_hash == pwd
logger.debug("got password in unknown format: {0!r}".format(pwd_format))
return False
|
[
"Check",
"the",
"password",
"validity",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L136-L185
|
[
"def",
"check_password",
"(",
"self",
",",
"username",
",",
"password",
",",
"properties",
")",
":",
"logger",
".",
"debug",
"(",
"\"check_password{0!r}\"",
".",
"format",
"(",
"(",
"username",
",",
"password",
",",
"properties",
")",
")",
")",
"pwd",
",",
"pwd_format",
"=",
"self",
".",
"get_password",
"(",
"username",
",",
"(",
"u\"plain\"",
",",
"u\"md5:user:realm:password\"",
")",
",",
"properties",
")",
"if",
"pwd_format",
"==",
"u\"plain\"",
":",
"logger",
".",
"debug",
"(",
"\"got plain password: {0!r}\"",
".",
"format",
"(",
"pwd",
")",
")",
"return",
"pwd",
"is",
"not",
"None",
"and",
"password",
"==",
"pwd",
"elif",
"pwd_format",
"in",
"(",
"u\"md5:user:realm:password\"",
")",
":",
"logger",
".",
"debug",
"(",
"\"got md5:user:realm:password password: {0!r}\"",
".",
"format",
"(",
"pwd",
")",
")",
"realm",
"=",
"properties",
".",
"get",
"(",
"\"realm\"",
")",
"if",
"realm",
"is",
"None",
":",
"realm",
"=",
"\"\"",
"else",
":",
"realm",
"=",
"realm",
".",
"encode",
"(",
"\"utf-8\"",
")",
"username",
"=",
"username",
".",
"encode",
"(",
"\"utf-8\"",
")",
"password",
"=",
"password",
".",
"encode",
"(",
"\"utf-8\"",
")",
"# pylint: disable-msg=E1101",
"urp_hash",
"=",
"hashlib",
".",
"md5",
"(",
"b\"%s:%s:%s\"",
")",
".",
"hexdigest",
"(",
")",
"return",
"urp_hash",
"==",
"pwd",
"logger",
".",
"debug",
"(",
"\"got password in unknown format: {0!r}\"",
".",
"format",
"(",
"pwd_format",
")",
")",
"return",
"False"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Reply.encode
|
Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
|
pyxmpp2/sasl/core.py
|
def encode(self):
"""Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
"""
if self.data is None:
return ""
elif not self.data:
return "="
else:
ret = standard_b64encode(self.data)
return ret.decode("us-ascii")
|
def encode(self):
"""Base64-encode the data contained in the reply when appropriate.
:return: encoded data.
:returntype: `unicode`
"""
if self.data is None:
return ""
elif not self.data:
return "="
else:
ret = standard_b64encode(self.data)
return ret.decode("us-ascii")
|
[
"Base64",
"-",
"encode",
"the",
"data",
"contained",
"in",
"the",
"reply",
"when",
"appropriate",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/core.py#L217-L229
|
[
"def",
"encode",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
"is",
"None",
":",
"return",
"\"\"",
"elif",
"not",
"self",
".",
"data",
":",
"return",
"\"=\"",
"else",
":",
"ret",
"=",
"standard_b64encode",
"(",
"self",
".",
"data",
")",
"return",
"ret",
".",
"decode",
"(",
"\"us-ascii\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SessionHandler.handle_authorized
|
Send session esteblishment request if the feature was advertised by
the server.
|
pyxmpp2/session.py
|
def handle_authorized(self, event):
"""Send session esteblishment request if the feature was advertised by
the server.
"""
stream = event.stream
if not stream:
return
if not stream.initiator:
return
if stream.features is None:
return
element = stream.features.find(SESSION_TAG)
if element is None:
return
logger.debug("Establishing IM session")
stanza = Iq(stanza_type = "set")
payload = XMLPayload(ElementTree.Element(SESSION_TAG))
stanza.set_payload(payload)
self.stanza_processor.set_response_handlers(stanza,
self._session_success,
self._session_error)
stream.send(stanza)
|
def handle_authorized(self, event):
"""Send session esteblishment request if the feature was advertised by
the server.
"""
stream = event.stream
if not stream:
return
if not stream.initiator:
return
if stream.features is None:
return
element = stream.features.find(SESSION_TAG)
if element is None:
return
logger.debug("Establishing IM session")
stanza = Iq(stanza_type = "set")
payload = XMLPayload(ElementTree.Element(SESSION_TAG))
stanza.set_payload(payload)
self.stanza_processor.set_response_handlers(stanza,
self._session_success,
self._session_error)
stream.send(stanza)
|
[
"Send",
"session",
"esteblishment",
"request",
"if",
"the",
"feature",
"was",
"advertised",
"by",
"the",
"server",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/session.py#L70-L91
|
[
"def",
"handle_authorized",
"(",
"self",
",",
"event",
")",
":",
"stream",
"=",
"event",
".",
"stream",
"if",
"not",
"stream",
":",
"return",
"if",
"not",
"stream",
".",
"initiator",
":",
"return",
"if",
"stream",
".",
"features",
"is",
"None",
":",
"return",
"element",
"=",
"stream",
".",
"features",
".",
"find",
"(",
"SESSION_TAG",
")",
"if",
"element",
"is",
"None",
":",
"return",
"logger",
".",
"debug",
"(",
"\"Establishing IM session\"",
")",
"stanza",
"=",
"Iq",
"(",
"stanza_type",
"=",
"\"set\"",
")",
"payload",
"=",
"XMLPayload",
"(",
"ElementTree",
".",
"Element",
"(",
"SESSION_TAG",
")",
")",
"stanza",
".",
"set_payload",
"(",
"payload",
")",
"self",
".",
"stanza_processor",
".",
"set_response_handlers",
"(",
"stanza",
",",
"self",
".",
"_session_success",
",",
"self",
".",
"_session_error",
")",
"stream",
".",
"send",
"(",
"stanza",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
_decode_asn1_string
|
Convert ASN.1 string to a Unicode string.
|
pyxmpp2/cert.py
|
def _decode_asn1_string(data):
"""Convert ASN.1 string to a Unicode string.
"""
if isinstance(data, BMPString):
return bytes(data).decode("utf-16-be")
else:
return bytes(data).decode("utf-8")
|
def _decode_asn1_string(data):
"""Convert ASN.1 string to a Unicode string.
"""
if isinstance(data, BMPString):
return bytes(data).decode("utf-16-be")
else:
return bytes(data).decode("utf-8")
|
[
"Convert",
"ASN",
".",
"1",
"string",
"to",
"a",
"Unicode",
"string",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L319-L325
|
[
"def",
"_decode_asn1_string",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"BMPString",
")",
":",
"return",
"bytes",
"(",
"data",
")",
".",
"decode",
"(",
"\"utf-16-be\"",
")",
"else",
":",
"return",
"bytes",
"(",
"data",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CertificateData.display_name
|
Get human-readable subject name derived from the SubjectName
or SubjectAltName field.
|
pyxmpp2/cert.py
|
def display_name(self):
"""Get human-readable subject name derived from the SubjectName
or SubjectAltName field.
"""
if self.subject_name:
return u", ".join( [ u", ".join(
[ u"{0}={1}".format(k,v) for k, v in dn_tuple ] )
for dn_tuple in self.subject_name ])
for name_type in ("XmppAddr", "DNS", "SRV"):
names = self.alt_names.get(name_type)
if names:
return names[0]
return u"<unknown>"
|
def display_name(self):
"""Get human-readable subject name derived from the SubjectName
or SubjectAltName field.
"""
if self.subject_name:
return u", ".join( [ u", ".join(
[ u"{0}={1}".format(k,v) for k, v in dn_tuple ] )
for dn_tuple in self.subject_name ])
for name_type in ("XmppAddr", "DNS", "SRV"):
names = self.alt_names.get(name_type)
if names:
return names[0]
return u"<unknown>"
|
[
"Get",
"human",
"-",
"readable",
"subject",
"name",
"derived",
"from",
"the",
"SubjectName",
"or",
"SubjectAltName",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L58-L70
|
[
"def",
"display_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"subject_name",
":",
"return",
"u\", \"",
".",
"join",
"(",
"[",
"u\", \"",
".",
"join",
"(",
"[",
"u\"{0}={1}\"",
".",
"format",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"dn_tuple",
"]",
")",
"for",
"dn_tuple",
"in",
"self",
".",
"subject_name",
"]",
")",
"for",
"name_type",
"in",
"(",
"\"XmppAddr\"",
",",
"\"DNS\"",
",",
"\"SRV\"",
")",
":",
"names",
"=",
"self",
".",
"alt_names",
".",
"get",
"(",
"name_type",
")",
"if",
"names",
":",
"return",
"names",
"[",
"0",
"]",
"return",
"u\"<unknown>\""
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CertificateData.get_jids
|
Return JIDs for which this certificate is valid (except the domain
wildcards).
:Returtype: `list` of `JID`
|
pyxmpp2/cert.py
|
def get_jids(self):
"""Return JIDs for which this certificate is valid (except the domain
wildcards).
:Returtype: `list` of `JID`
"""
result = []
if ("XmppAddr" in self.alt_names or "DNS" in self.alt_names
or "SRVName" in self.alt_names):
addrs = self.alt_names.get("XmppAddr", [])
addrs += [ addr for addr in self.alt_names.get("DNS", [])
if not addr.startswith("*.") ]
addrs += [ addr.split(".", 1)[1] for addr
in self.alt_names.get("SRVName", [])
if (addr.startswith("_xmpp-server.")
or addr.startswith("_xmpp-client."))]
warn_bad = True
elif self.common_names:
addrs = [addr for addr in self.common_names
if "@" not in addr and "/" not in addr]
warn_bad = False
else:
return []
for addr in addrs:
try:
jid = JID(addr)
if jid not in result:
result.append(jid)
except JIDError, err:
if warn_bad:
logger.warning(u"Bad JID in the certificate: {0!r}: {1}"
.format(addr, err))
return result
|
def get_jids(self):
"""Return JIDs for which this certificate is valid (except the domain
wildcards).
:Returtype: `list` of `JID`
"""
result = []
if ("XmppAddr" in self.alt_names or "DNS" in self.alt_names
or "SRVName" in self.alt_names):
addrs = self.alt_names.get("XmppAddr", [])
addrs += [ addr for addr in self.alt_names.get("DNS", [])
if not addr.startswith("*.") ]
addrs += [ addr.split(".", 1)[1] for addr
in self.alt_names.get("SRVName", [])
if (addr.startswith("_xmpp-server.")
or addr.startswith("_xmpp-client."))]
warn_bad = True
elif self.common_names:
addrs = [addr for addr in self.common_names
if "@" not in addr and "/" not in addr]
warn_bad = False
else:
return []
for addr in addrs:
try:
jid = JID(addr)
if jid not in result:
result.append(jid)
except JIDError, err:
if warn_bad:
logger.warning(u"Bad JID in the certificate: {0!r}: {1}"
.format(addr, err))
return result
|
[
"Return",
"JIDs",
"for",
"which",
"this",
"certificate",
"is",
"valid",
"(",
"except",
"the",
"domain",
"wildcards",
")",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L72-L104
|
[
"def",
"get_jids",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"if",
"(",
"\"XmppAddr\"",
"in",
"self",
".",
"alt_names",
"or",
"\"DNS\"",
"in",
"self",
".",
"alt_names",
"or",
"\"SRVName\"",
"in",
"self",
".",
"alt_names",
")",
":",
"addrs",
"=",
"self",
".",
"alt_names",
".",
"get",
"(",
"\"XmppAddr\"",
",",
"[",
"]",
")",
"addrs",
"+=",
"[",
"addr",
"for",
"addr",
"in",
"self",
".",
"alt_names",
".",
"get",
"(",
"\"DNS\"",
",",
"[",
"]",
")",
"if",
"not",
"addr",
".",
"startswith",
"(",
"\"*.\"",
")",
"]",
"addrs",
"+=",
"[",
"addr",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"1",
"]",
"for",
"addr",
"in",
"self",
".",
"alt_names",
".",
"get",
"(",
"\"SRVName\"",
",",
"[",
"]",
")",
"if",
"(",
"addr",
".",
"startswith",
"(",
"\"_xmpp-server.\"",
")",
"or",
"addr",
".",
"startswith",
"(",
"\"_xmpp-client.\"",
")",
")",
"]",
"warn_bad",
"=",
"True",
"elif",
"self",
".",
"common_names",
":",
"addrs",
"=",
"[",
"addr",
"for",
"addr",
"in",
"self",
".",
"common_names",
"if",
"\"@\"",
"not",
"in",
"addr",
"and",
"\"/\"",
"not",
"in",
"addr",
"]",
"warn_bad",
"=",
"False",
"else",
":",
"return",
"[",
"]",
"for",
"addr",
"in",
"addrs",
":",
"try",
":",
"jid",
"=",
"JID",
"(",
"addr",
")",
"if",
"jid",
"not",
"in",
"result",
":",
"result",
".",
"append",
"(",
"jid",
")",
"except",
"JIDError",
",",
"err",
":",
"if",
"warn_bad",
":",
"logger",
".",
"warning",
"(",
"u\"Bad JID in the certificate: {0!r}: {1}\"",
".",
"format",
"(",
"addr",
",",
"err",
")",
")",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CertificateData.verify_server
|
Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_name`: `unicode` or `JID`
- `srv_type`: `unicode`
:Return: `True` if the certificate is valid for given name, `False`
otherwise.
|
pyxmpp2/cert.py
|
def verify_server(self, server_name, srv_type = 'xmpp-client'):
"""Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_name`: `unicode` or `JID`
- `srv_type`: `unicode`
:Return: `True` if the certificate is valid for given name, `False`
otherwise.
"""
server_jid = JID(server_name)
if "XmppAddr" not in self.alt_names and "DNS" not in self.alt_names \
and "SRV" not in self.alt_names:
return self.verify_jid_against_common_name(server_jid)
names = [name for name in self.alt_names.get("DNS", [])
if not name.startswith(u"*.")]
names += self.alt_names.get("XmppAddr", [])
for name in names:
logger.debug("checking {0!r} against {1!r}".format(server_jid,
name))
try:
jid = JID(name)
except ValueError:
logger.debug("Not a valid JID: {0!r}".format(name))
continue
if jid == server_jid:
logger.debug("Match!")
return True
if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type):
return True
wildcards = [name[2:] for name in self.alt_names.get("DNS", [])
if name.startswith("*.")]
if not wildcards or not "." in server_jid.domain:
return False
logger.debug("checking {0!r} against wildcard domains: {1!r}"
.format(server_jid, wildcards))
server_domain = JID(domain = server_jid.domain.split(".", 1)[1])
for domain in wildcards:
logger.debug("checking {0!r} against {1!r}".format(server_domain,
domain))
try:
jid = JID(domain)
except ValueError:
logger.debug("Not a valid JID: {0!r}".format(name))
continue
if jid == server_domain:
logger.debug("Match!")
return True
return False
|
def verify_server(self, server_name, srv_type = 'xmpp-client'):
"""Verify certificate for a server.
:Parameters:
- `server_name`: name of the server presenting the cerificate
- `srv_type`: service type requested, as used in the SRV record
:Types:
- `server_name`: `unicode` or `JID`
- `srv_type`: `unicode`
:Return: `True` if the certificate is valid for given name, `False`
otherwise.
"""
server_jid = JID(server_name)
if "XmppAddr" not in self.alt_names and "DNS" not in self.alt_names \
and "SRV" not in self.alt_names:
return self.verify_jid_against_common_name(server_jid)
names = [name for name in self.alt_names.get("DNS", [])
if not name.startswith(u"*.")]
names += self.alt_names.get("XmppAddr", [])
for name in names:
logger.debug("checking {0!r} against {1!r}".format(server_jid,
name))
try:
jid = JID(name)
except ValueError:
logger.debug("Not a valid JID: {0!r}".format(name))
continue
if jid == server_jid:
logger.debug("Match!")
return True
if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type):
return True
wildcards = [name[2:] for name in self.alt_names.get("DNS", [])
if name.startswith("*.")]
if not wildcards or not "." in server_jid.domain:
return False
logger.debug("checking {0!r} against wildcard domains: {1!r}"
.format(server_jid, wildcards))
server_domain = JID(domain = server_jid.domain.split(".", 1)[1])
for domain in wildcards:
logger.debug("checking {0!r} against {1!r}".format(server_domain,
domain))
try:
jid = JID(domain)
except ValueError:
logger.debug("Not a valid JID: {0!r}".format(name))
continue
if jid == server_domain:
logger.debug("Match!")
return True
return False
|
[
"Verify",
"certificate",
"for",
"a",
"server",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L106-L157
|
[
"def",
"verify_server",
"(",
"self",
",",
"server_name",
",",
"srv_type",
"=",
"'xmpp-client'",
")",
":",
"server_jid",
"=",
"JID",
"(",
"server_name",
")",
"if",
"\"XmppAddr\"",
"not",
"in",
"self",
".",
"alt_names",
"and",
"\"DNS\"",
"not",
"in",
"self",
".",
"alt_names",
"and",
"\"SRV\"",
"not",
"in",
"self",
".",
"alt_names",
":",
"return",
"self",
".",
"verify_jid_against_common_name",
"(",
"server_jid",
")",
"names",
"=",
"[",
"name",
"for",
"name",
"in",
"self",
".",
"alt_names",
".",
"get",
"(",
"\"DNS\"",
",",
"[",
"]",
")",
"if",
"not",
"name",
".",
"startswith",
"(",
"u\"*.\"",
")",
"]",
"names",
"+=",
"self",
".",
"alt_names",
".",
"get",
"(",
"\"XmppAddr\"",
",",
"[",
"]",
")",
"for",
"name",
"in",
"names",
":",
"logger",
".",
"debug",
"(",
"\"checking {0!r} against {1!r}\"",
".",
"format",
"(",
"server_jid",
",",
"name",
")",
")",
"try",
":",
"jid",
"=",
"JID",
"(",
"name",
")",
"except",
"ValueError",
":",
"logger",
".",
"debug",
"(",
"\"Not a valid JID: {0!r}\"",
".",
"format",
"(",
"name",
")",
")",
"continue",
"if",
"jid",
"==",
"server_jid",
":",
"logger",
".",
"debug",
"(",
"\"Match!\"",
")",
"return",
"True",
"if",
"srv_type",
"and",
"self",
".",
"verify_jid_against_srv_name",
"(",
"server_jid",
",",
"srv_type",
")",
":",
"return",
"True",
"wildcards",
"=",
"[",
"name",
"[",
"2",
":",
"]",
"for",
"name",
"in",
"self",
".",
"alt_names",
".",
"get",
"(",
"\"DNS\"",
",",
"[",
"]",
")",
"if",
"name",
".",
"startswith",
"(",
"\"*.\"",
")",
"]",
"if",
"not",
"wildcards",
"or",
"not",
"\".\"",
"in",
"server_jid",
".",
"domain",
":",
"return",
"False",
"logger",
".",
"debug",
"(",
"\"checking {0!r} against wildcard domains: {1!r}\"",
".",
"format",
"(",
"server_jid",
",",
"wildcards",
")",
")",
"server_domain",
"=",
"JID",
"(",
"domain",
"=",
"server_jid",
".",
"domain",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"1",
"]",
")",
"for",
"domain",
"in",
"wildcards",
":",
"logger",
".",
"debug",
"(",
"\"checking {0!r} against {1!r}\"",
".",
"format",
"(",
"server_domain",
",",
"domain",
")",
")",
"try",
":",
"jid",
"=",
"JID",
"(",
"domain",
")",
"except",
"ValueError",
":",
"logger",
".",
"debug",
"(",
"\"Not a valid JID: {0!r}\"",
".",
"format",
"(",
"name",
")",
")",
"continue",
"if",
"jid",
"==",
"server_domain",
":",
"logger",
".",
"debug",
"(",
"\"Match!\"",
")",
"return",
"True",
"return",
"False"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CertificateData.verify_jid_against_common_name
|
Return `True` if jid is listed in the certificate commonName.
:Parameters:
- `jid`: JID requested (domain part only)
:Types:
- `jid`: `JID`
:Returntype: `bool`
|
pyxmpp2/cert.py
|
def verify_jid_against_common_name(self, jid):
"""Return `True` if jid is listed in the certificate commonName.
:Parameters:
- `jid`: JID requested (domain part only)
:Types:
- `jid`: `JID`
:Returntype: `bool`
"""
if not self.common_names:
return False
for name in self.common_names:
try:
cn_jid = JID(name)
except ValueError:
continue
if jid == cn_jid:
return True
return False
|
def verify_jid_against_common_name(self, jid):
"""Return `True` if jid is listed in the certificate commonName.
:Parameters:
- `jid`: JID requested (domain part only)
:Types:
- `jid`: `JID`
:Returntype: `bool`
"""
if not self.common_names:
return False
for name in self.common_names:
try:
cn_jid = JID(name)
except ValueError:
continue
if jid == cn_jid:
return True
return False
|
[
"Return",
"True",
"if",
"jid",
"is",
"listed",
"in",
"the",
"certificate",
"commonName",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L159-L178
|
[
"def",
"verify_jid_against_common_name",
"(",
"self",
",",
"jid",
")",
":",
"if",
"not",
"self",
".",
"common_names",
":",
"return",
"False",
"for",
"name",
"in",
"self",
".",
"common_names",
":",
"try",
":",
"cn_jid",
"=",
"JID",
"(",
"name",
")",
"except",
"ValueError",
":",
"continue",
"if",
"jid",
"==",
"cn_jid",
":",
"return",
"True",
"return",
"False"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CertificateData.verify_jid_against_srv_name
|
Check if the cerificate is valid for given domain-only JID
and a service type.
:Parameters:
- `jid`: JID requested (domain part only)
- `srv_type`: service type, e.g. 'xmpp-client'
:Types:
- `jid`: `JID`
- `srv_type`: `unicode`
:Returntype: `bool`
|
pyxmpp2/cert.py
|
def verify_jid_against_srv_name(self, jid, srv_type):
"""Check if the cerificate is valid for given domain-only JID
and a service type.
:Parameters:
- `jid`: JID requested (domain part only)
- `srv_type`: service type, e.g. 'xmpp-client'
:Types:
- `jid`: `JID`
- `srv_type`: `unicode`
:Returntype: `bool`
"""
srv_prefix = u"_" + srv_type + u"."
srv_prefix_l = len(srv_prefix)
for srv in self.alt_names.get("SRVName", []):
logger.debug("checking {0!r} against {1!r}".format(jid,
srv))
if not srv.startswith(srv_prefix):
logger.debug("{0!r} does not start with {1!r}"
.format(srv, srv_prefix))
continue
try:
srv_jid = JID(srv[srv_prefix_l:])
except ValueError:
continue
if srv_jid == jid:
logger.debug("Match!")
return True
return False
|
def verify_jid_against_srv_name(self, jid, srv_type):
"""Check if the cerificate is valid for given domain-only JID
and a service type.
:Parameters:
- `jid`: JID requested (domain part only)
- `srv_type`: service type, e.g. 'xmpp-client'
:Types:
- `jid`: `JID`
- `srv_type`: `unicode`
:Returntype: `bool`
"""
srv_prefix = u"_" + srv_type + u"."
srv_prefix_l = len(srv_prefix)
for srv in self.alt_names.get("SRVName", []):
logger.debug("checking {0!r} against {1!r}".format(jid,
srv))
if not srv.startswith(srv_prefix):
logger.debug("{0!r} does not start with {1!r}"
.format(srv, srv_prefix))
continue
try:
srv_jid = JID(srv[srv_prefix_l:])
except ValueError:
continue
if srv_jid == jid:
logger.debug("Match!")
return True
return False
|
[
"Check",
"if",
"the",
"cerificate",
"is",
"valid",
"for",
"given",
"domain",
"-",
"only",
"JID",
"and",
"a",
"service",
"type",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L180-L208
|
[
"def",
"verify_jid_against_srv_name",
"(",
"self",
",",
"jid",
",",
"srv_type",
")",
":",
"srv_prefix",
"=",
"u\"_\"",
"+",
"srv_type",
"+",
"u\".\"",
"srv_prefix_l",
"=",
"len",
"(",
"srv_prefix",
")",
"for",
"srv",
"in",
"self",
".",
"alt_names",
".",
"get",
"(",
"\"SRVName\"",
",",
"[",
"]",
")",
":",
"logger",
".",
"debug",
"(",
"\"checking {0!r} against {1!r}\"",
".",
"format",
"(",
"jid",
",",
"srv",
")",
")",
"if",
"not",
"srv",
".",
"startswith",
"(",
"srv_prefix",
")",
":",
"logger",
".",
"debug",
"(",
"\"{0!r} does not start with {1!r}\"",
".",
"format",
"(",
"srv",
",",
"srv_prefix",
")",
")",
"continue",
"try",
":",
"srv_jid",
"=",
"JID",
"(",
"srv",
"[",
"srv_prefix_l",
":",
"]",
")",
"except",
"ValueError",
":",
"continue",
"if",
"srv_jid",
"==",
"jid",
":",
"logger",
".",
"debug",
"(",
"\"Match!\"",
")",
"return",
"True",
"return",
"False"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
CertificateData.verify_client
|
Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `client_jid`: client name requested. May be `None` to allow
any name in one of the `domains`.
- `domains`: list of domains we can handle.
:Types:
- `client_jid`: `JID`
- `domains`: `list` of `unicode`
:Return: one of the jids in the certificate or `None` is no authorized
name is found.
|
pyxmpp2/cert.py
|
def verify_client(self, client_jid = None, domains = None):
"""Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `client_jid`: client name requested. May be `None` to allow
any name in one of the `domains`.
- `domains`: list of domains we can handle.
:Types:
- `client_jid`: `JID`
- `domains`: `list` of `unicode`
:Return: one of the jids in the certificate or `None` is no authorized
name is found.
"""
jids = [jid for jid in self.get_jids() if jid.local]
if not jids:
return None
if client_jid is not None and client_jid in jids:
return client_jid
if domains is None:
return jids[0]
for jid in jids:
for domain in domains:
if are_domains_equal(jid.domain, domain):
return jid
return None
|
def verify_client(self, client_jid = None, domains = None):
"""Verify certificate for a client.
Please note that `client_jid` is only a hint to choose from the names,
other JID may be returned if `client_jid` is not included in the
certificate.
:Parameters:
- `client_jid`: client name requested. May be `None` to allow
any name in one of the `domains`.
- `domains`: list of domains we can handle.
:Types:
- `client_jid`: `JID`
- `domains`: `list` of `unicode`
:Return: one of the jids in the certificate or `None` is no authorized
name is found.
"""
jids = [jid for jid in self.get_jids() if jid.local]
if not jids:
return None
if client_jid is not None and client_jid in jids:
return client_jid
if domains is None:
return jids[0]
for jid in jids:
for domain in domains:
if are_domains_equal(jid.domain, domain):
return jid
return None
|
[
"Verify",
"certificate",
"for",
"a",
"client",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L210-L239
|
[
"def",
"verify_client",
"(",
"self",
",",
"client_jid",
"=",
"None",
",",
"domains",
"=",
"None",
")",
":",
"jids",
"=",
"[",
"jid",
"for",
"jid",
"in",
"self",
".",
"get_jids",
"(",
")",
"if",
"jid",
".",
"local",
"]",
"if",
"not",
"jids",
":",
"return",
"None",
"if",
"client_jid",
"is",
"not",
"None",
"and",
"client_jid",
"in",
"jids",
":",
"return",
"client_jid",
"if",
"domains",
"is",
"None",
":",
"return",
"jids",
"[",
"0",
"]",
"for",
"jid",
"in",
"jids",
":",
"for",
"domain",
"in",
"domains",
":",
"if",
"are_domains_equal",
"(",
"jid",
".",
"domain",
",",
"domain",
")",
":",
"return",
"jid",
"return",
"None"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
BasicCertificateData.from_ssl_socket
|
Load certificate data from an SSL socket.
|
pyxmpp2/cert.py
|
def from_ssl_socket(cls, ssl_socket):
"""Load certificate data from an SSL socket.
"""
cert = cls()
try:
data = ssl_socket.getpeercert()
except AttributeError:
# PyPy doesn't have .getppercert
return cert
logger.debug("Certificate data from ssl module: {0!r}".format(data))
if not data:
return cert
cert.validated = True
cert.subject_name = data.get('subject')
cert.alt_names = defaultdict(list)
if 'subjectAltName' in data:
for name, value in data['subjectAltName']:
cert.alt_names[name].append(value)
if 'notAfter' in data:
tstamp = ssl.cert_time_to_seconds(data['notAfter'])
cert.not_after = datetime.utcfromtimestamp(tstamp)
if sys.version_info.major < 3:
cert._decode_names() # pylint: disable=W0212
cert.common_names = []
if cert.subject_name:
for part in cert.subject_name:
for name, value in part:
if name == 'commonName':
cert.common_names.append(value)
return cert
|
def from_ssl_socket(cls, ssl_socket):
"""Load certificate data from an SSL socket.
"""
cert = cls()
try:
data = ssl_socket.getpeercert()
except AttributeError:
# PyPy doesn't have .getppercert
return cert
logger.debug("Certificate data from ssl module: {0!r}".format(data))
if not data:
return cert
cert.validated = True
cert.subject_name = data.get('subject')
cert.alt_names = defaultdict(list)
if 'subjectAltName' in data:
for name, value in data['subjectAltName']:
cert.alt_names[name].append(value)
if 'notAfter' in data:
tstamp = ssl.cert_time_to_seconds(data['notAfter'])
cert.not_after = datetime.utcfromtimestamp(tstamp)
if sys.version_info.major < 3:
cert._decode_names() # pylint: disable=W0212
cert.common_names = []
if cert.subject_name:
for part in cert.subject_name:
for name, value in part:
if name == 'commonName':
cert.common_names.append(value)
return cert
|
[
"Load",
"certificate",
"data",
"from",
"an",
"SSL",
"socket",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L248-L277
|
[
"def",
"from_ssl_socket",
"(",
"cls",
",",
"ssl_socket",
")",
":",
"cert",
"=",
"cls",
"(",
")",
"try",
":",
"data",
"=",
"ssl_socket",
".",
"getpeercert",
"(",
")",
"except",
"AttributeError",
":",
"# PyPy doesn't have .getppercert",
"return",
"cert",
"logger",
".",
"debug",
"(",
"\"Certificate data from ssl module: {0!r}\"",
".",
"format",
"(",
"data",
")",
")",
"if",
"not",
"data",
":",
"return",
"cert",
"cert",
".",
"validated",
"=",
"True",
"cert",
".",
"subject_name",
"=",
"data",
".",
"get",
"(",
"'subject'",
")",
"cert",
".",
"alt_names",
"=",
"defaultdict",
"(",
"list",
")",
"if",
"'subjectAltName'",
"in",
"data",
":",
"for",
"name",
",",
"value",
"in",
"data",
"[",
"'subjectAltName'",
"]",
":",
"cert",
".",
"alt_names",
"[",
"name",
"]",
".",
"append",
"(",
"value",
")",
"if",
"'notAfter'",
"in",
"data",
":",
"tstamp",
"=",
"ssl",
".",
"cert_time_to_seconds",
"(",
"data",
"[",
"'notAfter'",
"]",
")",
"cert",
".",
"not_after",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"tstamp",
")",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
":",
"cert",
".",
"_decode_names",
"(",
")",
"# pylint: disable=W0212",
"cert",
".",
"common_names",
"=",
"[",
"]",
"if",
"cert",
".",
"subject_name",
":",
"for",
"part",
"in",
"cert",
".",
"subject_name",
":",
"for",
"name",
",",
"value",
"in",
"part",
":",
"if",
"name",
"==",
"'commonName'",
":",
"cert",
".",
"common_names",
".",
"append",
"(",
"value",
")",
"return",
"cert"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
BasicCertificateData._decode_names
|
Decode names (hopefully ASCII or UTF-8) into Unicode.
|
pyxmpp2/cert.py
|
def _decode_names(self):
"""Decode names (hopefully ASCII or UTF-8) into Unicode.
"""
if self.subject_name is not None:
subject_name = []
for part in self.subject_name:
new_part = []
for name, value in part:
try:
name = name.decode("utf-8")
value = value.decode("utf-8")
except UnicodeError:
continue
new_part.append((name, value))
subject_name.append(tuple(new_part))
self.subject_name = tuple(subject_name)
for key, old in self.alt_names.items():
new = []
for name in old:
try:
name = name.decode("utf-8")
except UnicodeError:
continue
new.append(name)
self.alt_names[key] = new
|
def _decode_names(self):
"""Decode names (hopefully ASCII or UTF-8) into Unicode.
"""
if self.subject_name is not None:
subject_name = []
for part in self.subject_name:
new_part = []
for name, value in part:
try:
name = name.decode("utf-8")
value = value.decode("utf-8")
except UnicodeError:
continue
new_part.append((name, value))
subject_name.append(tuple(new_part))
self.subject_name = tuple(subject_name)
for key, old in self.alt_names.items():
new = []
for name in old:
try:
name = name.decode("utf-8")
except UnicodeError:
continue
new.append(name)
self.alt_names[key] = new
|
[
"Decode",
"names",
"(",
"hopefully",
"ASCII",
"or",
"UTF",
"-",
"8",
")",
"into",
"Unicode",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L279-L303
|
[
"def",
"_decode_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"subject_name",
"is",
"not",
"None",
":",
"subject_name",
"=",
"[",
"]",
"for",
"part",
"in",
"self",
".",
"subject_name",
":",
"new_part",
"=",
"[",
"]",
"for",
"name",
",",
"value",
"in",
"part",
":",
"try",
":",
"name",
"=",
"name",
".",
"decode",
"(",
"\"utf-8\"",
")",
"value",
"=",
"value",
".",
"decode",
"(",
"\"utf-8\"",
")",
"except",
"UnicodeError",
":",
"continue",
"new_part",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")",
"subject_name",
".",
"append",
"(",
"tuple",
"(",
"new_part",
")",
")",
"self",
".",
"subject_name",
"=",
"tuple",
"(",
"subject_name",
")",
"for",
"key",
",",
"old",
"in",
"self",
".",
"alt_names",
".",
"items",
"(",
")",
":",
"new",
"=",
"[",
"]",
"for",
"name",
"in",
"old",
":",
"try",
":",
"name",
"=",
"name",
".",
"decode",
"(",
"\"utf-8\"",
")",
"except",
"UnicodeError",
":",
"continue",
"new",
".",
"append",
"(",
"name",
")",
"self",
".",
"alt_names",
"[",
"key",
"]",
"=",
"new"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ASN1CertificateData.from_ssl_socket
|
Get certificate data from an SSL socket.
|
pyxmpp2/cert.py
|
def from_ssl_socket(cls, ssl_socket):
"""Get certificate data from an SSL socket.
"""
try:
data = ssl_socket.getpeercert(True)
except AttributeError:
# PyPy doesn't have .getpeercert
data = None
if not data:
logger.debug("No certificate infromation")
return cls()
result = cls.from_der_data(data)
result.validated = bool(ssl_socket.getpeercert())
return result
|
def from_ssl_socket(cls, ssl_socket):
"""Get certificate data from an SSL socket.
"""
try:
data = ssl_socket.getpeercert(True)
except AttributeError:
# PyPy doesn't have .getpeercert
data = None
if not data:
logger.debug("No certificate infromation")
return cls()
result = cls.from_der_data(data)
result.validated = bool(ssl_socket.getpeercert())
return result
|
[
"Get",
"certificate",
"data",
"from",
"an",
"SSL",
"socket",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L397-L410
|
[
"def",
"from_ssl_socket",
"(",
"cls",
",",
"ssl_socket",
")",
":",
"try",
":",
"data",
"=",
"ssl_socket",
".",
"getpeercert",
"(",
"True",
")",
"except",
"AttributeError",
":",
"# PyPy doesn't have .getpeercert",
"data",
"=",
"None",
"if",
"not",
"data",
":",
"logger",
".",
"debug",
"(",
"\"No certificate infromation\"",
")",
"return",
"cls",
"(",
")",
"result",
"=",
"cls",
".",
"from_der_data",
"(",
"data",
")",
"result",
".",
"validated",
"=",
"bool",
"(",
"ssl_socket",
".",
"getpeercert",
"(",
")",
")",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ASN1CertificateData.from_der_data
|
Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData
|
pyxmpp2/cert.py
|
def from_der_data(cls, data):
"""Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData
"""
# pylint: disable=W0212
logger.debug("Decoding DER certificate: {0!r}".format(data))
if cls._cert_asn1_type is None:
cls._cert_asn1_type = Certificate()
cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0]
result = cls()
tbs_cert = cert.getComponentByName('tbsCertificate')
subject = tbs_cert.getComponentByName('subject')
logger.debug("Subject: {0!r}".format(subject))
result._decode_subject(subject)
validity = tbs_cert.getComponentByName('validity')
result._decode_validity(validity)
extensions = tbs_cert.getComponentByName('extensions')
if extensions:
for extension in extensions:
logger.debug("Extension: {0!r}".format(extension))
oid = extension.getComponentByName('extnID')
logger.debug("OID: {0!r}".format(oid))
if oid != SUBJECT_ALT_NAME_OID:
continue
value = extension.getComponentByName('extnValue')
logger.debug("Value: {0!r}".format(value))
if isinstance(value, Any):
# should be OctetString, but is Any
# in pyasn1_modules-0.0.1a
value = der_decoder.decode(value,
asn1Spec = OctetString())[0]
alt_names = der_decoder.decode(value,
asn1Spec = GeneralNames())[0]
logger.debug("SubjectAltName: {0!r}".format(alt_names))
result._decode_alt_names(alt_names)
return result
|
def from_der_data(cls, data):
"""Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData
"""
# pylint: disable=W0212
logger.debug("Decoding DER certificate: {0!r}".format(data))
if cls._cert_asn1_type is None:
cls._cert_asn1_type = Certificate()
cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0]
result = cls()
tbs_cert = cert.getComponentByName('tbsCertificate')
subject = tbs_cert.getComponentByName('subject')
logger.debug("Subject: {0!r}".format(subject))
result._decode_subject(subject)
validity = tbs_cert.getComponentByName('validity')
result._decode_validity(validity)
extensions = tbs_cert.getComponentByName('extensions')
if extensions:
for extension in extensions:
logger.debug("Extension: {0!r}".format(extension))
oid = extension.getComponentByName('extnID')
logger.debug("OID: {0!r}".format(oid))
if oid != SUBJECT_ALT_NAME_OID:
continue
value = extension.getComponentByName('extnValue')
logger.debug("Value: {0!r}".format(value))
if isinstance(value, Any):
# should be OctetString, but is Any
# in pyasn1_modules-0.0.1a
value = der_decoder.decode(value,
asn1Spec = OctetString())[0]
alt_names = der_decoder.decode(value,
asn1Spec = GeneralNames())[0]
logger.debug("SubjectAltName: {0!r}".format(alt_names))
result._decode_alt_names(alt_names)
return result
|
[
"Decode",
"DER",
"-",
"encoded",
"certificate",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L413-L455
|
[
"def",
"from_der_data",
"(",
"cls",
",",
"data",
")",
":",
"# pylint: disable=W0212",
"logger",
".",
"debug",
"(",
"\"Decoding DER certificate: {0!r}\"",
".",
"format",
"(",
"data",
")",
")",
"if",
"cls",
".",
"_cert_asn1_type",
"is",
"None",
":",
"cls",
".",
"_cert_asn1_type",
"=",
"Certificate",
"(",
")",
"cert",
"=",
"der_decoder",
".",
"decode",
"(",
"data",
",",
"asn1Spec",
"=",
"cls",
".",
"_cert_asn1_type",
")",
"[",
"0",
"]",
"result",
"=",
"cls",
"(",
")",
"tbs_cert",
"=",
"cert",
".",
"getComponentByName",
"(",
"'tbsCertificate'",
")",
"subject",
"=",
"tbs_cert",
".",
"getComponentByName",
"(",
"'subject'",
")",
"logger",
".",
"debug",
"(",
"\"Subject: {0!r}\"",
".",
"format",
"(",
"subject",
")",
")",
"result",
".",
"_decode_subject",
"(",
"subject",
")",
"validity",
"=",
"tbs_cert",
".",
"getComponentByName",
"(",
"'validity'",
")",
"result",
".",
"_decode_validity",
"(",
"validity",
")",
"extensions",
"=",
"tbs_cert",
".",
"getComponentByName",
"(",
"'extensions'",
")",
"if",
"extensions",
":",
"for",
"extension",
"in",
"extensions",
":",
"logger",
".",
"debug",
"(",
"\"Extension: {0!r}\"",
".",
"format",
"(",
"extension",
")",
")",
"oid",
"=",
"extension",
".",
"getComponentByName",
"(",
"'extnID'",
")",
"logger",
".",
"debug",
"(",
"\"OID: {0!r}\"",
".",
"format",
"(",
"oid",
")",
")",
"if",
"oid",
"!=",
"SUBJECT_ALT_NAME_OID",
":",
"continue",
"value",
"=",
"extension",
".",
"getComponentByName",
"(",
"'extnValue'",
")",
"logger",
".",
"debug",
"(",
"\"Value: {0!r}\"",
".",
"format",
"(",
"value",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"Any",
")",
":",
"# should be OctetString, but is Any",
"# in pyasn1_modules-0.0.1a",
"value",
"=",
"der_decoder",
".",
"decode",
"(",
"value",
",",
"asn1Spec",
"=",
"OctetString",
"(",
")",
")",
"[",
"0",
"]",
"alt_names",
"=",
"der_decoder",
".",
"decode",
"(",
"value",
",",
"asn1Spec",
"=",
"GeneralNames",
"(",
")",
")",
"[",
"0",
"]",
"logger",
".",
"debug",
"(",
"\"SubjectAltName: {0!r}\"",
".",
"format",
"(",
"alt_names",
")",
")",
"result",
".",
"_decode_alt_names",
"(",
"alt_names",
")",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ASN1CertificateData._decode_subject
|
Load data from a ASN.1 subject.
|
pyxmpp2/cert.py
|
def _decode_subject(self, subject):
"""Load data from a ASN.1 subject.
"""
self.common_names = []
subject_name = []
for rdnss in subject:
for rdns in rdnss:
rdnss_list = []
for nameval in rdns:
val_type = nameval.getComponentByName('type')
value = nameval.getComponentByName('value')
if val_type not in DN_OIDS:
logger.debug("OID {0} not supported".format(val_type))
continue
val_type = DN_OIDS[val_type]
value = der_decoder.decode(value,
asn1Spec = DirectoryString())[0]
value = value.getComponent()
try:
value = _decode_asn1_string(value)
except UnicodeError:
logger.debug("Cannot decode value: {0!r}".format(value))
continue
if val_type == u"commonName":
self.common_names.append(value)
rdnss_list.append((val_type, value))
subject_name.append(tuple(rdnss_list))
self.subject_name = tuple(subject_name)
|
def _decode_subject(self, subject):
"""Load data from a ASN.1 subject.
"""
self.common_names = []
subject_name = []
for rdnss in subject:
for rdns in rdnss:
rdnss_list = []
for nameval in rdns:
val_type = nameval.getComponentByName('type')
value = nameval.getComponentByName('value')
if val_type not in DN_OIDS:
logger.debug("OID {0} not supported".format(val_type))
continue
val_type = DN_OIDS[val_type]
value = der_decoder.decode(value,
asn1Spec = DirectoryString())[0]
value = value.getComponent()
try:
value = _decode_asn1_string(value)
except UnicodeError:
logger.debug("Cannot decode value: {0!r}".format(value))
continue
if val_type == u"commonName":
self.common_names.append(value)
rdnss_list.append((val_type, value))
subject_name.append(tuple(rdnss_list))
self.subject_name = tuple(subject_name)
|
[
"Load",
"data",
"from",
"a",
"ASN",
".",
"1",
"subject",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L457-L484
|
[
"def",
"_decode_subject",
"(",
"self",
",",
"subject",
")",
":",
"self",
".",
"common_names",
"=",
"[",
"]",
"subject_name",
"=",
"[",
"]",
"for",
"rdnss",
"in",
"subject",
":",
"for",
"rdns",
"in",
"rdnss",
":",
"rdnss_list",
"=",
"[",
"]",
"for",
"nameval",
"in",
"rdns",
":",
"val_type",
"=",
"nameval",
".",
"getComponentByName",
"(",
"'type'",
")",
"value",
"=",
"nameval",
".",
"getComponentByName",
"(",
"'value'",
")",
"if",
"val_type",
"not",
"in",
"DN_OIDS",
":",
"logger",
".",
"debug",
"(",
"\"OID {0} not supported\"",
".",
"format",
"(",
"val_type",
")",
")",
"continue",
"val_type",
"=",
"DN_OIDS",
"[",
"val_type",
"]",
"value",
"=",
"der_decoder",
".",
"decode",
"(",
"value",
",",
"asn1Spec",
"=",
"DirectoryString",
"(",
")",
")",
"[",
"0",
"]",
"value",
"=",
"value",
".",
"getComponent",
"(",
")",
"try",
":",
"value",
"=",
"_decode_asn1_string",
"(",
"value",
")",
"except",
"UnicodeError",
":",
"logger",
".",
"debug",
"(",
"\"Cannot decode value: {0!r}\"",
".",
"format",
"(",
"value",
")",
")",
"continue",
"if",
"val_type",
"==",
"u\"commonName\"",
":",
"self",
".",
"common_names",
".",
"append",
"(",
"value",
")",
"rdnss_list",
".",
"append",
"(",
"(",
"val_type",
",",
"value",
")",
")",
"subject_name",
".",
"append",
"(",
"tuple",
"(",
"rdnss_list",
")",
")",
"self",
".",
"subject_name",
"=",
"tuple",
"(",
"subject_name",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ASN1CertificateData._decode_validity
|
Load data from a ASN.1 validity value.
|
pyxmpp2/cert.py
|
def _decode_validity(self, validity):
"""Load data from a ASN.1 validity value.
"""
not_after = validity.getComponentByName('notAfter')
not_after = str(not_after.getComponent())
if isinstance(not_after, GeneralizedTime):
self.not_after = datetime.strptime(not_after, "%Y%m%d%H%M%SZ")
else:
self.not_after = datetime.strptime(not_after, "%y%m%d%H%M%SZ")
self.alt_names = defaultdict(list)
|
def _decode_validity(self, validity):
"""Load data from a ASN.1 validity value.
"""
not_after = validity.getComponentByName('notAfter')
not_after = str(not_after.getComponent())
if isinstance(not_after, GeneralizedTime):
self.not_after = datetime.strptime(not_after, "%Y%m%d%H%M%SZ")
else:
self.not_after = datetime.strptime(not_after, "%y%m%d%H%M%SZ")
self.alt_names = defaultdict(list)
|
[
"Load",
"data",
"from",
"a",
"ASN",
".",
"1",
"validity",
"value",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L486-L495
|
[
"def",
"_decode_validity",
"(",
"self",
",",
"validity",
")",
":",
"not_after",
"=",
"validity",
".",
"getComponentByName",
"(",
"'notAfter'",
")",
"not_after",
"=",
"str",
"(",
"not_after",
".",
"getComponent",
"(",
")",
")",
"if",
"isinstance",
"(",
"not_after",
",",
"GeneralizedTime",
")",
":",
"self",
".",
"not_after",
"=",
"datetime",
".",
"strptime",
"(",
"not_after",
",",
"\"%Y%m%d%H%M%SZ\"",
")",
"else",
":",
"self",
".",
"not_after",
"=",
"datetime",
".",
"strptime",
"(",
"not_after",
",",
"\"%y%m%d%H%M%SZ\"",
")",
"self",
".",
"alt_names",
"=",
"defaultdict",
"(",
"list",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ASN1CertificateData._decode_alt_names
|
Load SubjectAltName from a ASN.1 GeneralNames value.
:Values:
- `alt_names`: the SubjectAltNama extension value
:Types:
- `alt_name`: `GeneralNames`
|
pyxmpp2/cert.py
|
def _decode_alt_names(self, alt_names):
"""Load SubjectAltName from a ASN.1 GeneralNames value.
:Values:
- `alt_names`: the SubjectAltNama extension value
:Types:
- `alt_name`: `GeneralNames`
"""
for alt_name in alt_names:
tname = alt_name.getName()
comp = alt_name.getComponent()
if tname == "dNSName":
key = "DNS"
value = _decode_asn1_string(comp)
elif tname == "uniformResourceIdentifier":
key = "URI"
value = _decode_asn1_string(comp)
elif tname == "otherName":
oid = comp.getComponentByName("type-id")
value = comp.getComponentByName("value")
if oid == XMPPADDR_OID:
key = "XmppAddr"
value = der_decoder.decode(value,
asn1Spec = UTF8String())[0]
value = _decode_asn1_string(value)
elif oid == SRVNAME_OID:
key = "SRVName"
value = der_decoder.decode(value,
asn1Spec = IA5String())[0]
value = _decode_asn1_string(value)
else:
logger.debug("Unknown other name: {0}".format(oid))
continue
else:
logger.debug("Unsupported general name: {0}"
.format(tname))
continue
self.alt_names[key].append(value)
|
def _decode_alt_names(self, alt_names):
"""Load SubjectAltName from a ASN.1 GeneralNames value.
:Values:
- `alt_names`: the SubjectAltNama extension value
:Types:
- `alt_name`: `GeneralNames`
"""
for alt_name in alt_names:
tname = alt_name.getName()
comp = alt_name.getComponent()
if tname == "dNSName":
key = "DNS"
value = _decode_asn1_string(comp)
elif tname == "uniformResourceIdentifier":
key = "URI"
value = _decode_asn1_string(comp)
elif tname == "otherName":
oid = comp.getComponentByName("type-id")
value = comp.getComponentByName("value")
if oid == XMPPADDR_OID:
key = "XmppAddr"
value = der_decoder.decode(value,
asn1Spec = UTF8String())[0]
value = _decode_asn1_string(value)
elif oid == SRVNAME_OID:
key = "SRVName"
value = der_decoder.decode(value,
asn1Spec = IA5String())[0]
value = _decode_asn1_string(value)
else:
logger.debug("Unknown other name: {0}".format(oid))
continue
else:
logger.debug("Unsupported general name: {0}"
.format(tname))
continue
self.alt_names[key].append(value)
|
[
"Load",
"SubjectAltName",
"from",
"a",
"ASN",
".",
"1",
"GeneralNames",
"value",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L497-L534
|
[
"def",
"_decode_alt_names",
"(",
"self",
",",
"alt_names",
")",
":",
"for",
"alt_name",
"in",
"alt_names",
":",
"tname",
"=",
"alt_name",
".",
"getName",
"(",
")",
"comp",
"=",
"alt_name",
".",
"getComponent",
"(",
")",
"if",
"tname",
"==",
"\"dNSName\"",
":",
"key",
"=",
"\"DNS\"",
"value",
"=",
"_decode_asn1_string",
"(",
"comp",
")",
"elif",
"tname",
"==",
"\"uniformResourceIdentifier\"",
":",
"key",
"=",
"\"URI\"",
"value",
"=",
"_decode_asn1_string",
"(",
"comp",
")",
"elif",
"tname",
"==",
"\"otherName\"",
":",
"oid",
"=",
"comp",
".",
"getComponentByName",
"(",
"\"type-id\"",
")",
"value",
"=",
"comp",
".",
"getComponentByName",
"(",
"\"value\"",
")",
"if",
"oid",
"==",
"XMPPADDR_OID",
":",
"key",
"=",
"\"XmppAddr\"",
"value",
"=",
"der_decoder",
".",
"decode",
"(",
"value",
",",
"asn1Spec",
"=",
"UTF8String",
"(",
")",
")",
"[",
"0",
"]",
"value",
"=",
"_decode_asn1_string",
"(",
"value",
")",
"elif",
"oid",
"==",
"SRVNAME_OID",
":",
"key",
"=",
"\"SRVName\"",
"value",
"=",
"der_decoder",
".",
"decode",
"(",
"value",
",",
"asn1Spec",
"=",
"IA5String",
"(",
")",
")",
"[",
"0",
"]",
"value",
"=",
"_decode_asn1_string",
"(",
"value",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Unknown other name: {0}\"",
".",
"format",
"(",
"oid",
")",
")",
"continue",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Unsupported general name: {0}\"",
".",
"format",
"(",
"tname",
")",
")",
"continue",
"self",
".",
"alt_names",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ASN1CertificateData.from_file
|
Load certificate from a file.
|
pyxmpp2/cert.py
|
def from_file(cls, filename):
"""Load certificate from a file.
"""
with open(filename, "r") as pem_file:
data = pem.readPemFromFile(pem_file)
return cls.from_der_data(data)
|
def from_file(cls, filename):
"""Load certificate from a file.
"""
with open(filename, "r") as pem_file:
data = pem.readPemFromFile(pem_file)
return cls.from_der_data(data)
|
[
"Load",
"certificate",
"from",
"a",
"file",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/cert.py#L537-L542
|
[
"def",
"from_file",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"pem_file",
":",
"data",
"=",
"pem",
".",
"readPemFromFile",
"(",
"pem_file",
")",
"return",
"cls",
".",
"from_der_data",
"(",
"data",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
main
|
Parse the command-line arguments and run the bot.
|
examples/roster.py
|
def main():
"""Parse the command-line arguments and run the bot."""
parser = argparse.ArgumentParser(description = 'XMPP echo bot',
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument('--debug',
action = 'store_const', dest = 'log_level',
const = logging.DEBUG, default = logging.INFO,
help = 'Print debug messages')
parser.add_argument('--quiet', const = logging.ERROR,
action = 'store_const', dest = 'log_level',
help = 'Print only error messages')
parser.add_argument('--trace', action = 'store_true',
help = 'Print XML data sent and received')
parser.add_argument('--roster-cache',
help = 'Store roster in this file')
parser.add_argument('jid', metavar = 'JID',
help = 'The bot JID')
subparsers = parser.add_subparsers(help = 'Action', dest = "action")
show_p = subparsers.add_parser('show', help = 'Show roster and exit')
show_p.add_argument('--presence', action = 'store_true',
help = 'Wait 5 s for contact presence information'
' and display it with the roster')
mon_p = subparsers.add_parser('monitor', help =
'Show roster and subsequent changes')
mon_p.add_argument('--presence', action = 'store_true',
help = 'Show contact presence changes too')
add_p = subparsers.add_parser('add', help = 'Add an item to the roster')
add_p.add_argument('--subscribe', action = 'store_true', dest = 'subscribe',
help = 'Request a presence subscription too')
add_p.add_argument('--approve', action = 'store_true', dest = 'approve',
help = 'Pre-approve subscription from the contact'
' (requires server support)')
add_p.add_argument('contact', metavar = 'CONTACT', help = 'The JID to add')
add_p.add_argument('name', metavar = 'NAME', nargs = '?',
help = 'Contact name')
add_p.add_argument('groups', metavar = 'GROUP', nargs = '*',
help = 'Group names')
rm_p = subparsers.add_parser('remove',
help = 'Remove an item from the roster')
rm_p.add_argument('contact', metavar = 'CONTACT',
help = 'The JID to remove')
upd_p = subparsers.add_parser('update',
help = 'Update an item in the roster')
upd_p.add_argument('contact', metavar = 'CONTACT',
help = 'The JID to update')
upd_p.add_argument('name', metavar = 'NAME', nargs = '?',
help = 'Contact name')
upd_p.add_argument('groups', metavar = 'GROUP', nargs = '*',
help = 'Group names')
args = parser.parse_args()
settings = XMPPSettings()
settings.load_arguments(args)
if settings.get("password") is None:
password = getpass("{0!r} password: ".format(args.jid))
if sys.version_info.major < 3:
password = password.decode("utf-8")
settings["password"] = password
if sys.version_info.major < 3:
args.jid = args.jid.decode("utf-8")
if getattr(args, "contact", None):
args.contact = args.contact.decode("utf-8")
if getattr(args, "name", None):
args.name = args.name.decode("utf-8")
if getattr(args, "groups", None):
args.groups = [g.decode("utf-8") for g in args.groups]
logging.basicConfig(level = args.log_level)
if args.trace:
print "enabling trace"
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
for logger in ("pyxmpp2.IN", "pyxmpp2.OUT"):
logger = logging.getLogger(logger)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.propagate = False
if args.action == "monitor" or args.action == "show" and args.presence:
# According to RFC6121 it could be None for 'monitor' (no need to send
# initial presence to request roster), but Google seems to require that
# to send roster pushes
settings["initial_presence"] = Presence(priority = -1)
else:
settings["initial_presence"] = None
tool = RosterTool(JID(args.jid), args, settings)
try:
tool.run()
except KeyboardInterrupt:
tool.disconnect()
|
def main():
"""Parse the command-line arguments and run the bot."""
parser = argparse.ArgumentParser(description = 'XMPP echo bot',
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument('--debug',
action = 'store_const', dest = 'log_level',
const = logging.DEBUG, default = logging.INFO,
help = 'Print debug messages')
parser.add_argument('--quiet', const = logging.ERROR,
action = 'store_const', dest = 'log_level',
help = 'Print only error messages')
parser.add_argument('--trace', action = 'store_true',
help = 'Print XML data sent and received')
parser.add_argument('--roster-cache',
help = 'Store roster in this file')
parser.add_argument('jid', metavar = 'JID',
help = 'The bot JID')
subparsers = parser.add_subparsers(help = 'Action', dest = "action")
show_p = subparsers.add_parser('show', help = 'Show roster and exit')
show_p.add_argument('--presence', action = 'store_true',
help = 'Wait 5 s for contact presence information'
' and display it with the roster')
mon_p = subparsers.add_parser('monitor', help =
'Show roster and subsequent changes')
mon_p.add_argument('--presence', action = 'store_true',
help = 'Show contact presence changes too')
add_p = subparsers.add_parser('add', help = 'Add an item to the roster')
add_p.add_argument('--subscribe', action = 'store_true', dest = 'subscribe',
help = 'Request a presence subscription too')
add_p.add_argument('--approve', action = 'store_true', dest = 'approve',
help = 'Pre-approve subscription from the contact'
' (requires server support)')
add_p.add_argument('contact', metavar = 'CONTACT', help = 'The JID to add')
add_p.add_argument('name', metavar = 'NAME', nargs = '?',
help = 'Contact name')
add_p.add_argument('groups', metavar = 'GROUP', nargs = '*',
help = 'Group names')
rm_p = subparsers.add_parser('remove',
help = 'Remove an item from the roster')
rm_p.add_argument('contact', metavar = 'CONTACT',
help = 'The JID to remove')
upd_p = subparsers.add_parser('update',
help = 'Update an item in the roster')
upd_p.add_argument('contact', metavar = 'CONTACT',
help = 'The JID to update')
upd_p.add_argument('name', metavar = 'NAME', nargs = '?',
help = 'Contact name')
upd_p.add_argument('groups', metavar = 'GROUP', nargs = '*',
help = 'Group names')
args = parser.parse_args()
settings = XMPPSettings()
settings.load_arguments(args)
if settings.get("password") is None:
password = getpass("{0!r} password: ".format(args.jid))
if sys.version_info.major < 3:
password = password.decode("utf-8")
settings["password"] = password
if sys.version_info.major < 3:
args.jid = args.jid.decode("utf-8")
if getattr(args, "contact", None):
args.contact = args.contact.decode("utf-8")
if getattr(args, "name", None):
args.name = args.name.decode("utf-8")
if getattr(args, "groups", None):
args.groups = [g.decode("utf-8") for g in args.groups]
logging.basicConfig(level = args.log_level)
if args.trace:
print "enabling trace"
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
for logger in ("pyxmpp2.IN", "pyxmpp2.OUT"):
logger = logging.getLogger(logger)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.propagate = False
if args.action == "monitor" or args.action == "show" and args.presence:
# According to RFC6121 it could be None for 'monitor' (no need to send
# initial presence to request roster), but Google seems to require that
# to send roster pushes
settings["initial_presence"] = Presence(priority = -1)
else:
settings["initial_presence"] = None
tool = RosterTool(JID(args.jid), args, settings)
try:
tool.run()
except KeyboardInterrupt:
tool.disconnect()
|
[
"Parse",
"the",
"command",
"-",
"line",
"arguments",
"and",
"run",
"the",
"bot",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/examples/roster.py#L296-L388
|
[
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'XMPP echo bot'",
",",
"parents",
"=",
"[",
"XMPPSettings",
".",
"get_arg_parser",
"(",
")",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--debug'",
",",
"action",
"=",
"'store_const'",
",",
"dest",
"=",
"'log_level'",
",",
"const",
"=",
"logging",
".",
"DEBUG",
",",
"default",
"=",
"logging",
".",
"INFO",
",",
"help",
"=",
"'Print debug messages'",
")",
"parser",
".",
"add_argument",
"(",
"'--quiet'",
",",
"const",
"=",
"logging",
".",
"ERROR",
",",
"action",
"=",
"'store_const'",
",",
"dest",
"=",
"'log_level'",
",",
"help",
"=",
"'Print only error messages'",
")",
"parser",
".",
"add_argument",
"(",
"'--trace'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Print XML data sent and received'",
")",
"parser",
".",
"add_argument",
"(",
"'--roster-cache'",
",",
"help",
"=",
"'Store roster in this file'",
")",
"parser",
".",
"add_argument",
"(",
"'jid'",
",",
"metavar",
"=",
"'JID'",
",",
"help",
"=",
"'The bot JID'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"help",
"=",
"'Action'",
",",
"dest",
"=",
"\"action\"",
")",
"show_p",
"=",
"subparsers",
".",
"add_parser",
"(",
"'show'",
",",
"help",
"=",
"'Show roster and exit'",
")",
"show_p",
".",
"add_argument",
"(",
"'--presence'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Wait 5 s for contact presence information'",
"' and display it with the roster'",
")",
"mon_p",
"=",
"subparsers",
".",
"add_parser",
"(",
"'monitor'",
",",
"help",
"=",
"'Show roster and subsequent changes'",
")",
"mon_p",
".",
"add_argument",
"(",
"'--presence'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Show contact presence changes too'",
")",
"add_p",
"=",
"subparsers",
".",
"add_parser",
"(",
"'add'",
",",
"help",
"=",
"'Add an item to the roster'",
")",
"add_p",
".",
"add_argument",
"(",
"'--subscribe'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'subscribe'",
",",
"help",
"=",
"'Request a presence subscription too'",
")",
"add_p",
".",
"add_argument",
"(",
"'--approve'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'approve'",
",",
"help",
"=",
"'Pre-approve subscription from the contact'",
"' (requires server support)'",
")",
"add_p",
".",
"add_argument",
"(",
"'contact'",
",",
"metavar",
"=",
"'CONTACT'",
",",
"help",
"=",
"'The JID to add'",
")",
"add_p",
".",
"add_argument",
"(",
"'name'",
",",
"metavar",
"=",
"'NAME'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'Contact name'",
")",
"add_p",
".",
"add_argument",
"(",
"'groups'",
",",
"metavar",
"=",
"'GROUP'",
",",
"nargs",
"=",
"'*'",
",",
"help",
"=",
"'Group names'",
")",
"rm_p",
"=",
"subparsers",
".",
"add_parser",
"(",
"'remove'",
",",
"help",
"=",
"'Remove an item from the roster'",
")",
"rm_p",
".",
"add_argument",
"(",
"'contact'",
",",
"metavar",
"=",
"'CONTACT'",
",",
"help",
"=",
"'The JID to remove'",
")",
"upd_p",
"=",
"subparsers",
".",
"add_parser",
"(",
"'update'",
",",
"help",
"=",
"'Update an item in the roster'",
")",
"upd_p",
".",
"add_argument",
"(",
"'contact'",
",",
"metavar",
"=",
"'CONTACT'",
",",
"help",
"=",
"'The JID to update'",
")",
"upd_p",
".",
"add_argument",
"(",
"'name'",
",",
"metavar",
"=",
"'NAME'",
",",
"nargs",
"=",
"'?'",
",",
"help",
"=",
"'Contact name'",
")",
"upd_p",
".",
"add_argument",
"(",
"'groups'",
",",
"metavar",
"=",
"'GROUP'",
",",
"nargs",
"=",
"'*'",
",",
"help",
"=",
"'Group names'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"settings",
"=",
"XMPPSettings",
"(",
")",
"settings",
".",
"load_arguments",
"(",
"args",
")",
"if",
"settings",
".",
"get",
"(",
"\"password\"",
")",
"is",
"None",
":",
"password",
"=",
"getpass",
"(",
"\"{0!r} password: \"",
".",
"format",
"(",
"args",
".",
"jid",
")",
")",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
":",
"password",
"=",
"password",
".",
"decode",
"(",
"\"utf-8\"",
")",
"settings",
"[",
"\"password\"",
"]",
"=",
"password",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
":",
"args",
".",
"jid",
"=",
"args",
".",
"jid",
".",
"decode",
"(",
"\"utf-8\"",
")",
"if",
"getattr",
"(",
"args",
",",
"\"contact\"",
",",
"None",
")",
":",
"args",
".",
"contact",
"=",
"args",
".",
"contact",
".",
"decode",
"(",
"\"utf-8\"",
")",
"if",
"getattr",
"(",
"args",
",",
"\"name\"",
",",
"None",
")",
":",
"args",
".",
"name",
"=",
"args",
".",
"name",
".",
"decode",
"(",
"\"utf-8\"",
")",
"if",
"getattr",
"(",
"args",
",",
"\"groups\"",
",",
"None",
")",
":",
"args",
".",
"groups",
"=",
"[",
"g",
".",
"decode",
"(",
"\"utf-8\"",
")",
"for",
"g",
"in",
"args",
".",
"groups",
"]",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"args",
".",
"log_level",
")",
"if",
"args",
".",
"trace",
":",
"print",
"\"enabling trace\"",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"for",
"logger",
"in",
"(",
"\"pyxmpp2.IN\"",
",",
"\"pyxmpp2.OUT\"",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"logger",
".",
"propagate",
"=",
"False",
"if",
"args",
".",
"action",
"==",
"\"monitor\"",
"or",
"args",
".",
"action",
"==",
"\"show\"",
"and",
"args",
".",
"presence",
":",
"# According to RFC6121 it could be None for 'monitor' (no need to send",
"# initial presence to request roster), but Google seems to require that",
"# to send roster pushes",
"settings",
"[",
"\"initial_presence\"",
"]",
"=",
"Presence",
"(",
"priority",
"=",
"-",
"1",
")",
"else",
":",
"settings",
"[",
"\"initial_presence\"",
"]",
"=",
"None",
"tool",
"=",
"RosterTool",
"(",
"JID",
"(",
"args",
".",
"jid",
")",
",",
"args",
",",
"settings",
")",
"try",
":",
"tool",
".",
"run",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"tool",
".",
"disconnect",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
RosterTool.run
|
Request client connection and start the main loop.
|
examples/roster.py
|
def run(self):
"""Request client connection and start the main loop."""
if self.args.roster_cache and os.path.exists(self.args.roster_cache):
logging.info(u"Loading roster from {0!r}"
.format(self.args.roster_cache))
try:
self.client.roster_client.load_roster(self.args.roster_cache)
except (IOError, ValueError), err:
logging.error(u"Could not load the roster: {0!r}".format(err))
self.client.connect()
self.client.run()
|
def run(self):
"""Request client connection and start the main loop."""
if self.args.roster_cache and os.path.exists(self.args.roster_cache):
logging.info(u"Loading roster from {0!r}"
.format(self.args.roster_cache))
try:
self.client.roster_client.load_roster(self.args.roster_cache)
except (IOError, ValueError), err:
logging.error(u"Could not load the roster: {0!r}".format(err))
self.client.connect()
self.client.run()
|
[
"Request",
"client",
"connection",
"and",
"start",
"the",
"main",
"loop",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/examples/roster.py#L53-L63
|
[
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
".",
"roster_cache",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"args",
".",
"roster_cache",
")",
":",
"logging",
".",
"info",
"(",
"u\"Loading roster from {0!r}\"",
".",
"format",
"(",
"self",
".",
"args",
".",
"roster_cache",
")",
")",
"try",
":",
"self",
".",
"client",
".",
"roster_client",
".",
"load_roster",
"(",
"self",
".",
"args",
".",
"roster_cache",
")",
"except",
"(",
"IOError",
",",
"ValueError",
")",
",",
"err",
":",
"logging",
".",
"error",
"(",
"u\"Could not load the roster: {0!r}\"",
".",
"format",
"(",
"err",
")",
")",
"self",
".",
"client",
".",
"connect",
"(",
")",
"self",
".",
"client",
".",
"run",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
EventDispatcher.add_handler
|
Add a handler object.
:Parameters:
- `handler`: the object providing event handler methods
:Types:
- `handler`: `EventHandler`
|
pyxmpp2/mainloop/events.py
|
def add_handler(self, handler):
"""Add a handler object.
:Parameters:
- `handler`: the object providing event handler methods
:Types:
- `handler`: `EventHandler`
"""
if not isinstance(handler, EventHandler):
raise TypeError, "Not an EventHandler"
with self.lock:
if handler in self.handlers:
return
self.handlers.append(handler)
self._update_handlers()
|
def add_handler(self, handler):
"""Add a handler object.
:Parameters:
- `handler`: the object providing event handler methods
:Types:
- `handler`: `EventHandler`
"""
if not isinstance(handler, EventHandler):
raise TypeError, "Not an EventHandler"
with self.lock:
if handler in self.handlers:
return
self.handlers.append(handler)
self._update_handlers()
|
[
"Add",
"a",
"handler",
"object",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L78-L92
|
[
"def",
"add_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"not",
"isinstance",
"(",
"handler",
",",
"EventHandler",
")",
":",
"raise",
"TypeError",
",",
"\"Not an EventHandler\"",
"with",
"self",
".",
"lock",
":",
"if",
"handler",
"in",
"self",
".",
"handlers",
":",
"return",
"self",
".",
"handlers",
".",
"append",
"(",
"handler",
")",
"self",
".",
"_update_handlers",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
EventDispatcher.remove_handler
|
Remove a handler object.
:Parameters:
- `handler`: the object to remove
|
pyxmpp2/mainloop/events.py
|
def remove_handler(self, handler):
"""Remove a handler object.
:Parameters:
- `handler`: the object to remove
"""
with self.lock:
if handler in self.handlers:
self.handlers.remove(handler)
self._update_handlers()
|
def remove_handler(self, handler):
"""Remove a handler object.
:Parameters:
- `handler`: the object to remove
"""
with self.lock:
if handler in self.handlers:
self.handlers.remove(handler)
self._update_handlers()
|
[
"Remove",
"a",
"handler",
"object",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L94-L103
|
[
"def",
"remove_handler",
"(",
"self",
",",
"handler",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"handler",
"in",
"self",
".",
"handlers",
":",
"self",
".",
"handlers",
".",
"remove",
"(",
"handler",
")",
"self",
".",
"_update_handlers",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
EventDispatcher._update_handlers
|
Update `_handler_map` after `handlers` have been
modified.
|
pyxmpp2/mainloop/events.py
|
def _update_handlers(self):
"""Update `_handler_map` after `handlers` have been
modified."""
handler_map = defaultdict(list)
for i, obj in enumerate(self.handlers):
for dummy, handler in inspect.getmembers(obj, callable):
if not hasattr(handler, "_pyxmpp_event_handled"):
continue
# pylint: disable-msg=W0212
event_class = handler._pyxmpp_event_handled
handler_map[event_class].append( (i, handler) )
self._handler_map = handler_map
|
def _update_handlers(self):
"""Update `_handler_map` after `handlers` have been
modified."""
handler_map = defaultdict(list)
for i, obj in enumerate(self.handlers):
for dummy, handler in inspect.getmembers(obj, callable):
if not hasattr(handler, "_pyxmpp_event_handled"):
continue
# pylint: disable-msg=W0212
event_class = handler._pyxmpp_event_handled
handler_map[event_class].append( (i, handler) )
self._handler_map = handler_map
|
[
"Update",
"_handler_map",
"after",
"handlers",
"have",
"been",
"modified",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L105-L116
|
[
"def",
"_update_handlers",
"(",
"self",
")",
":",
"handler_map",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"i",
",",
"obj",
"in",
"enumerate",
"(",
"self",
".",
"handlers",
")",
":",
"for",
"dummy",
",",
"handler",
"in",
"inspect",
".",
"getmembers",
"(",
"obj",
",",
"callable",
")",
":",
"if",
"not",
"hasattr",
"(",
"handler",
",",
"\"_pyxmpp_event_handled\"",
")",
":",
"continue",
"# pylint: disable-msg=W0212",
"event_class",
"=",
"handler",
".",
"_pyxmpp_event_handled",
"handler_map",
"[",
"event_class",
"]",
".",
"append",
"(",
"(",
"i",
",",
"handler",
")",
")",
"self",
".",
"_handler_map",
"=",
"handler_map"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
EventDispatcher.dispatch
|
Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Types:
- `block`: `bool`
- `timeout`: `float`
:Return: the event handled (may be `QUIT`) or `None`
|
pyxmpp2/mainloop/events.py
|
def dispatch(self, block = False, timeout = None):
"""Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Types:
- `block`: `bool`
- `timeout`: `float`
:Return: the event handled (may be `QUIT`) or `None`
"""
logger.debug(" dispatching...")
try:
event = self.queue.get(block, timeout)
except Queue.Empty:
logger.debug(" queue empty")
return None
try:
logger.debug(" event: {0!r}".format(event))
if event is QUIT:
return QUIT
handlers = list(self._handler_map[None])
klass = event.__class__
if klass in self._handler_map:
handlers += self._handler_map[klass]
logger.debug(" handlers: {0!r}".format(handlers))
# to restore the original order of handler objects
handlers.sort(key = lambda x: x[0])
for dummy, handler in handlers:
logger.debug(u" passing the event to: {0!r}".format(handler))
result = handler(event)
if isinstance(result, Event):
self.queue.put(result)
elif result and event is not QUIT:
return event
return event
finally:
self.queue.task_done()
|
def dispatch(self, block = False, timeout = None):
"""Get the next event from the queue and pass it to
the appropriate handlers.
:Parameters:
- `block`: wait for event if the queue is empty
- `timeout`: maximum time, in seconds, to wait if `block` is `True`
:Types:
- `block`: `bool`
- `timeout`: `float`
:Return: the event handled (may be `QUIT`) or `None`
"""
logger.debug(" dispatching...")
try:
event = self.queue.get(block, timeout)
except Queue.Empty:
logger.debug(" queue empty")
return None
try:
logger.debug(" event: {0!r}".format(event))
if event is QUIT:
return QUIT
handlers = list(self._handler_map[None])
klass = event.__class__
if klass in self._handler_map:
handlers += self._handler_map[klass]
logger.debug(" handlers: {0!r}".format(handlers))
# to restore the original order of handler objects
handlers.sort(key = lambda x: x[0])
for dummy, handler in handlers:
logger.debug(u" passing the event to: {0!r}".format(handler))
result = handler(event)
if isinstance(result, Event):
self.queue.put(result)
elif result and event is not QUIT:
return event
return event
finally:
self.queue.task_done()
|
[
"Get",
"the",
"next",
"event",
"from",
"the",
"queue",
"and",
"pass",
"it",
"to",
"the",
"appropriate",
"handlers",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L118-L157
|
[
"def",
"dispatch",
"(",
"self",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\" dispatching...\"",
")",
"try",
":",
"event",
"=",
"self",
".",
"queue",
".",
"get",
"(",
"block",
",",
"timeout",
")",
"except",
"Queue",
".",
"Empty",
":",
"logger",
".",
"debug",
"(",
"\" queue empty\"",
")",
"return",
"None",
"try",
":",
"logger",
".",
"debug",
"(",
"\" event: {0!r}\"",
".",
"format",
"(",
"event",
")",
")",
"if",
"event",
"is",
"QUIT",
":",
"return",
"QUIT",
"handlers",
"=",
"list",
"(",
"self",
".",
"_handler_map",
"[",
"None",
"]",
")",
"klass",
"=",
"event",
".",
"__class__",
"if",
"klass",
"in",
"self",
".",
"_handler_map",
":",
"handlers",
"+=",
"self",
".",
"_handler_map",
"[",
"klass",
"]",
"logger",
".",
"debug",
"(",
"\" handlers: {0!r}\"",
".",
"format",
"(",
"handlers",
")",
")",
"# to restore the original order of handler objects",
"handlers",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"for",
"dummy",
",",
"handler",
"in",
"handlers",
":",
"logger",
".",
"debug",
"(",
"u\" passing the event to: {0!r}\"",
".",
"format",
"(",
"handler",
")",
")",
"result",
"=",
"handler",
"(",
"event",
")",
"if",
"isinstance",
"(",
"result",
",",
"Event",
")",
":",
"self",
".",
"queue",
".",
"put",
"(",
"result",
")",
"elif",
"result",
"and",
"event",
"is",
"not",
"QUIT",
":",
"return",
"event",
"return",
"event",
"finally",
":",
"self",
".",
"queue",
".",
"task_done",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
EventDispatcher.flush
|
Read all events currently in the queue and dispatch them to the
handlers unless `dispatch` is `False`.
Note: If the queue contains `QUIT` the events after it won't be
removed.
:Parameters:
- `dispatch`: if the events should be handled (`True`) or ignored
(`False`)
:Return: `QUIT` if the `QUIT` event was reached.
|
pyxmpp2/mainloop/events.py
|
def flush(self, dispatch = True):
"""Read all events currently in the queue and dispatch them to the
handlers unless `dispatch` is `False`.
Note: If the queue contains `QUIT` the events after it won't be
removed.
:Parameters:
- `dispatch`: if the events should be handled (`True`) or ignored
(`False`)
:Return: `QUIT` if the `QUIT` event was reached.
"""
if dispatch:
while True:
event = self.dispatch(False)
if event in (None, QUIT):
return event
else:
while True:
try:
self.queue.get(False)
except Queue.Empty:
return None
|
def flush(self, dispatch = True):
"""Read all events currently in the queue and dispatch them to the
handlers unless `dispatch` is `False`.
Note: If the queue contains `QUIT` the events after it won't be
removed.
:Parameters:
- `dispatch`: if the events should be handled (`True`) or ignored
(`False`)
:Return: `QUIT` if the `QUIT` event was reached.
"""
if dispatch:
while True:
event = self.dispatch(False)
if event in (None, QUIT):
return event
else:
while True:
try:
self.queue.get(False)
except Queue.Empty:
return None
|
[
"Read",
"all",
"events",
"currently",
"in",
"the",
"queue",
"and",
"dispatch",
"them",
"to",
"the",
"handlers",
"unless",
"dispatch",
"is",
"False",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/events.py#L159-L182
|
[
"def",
"flush",
"(",
"self",
",",
"dispatch",
"=",
"True",
")",
":",
"if",
"dispatch",
":",
"while",
"True",
":",
"event",
"=",
"self",
".",
"dispatch",
"(",
"False",
")",
"if",
"event",
"in",
"(",
"None",
",",
"QUIT",
")",
":",
"return",
"event",
"else",
":",
"while",
"True",
":",
"try",
":",
"self",
".",
"queue",
".",
"get",
"(",
"False",
")",
"except",
"Queue",
".",
"Empty",
":",
"return",
"None"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
PollMainLoop._configure_io_handler
|
Register an io-handler at the polling object.
|
pyxmpp2/mainloop/poll.py
|
def _configure_io_handler(self, handler):
"""Register an io-handler at the polling object."""
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:
del self._handlers[old_fileno]
try:
self.poll.unregister(old_fileno)
except KeyError:
# The socket has changed, but the old one isn't registered,
# e.g. ``prepare`` wants to connect again
pass
if not prepared:
self._unprepared_handlers[handler] = fileno
if not fileno:
return
self._handlers[fileno] = handler
events = 0
if handler.is_readable():
logger.debug(" {0!r} readable".format(handler))
events |= select.POLLIN
if handler.is_writable():
logger.debug(" {0!r} writable".format(handler))
events |= select.POLLOUT
if events:
logger.debug(" registering {0!r} handler fileno {1} for"
" events {2}".format(handler, fileno, events))
self.poll.register(fileno, events)
|
def _configure_io_handler(self, handler):
"""Register an io-handler at the polling object."""
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:
del self._handlers[old_fileno]
try:
self.poll.unregister(old_fileno)
except KeyError:
# The socket has changed, but the old one isn't registered,
# e.g. ``prepare`` wants to connect again
pass
if not prepared:
self._unprepared_handlers[handler] = fileno
if not fileno:
return
self._handlers[fileno] = handler
events = 0
if handler.is_readable():
logger.debug(" {0!r} readable".format(handler))
events |= select.POLLIN
if handler.is_writable():
logger.debug(" {0!r} writable".format(handler))
events |= select.POLLOUT
if events:
logger.debug(" registering {0!r} handler fileno {1} for"
" events {2}".format(handler, fileno, events))
self.poll.register(fileno, events)
|
[
"Register",
"an",
"io",
"-",
"handler",
"at",
"the",
"polling",
"object",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/poll.py#L53-L87
|
[
"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",
":",
"del",
"self",
".",
"_handlers",
"[",
"old_fileno",
"]",
"try",
":",
"self",
".",
"poll",
".",
"unregister",
"(",
"old_fileno",
")",
"except",
"KeyError",
":",
"# The socket has changed, but the old one isn't registered,",
"# e.g. ``prepare`` wants to connect again",
"pass",
"if",
"not",
"prepared",
":",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"=",
"fileno",
"if",
"not",
"fileno",
":",
"return",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
"=",
"handler",
"events",
"=",
"0",
"if",
"handler",
".",
"is_readable",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\" {0!r} readable\"",
".",
"format",
"(",
"handler",
")",
")",
"events",
"|=",
"select",
".",
"POLLIN",
"if",
"handler",
".",
"is_writable",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\" {0!r} writable\"",
".",
"format",
"(",
"handler",
")",
")",
"events",
"|=",
"select",
".",
"POLLOUT",
"if",
"events",
":",
"logger",
".",
"debug",
"(",
"\" registering {0!r} handler fileno {1} for\"",
"\" events {2}\"",
".",
"format",
"(",
"handler",
",",
"fileno",
",",
"events",
")",
")",
"self",
".",
"poll",
".",
"register",
"(",
"fileno",
",",
"events",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
PollMainLoop._prepare_io_handler
|
Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
|
pyxmpp2/mainloop/poll.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))
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 is not None:
if self._timeout is not None:
self._timeout = min(self._timeout, ret.timeout)
else:
self._timeout = ret.timeout
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))
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 is not None:
if self._timeout is not None:
self._timeout = min(self._timeout, ret.timeout)
else:
self._timeout = ret.timeout
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/poll.py#L89-L108
|
[
"def",
"_prepare_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"logger",
".",
"debug",
"(",
"\" preparing handler: {0!r}\"",
".",
"format",
"(",
"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",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_timeout",
"is",
"not",
"None",
":",
"self",
".",
"_timeout",
"=",
"min",
"(",
"self",
".",
"_timeout",
",",
"ret",
".",
"timeout",
")",
"else",
":",
"self",
".",
"_timeout",
"=",
"ret",
".",
"timeout",
"prepared",
"=",
"False",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unexpected result type from prepare()\"",
")",
"return",
"prepared"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
PollMainLoop._remove_io_handler
|
Remove an i/o-handler.
|
pyxmpp2/mainloop/poll.py
|
def _remove_io_handler(self, handler):
"""Remove an i/o-handler."""
if handler in self._unprepared_handlers:
old_fileno = self._unprepared_handlers[handler]
del self._unprepared_handlers[handler]
else:
old_fileno = handler.fileno()
if old_fileno is not None:
try:
del self._handlers[old_fileno]
self.poll.unregister(old_fileno)
except KeyError:
pass
|
def _remove_io_handler(self, handler):
"""Remove an i/o-handler."""
if handler in self._unprepared_handlers:
old_fileno = self._unprepared_handlers[handler]
del self._unprepared_handlers[handler]
else:
old_fileno = handler.fileno()
if old_fileno is not None:
try:
del self._handlers[old_fileno]
self.poll.unregister(old_fileno)
except KeyError:
pass
|
[
"Remove",
"an",
"i",
"/",
"o",
"-",
"handler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/poll.py#L110-L122
|
[
"def",
"_remove_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"handler",
"in",
"self",
".",
"_unprepared_handlers",
":",
"old_fileno",
"=",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"del",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"else",
":",
"old_fileno",
"=",
"handler",
".",
"fileno",
"(",
")",
"if",
"old_fileno",
"is",
"not",
"None",
":",
"try",
":",
"del",
"self",
".",
"_handlers",
"[",
"old_fileno",
"]",
"self",
".",
"poll",
".",
"unregister",
"(",
"old_fileno",
")",
"except",
"KeyError",
":",
"pass"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
PollMainLoop.loop_iteration
|
A loop iteration - check any scheduled events
and I/O available and run the handlers.
|
pyxmpp2/mainloop/poll.py
|
def loop_iteration(self, timeout = 60):
"""A loop iteration - check any scheduled events
and I/O available and run the handlers.
"""
next_timeout, sources_handled = self._call_timeout_handlers()
if self._quit:
return sources_handled
if self._timeout is not None:
timeout = min(timeout, self._timeout)
if next_timeout is not None:
timeout = min(next_timeout, timeout)
for handler in list(self._unprepared_handlers):
self._configure_io_handler(handler)
events = self.poll.poll(timeout * 1000)
self._timeout = None
for (fileno, event) in events:
if event & select.POLLHUP:
self._handlers[fileno].handle_hup()
if event & select.POLLNVAL:
self._handlers[fileno].handle_nval()
if event & select.POLLIN:
self._handlers[fileno].handle_read()
elif event & select.POLLERR:
# if POLLIN was set this condition should be already handled
self._handlers[fileno].handle_err()
if event & select.POLLOUT:
self._handlers[fileno].handle_write()
sources_handled += 1
self._configure_io_handler(self._handlers[fileno])
return sources_handled
|
def loop_iteration(self, timeout = 60):
"""A loop iteration - check any scheduled events
and I/O available and run the handlers.
"""
next_timeout, sources_handled = self._call_timeout_handlers()
if self._quit:
return sources_handled
if self._timeout is not None:
timeout = min(timeout, self._timeout)
if next_timeout is not None:
timeout = min(next_timeout, timeout)
for handler in list(self._unprepared_handlers):
self._configure_io_handler(handler)
events = self.poll.poll(timeout * 1000)
self._timeout = None
for (fileno, event) in events:
if event & select.POLLHUP:
self._handlers[fileno].handle_hup()
if event & select.POLLNVAL:
self._handlers[fileno].handle_nval()
if event & select.POLLIN:
self._handlers[fileno].handle_read()
elif event & select.POLLERR:
# if POLLIN was set this condition should be already handled
self._handlers[fileno].handle_err()
if event & select.POLLOUT:
self._handlers[fileno].handle_write()
sources_handled += 1
self._configure_io_handler(self._handlers[fileno])
return sources_handled
|
[
"A",
"loop",
"iteration",
"-",
"check",
"any",
"scheduled",
"events",
"and",
"I",
"/",
"O",
"available",
"and",
"run",
"the",
"handlers",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/poll.py#L124-L153
|
[
"def",
"loop_iteration",
"(",
"self",
",",
"timeout",
"=",
"60",
")",
":",
"next_timeout",
",",
"sources_handled",
"=",
"self",
".",
"_call_timeout_handlers",
"(",
")",
"if",
"self",
".",
"_quit",
":",
"return",
"sources_handled",
"if",
"self",
".",
"_timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"min",
"(",
"timeout",
",",
"self",
".",
"_timeout",
")",
"if",
"next_timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"min",
"(",
"next_timeout",
",",
"timeout",
")",
"for",
"handler",
"in",
"list",
"(",
"self",
".",
"_unprepared_handlers",
")",
":",
"self",
".",
"_configure_io_handler",
"(",
"handler",
")",
"events",
"=",
"self",
".",
"poll",
".",
"poll",
"(",
"timeout",
"*",
"1000",
")",
"self",
".",
"_timeout",
"=",
"None",
"for",
"(",
"fileno",
",",
"event",
")",
"in",
"events",
":",
"if",
"event",
"&",
"select",
".",
"POLLHUP",
":",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
".",
"handle_hup",
"(",
")",
"if",
"event",
"&",
"select",
".",
"POLLNVAL",
":",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
".",
"handle_nval",
"(",
")",
"if",
"event",
"&",
"select",
".",
"POLLIN",
":",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
".",
"handle_read",
"(",
")",
"elif",
"event",
"&",
"select",
".",
"POLLERR",
":",
"# if POLLIN was set this condition should be already handled",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
".",
"handle_err",
"(",
")",
"if",
"event",
"&",
"select",
".",
"POLLOUT",
":",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
".",
"handle_write",
"(",
")",
"sources_handled",
"+=",
"1",
"self",
".",
"_configure_io_handler",
"(",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
")",
"return",
"sources_handled"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SCRAMOperations.Normalize
|
The Normalize(str) function.
This one also accepts Unicode string input (in the RFC only UTF-8
strings are used).
|
pyxmpp2/sasl/scram.py
|
def Normalize(str_):
"""The Normalize(str) function.
This one also accepts Unicode string input (in the RFC only UTF-8
strings are used).
"""
# pylint: disable=C0103
if isinstance(str_, bytes):
str_ = str_.decode("utf-8")
return SASLPREP.prepare(str_).encode("utf-8")
|
def Normalize(str_):
"""The Normalize(str) function.
This one also accepts Unicode string input (in the RFC only UTF-8
strings are used).
"""
# pylint: disable=C0103
if isinstance(str_, bytes):
str_ = str_.decode("utf-8")
return SASLPREP.prepare(str_).encode("utf-8")
|
[
"The",
"Normalize",
"(",
"str",
")",
"function",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L92-L101
|
[
"def",
"Normalize",
"(",
"str_",
")",
":",
"# pylint: disable=C0103",
"if",
"isinstance",
"(",
"str_",
",",
"bytes",
")",
":",
"str_",
"=",
"str_",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"SASLPREP",
".",
"prepare",
"(",
"str_",
")",
".",
"encode",
"(",
"\"utf-8\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SCRAMOperations.HMAC
|
The HMAC(key, str) function.
|
pyxmpp2/sasl/scram.py
|
def HMAC(self, key, str_):
"""The HMAC(key, str) function."""
# pylint: disable=C0103
return hmac.new(key, str_, self.hash_factory).digest()
|
def HMAC(self, key, str_):
"""The HMAC(key, str) function."""
# pylint: disable=C0103
return hmac.new(key, str_, self.hash_factory).digest()
|
[
"The",
"HMAC",
"(",
"key",
"str",
")",
"function",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L103-L106
|
[
"def",
"HMAC",
"(",
"self",
",",
"key",
",",
"str_",
")",
":",
"# pylint: disable=C0103",
"return",
"hmac",
".",
"new",
"(",
"key",
",",
"str_",
",",
"self",
".",
"hash_factory",
")",
".",
"digest",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SCRAMOperations.Hi
|
The Hi(str, salt, i) function.
|
pyxmpp2/sasl/scram.py
|
def Hi(self, str_, salt, i):
"""The Hi(str, salt, i) function."""
# pylint: disable=C0103
Uj = self.HMAC(str_, salt + b"\000\000\000\001") # U1
result = Uj
for _ in range(2, i + 1):
Uj = self.HMAC(str_, Uj) # Uj = HMAC(str, Uj-1)
result = self.XOR(result, Uj) # ... XOR Uj-1 XOR Uj
return result
|
def Hi(self, str_, salt, i):
"""The Hi(str, salt, i) function."""
# pylint: disable=C0103
Uj = self.HMAC(str_, salt + b"\000\000\000\001") # U1
result = Uj
for _ in range(2, i + 1):
Uj = self.HMAC(str_, Uj) # Uj = HMAC(str, Uj-1)
result = self.XOR(result, Uj) # ... XOR Uj-1 XOR Uj
return result
|
[
"The",
"Hi",
"(",
"str",
"salt",
"i",
")",
"function",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L126-L134
|
[
"def",
"Hi",
"(",
"self",
",",
"str_",
",",
"salt",
",",
"i",
")",
":",
"# pylint: disable=C0103",
"Uj",
"=",
"self",
".",
"HMAC",
"(",
"str_",
",",
"salt",
"+",
"b\"\\000\\000\\000\\001\"",
")",
"# U1",
"result",
"=",
"Uj",
"for",
"_",
"in",
"range",
"(",
"2",
",",
"i",
"+",
"1",
")",
":",
"Uj",
"=",
"self",
".",
"HMAC",
"(",
"str_",
",",
"Uj",
")",
"# Uj = HMAC(str, Uj-1)",
"result",
"=",
"self",
".",
"XOR",
"(",
"result",
",",
"Uj",
")",
"# ... XOR Uj-1 XOR Uj",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SCRAMClientAuthenticator.challenge
|
Process a challenge and return the response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
|
pyxmpp2/sasl/scram.py
|
def challenge(self, challenge):
"""Process a challenge and return the response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
# pylint: disable=R0911
if not challenge:
logger.debug("Empty challenge")
return Failure("bad-challenge")
if self._server_first_message:
return self._final_challenge(challenge)
match = SERVER_FIRST_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad challenge syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
self._server_first_message = challenge
mext = match.group("mext")
if mext:
logger.debug("Unsupported extension received: {0!r}".format(mext))
return Failure("bad-challenge")
nonce = match.group("nonce")
if not nonce.startswith(self._c_nonce):
logger.debug("Nonce does not start with our nonce")
return Failure("bad-challenge")
salt = match.group("salt")
try:
salt = a2b_base64(salt)
except ValueError:
logger.debug("Bad base64 encoding for salt: {0!r}".format(salt))
return Failure("bad-challenge")
iteration_count = match.group("iteration_count")
try:
iteration_count = int(iteration_count)
except ValueError:
logger.debug("Bad iteration_count: {0!r}".format(iteration_count))
return Failure("bad-challenge")
return self._make_response(nonce, salt, iteration_count)
|
def challenge(self, challenge):
"""Process a challenge and return the response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
# pylint: disable=R0911
if not challenge:
logger.debug("Empty challenge")
return Failure("bad-challenge")
if self._server_first_message:
return self._final_challenge(challenge)
match = SERVER_FIRST_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad challenge syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
self._server_first_message = challenge
mext = match.group("mext")
if mext:
logger.debug("Unsupported extension received: {0!r}".format(mext))
return Failure("bad-challenge")
nonce = match.group("nonce")
if not nonce.startswith(self._c_nonce):
logger.debug("Nonce does not start with our nonce")
return Failure("bad-challenge")
salt = match.group("salt")
try:
salt = a2b_base64(salt)
except ValueError:
logger.debug("Bad base64 encoding for salt: {0!r}".format(salt))
return Failure("bad-challenge")
iteration_count = match.group("iteration_count")
try:
iteration_count = int(iteration_count)
except ValueError:
logger.debug("Bad iteration_count: {0!r}".format(iteration_count))
return Failure("bad-challenge")
return self._make_response(nonce, salt, iteration_count)
|
[
"Process",
"a",
"challenge",
"and",
"return",
"the",
"response",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L247-L297
|
[
"def",
"challenge",
"(",
"self",
",",
"challenge",
")",
":",
"# pylint: disable=R0911",
"if",
"not",
"challenge",
":",
"logger",
".",
"debug",
"(",
"\"Empty challenge\"",
")",
"return",
"Failure",
"(",
"\"bad-challenge\"",
")",
"if",
"self",
".",
"_server_first_message",
":",
"return",
"self",
".",
"_final_challenge",
"(",
"challenge",
")",
"match",
"=",
"SERVER_FIRST_MESSAGE_RE",
".",
"match",
"(",
"challenge",
")",
"if",
"not",
"match",
":",
"logger",
".",
"debug",
"(",
"\"Bad challenge syntax: {0!r}\"",
".",
"format",
"(",
"challenge",
")",
")",
"return",
"Failure",
"(",
"\"bad-challenge\"",
")",
"self",
".",
"_server_first_message",
"=",
"challenge",
"mext",
"=",
"match",
".",
"group",
"(",
"\"mext\"",
")",
"if",
"mext",
":",
"logger",
".",
"debug",
"(",
"\"Unsupported extension received: {0!r}\"",
".",
"format",
"(",
"mext",
")",
")",
"return",
"Failure",
"(",
"\"bad-challenge\"",
")",
"nonce",
"=",
"match",
".",
"group",
"(",
"\"nonce\"",
")",
"if",
"not",
"nonce",
".",
"startswith",
"(",
"self",
".",
"_c_nonce",
")",
":",
"logger",
".",
"debug",
"(",
"\"Nonce does not start with our nonce\"",
")",
"return",
"Failure",
"(",
"\"bad-challenge\"",
")",
"salt",
"=",
"match",
".",
"group",
"(",
"\"salt\"",
")",
"try",
":",
"salt",
"=",
"a2b_base64",
"(",
"salt",
")",
"except",
"ValueError",
":",
"logger",
".",
"debug",
"(",
"\"Bad base64 encoding for salt: {0!r}\"",
".",
"format",
"(",
"salt",
")",
")",
"return",
"Failure",
"(",
"\"bad-challenge\"",
")",
"iteration_count",
"=",
"match",
".",
"group",
"(",
"\"iteration_count\"",
")",
"try",
":",
"iteration_count",
"=",
"int",
"(",
"iteration_count",
")",
"except",
"ValueError",
":",
"logger",
".",
"debug",
"(",
"\"Bad iteration_count: {0!r}\"",
".",
"format",
"(",
"iteration_count",
")",
")",
"return",
"Failure",
"(",
"\"bad-challenge\"",
")",
"return",
"self",
".",
"_make_response",
"(",
"nonce",
",",
"salt",
",",
"iteration_count",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SCRAMClientAuthenticator._make_response
|
Make a response for the first challenge from the server.
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
|
pyxmpp2/sasl/scram.py
|
def _make_response(self, nonce, salt, iteration_count):
"""Make a response for the first challenge from the server.
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
self._salted_password = self.Hi(self.Normalize(self.password), salt,
iteration_count)
self.password = None # not needed any more
if self.channel_binding:
channel_binding = b"c=" + standard_b64encode(self._gs2_header +
self._cb_data)
else:
channel_binding = b"c=" + standard_b64encode(self._gs2_header)
# pylint: disable=C0103
client_final_message_without_proof = (channel_binding + b",r=" + nonce)
client_key = self.HMAC(self._salted_password, b"Client Key")
stored_key = self.H(client_key)
auth_message = ( self._client_first_message_bare + b"," +
self._server_first_message + b"," +
client_final_message_without_proof )
self._auth_message = auth_message
client_signature = self.HMAC(stored_key, auth_message)
client_proof = self.XOR(client_key, client_signature)
proof = b"p=" + standard_b64encode(client_proof)
client_final_message = (client_final_message_without_proof + b"," +
proof)
return Response(client_final_message)
|
def _make_response(self, nonce, salt, iteration_count):
"""Make a response for the first challenge from the server.
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
self._salted_password = self.Hi(self.Normalize(self.password), salt,
iteration_count)
self.password = None # not needed any more
if self.channel_binding:
channel_binding = b"c=" + standard_b64encode(self._gs2_header +
self._cb_data)
else:
channel_binding = b"c=" + standard_b64encode(self._gs2_header)
# pylint: disable=C0103
client_final_message_without_proof = (channel_binding + b",r=" + nonce)
client_key = self.HMAC(self._salted_password, b"Client Key")
stored_key = self.H(client_key)
auth_message = ( self._client_first_message_bare + b"," +
self._server_first_message + b"," +
client_final_message_without_proof )
self._auth_message = auth_message
client_signature = self.HMAC(stored_key, auth_message)
client_proof = self.XOR(client_key, client_signature)
proof = b"p=" + standard_b64encode(client_proof)
client_final_message = (client_final_message_without_proof + b"," +
proof)
return Response(client_final_message)
|
[
"Make",
"a",
"response",
"for",
"the",
"first",
"challenge",
"from",
"the",
"server",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L299-L328
|
[
"def",
"_make_response",
"(",
"self",
",",
"nonce",
",",
"salt",
",",
"iteration_count",
")",
":",
"self",
".",
"_salted_password",
"=",
"self",
".",
"Hi",
"(",
"self",
".",
"Normalize",
"(",
"self",
".",
"password",
")",
",",
"salt",
",",
"iteration_count",
")",
"self",
".",
"password",
"=",
"None",
"# not needed any more",
"if",
"self",
".",
"channel_binding",
":",
"channel_binding",
"=",
"b\"c=\"",
"+",
"standard_b64encode",
"(",
"self",
".",
"_gs2_header",
"+",
"self",
".",
"_cb_data",
")",
"else",
":",
"channel_binding",
"=",
"b\"c=\"",
"+",
"standard_b64encode",
"(",
"self",
".",
"_gs2_header",
")",
"# pylint: disable=C0103",
"client_final_message_without_proof",
"=",
"(",
"channel_binding",
"+",
"b\",r=\"",
"+",
"nonce",
")",
"client_key",
"=",
"self",
".",
"HMAC",
"(",
"self",
".",
"_salted_password",
",",
"b\"Client Key\"",
")",
"stored_key",
"=",
"self",
".",
"H",
"(",
"client_key",
")",
"auth_message",
"=",
"(",
"self",
".",
"_client_first_message_bare",
"+",
"b\",\"",
"+",
"self",
".",
"_server_first_message",
"+",
"b\",\"",
"+",
"client_final_message_without_proof",
")",
"self",
".",
"_auth_message",
"=",
"auth_message",
"client_signature",
"=",
"self",
".",
"HMAC",
"(",
"stored_key",
",",
"auth_message",
")",
"client_proof",
"=",
"self",
".",
"XOR",
"(",
"client_key",
",",
"client_signature",
")",
"proof",
"=",
"b\"p=\"",
"+",
"standard_b64encode",
"(",
"client_proof",
")",
"client_final_message",
"=",
"(",
"client_final_message_without_proof",
"+",
"b\",\"",
"+",
"proof",
")",
"return",
"Response",
"(",
"client_final_message",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SCRAMClientAuthenticator._final_challenge
|
Process the second challenge from the server and return the
response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
|
pyxmpp2/sasl/scram.py
|
def _final_challenge(self, challenge):
"""Process the second challenge from the server and return the
response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
if self._finished:
return Failure("extra-challenge")
match = SERVER_FINAL_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad final message syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
error = match.group("error")
if error:
logger.debug("Server returned SCRAM error: {0!r}".format(error))
return Failure(u"scram-" + error.decode("utf-8"))
verifier = match.group("verifier")
if not verifier:
logger.debug("No verifier value in the final message")
return Failure("bad-succes")
server_key = self.HMAC(self._salted_password, b"Server Key")
server_signature = self.HMAC(server_key, self._auth_message)
if server_signature != a2b_base64(verifier):
logger.debug("Server verifier does not match")
return Failure("bad-succes")
self._finished = True
return Response(None)
|
def _final_challenge(self, challenge):
"""Process the second challenge from the server and return the
response.
:Parameters:
- `challenge`: the challenge from server.
:Types:
- `challenge`: `bytes`
:return: the response or a failure indicator.
:returntype: `sasl.Response` or `sasl.Failure`
"""
if self._finished:
return Failure("extra-challenge")
match = SERVER_FINAL_MESSAGE_RE.match(challenge)
if not match:
logger.debug("Bad final message syntax: {0!r}".format(challenge))
return Failure("bad-challenge")
error = match.group("error")
if error:
logger.debug("Server returned SCRAM error: {0!r}".format(error))
return Failure(u"scram-" + error.decode("utf-8"))
verifier = match.group("verifier")
if not verifier:
logger.debug("No verifier value in the final message")
return Failure("bad-succes")
server_key = self.HMAC(self._salted_password, b"Server Key")
server_signature = self.HMAC(server_key, self._auth_message)
if server_signature != a2b_base64(verifier):
logger.debug("Server verifier does not match")
return Failure("bad-succes")
self._finished = True
return Response(None)
|
[
"Process",
"the",
"second",
"challenge",
"from",
"the",
"server",
"and",
"return",
"the",
"response",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L330-L367
|
[
"def",
"_final_challenge",
"(",
"self",
",",
"challenge",
")",
":",
"if",
"self",
".",
"_finished",
":",
"return",
"Failure",
"(",
"\"extra-challenge\"",
")",
"match",
"=",
"SERVER_FINAL_MESSAGE_RE",
".",
"match",
"(",
"challenge",
")",
"if",
"not",
"match",
":",
"logger",
".",
"debug",
"(",
"\"Bad final message syntax: {0!r}\"",
".",
"format",
"(",
"challenge",
")",
")",
"return",
"Failure",
"(",
"\"bad-challenge\"",
")",
"error",
"=",
"match",
".",
"group",
"(",
"\"error\"",
")",
"if",
"error",
":",
"logger",
".",
"debug",
"(",
"\"Server returned SCRAM error: {0!r}\"",
".",
"format",
"(",
"error",
")",
")",
"return",
"Failure",
"(",
"u\"scram-\"",
"+",
"error",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"verifier",
"=",
"match",
".",
"group",
"(",
"\"verifier\"",
")",
"if",
"not",
"verifier",
":",
"logger",
".",
"debug",
"(",
"\"No verifier value in the final message\"",
")",
"return",
"Failure",
"(",
"\"bad-succes\"",
")",
"server_key",
"=",
"self",
".",
"HMAC",
"(",
"self",
".",
"_salted_password",
",",
"b\"Server Key\"",
")",
"server_signature",
"=",
"self",
".",
"HMAC",
"(",
"server_key",
",",
"self",
".",
"_auth_message",
")",
"if",
"server_signature",
"!=",
"a2b_base64",
"(",
"verifier",
")",
":",
"logger",
".",
"debug",
"(",
"\"Server verifier does not match\"",
")",
"return",
"Failure",
"(",
"\"bad-succes\"",
")",
"self",
".",
"_finished",
"=",
"True",
"return",
"Response",
"(",
"None",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
SCRAMClientAuthenticator.finish
|
Process success indicator from the server.
Process any addiitional data passed with the success.
Fail if the server was not authenticated.
:Parameters:
- `data`: an optional additional data with success.
:Types:
- `data`: `bytes`
:return: success or failure indicator.
:returntype: `sasl.Success` or `sasl.Failure`
|
pyxmpp2/sasl/scram.py
|
def finish(self, data):
"""Process success indicator from the server.
Process any addiitional data passed with the success.
Fail if the server was not authenticated.
:Parameters:
- `data`: an optional additional data with success.
:Types:
- `data`: `bytes`
:return: success or failure indicator.
:returntype: `sasl.Success` or `sasl.Failure`"""
if not self._server_first_message:
logger.debug("Got success too early")
return Failure("bad-success")
if self._finished:
return Success({"username": self.username, "authzid": self.authzid})
else:
ret = self._final_challenge(data)
if isinstance(ret, Failure):
return ret
if self._finished:
return Success({"username": self.username,
"authzid": self.authzid})
else:
logger.debug("Something went wrong when processing additional"
" data with success?")
return Failure("bad-success")
|
def finish(self, data):
"""Process success indicator from the server.
Process any addiitional data passed with the success.
Fail if the server was not authenticated.
:Parameters:
- `data`: an optional additional data with success.
:Types:
- `data`: `bytes`
:return: success or failure indicator.
:returntype: `sasl.Success` or `sasl.Failure`"""
if not self._server_first_message:
logger.debug("Got success too early")
return Failure("bad-success")
if self._finished:
return Success({"username": self.username, "authzid": self.authzid})
else:
ret = self._final_challenge(data)
if isinstance(ret, Failure):
return ret
if self._finished:
return Success({"username": self.username,
"authzid": self.authzid})
else:
logger.debug("Something went wrong when processing additional"
" data with success?")
return Failure("bad-success")
|
[
"Process",
"success",
"indicator",
"from",
"the",
"server",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/sasl/scram.py#L369-L397
|
[
"def",
"finish",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"_server_first_message",
":",
"logger",
".",
"debug",
"(",
"\"Got success too early\"",
")",
"return",
"Failure",
"(",
"\"bad-success\"",
")",
"if",
"self",
".",
"_finished",
":",
"return",
"Success",
"(",
"{",
"\"username\"",
":",
"self",
".",
"username",
",",
"\"authzid\"",
":",
"self",
".",
"authzid",
"}",
")",
"else",
":",
"ret",
"=",
"self",
".",
"_final_challenge",
"(",
"data",
")",
"if",
"isinstance",
"(",
"ret",
",",
"Failure",
")",
":",
"return",
"ret",
"if",
"self",
".",
"_finished",
":",
"return",
"Success",
"(",
"{",
"\"username\"",
":",
"self",
".",
"username",
",",
"\"authzid\"",
":",
"self",
".",
"authzid",
"}",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Something went wrong when processing additional\"",
"\" data with success?\"",
")",
"return",
"Failure",
"(",
"\"bad-success\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
feature_uri
|
Decorating attaching a feature URI (for Service Discovery or Capability
to a XMPPFeatureHandler class.
|
pyxmpp2/interfaces.py
|
def feature_uri(uri):
"""Decorating attaching a feature URI (for Service Discovery or Capability
to a XMPPFeatureHandler class."""
def decorator(class_):
"""Returns a decorated class"""
if "_pyxmpp_feature_uris" not in class_.__dict__:
class_._pyxmpp_feature_uris = set()
class_._pyxmpp_feature_uris.add(uri)
return class_
return decorator
|
def feature_uri(uri):
"""Decorating attaching a feature URI (for Service Discovery or Capability
to a XMPPFeatureHandler class."""
def decorator(class_):
"""Returns a decorated class"""
if "_pyxmpp_feature_uris" not in class_.__dict__:
class_._pyxmpp_feature_uris = set()
class_._pyxmpp_feature_uris.add(uri)
return class_
return decorator
|
[
"Decorating",
"attaching",
"a",
"feature",
"URI",
"(",
"for",
"Service",
"Discovery",
"or",
"Capability",
"to",
"a",
"XMPPFeatureHandler",
"class",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L216-L225
|
[
"def",
"feature_uri",
"(",
"uri",
")",
":",
"def",
"decorator",
"(",
"class_",
")",
":",
"\"\"\"Returns a decorated class\"\"\"",
"if",
"\"_pyxmpp_feature_uris\"",
"not",
"in",
"class_",
".",
"__dict__",
":",
"class_",
".",
"_pyxmpp_feature_uris",
"=",
"set",
"(",
")",
"class_",
".",
"_pyxmpp_feature_uris",
".",
"add",
"(",
"uri",
")",
"return",
"class_",
"return",
"decorator"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
_iq_handler
|
Method decorator generator for decorating <iq type='get'/> stanza
handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `usage_restriction`: `unicode`
|
pyxmpp2/interfaces.py
|
def _iq_handler(iq_type, payload_class, payload_key, usage_restriction):
"""Method decorator generator for decorating <iq type='get'/> stanza
handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stanza_handled = ("iq", iq_type)
func._pyxmpp_payload_class_handled = payload_class
func._pyxmpp_payload_key = payload_key
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator
|
def _iq_handler(iq_type, payload_class, payload_key, usage_restriction):
"""Method decorator generator for decorating <iq type='get'/> stanza
handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stanza_handled = ("iq", iq_type)
func._pyxmpp_payload_class_handled = payload_class
func._pyxmpp_payload_key = payload_key
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator
|
[
"Method",
"decorator",
"generator",
"for",
"decorating",
"<iq",
"type",
"=",
"get",
"/",
">",
"stanza",
"handler",
"methods",
"in",
"XMPPFeatureHandler",
"subclasses",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L227-L247
|
[
"def",
"_iq_handler",
"(",
"iq_type",
",",
"payload_class",
",",
"payload_key",
",",
"usage_restriction",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"The decorator\"\"\"",
"func",
".",
"_pyxmpp_stanza_handled",
"=",
"(",
"\"iq\"",
",",
"iq_type",
")",
"func",
".",
"_pyxmpp_payload_class_handled",
"=",
"payload_class",
"func",
".",
"_pyxmpp_payload_key",
"=",
"payload_key",
"func",
".",
"_pyxmpp_usage_restriction",
"=",
"usage_restriction",
"return",
"func",
"return",
"decorator"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
_stanza_handler
|
Method decorator generator for decorating <message/> or <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `element_name`: "message" or "presence"
- `stanza_type`: expected value of the 'type' attribute of the stanza
- `payload_class`: payload class expected
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `element_name`: `unicode`
- `stanza_type`: `unicode`
- `payload_class`: subclass of `StanzaPayload`
- `usage_restriction`: `unicode`
|
pyxmpp2/interfaces.py
|
def _stanza_handler(element_name, stanza_type, payload_class, payload_key,
usage_restriction):
"""Method decorator generator for decorating <message/> or <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `element_name`: "message" or "presence"
- `stanza_type`: expected value of the 'type' attribute of the stanza
- `payload_class`: payload class expected
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `element_name`: `unicode`
- `stanza_type`: `unicode`
- `payload_class`: subclass of `StanzaPayload`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stanza_handled = (element_name, stanza_type)
func._pyxmpp_payload_class_handled = payload_class
func._pyxmpp_payload_key = payload_key
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator
|
def _stanza_handler(element_name, stanza_type, payload_class, payload_key,
usage_restriction):
"""Method decorator generator for decorating <message/> or <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `element_name`: "message" or "presence"
- `stanza_type`: expected value of the 'type' attribute of the stanza
- `payload_class`: payload class expected
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `element_name`: `unicode`
- `stanza_type`: `unicode`
- `payload_class`: subclass of `StanzaPayload`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stanza_handled = (element_name, stanza_type)
func._pyxmpp_payload_class_handled = payload_class
func._pyxmpp_payload_key = payload_key
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator
|
[
"Method",
"decorator",
"generator",
"for",
"decorating",
"<message",
"/",
">",
"or",
"<presence",
"/",
">",
"stanza",
"handler",
"methods",
"in",
"XMPPFeatureHandler",
"subclasses",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L282-L307
|
[
"def",
"_stanza_handler",
"(",
"element_name",
",",
"stanza_type",
",",
"payload_class",
",",
"payload_key",
",",
"usage_restriction",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"The decorator\"\"\"",
"func",
".",
"_pyxmpp_stanza_handled",
"=",
"(",
"element_name",
",",
"stanza_type",
")",
"func",
".",
"_pyxmpp_payload_class_handled",
"=",
"payload_class",
"func",
".",
"_pyxmpp_payload_key",
"=",
"payload_key",
"func",
".",
"_pyxmpp_usage_restriction",
"=",
"usage_restriction",
"return",
"func",
"return",
"decorator"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
message_stanza_handler
|
Method decorator generator for decorating <message/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `stanza_type`: expected value of the 'type' attribute of the stanza.
`None` means all types except 'error'
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `stanza_type`: `unicode`
- `usage_restriction`: `unicode`
|
pyxmpp2/interfaces.py
|
def message_stanza_handler(stanza_type = None, payload_class = None,
payload_key = None, usage_restriction = "post-auth"):
"""Method decorator generator for decorating <message/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `stanza_type`: expected value of the 'type' attribute of the stanza.
`None` means all types except 'error'
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `stanza_type`: `unicode`
- `usage_restriction`: `unicode`
"""
if stanza_type is None:
stanza_type = "normal"
return _stanza_handler("message", stanza_type, payload_class, payload_key,
usage_restriction)
|
def message_stanza_handler(stanza_type = None, payload_class = None,
payload_key = None, usage_restriction = "post-auth"):
"""Method decorator generator for decorating <message/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `stanza_type`: expected value of the 'type' attribute of the stanza.
`None` means all types except 'error'
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `stanza_type`: `unicode`
- `usage_restriction`: `unicode`
"""
if stanza_type is None:
stanza_type = "normal"
return _stanza_handler("message", stanza_type, payload_class, payload_key,
usage_restriction)
|
[
"Method",
"decorator",
"generator",
"for",
"decorating",
"<message",
"/",
">",
"stanza",
"handler",
"methods",
"in",
"XMPPFeatureHandler",
"subclasses",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L309-L329
|
[
"def",
"message_stanza_handler",
"(",
"stanza_type",
"=",
"None",
",",
"payload_class",
"=",
"None",
",",
"payload_key",
"=",
"None",
",",
"usage_restriction",
"=",
"\"post-auth\"",
")",
":",
"if",
"stanza_type",
"is",
"None",
":",
"stanza_type",
"=",
"\"normal\"",
"return",
"_stanza_handler",
"(",
"\"message\"",
",",
"stanza_type",
",",
"payload_class",
",",
"payload_key",
",",
"usage_restriction",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
presence_stanza_handler
|
Method decorator generator for decorating <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `stanza_type`: expected value of the 'type' attribute of the stanza.
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `stanza_type`: `unicode`
- `usage_restriction`: `unicode`
|
pyxmpp2/interfaces.py
|
def presence_stanza_handler(stanza_type = None, payload_class = None,
payload_key = None, usage_restriction = "post-auth"):
"""Method decorator generator for decorating <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `stanza_type`: expected value of the 'type' attribute of the stanza.
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `stanza_type`: `unicode`
- `usage_restriction`: `unicode`
"""
return _stanza_handler("presence", stanza_type, payload_class, payload_key,
usage_restriction)
|
def presence_stanza_handler(stanza_type = None, payload_class = None,
payload_key = None, usage_restriction = "post-auth"):
"""Method decorator generator for decorating <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `stanza_type`: expected value of the 'type' attribute of the stanza.
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `payload_class`: subclass of `StanzaPayload`
- `stanza_type`: `unicode`
- `usage_restriction`: `unicode`
"""
return _stanza_handler("presence", stanza_type, payload_class, payload_key,
usage_restriction)
|
[
"Method",
"decorator",
"generator",
"for",
"decorating",
"<presence",
"/",
">",
"stanza",
"handler",
"methods",
"in",
"XMPPFeatureHandler",
"subclasses",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L331-L348
|
[
"def",
"presence_stanza_handler",
"(",
"stanza_type",
"=",
"None",
",",
"payload_class",
"=",
"None",
",",
"payload_key",
"=",
"None",
",",
"usage_restriction",
"=",
"\"post-auth\"",
")",
":",
"return",
"_stanza_handler",
"(",
"\"presence\"",
",",
"stanza_type",
",",
"payload_class",
",",
"payload_key",
",",
"usage_restriction",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
payload_element_name
|
Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode`
|
pyxmpp2/interfaces.py
|
def payload_element_name(element_name):
"""Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode`
"""
def decorator(klass):
"""The payload_element_name decorator."""
# pylint: disable-msg=W0212,W0404
from .stanzapayload import STANZA_PAYLOAD_CLASSES
from .stanzapayload import STANZA_PAYLOAD_ELEMENTS
if hasattr(klass, "_pyxmpp_payload_element_name"):
klass._pyxmpp_payload_element_name.append(element_name)
else:
klass._pyxmpp_payload_element_name = [element_name]
if element_name in STANZA_PAYLOAD_CLASSES:
logger = logging.getLogger('pyxmpp.payload_element_name')
logger.warning("Overriding payload class for {0!r}".format(
element_name))
STANZA_PAYLOAD_CLASSES[element_name] = klass
STANZA_PAYLOAD_ELEMENTS[klass].append(element_name)
return klass
return decorator
|
def payload_element_name(element_name):
"""Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode`
"""
def decorator(klass):
"""The payload_element_name decorator."""
# pylint: disable-msg=W0212,W0404
from .stanzapayload import STANZA_PAYLOAD_CLASSES
from .stanzapayload import STANZA_PAYLOAD_ELEMENTS
if hasattr(klass, "_pyxmpp_payload_element_name"):
klass._pyxmpp_payload_element_name.append(element_name)
else:
klass._pyxmpp_payload_element_name = [element_name]
if element_name in STANZA_PAYLOAD_CLASSES:
logger = logging.getLogger('pyxmpp.payload_element_name')
logger.warning("Overriding payload class for {0!r}".format(
element_name))
STANZA_PAYLOAD_CLASSES[element_name] = klass
STANZA_PAYLOAD_ELEMENTS[klass].append(element_name)
return klass
return decorator
|
[
"Class",
"decorator",
"generator",
"for",
"decorationg",
"StanzaPayload",
"subclasses",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L391-L416
|
[
"def",
"payload_element_name",
"(",
"element_name",
")",
":",
"def",
"decorator",
"(",
"klass",
")",
":",
"\"\"\"The payload_element_name decorator.\"\"\"",
"# pylint: disable-msg=W0212,W0404",
"from",
".",
"stanzapayload",
"import",
"STANZA_PAYLOAD_CLASSES",
"from",
".",
"stanzapayload",
"import",
"STANZA_PAYLOAD_ELEMENTS",
"if",
"hasattr",
"(",
"klass",
",",
"\"_pyxmpp_payload_element_name\"",
")",
":",
"klass",
".",
"_pyxmpp_payload_element_name",
".",
"append",
"(",
"element_name",
")",
"else",
":",
"klass",
".",
"_pyxmpp_payload_element_name",
"=",
"[",
"element_name",
"]",
"if",
"element_name",
"in",
"STANZA_PAYLOAD_CLASSES",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'pyxmpp.payload_element_name'",
")",
"logger",
".",
"warning",
"(",
"\"Overriding payload class for {0!r}\"",
".",
"format",
"(",
"element_name",
")",
")",
"STANZA_PAYLOAD_CLASSES",
"[",
"element_name",
"]",
"=",
"klass",
"STANZA_PAYLOAD_ELEMENTS",
"[",
"klass",
"]",
".",
"append",
"(",
"element_name",
")",
"return",
"klass",
"return",
"decorator"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
stream_element_handler
|
Method decorator generator for decorating stream element
handler methods in `StreamFeatureHandler` subclasses.
:Parameters:
- `element_name`: stream element QName
- `usage_restriction`: optional usage restriction: "initiator" or
"receiver"
:Types:
- `element_name`: `unicode`
- `usage_restriction`: `unicode`
|
pyxmpp2/interfaces.py
|
def stream_element_handler(element_name, usage_restriction = None):
"""Method decorator generator for decorating stream element
handler methods in `StreamFeatureHandler` subclasses.
:Parameters:
- `element_name`: stream element QName
- `usage_restriction`: optional usage restriction: "initiator" or
"receiver"
:Types:
- `element_name`: `unicode`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stream_element_handled = element_name
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator
|
def stream_element_handler(element_name, usage_restriction = None):
"""Method decorator generator for decorating stream element
handler methods in `StreamFeatureHandler` subclasses.
:Parameters:
- `element_name`: stream element QName
- `usage_restriction`: optional usage restriction: "initiator" or
"receiver"
:Types:
- `element_name`: `unicode`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stream_element_handled = element_name
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator
|
[
"Method",
"decorator",
"generator",
"for",
"decorating",
"stream",
"element",
"handler",
"methods",
"in",
"StreamFeatureHandler",
"subclasses",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/interfaces.py#L501-L518
|
[
"def",
"stream_element_handler",
"(",
"element_name",
",",
"usage_restriction",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"The decorator\"\"\"",
"func",
".",
"_pyxmpp_stream_element_handled",
"=",
"element_name",
"func",
".",
"_pyxmpp_usage_restriction",
"=",
"usage_restriction",
"return",
"func",
"return",
"decorator"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Option.complete_xml_element
|
Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`
|
pyxmpp2/ext/dataforms.py
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
_unused = doc
if self.label is not None:
xmlnode.setProp("label", self.label.encode("utf-8"))
xmlnode.newTextChild(xmlnode.ns(), "value", self.value.encode("utf-8"))
return xmlnode
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
_unused = doc
if self.label is not None:
xmlnode.setProp("label", self.label.encode("utf-8"))
xmlnode.newTextChild(xmlnode.ns(), "value", self.value.encode("utf-8"))
return xmlnode
|
[
"Complete",
"the",
"XML",
"node",
"with",
"self",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L81-L95
|
[
"def",
"complete_xml_element",
"(",
"self",
",",
"xmlnode",
",",
"doc",
")",
":",
"_unused",
"=",
"doc",
"if",
"self",
".",
"label",
"is",
"not",
"None",
":",
"xmlnode",
".",
"setProp",
"(",
"\"label\"",
",",
"self",
".",
"label",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"xmlnode",
".",
"newTextChild",
"(",
"xmlnode",
".",
"ns",
"(",
")",
",",
"\"value\"",
",",
"self",
".",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"return",
"xmlnode"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Option._new_from_xml
|
Create a new `Option` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Option`
|
pyxmpp2/ext/dataforms.py
|
def _new_from_xml(cls, xmlnode):
"""Create a new `Option` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Option`
"""
label = from_utf8(xmlnode.prop("label"))
child = xmlnode.children
value = None
for child in xml_element_ns_iter(xmlnode.children, DATAFORM_NS):
if child.name == "value":
value = from_utf8(child.getContent())
break
if value is None:
raise BadRequestProtocolError("No value in <option/> element")
return cls(value, label)
|
def _new_from_xml(cls, xmlnode):
"""Create a new `Option` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Option`
"""
label = from_utf8(xmlnode.prop("label"))
child = xmlnode.children
value = None
for child in xml_element_ns_iter(xmlnode.children, DATAFORM_NS):
if child.name == "value":
value = from_utf8(child.getContent())
break
if value is None:
raise BadRequestProtocolError("No value in <option/> element")
return cls(value, label)
|
[
"Create",
"a",
"new",
"Option",
"object",
"from",
"an",
"XML",
"element",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L98-L118
|
[
"def",
"_new_from_xml",
"(",
"cls",
",",
"xmlnode",
")",
":",
"label",
"=",
"from_utf8",
"(",
"xmlnode",
".",
"prop",
"(",
"\"label\"",
")",
")",
"child",
"=",
"xmlnode",
".",
"children",
"value",
"=",
"None",
"for",
"child",
"in",
"xml_element_ns_iter",
"(",
"xmlnode",
".",
"children",
",",
"DATAFORM_NS",
")",
":",
"if",
"child",
".",
"name",
"==",
"\"value\"",
":",
"value",
"=",
"from_utf8",
"(",
"child",
".",
"getContent",
"(",
")",
")",
"break",
"if",
"value",
"is",
"None",
":",
"raise",
"BadRequestProtocolError",
"(",
"\"No value in <option/> element\"",
")",
"return",
"cls",
"(",
"value",
",",
"label",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Field.add_option
|
Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`
|
pyxmpp2/ext/dataforms.py
|
def add_option(self, value, label):
"""Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`
"""
if type(value) is list:
warnings.warn(".add_option() accepts single value now.", DeprecationWarning, stacklevel=1)
value = value[0]
if self.type not in ("list-multi", "list-single"):
raise ValueError("Options are allowed only for list types.")
option = Option(value, label)
self.options.append(option)
return option
|
def add_option(self, value, label):
"""Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`
"""
if type(value) is list:
warnings.warn(".add_option() accepts single value now.", DeprecationWarning, stacklevel=1)
value = value[0]
if self.type not in ("list-multi", "list-single"):
raise ValueError("Options are allowed only for list types.")
option = Option(value, label)
self.options.append(option)
return option
|
[
"Add",
"an",
"option",
"for",
"the",
"field",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L251-L268
|
[
"def",
"add_option",
"(",
"self",
",",
"value",
",",
"label",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"list",
":",
"warnings",
".",
"warn",
"(",
"\".add_option() accepts single value now.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"1",
")",
"value",
"=",
"value",
"[",
"0",
"]",
"if",
"self",
".",
"type",
"not",
"in",
"(",
"\"list-multi\"",
",",
"\"list-single\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Options are allowed only for list types.\"",
")",
"option",
"=",
"Option",
"(",
"value",
",",
"label",
")",
"self",
".",
"options",
".",
"append",
"(",
"option",
")",
"return",
"option"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Field.complete_xml_element
|
Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`
|
pyxmpp2/ext/dataforms.py
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
if self.type is not None and self.type not in self.allowed_types:
raise ValueError("Invalid form field type: %r" % (self.type,))
if self.type is not None:
xmlnode.setProp("type", self.type)
if not self.label is None:
xmlnode.setProp("label", to_utf8(self.label))
if not self.name is None:
xmlnode.setProp("var", to_utf8(self.name))
if self.values:
if self.type and len(self.values) > 1 and not self.type.endswith(u"-multi"):
raise ValueError("Multiple values not allowed for %r field" % (self.type,))
for value in self.values:
xmlnode.newTextChild(xmlnode.ns(), "value", to_utf8(value))
for option in self.options:
option.as_xml(xmlnode, doc)
if self.required:
xmlnode.newChild(xmlnode.ns(), "required", None)
if self.desc:
xmlnode.newTextChild(xmlnode.ns(), "desc", to_utf8(self.desc))
return xmlnode
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
if self.type is not None and self.type not in self.allowed_types:
raise ValueError("Invalid form field type: %r" % (self.type,))
if self.type is not None:
xmlnode.setProp("type", self.type)
if not self.label is None:
xmlnode.setProp("label", to_utf8(self.label))
if not self.name is None:
xmlnode.setProp("var", to_utf8(self.name))
if self.values:
if self.type and len(self.values) > 1 and not self.type.endswith(u"-multi"):
raise ValueError("Multiple values not allowed for %r field" % (self.type,))
for value in self.values:
xmlnode.newTextChild(xmlnode.ns(), "value", to_utf8(value))
for option in self.options:
option.as_xml(xmlnode, doc)
if self.required:
xmlnode.newChild(xmlnode.ns(), "required", None)
if self.desc:
xmlnode.newTextChild(xmlnode.ns(), "desc", to_utf8(self.desc))
return xmlnode
|
[
"Complete",
"the",
"XML",
"node",
"with",
"self",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L270-L299
|
[
"def",
"complete_xml_element",
"(",
"self",
",",
"xmlnode",
",",
"doc",
")",
":",
"if",
"self",
".",
"type",
"is",
"not",
"None",
"and",
"self",
".",
"type",
"not",
"in",
"self",
".",
"allowed_types",
":",
"raise",
"ValueError",
"(",
"\"Invalid form field type: %r\"",
"%",
"(",
"self",
".",
"type",
",",
")",
")",
"if",
"self",
".",
"type",
"is",
"not",
"None",
":",
"xmlnode",
".",
"setProp",
"(",
"\"type\"",
",",
"self",
".",
"type",
")",
"if",
"not",
"self",
".",
"label",
"is",
"None",
":",
"xmlnode",
".",
"setProp",
"(",
"\"label\"",
",",
"to_utf8",
"(",
"self",
".",
"label",
")",
")",
"if",
"not",
"self",
".",
"name",
"is",
"None",
":",
"xmlnode",
".",
"setProp",
"(",
"\"var\"",
",",
"to_utf8",
"(",
"self",
".",
"name",
")",
")",
"if",
"self",
".",
"values",
":",
"if",
"self",
".",
"type",
"and",
"len",
"(",
"self",
".",
"values",
")",
">",
"1",
"and",
"not",
"self",
".",
"type",
".",
"endswith",
"(",
"u\"-multi\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Multiple values not allowed for %r field\"",
"%",
"(",
"self",
".",
"type",
",",
")",
")",
"for",
"value",
"in",
"self",
".",
"values",
":",
"xmlnode",
".",
"newTextChild",
"(",
"xmlnode",
".",
"ns",
"(",
")",
",",
"\"value\"",
",",
"to_utf8",
"(",
"value",
")",
")",
"for",
"option",
"in",
"self",
".",
"options",
":",
"option",
".",
"as_xml",
"(",
"xmlnode",
",",
"doc",
")",
"if",
"self",
".",
"required",
":",
"xmlnode",
".",
"newChild",
"(",
"xmlnode",
".",
"ns",
"(",
")",
",",
"\"required\"",
",",
"None",
")",
"if",
"self",
".",
"desc",
":",
"xmlnode",
".",
"newTextChild",
"(",
"xmlnode",
".",
"ns",
"(",
")",
",",
"\"desc\"",
",",
"to_utf8",
"(",
"self",
".",
"desc",
")",
")",
"return",
"xmlnode"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Field._new_from_xml
|
Create a new `Field` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Field`
|
pyxmpp2/ext/dataforms.py
|
def _new_from_xml(cls, xmlnode):
"""Create a new `Field` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Field`
"""
field_type = xmlnode.prop("type")
label = from_utf8(xmlnode.prop("label"))
name = from_utf8(xmlnode.prop("var"))
child = xmlnode.children
values = []
options = []
required = False
desc = None
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "required":
required = True
elif child.name == "desc":
desc = from_utf8(child.getContent())
elif child.name == "value":
values.append(from_utf8(child.getContent()))
elif child.name == "option":
options.append(Option._new_from_xml(child))
child = child.next
if field_type and not field_type.endswith("-multi") and len(values) > 1:
raise BadRequestProtocolError("Multiple values for a single-value field")
return cls(name, values, field_type, label, options, required, desc)
|
def _new_from_xml(cls, xmlnode):
"""Create a new `Field` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Field`
"""
field_type = xmlnode.prop("type")
label = from_utf8(xmlnode.prop("label"))
name = from_utf8(xmlnode.prop("var"))
child = xmlnode.children
values = []
options = []
required = False
desc = None
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "required":
required = True
elif child.name == "desc":
desc = from_utf8(child.getContent())
elif child.name == "value":
values.append(from_utf8(child.getContent()))
elif child.name == "option":
options.append(Option._new_from_xml(child))
child = child.next
if field_type and not field_type.endswith("-multi") and len(values) > 1:
raise BadRequestProtocolError("Multiple values for a single-value field")
return cls(name, values, field_type, label, options, required, desc)
|
[
"Create",
"a",
"new",
"Field",
"object",
"from",
"an",
"XML",
"element",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L302-L335
|
[
"def",
"_new_from_xml",
"(",
"cls",
",",
"xmlnode",
")",
":",
"field_type",
"=",
"xmlnode",
".",
"prop",
"(",
"\"type\"",
")",
"label",
"=",
"from_utf8",
"(",
"xmlnode",
".",
"prop",
"(",
"\"label\"",
")",
")",
"name",
"=",
"from_utf8",
"(",
"xmlnode",
".",
"prop",
"(",
"\"var\"",
")",
")",
"child",
"=",
"xmlnode",
".",
"children",
"values",
"=",
"[",
"]",
"options",
"=",
"[",
"]",
"required",
"=",
"False",
"desc",
"=",
"None",
"while",
"child",
":",
"if",
"child",
".",
"type",
"!=",
"\"element\"",
"or",
"child",
".",
"ns",
"(",
")",
".",
"content",
"!=",
"DATAFORM_NS",
":",
"pass",
"elif",
"child",
".",
"name",
"==",
"\"required\"",
":",
"required",
"=",
"True",
"elif",
"child",
".",
"name",
"==",
"\"desc\"",
":",
"desc",
"=",
"from_utf8",
"(",
"child",
".",
"getContent",
"(",
")",
")",
"elif",
"child",
".",
"name",
"==",
"\"value\"",
":",
"values",
".",
"append",
"(",
"from_utf8",
"(",
"child",
".",
"getContent",
"(",
")",
")",
")",
"elif",
"child",
".",
"name",
"==",
"\"option\"",
":",
"options",
".",
"append",
"(",
"Option",
".",
"_new_from_xml",
"(",
"child",
")",
")",
"child",
"=",
"child",
".",
"next",
"if",
"field_type",
"and",
"not",
"field_type",
".",
"endswith",
"(",
"\"-multi\"",
")",
"and",
"len",
"(",
"values",
")",
">",
"1",
":",
"raise",
"BadRequestProtocolError",
"(",
"\"Multiple values for a single-value field\"",
")",
"return",
"cls",
"(",
"name",
",",
"values",
",",
"field_type",
",",
"label",
",",
"options",
",",
"required",
",",
"desc",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Item.add_field
|
Add a field to the item.
:Parameters:
- `name`: field name.
- `values`: raw field values. Not to be used together with `value`.
- `field_type`: field type.
- `label`: field label.
- `options`: optional values for the field.
- `required`: `True` if the field is required.
- `desc`: natural-language description of the field.
- `value`: field value or values in a field_type-specific type. May be used only
if `values` parameter is not provided.
:Types:
- `name`: `unicode`
- `values`: `list` of `unicode`
- `field_type`: `str`
- `label`: `unicode`
- `options`: `list` of `Option`
- `required`: `bool`
- `desc`: `unicode`
- `value`: `bool` for "boolean" field, `JID` for "jid-single", `list` of `JID`
for "jid-multi", `list` of `unicode` for "list-multi" and "text-multi"
and `unicode` for other field types.
:return: the field added.
:returntype: `Field`
|
pyxmpp2/ext/dataforms.py
|
def add_field(self, name = None, values = None, field_type = None,
label = None, options = None, required = False, desc = None, value = None):
"""Add a field to the item.
:Parameters:
- `name`: field name.
- `values`: raw field values. Not to be used together with `value`.
- `field_type`: field type.
- `label`: field label.
- `options`: optional values for the field.
- `required`: `True` if the field is required.
- `desc`: natural-language description of the field.
- `value`: field value or values in a field_type-specific type. May be used only
if `values` parameter is not provided.
:Types:
- `name`: `unicode`
- `values`: `list` of `unicode`
- `field_type`: `str`
- `label`: `unicode`
- `options`: `list` of `Option`
- `required`: `bool`
- `desc`: `unicode`
- `value`: `bool` for "boolean" field, `JID` for "jid-single", `list` of `JID`
for "jid-multi", `list` of `unicode` for "list-multi" and "text-multi"
and `unicode` for other field types.
:return: the field added.
:returntype: `Field`
"""
field = Field(name, values, field_type, label, options, required, desc, value)
self.fields.append(field)
return field
|
def add_field(self, name = None, values = None, field_type = None,
label = None, options = None, required = False, desc = None, value = None):
"""Add a field to the item.
:Parameters:
- `name`: field name.
- `values`: raw field values. Not to be used together with `value`.
- `field_type`: field type.
- `label`: field label.
- `options`: optional values for the field.
- `required`: `True` if the field is required.
- `desc`: natural-language description of the field.
- `value`: field value or values in a field_type-specific type. May be used only
if `values` parameter is not provided.
:Types:
- `name`: `unicode`
- `values`: `list` of `unicode`
- `field_type`: `str`
- `label`: `unicode`
- `options`: `list` of `Option`
- `required`: `bool`
- `desc`: `unicode`
- `value`: `bool` for "boolean" field, `JID` for "jid-single", `list` of `JID`
for "jid-multi", `list` of `unicode` for "list-multi" and "text-multi"
and `unicode` for other field types.
:return: the field added.
:returntype: `Field`
"""
field = Field(name, values, field_type, label, options, required, desc, value)
self.fields.append(field)
return field
|
[
"Add",
"a",
"field",
"to",
"the",
"item",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L394-L425
|
[
"def",
"add_field",
"(",
"self",
",",
"name",
"=",
"None",
",",
"values",
"=",
"None",
",",
"field_type",
"=",
"None",
",",
"label",
"=",
"None",
",",
"options",
"=",
"None",
",",
"required",
"=",
"False",
",",
"desc",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"field",
"=",
"Field",
"(",
"name",
",",
"values",
",",
"field_type",
",",
"label",
",",
"options",
",",
"required",
",",
"desc",
",",
"value",
")",
"self",
".",
"fields",
".",
"append",
"(",
"field",
")",
"return",
"field"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Item.complete_xml_element
|
Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`
|
pyxmpp2/ext/dataforms.py
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
for field in self.fields:
field.as_xml(xmlnode, doc)
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
for field in self.fields:
field.as_xml(xmlnode, doc)
|
[
"Complete",
"the",
"XML",
"node",
"with",
"self",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L427-L438
|
[
"def",
"complete_xml_element",
"(",
"self",
",",
"xmlnode",
",",
"doc",
")",
":",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"field",
".",
"as_xml",
"(",
"xmlnode",
",",
"doc",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Item._new_from_xml
|
Create a new `Item` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Item`
|
pyxmpp2/ext/dataforms.py
|
def _new_from_xml(cls, xmlnode):
"""Create a new `Item` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Item`
"""
child = xmlnode.children
fields = []
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "field":
fields.append(Field._new_from_xml(child))
child = child.next
return cls(fields)
|
def _new_from_xml(cls, xmlnode):
"""Create a new `Item` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
:return: the object created.
:returntype: `Item`
"""
child = xmlnode.children
fields = []
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "field":
fields.append(Field._new_from_xml(child))
child = child.next
return cls(fields)
|
[
"Create",
"a",
"new",
"Item",
"object",
"from",
"an",
"XML",
"element",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L441-L460
|
[
"def",
"_new_from_xml",
"(",
"cls",
",",
"xmlnode",
")",
":",
"child",
"=",
"xmlnode",
".",
"children",
"fields",
"=",
"[",
"]",
"while",
"child",
":",
"if",
"child",
".",
"type",
"!=",
"\"element\"",
"or",
"child",
".",
"ns",
"(",
")",
".",
"content",
"!=",
"DATAFORM_NS",
":",
"pass",
"elif",
"child",
".",
"name",
"==",
"\"field\"",
":",
"fields",
".",
"append",
"(",
"Field",
".",
"_new_from_xml",
"(",
"child",
")",
")",
"child",
"=",
"child",
".",
"next",
"return",
"cls",
"(",
"fields",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Form.add_item
|
Add and item to the form.
:Parameters:
- `fields`: fields of the item (they may be added later).
:Types:
- `fields`: `list` of `Field`
:return: the item added.
:returntype: `Item`
|
pyxmpp2/ext/dataforms.py
|
def add_item(self, fields = None):
"""Add and item to the form.
:Parameters:
- `fields`: fields of the item (they may be added later).
:Types:
- `fields`: `list` of `Field`
:return: the item added.
:returntype: `Item`
"""
item = Item(fields)
self.items.append(item)
return item
|
def add_item(self, fields = None):
"""Add and item to the form.
:Parameters:
- `fields`: fields of the item (they may be added later).
:Types:
- `fields`: `list` of `Field`
:return: the item added.
:returntype: `Item`
"""
item = Item(fields)
self.items.append(item)
return item
|
[
"Add",
"and",
"item",
"to",
"the",
"form",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L584-L597
|
[
"def",
"add_item",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"item",
"=",
"Item",
"(",
"fields",
")",
"self",
".",
"items",
".",
"append",
"(",
"item",
")",
"return",
"item"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Form.make_submit
|
Make a "submit" form using data in `self`.
Remove uneeded information from the form. The information removed
includes: title, instructions, field labels, fixed fields etc.
:raise ValueError: when any required field has no value.
:Parameters:
- `keep_types`: when `True` field type information will be included
in the result form. That is usually not needed.
:Types:
- `keep_types`: `bool`
:return: the form created.
:returntype: `Form`
|
pyxmpp2/ext/dataforms.py
|
def make_submit(self, keep_types = False):
"""Make a "submit" form using data in `self`.
Remove uneeded information from the form. The information removed
includes: title, instructions, field labels, fixed fields etc.
:raise ValueError: when any required field has no value.
:Parameters:
- `keep_types`: when `True` field type information will be included
in the result form. That is usually not needed.
:Types:
- `keep_types`: `bool`
:return: the form created.
:returntype: `Form`"""
result = Form("submit")
for field in self.fields:
if field.type == "fixed":
continue
if not field.values:
if field.required:
raise ValueError("Required field with no value!")
continue
if keep_types:
result.add_field(field.name, field.values, field.type)
else:
result.add_field(field.name, field.values)
return result
|
def make_submit(self, keep_types = False):
"""Make a "submit" form using data in `self`.
Remove uneeded information from the form. The information removed
includes: title, instructions, field labels, fixed fields etc.
:raise ValueError: when any required field has no value.
:Parameters:
- `keep_types`: when `True` field type information will be included
in the result form. That is usually not needed.
:Types:
- `keep_types`: `bool`
:return: the form created.
:returntype: `Form`"""
result = Form("submit")
for field in self.fields:
if field.type == "fixed":
continue
if not field.values:
if field.required:
raise ValueError("Required field with no value!")
continue
if keep_types:
result.add_field(field.name, field.values, field.type)
else:
result.add_field(field.name, field.values)
return result
|
[
"Make",
"a",
"submit",
"form",
"using",
"data",
"in",
"self",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L599-L627
|
[
"def",
"make_submit",
"(",
"self",
",",
"keep_types",
"=",
"False",
")",
":",
"result",
"=",
"Form",
"(",
"\"submit\"",
")",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"if",
"field",
".",
"type",
"==",
"\"fixed\"",
":",
"continue",
"if",
"not",
"field",
".",
"values",
":",
"if",
"field",
".",
"required",
":",
"raise",
"ValueError",
"(",
"\"Required field with no value!\"",
")",
"continue",
"if",
"keep_types",
":",
"result",
".",
"add_field",
"(",
"field",
".",
"name",
",",
"field",
".",
"values",
",",
"field",
".",
"type",
")",
"else",
":",
"result",
".",
"add_field",
"(",
"field",
".",
"name",
",",
"field",
".",
"values",
")",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Form.complete_xml_element
|
Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`
|
pyxmpp2/ext/dataforms.py
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
if self.type not in self.allowed_types:
raise ValueError("Form type %r not allowed." % (self.type,))
xmlnode.setProp("type", self.type)
if self.type == "cancel":
return
ns = xmlnode.ns()
if self.title is not None:
xmlnode.newTextChild(ns, "title", to_utf8(self.title))
if self.instructions is not None:
xmlnode.newTextChild(ns, "instructions", to_utf8(self.instructions))
for field in self.fields:
field.as_xml(xmlnode, doc)
if self.type != "result":
return
if self.reported_fields:
reported = xmlnode.newChild(ns, "reported", None)
for field in self.reported_fields:
field.as_xml(reported, doc)
for item in self.items:
item.as_xml(xmlnode, doc)
|
def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the element belongs.
:Types:
- `xmlnode`: `libxml2.xmlNode`
- `doc`: `libxml2.xmlDoc`"""
if self.type not in self.allowed_types:
raise ValueError("Form type %r not allowed." % (self.type,))
xmlnode.setProp("type", self.type)
if self.type == "cancel":
return
ns = xmlnode.ns()
if self.title is not None:
xmlnode.newTextChild(ns, "title", to_utf8(self.title))
if self.instructions is not None:
xmlnode.newTextChild(ns, "instructions", to_utf8(self.instructions))
for field in self.fields:
field.as_xml(xmlnode, doc)
if self.type != "result":
return
if self.reported_fields:
reported = xmlnode.newChild(ns, "reported", None)
for field in self.reported_fields:
field.as_xml(reported, doc)
for item in self.items:
item.as_xml(xmlnode, doc)
|
[
"Complete",
"the",
"XML",
"node",
"with",
"self",
"content",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L636-L665
|
[
"def",
"complete_xml_element",
"(",
"self",
",",
"xmlnode",
",",
"doc",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"self",
".",
"allowed_types",
":",
"raise",
"ValueError",
"(",
"\"Form type %r not allowed.\"",
"%",
"(",
"self",
".",
"type",
",",
")",
")",
"xmlnode",
".",
"setProp",
"(",
"\"type\"",
",",
"self",
".",
"type",
")",
"if",
"self",
".",
"type",
"==",
"\"cancel\"",
":",
"return",
"ns",
"=",
"xmlnode",
".",
"ns",
"(",
")",
"if",
"self",
".",
"title",
"is",
"not",
"None",
":",
"xmlnode",
".",
"newTextChild",
"(",
"ns",
",",
"\"title\"",
",",
"to_utf8",
"(",
"self",
".",
"title",
")",
")",
"if",
"self",
".",
"instructions",
"is",
"not",
"None",
":",
"xmlnode",
".",
"newTextChild",
"(",
"ns",
",",
"\"instructions\"",
",",
"to_utf8",
"(",
"self",
".",
"instructions",
")",
")",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"field",
".",
"as_xml",
"(",
"xmlnode",
",",
"doc",
")",
"if",
"self",
".",
"type",
"!=",
"\"result\"",
":",
"return",
"if",
"self",
".",
"reported_fields",
":",
"reported",
"=",
"xmlnode",
".",
"newChild",
"(",
"ns",
",",
"\"reported\"",
",",
"None",
")",
"for",
"field",
"in",
"self",
".",
"reported_fields",
":",
"field",
".",
"as_xml",
"(",
"reported",
",",
"doc",
")",
"for",
"item",
"in",
"self",
".",
"items",
":",
"item",
".",
"as_xml",
"(",
"xmlnode",
",",
"doc",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
Form.__from_xml
|
Initialize a `Form` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
|
pyxmpp2/ext/dataforms.py
|
def __from_xml(self, xmlnode):
"""Initialize a `Form` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
"""
self.fields = []
self.reported_fields = []
self.items = []
self.title = None
self.instructions = None
if (xmlnode.type != "element" or xmlnode.name != "x"
or xmlnode.ns().content != DATAFORM_NS):
raise ValueError("Not a form: " + xmlnode.serialize())
self.type = xmlnode.prop("type")
if not self.type in self.allowed_types:
raise BadRequestProtocolError("Bad form type: %r" % (self.type,))
child = xmlnode.children
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "title":
self.title = from_utf8(child.getContent())
elif child.name == "instructions":
self.instructions = from_utf8(child.getContent())
elif child.name == "field":
self.fields.append(Field._new_from_xml(child))
elif child.name == "item":
self.items.append(Item._new_from_xml(child))
elif child.name == "reported":
self.__get_reported(child)
child = child.next
|
def __from_xml(self, xmlnode):
"""Initialize a `Form` object from an XML element.
:Parameters:
- `xmlnode`: the XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`
"""
self.fields = []
self.reported_fields = []
self.items = []
self.title = None
self.instructions = None
if (xmlnode.type != "element" or xmlnode.name != "x"
or xmlnode.ns().content != DATAFORM_NS):
raise ValueError("Not a form: " + xmlnode.serialize())
self.type = xmlnode.prop("type")
if not self.type in self.allowed_types:
raise BadRequestProtocolError("Bad form type: %r" % (self.type,))
child = xmlnode.children
while child:
if child.type != "element" or child.ns().content != DATAFORM_NS:
pass
elif child.name == "title":
self.title = from_utf8(child.getContent())
elif child.name == "instructions":
self.instructions = from_utf8(child.getContent())
elif child.name == "field":
self.fields.append(Field._new_from_xml(child))
elif child.name == "item":
self.items.append(Item._new_from_xml(child))
elif child.name == "reported":
self.__get_reported(child)
child = child.next
|
[
"Initialize",
"a",
"Form",
"object",
"from",
"an",
"XML",
"element",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/dataforms.py#L667-L700
|
[
"def",
"__from_xml",
"(",
"self",
",",
"xmlnode",
")",
":",
"self",
".",
"fields",
"=",
"[",
"]",
"self",
".",
"reported_fields",
"=",
"[",
"]",
"self",
".",
"items",
"=",
"[",
"]",
"self",
".",
"title",
"=",
"None",
"self",
".",
"instructions",
"=",
"None",
"if",
"(",
"xmlnode",
".",
"type",
"!=",
"\"element\"",
"or",
"xmlnode",
".",
"name",
"!=",
"\"x\"",
"or",
"xmlnode",
".",
"ns",
"(",
")",
".",
"content",
"!=",
"DATAFORM_NS",
")",
":",
"raise",
"ValueError",
"(",
"\"Not a form: \"",
"+",
"xmlnode",
".",
"serialize",
"(",
")",
")",
"self",
".",
"type",
"=",
"xmlnode",
".",
"prop",
"(",
"\"type\"",
")",
"if",
"not",
"self",
".",
"type",
"in",
"self",
".",
"allowed_types",
":",
"raise",
"BadRequestProtocolError",
"(",
"\"Bad form type: %r\"",
"%",
"(",
"self",
".",
"type",
",",
")",
")",
"child",
"=",
"xmlnode",
".",
"children",
"while",
"child",
":",
"if",
"child",
".",
"type",
"!=",
"\"element\"",
"or",
"child",
".",
"ns",
"(",
")",
".",
"content",
"!=",
"DATAFORM_NS",
":",
"pass",
"elif",
"child",
".",
"name",
"==",
"\"title\"",
":",
"self",
".",
"title",
"=",
"from_utf8",
"(",
"child",
".",
"getContent",
"(",
")",
")",
"elif",
"child",
".",
"name",
"==",
"\"instructions\"",
":",
"self",
".",
"instructions",
"=",
"from_utf8",
"(",
"child",
".",
"getContent",
"(",
")",
")",
"elif",
"child",
".",
"name",
"==",
"\"field\"",
":",
"self",
".",
"fields",
".",
"append",
"(",
"Field",
".",
"_new_from_xml",
"(",
"child",
")",
")",
"elif",
"child",
".",
"name",
"==",
"\"item\"",
":",
"self",
".",
"items",
".",
"append",
"(",
"Item",
".",
"_new_from_xml",
"(",
"child",
")",
")",
"elif",
"child",
".",
"name",
"==",
"\"reported\"",
":",
"self",
".",
"__get_reported",
"(",
"child",
")",
"child",
"=",
"child",
".",
"next"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.