desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Returns the value of the \'key\' attribute for the tag, or
the value given for \'default\' if it doesn\'t have that
attribute.'
| def get(self, key, default=None):
| return self._getAttrMap().get(key, default)
|
'Extract all children.'
| def clear(self):
| for child in self.contents[:]:
child.extract()
|
'tag[key] returns the value of the \'key\' attribute for the tag,
and throws an exception if it\'s not there.'
| def __getitem__(self, key):
| return self._getAttrMap()[key]
|
'Iterating over a tag iterates over its contents.'
| def __iter__(self):
| return iter(self.contents)
|
'The length of a tag is the length of its list of contents.'
| def __len__(self):
| return len(self.contents)
|
'A tag is non-None even if it has no contents.'
| def __nonzero__(self):
| return True
|
'Setting tag[key] sets the value of the \'key\' attribute for the
tag.'
| def __setitem__(self, key, value):
| self._getAttrMap()
self.attrMap[key] = value
found = False
for i in xrange(0, len(self.attrs)):
if (self.attrs[i][0] == key):
self.attrs[i] = (key, value)
found = True
if (not found):
self.attrs.append((key, value))
self._getAttrMap()[key] = value
|
'Deleting tag[key] deletes all \'key\' attributes for the tag.'
| def __delitem__(self, key):
| for item in self.attrs:
if (item[0] == key):
self.attrs.remove(item)
self._getAttrMap()
if self.attrMap.has_key(key):
del self.attrMap[key]
|
'Calling a tag like a function is the same as calling its
findAll() method. Eg. tag(\'a\') returns a list of all the A tags
found within this tag.'
| def __call__(self, *args, **kwargs):
| return apply(self.findAll, args, kwargs)
|
'Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.
NOTE: right now this will return false if two tags have the
same attributes in a different order. Should this be fixed?'
| def __eq__(self, other):
| if (other is self):
return True
if ((not hasattr(other, 'name')) or (not hasattr(other, 'attrs')) or (not hasattr(other, 'contents')) or (self.name != other.name) or (self.attrs != other.attrs) or (len(self) != len(other))):
return False
for i in xrange(0, len(self.contents)):
if (self.contents[i] != other.contents[i]):
return False
return True
|
'Returns true iff this tag is not identical to the other tag,
as defined in __eq__.'
| def __ne__(self, other):
| return (not (self == other))
|
'Renders this tag as a string.'
| def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
| return self.__str__(encoding)
|
'Returns a string or Unicode representation of this tag and
its contents. To get Unicode, pass None for encoding.
NOTE: since Python\'s HTML parser consumes whitespace, this
method is not certain to reproduce the whitespace present in
the original string.'
| def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0):
| encodedName = self.toEncoding(self.name, encoding)
attrs = []
if self.attrs:
for (key, val) in self.attrs:
fmt = '%s="%s"'
if isinstance(val, basestring):
if (self.containsSubstitutions and ('%SOUP-ENCODING%' in val)):
val = self.substituteEncoding(val, encoding)
if ('"' in val):
fmt = "%s='%s'"
if ("'" in val):
val = val.replace("'", '&squot;')
val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val)
attrs.append((fmt % (self.toEncoding(key, encoding), self.toEncoding(val, encoding))))
close = ''
closeTag = ''
if self.isSelfClosing:
close = ' /'
else:
closeTag = ('</%s>' % encodedName)
(indentTag, indentContents) = (0, 0)
if prettyPrint:
indentTag = indentLevel
space = (' ' * (indentTag - 1))
indentContents = (indentTag + 1)
contents = self.renderContents(encoding, prettyPrint, indentContents)
if self.hidden:
s = contents
else:
s = []
attributeString = ''
if attrs:
attributeString = (' ' + ' '.join(attrs))
if prettyPrint:
s.append(space)
s.append(('<%s%s%s>' % (encodedName, attributeString, close)))
if prettyPrint:
s.append('\n')
s.append(contents)
if (prettyPrint and contents and (contents[(-1)] != '\n')):
s.append('\n')
if (prettyPrint and closeTag):
s.append(space)
s.append(closeTag)
if (prettyPrint and closeTag and self.nextSibling):
s.append('\n')
s = ''.join(s)
return s
|
'Recursively destroys the contents of this tree.'
| def decompose(self):
| self.extract()
if (len(self.contents) == 0):
return
current = self.contents[0]
while (current is not None):
next = current.next
if isinstance(current, Tag):
del current.contents[:]
current.parent = None
current.previous = None
current.previousSibling = None
current.next = None
current.nextSibling = None
current = next
|
'Renders the contents of this tag as a string in the given
encoding. If encoding is None, returns a Unicode string..'
| def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0):
| s = []
for c in self:
text = None
if isinstance(c, NavigableString):
text = c.__str__(encoding)
elif isinstance(c, Tag):
s.append(c.__str__(encoding, prettyPrint, indentLevel))
if (text and prettyPrint):
text = text.strip()
if text:
if prettyPrint:
s.append((' ' * (indentLevel - 1)))
s.append(text)
if prettyPrint:
s.append('\n')
return ''.join(s)
|
'Return only the first child of this Tag matching the given
criteria.'
| def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs):
| r = None
l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
|
'Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the \'attrs\' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of \'matches\'. The
same is true of the tag name.'
| def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs):
| generator = self.recursiveChildGenerator
if (not recursive):
generator = self.childGenerator
return self._findAll(name, attrs, text, limit, generator, **kwargs)
|
'Initializes a map representation of this tag\'s attributes,
if not already initialized.'
| def _getAttrMap(self):
| if (not getattr(self, 'attrMap')):
self.attrMap = {}
for (key, value) in self.attrs:
self.attrMap[key] = value
return self.attrMap
|
'The Soup object is initialized as the \'root tag\', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser.
sgmllib will process most bad HTML, and the BeautifulSoup
class has some tricks for dealing with some HTML that kills
sgmllib, but Beautiful Soup can nonetheless choke or lose data
if your data uses self-closing tags or declarations
incorrectly.
By default, Beautiful Soup uses regexes to sanitize input,
avoiding the vast majority of these problems. If the problems
don\'t apply to you, pass in False for markupMassage, and
you\'ll get better performance.
The default parser massage techniques fix the two most common
instances of invalid HTML that choke sgmllib:
<br/> (No space between name of closing tag and tag close)
<! --Comment--> (Extraneous whitespace in declaration)
You can pass in a custom list of (RE object, replace method)
tuples to get Beautiful Soup to scrub your input the way you
want.'
| def __init__(self, markup='', parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None, isHTML=False):
| self.parseOnlyThese = parseOnlyThese
self.fromEncoding = fromEncoding
self.smartQuotesTo = smartQuotesTo
self.convertEntities = convertEntities
if self.convertEntities:
self.smartQuotesTo = None
if (convertEntities == self.HTML_ENTITIES):
self.convertXMLEntities = False
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = True
elif (convertEntities == self.XHTML_ENTITIES):
self.convertXMLEntities = True
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = False
elif (convertEntities == self.XML_ENTITIES):
self.convertXMLEntities = True
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
else:
self.convertXMLEntities = False
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
SGMLParser.__init__(self)
if hasattr(markup, 'read'):
markup = markup.read()
self.markup = markup
self.markupMassage = markupMassage
try:
self._feed(isHTML=isHTML)
except StopParsing:
pass
self.markup = None
|
'This method fixes a bug in Python\'s SGMLParser.'
| def convert_charref(self, name):
| try:
n = int(name)
except ValueError:
return
if (not (0 <= n <= 127)):
return
return self.convert_codepoint(n)
|
'This method routes method call requests to either the SGMLParser
superclass or the Tag superclass, depending on the method name.'
| def __getattr__(self, methodName):
| if (methodName.startswith('start_') or methodName.startswith('end_') or methodName.startswith('do_')):
return SGMLParser.__getattr__(self, methodName)
elif (not methodName.startswith('__')):
return Tag.__getattr__(self, methodName)
else:
raise AttributeError
|
'Returns true iff the given string is the name of a
self-closing tag according to this parser.'
| def isSelfClosingTag(self, name):
| return (self.SELF_CLOSING_TAGS.has_key(name) or self.instanceSelfClosingTags.has_key(name))
|
'Pops the tag stack up to and including the most recent
instance of the given tag. If inclusivePop is false, pops the tag
stack up to but *not* including the most recent instqance of
the given tag.'
| def _popToTag(self, name, inclusivePop=True):
| if (name == self.ROOT_TAG_NAME):
return
numPops = 0
mostRecentTag = None
for i in xrange((len(self.tagStack) - 1), 0, (-1)):
if (name == self.tagStack[i].name):
numPops = (len(self.tagStack) - i)
break
if (not inclusivePop):
numPops = (numPops - 1)
for i in xrange(0, numPops):
mostRecentTag = self.popTag()
return mostRecentTag
|
'We need to pop up to the previous tag of this type, unless
one of this tag\'s nesting reset triggers comes between this
tag and the previous tag of this type, OR unless this tag is a
generic nesting trigger and another generic nesting trigger
comes between this tag and the previous tag of this type.
Examples:
<p>Foo<b>Bar *<p>* should pop to \'p\', not \'b\'.
<p>Foo<table>Bar *<p>* should pop to \'table\', not \'p\'.
<p>Foo<table><tr>Bar *<p>* should pop to \'tr\', not \'p\'.
<li><ul><li> *<li>* should pop to \'ul\', not the first \'li\'.
<tr><table><tr> *<tr>* should pop to \'table\', not the first \'tr\'
<td><tr><td> *<td>* should pop to \'tr\', not the first \'td\''
| def _smartPop(self, name):
| nestingResetTriggers = self.NESTABLE_TAGS.get(name)
isNestable = (nestingResetTriggers != None)
isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
popTo = None
inclusive = True
for i in xrange((len(self.tagStack) - 1), 0, (-1)):
p = self.tagStack[i]
if (((not p) or (p.name == name)) and (not isNestable)):
popTo = name
break
if (((nestingResetTriggers is not None) and (p.name in nestingResetTriggers)) or ((nestingResetTriggers is None) and isResetNesting and self.RESET_NESTING_TAGS.has_key(p.name))):
popTo = p.name
inclusive = False
break
p = p.parent
if popTo:
self._popToTag(popTo, inclusive)
|
'Adds a certain piece of text to the tree as a NavigableString
subclass.'
| def _toStringSubclass(self, text, subclass):
| self.endData()
self.handle_data(text)
self.endData(subclass)
|
'Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later.'
| def handle_pi(self, text):
| if (text[:3] == 'xml'):
text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
self._toStringSubclass(text, ProcessingInstruction)
|
'Handle comments as Comment objects.'
| def handle_comment(self, text):
| self._toStringSubclass(text, Comment)
|
'Handle character references as data.'
| def handle_charref(self, ref):
| if self.convertEntities:
data = unichr(int(ref))
else:
data = ('&#%s;' % ref)
self.handle_data(data)
|
'Handle entity references as data, possibly converting known
HTML and/or XML entity references to the corresponding Unicode
characters.'
| def handle_entityref(self, ref):
| data = None
if self.convertHTMLEntities:
try:
data = unichr(name2codepoint[ref])
except KeyError:
pass
if ((not data) and self.convertXMLEntities):
data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref)
if ((not data) and self.convertHTMLEntities and (not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref))):
data = ('&%s' % ref)
if (not data):
data = ('&%s;' % ref)
self.handle_data(data)
|
'Handle DOCTYPEs and the like as Declaration objects.'
| def handle_decl(self, data):
| self._toStringSubclass(data, Declaration)
|
'Treat a bogus SGML declaration as raw data. Treat a CDATA
declaration as a CData object.'
| def parse_declaration(self, i):
| j = None
if (self.rawdata[i:(i + 9)] == '<![CDATA['):
k = self.rawdata.find(']]>', i)
if (k == (-1)):
k = len(self.rawdata)
data = self.rawdata[(i + 9):k]
j = (k + 3)
self._toStringSubclass(data, CData)
else:
try:
j = SGMLParser.parse_declaration(self, i)
except SGMLParseError:
toHandle = self.rawdata[i:]
self.handle_data(toHandle)
j = (i + len(toHandle))
return j
|
'Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning.'
| def start_meta(self, attrs):
| httpEquiv = None
contentType = None
contentTypeIndex = None
tagNeedsEncodingSubstitution = False
for i in xrange(0, len(attrs)):
(key, value) = attrs[i]
key = key.lower()
if (key == 'http-equiv'):
httpEquiv = value
elif (key == 'content'):
contentType = value
contentTypeIndex = i
if (httpEquiv and contentType):
match = self.CHARSET_RE.search(contentType)
if match:
if ((self.declaredHTMLEncoding is not None) or (self.originalEncoding == self.fromEncoding)):
def rewrite(match):
return (match.group(1) + '%SOUP-ENCODING%')
newAttr = self.CHARSET_RE.sub(rewrite, contentType)
attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], newAttr)
tagNeedsEncodingSubstitution = True
else:
newCharset = match.group(3)
if (newCharset and (newCharset != self.originalEncoding)):
self.declaredHTMLEncoding = newCharset
self._feed(self.declaredHTMLEncoding)
raise StopParsing
pass
tag = self.unknown_starttag('meta', attrs)
if (tag and tagNeedsEncodingSubstitution):
tag.containsSubstitutions = True
|
'Changes a MS smart quote character to an XML or HTML
entity.'
| def _subMSChar(self, orig):
| sub = self.MS_CHARS.get(orig)
if isinstance(sub, tuple):
if (self.smartQuotesTo == 'xml'):
sub = ('&#x%s;' % sub[1])
else:
sub = ('&%s;' % sub[0])
return sub
|
'Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'
| def _toUnicode(self, data, encoding):
| if ((len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00')):
encoding = 'utf-16be'
data = data[2:]
elif ((len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00')):
encoding = 'utf-16le'
data = data[2:]
elif (data[:3] == '\xef\xbb\xbf'):
encoding = 'utf-8'
data = data[3:]
elif (data[:4] == '\x00\x00\xfe\xff'):
encoding = 'utf-32be'
data = data[4:]
elif (data[:4] == '\xff\xfe\x00\x00'):
encoding = 'utf-32le'
data = data[4:]
newdata = unicode(data, encoding)
return newdata
|
'Given a document, tries to detect its XML encoding.'
| def _detectEncoding(self, xml_data, isHTML=False):
| xml_encoding = sniffed_xml_encoding = None
try:
if (xml_data[:4] == 'Lo\xa7\x94'):
xml_data = self._ebcdic_to_ascii(xml_data)
elif (xml_data[:4] == '\x00<\x00?'):
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
elif ((len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') and (xml_data[2:4] != '\x00\x00')):
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
elif (xml_data[:4] == '<\x00?\x00'):
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
elif ((len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and (xml_data[2:4] != '\x00\x00')):
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
elif (xml_data[:4] == '\x00\x00\x00<'):
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
elif (xml_data[:4] == '<\x00\x00\x00'):
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
elif (xml_data[:4] == '\x00\x00\xfe\xff'):
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
elif (xml_data[:4] == '\xff\xfe\x00\x00'):
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
elif (xml_data[:3] == '\xef\xbb\xbf'):
sniffed_xml_encoding = 'utf-8'
xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
else:
sniffed_xml_encoding = 'ascii'
pass
except:
xml_encoding_match = None
xml_encoding_match = re.compile('^<\\?.*encoding=[\'"](.*?)[\'"].*\\?>').match(xml_data)
if ((not xml_encoding_match) and isHTML):
regexp = re.compile('<\\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I)
xml_encoding_match = regexp.search(xml_data)
if (xml_encoding_match is not None):
xml_encoding = xml_encoding_match.groups()[0].lower()
if isHTML:
self.declaredHTMLEncoding = xml_encoding
if (sniffed_xml_encoding and (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16'))):
xml_encoding = sniffed_xml_encoding
return (xml_data, xml_encoding, sniffed_xml_encoding)
|
'Create a copy of this pen.'
| def copy(self):
| pen = Pen()
pen.__dict__ = self.__dict__.copy()
return pen
|
'Draw this shape with the given cairo context'
| def draw(self, cr, highlight=False):
| raise NotImplementedError
|
'Override this method in subclass to process
click events. Note that element can be None
(click on empty space).'
| def on_click(self, element, event):
| return False
|
'getKey() -> bytes'
| def getKey(self):
| return self.__key
|
'Will set the crypting key for this object.'
| def setKey(self, key):
| key = self._guardAgainstUnicode(key)
self.__key = key
|
'getMode() -> pyDes.ECB or pyDes.CBC'
| def getMode(self):
| return self._mode
|
'Sets the type of crypting mode, pyDes.ECB or pyDes.CBC'
| def setMode(self, mode):
| self._mode = mode
|
'getPadding() -> bytes of length 1. Padding character.'
| def getPadding(self):
| return self._padding
|
'setPadding() -> bytes of length 1. Padding character.'
| def setPadding(self, pad):
| if (pad is not None):
pad = self._guardAgainstUnicode(pad)
self._padding = pad
|
'getPadMode() -> pyDes.PAD_NORMAL or pyDes.PAD_PKCS5'
| def getPadMode(self):
| return self._padmode
|
'Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5'
| def setPadMode(self, mode):
| self._padmode = mode
|
'getIV() -> bytes'
| def getIV(self):
| return self._iv
|
'Will set the Initial Value, used in conjunction with CBC mode'
| def setIV(self, IV):
| if ((not IV) or (len(IV) != self.block_size)):
raise ValueError((('Invalid Initial Value (IV), must be a multiple of ' + str(self.block_size)) + ' bytes'))
IV = self._guardAgainstUnicode(IV)
self._iv = IV
|
'Will set the crypting key for this object. Must be 8 bytes.'
| def setKey(self, key):
| _baseDes.setKey(self, key)
self.__create_sub_keys()
|
'Turn the string data, into a list of bits (1, 0)\'s'
| def __String_to_BitList(self, data):
| if (_pythonMajorVersion < 3):
data = [ord(c) for c in data]
l = (len(data) * 8)
result = ([0] * l)
pos = 0
for ch in data:
i = 7
while (i >= 0):
if ((ch & (1 << i)) != 0):
result[pos] = 1
else:
result[pos] = 0
pos += 1
i -= 1
return result
|
'Turn the list of bits -> data, into a string'
| def __BitList_to_String(self, data):
| result = []
pos = 0
c = 0
while (pos < len(data)):
c += (data[pos] << (7 - (pos % 8)))
if ((pos % 8) == 7):
result.append(c)
c = 0
pos += 1
if (_pythonMajorVersion < 3):
return ''.join([chr(c) for c in result])
else:
return bytes(result)
|
'Permutate this block with the specified table'
| def __permutate(self, table, block):
| return list(map((lambda x: block[x]), table))
|
'Create the 16 subkeys K[1] to K[16] from the given key'
| def __create_sub_keys(self):
| key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey()))
i = 0
self.L = key[:28]
self.R = key[28:]
while (i < 16):
j = 0
while (j < des.__left_rotations[i]):
self.L.append(self.L[0])
del self.L[0]
self.R.append(self.R[0])
del self.R[0]
j += 1
self.Kn[i] = self.__permutate(des.__pc2, (self.L + self.R))
i += 1
|
'Crypt the block of data through DES bit-manipulation'
| def __des_crypt(self, block, crypt_type):
| block = self.__permutate(des.__ip, block)
self.L = block[:32]
self.R = block[32:]
if (crypt_type == des.ENCRYPT):
iteration = 0
iteration_adjustment = 1
else:
iteration = 15
iteration_adjustment = (-1)
i = 0
while (i < 16):
tempR = self.R[:]
self.R = self.__permutate(des.__expansion_table, self.R)
self.R = list(map((lambda x, y: (x ^ y)), self.R, self.Kn[iteration]))
B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]]
j = 0
Bn = ([0] * 32)
pos = 0
while (j < 8):
m = ((B[j][0] << 1) + B[j][5])
n = ((((B[j][1] << 3) + (B[j][2] << 2)) + (B[j][3] << 1)) + B[j][4])
v = des.__sbox[j][((m << 4) + n)]
Bn[pos] = ((v & 8) >> 3)
Bn[(pos + 1)] = ((v & 4) >> 2)
Bn[(pos + 2)] = ((v & 2) >> 1)
Bn[(pos + 3)] = (v & 1)
pos += 4
j += 1
self.R = self.__permutate(des.__p, Bn)
self.R = list(map((lambda x, y: (x ^ y)), self.R, self.L))
self.L = tempR
i += 1
iteration += iteration_adjustment
self.final = self.__permutate(des.__fp, (self.R + self.L))
return self.final
|
'Crypt the data in blocks, running it through des_crypt()'
| def crypt(self, data, crypt_type):
| if (not data):
return ''
if ((len(data) % self.block_size) != 0):
if (crypt_type == des.DECRYPT):
raise ValueError((('Invalid data length, data must be a multiple of ' + str(self.block_size)) + ' bytes\n.'))
if (not self.getPadding()):
raise ValueError((('Invalid data length, data must be a multiple of ' + str(self.block_size)) + ' bytes\n. Try setting the optional padding character'))
else:
data += ((self.block_size - (len(data) % self.block_size)) * self.getPadding())
if (self.getMode() == CBC):
if self.getIV():
iv = self.__String_to_BitList(self.getIV())
else:
raise ValueError('For CBC mode, you must supply the Initial Value (IV) for ciphering')
i = 0
dict = {}
result = []
while (i < len(data)):
block = self.__String_to_BitList(data[i:(i + 8)])
if (self.getMode() == CBC):
if (crypt_type == des.ENCRYPT):
block = list(map((lambda x, y: (x ^ y)), block, iv))
processed_block = self.__des_crypt(block, crypt_type)
if (crypt_type == des.DECRYPT):
processed_block = list(map((lambda x, y: (x ^ y)), processed_block, iv))
iv = block
else:
iv = processed_block
else:
processed_block = self.__des_crypt(block, crypt_type)
result.append(self.__BitList_to_String(processed_block))
i += 8
if (_pythonMajorVersion < 3):
return ''.join(result)
else:
return bytes.fromhex('').join(result)
|
'encrypt(data, [pad], [padmode]) -> bytes
data : Bytes to be encrypted
pad : Optional argument for encryption padding. Must only be one byte
padmode : Optional argument for overriding the padding mode.
The data must be a multiple of 8 bytes and will be encrypted
with the already specified key. Data does not have to be a
multiple of 8 bytes if the padding character is supplied, or
the padmode is set to PAD_PKCS5, as bytes will then added to
ensure the be padded data is a multiple of 8 bytes.'
| def encrypt(self, data, pad=None, padmode=None):
| data = self._guardAgainstUnicode(data)
if (pad is not None):
pad = self._guardAgainstUnicode(pad)
data = self._padData(data, pad, padmode)
return self.crypt(data, des.ENCRYPT)
|
'decrypt(data, [pad], [padmode]) -> bytes
data : Bytes to be encrypted
pad : Optional argument for decryption padding. Must only be one byte
padmode : Optional argument for overriding the padding mode.
The data must be a multiple of 8 bytes and will be decrypted
with the already specified key. In PAD_NORMAL mode, if the
optional padding character is supplied, then the un-encrypted
data will have the padding characters removed from the end of
the bytes. This pad removal only occurs on the last 8 bytes of
the data (last data block). In PAD_PKCS5 mode, the special
padding end markers will be removed from the data after decrypting.'
| def decrypt(self, data, pad=None, padmode=None):
| data = self._guardAgainstUnicode(data)
if (pad is not None):
pad = self._guardAgainstUnicode(pad)
data = self.crypt(data, des.DECRYPT)
return self._unpadData(data, pad, padmode)
|
'Will set the crypting key for this object. Either 16 or 24 bytes long.'
| def setKey(self, key):
| self.key_size = 24
if (len(key) != self.key_size):
if (len(key) == 16):
self.key_size = 16
else:
raise ValueError('Invalid triple DES key size. Key must be either 16 or 24 bytes long')
if (self.getMode() == CBC):
if (not self.getIV()):
self._iv = key[:self.block_size]
if (len(self.getIV()) != self.block_size):
raise ValueError('Invalid IV, must be 8 bytes in length')
self.__key1 = des(key[:8], self._mode, self._iv, self._padding, self._padmode)
self.__key2 = des(key[8:16], self._mode, self._iv, self._padding, self._padmode)
if (self.key_size == 16):
self.__key3 = self.__key1
else:
self.__key3 = des(key[16:], self._mode, self._iv, self._padding, self._padmode)
_baseDes.setKey(self, key)
|
'Sets the type of crypting mode, pyDes.ECB or pyDes.CBC'
| def setMode(self, mode):
| _baseDes.setMode(self, mode)
for key in (self.__key1, self.__key2, self.__key3):
key.setMode(mode)
|
'setPadding() -> bytes of length 1. Padding character.'
| def setPadding(self, pad):
| _baseDes.setPadding(self, pad)
for key in (self.__key1, self.__key2, self.__key3):
key.setPadding(pad)
|
'Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5'
| def setPadMode(self, mode):
| _baseDes.setPadMode(self, mode)
for key in (self.__key1, self.__key2, self.__key3):
key.setPadMode(mode)
|
'Will set the Initial Value, used in conjunction with CBC mode'
| def setIV(self, IV):
| _baseDes.setIV(self, IV)
for key in (self.__key1, self.__key2, self.__key3):
key.setIV(IV)
|
'encrypt(data, [pad], [padmode]) -> bytes
data : bytes to be encrypted
pad : Optional argument for encryption padding. Must only be one byte
padmode : Optional argument for overriding the padding mode.
The data must be a multiple of 8 bytes and will be encrypted
with the already specified key. Data does not have to be a
multiple of 8 bytes if the padding character is supplied, or
the padmode is set to PAD_PKCS5, as bytes will then added to
ensure the be padded data is a multiple of 8 bytes.'
| def encrypt(self, data, pad=None, padmode=None):
| ENCRYPT = des.ENCRYPT
DECRYPT = des.DECRYPT
data = self._guardAgainstUnicode(data)
if (pad is not None):
pad = self._guardAgainstUnicode(pad)
data = self._padData(data, pad, padmode)
if (self.getMode() == CBC):
self.__key1.setIV(self.getIV())
self.__key2.setIV(self.getIV())
self.__key3.setIV(self.getIV())
i = 0
result = []
while (i < len(data)):
block = self.__key1.crypt(data[i:(i + 8)], ENCRYPT)
block = self.__key2.crypt(block, DECRYPT)
block = self.__key3.crypt(block, ENCRYPT)
self.__key1.setIV(block)
self.__key2.setIV(block)
self.__key3.setIV(block)
result.append(block)
i += 8
if (_pythonMajorVersion < 3):
return ''.join(result)
else:
return bytes.fromhex('').join(result)
else:
data = self.__key1.crypt(data, ENCRYPT)
data = self.__key2.crypt(data, DECRYPT)
return self.__key3.crypt(data, ENCRYPT)
|
'decrypt(data, [pad], [padmode]) -> bytes
data : bytes to be encrypted
pad : Optional argument for decryption padding. Must only be one byte
padmode : Optional argument for overriding the padding mode.
The data must be a multiple of 8 bytes and will be decrypted
with the already specified key. In PAD_NORMAL mode, if the
optional padding character is supplied, then the un-encrypted
data will have the padding characters removed from the end of
the bytes. This pad removal only occurs on the last 8 bytes of
the data (last data block). In PAD_PKCS5 mode, the special
padding end markers will be removed from the data after
decrypting, no pad character is required for PAD_PKCS5.'
| def decrypt(self, data, pad=None, padmode=None):
| ENCRYPT = des.ENCRYPT
DECRYPT = des.DECRYPT
data = self._guardAgainstUnicode(data)
if (pad is not None):
pad = self._guardAgainstUnicode(pad)
if (self.getMode() == CBC):
self.__key1.setIV(self.getIV())
self.__key2.setIV(self.getIV())
self.__key3.setIV(self.getIV())
i = 0
result = []
while (i < len(data)):
iv = data[i:(i + 8)]
block = self.__key3.crypt(iv, DECRYPT)
block = self.__key2.crypt(block, ENCRYPT)
block = self.__key1.crypt(block, DECRYPT)
self.__key1.setIV(iv)
self.__key2.setIV(iv)
self.__key3.setIV(iv)
result.append(block)
i += 8
if (_pythonMajorVersion < 3):
data = ''.join(result)
else:
data = bytes.fromhex('').join(result)
else:
data = self.__key3.crypt(data, DECRYPT)
data = self.__key2.crypt(data, ENCRYPT)
data = self.__key1.crypt(data, DECRYPT)
return self._unpadData(data, pad, padmode)
|
'Receive EXACTLY the number of bytes requested from the file object.
Blocks until the required number of bytes have been received.'
| def _readall(self, file, count):
| data = ''
while (len(data) < count):
d = file.read((count - len(data)))
if (not d):
raise GeneralProxyError('Connection closed unexpectedly')
data += d
return data
|
'set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxy_type - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be performed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided.'
| def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
| self.proxy = (proxy_type, addr, port, rdns, (username.encode() if username else None), (password.encode() if password else None))
|
'Implements proxy connection for UDP sockets,
which happens during the bind() phase.'
| def bind(self, *pos, **kw):
| (proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy
if ((not proxy_type) or (self.type != socket.SOCK_DGRAM)):
return _orig_socket.bind(self, *pos, **kw)
if self._proxyconn:
raise socket.error(EINVAL, 'Socket already bound to an address')
if (proxy_type != SOCKS5):
msg = 'UDP only supported by SOCKS5 proxy type'
raise socket.error(EOPNOTSUPP, msg)
_BaseSocket.bind(self, *pos, **kw)
(_, port) = self.getsockname()
dst = ('0', port)
self._proxyconn = _orig_socket()
proxy = self._proxy_addr()
self._proxyconn.connect(proxy)
UDP_ASSOCIATE = '\x03'
(_, relay) = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
(host, _) = proxy
(_, port) = relay
_BaseSocket.connect(self, (host, port))
self.proxy_sockname = ('0.0.0.0', 0)
|
'Returns the bound IP address and port number at the proxy.'
| def get_proxy_sockname(self):
| return self.proxy_sockname
|
'Returns the IP and port number of the proxy.'
| def get_proxy_peername(self):
| return _BaseSocket.getpeername(self)
|
'Returns the IP address and port number of the destination
machine (note: get_proxy_peername returns the proxy)'
| def get_peername(self):
| return self.proxy_peername
|
'Negotiates a stream connection through a SOCKS5 server.'
| def _negotiate_SOCKS5(self, *dest_addr):
| CONNECT = '\x01'
(self.proxy_peername, self.proxy_sockname) = self._SOCKS5_request(self, CONNECT, dest_addr)
|
'Send SOCKS5 request with given command (CMD field) and
address (DST field). Returns resolved DST address that was used.'
| def _SOCKS5_request(self, conn, cmd, dst):
| (proxy_type, addr, port, rdns, username, password) = self.proxy
writer = conn.makefile('wb')
reader = conn.makefile('rb', 0)
try:
if (username and password):
writer.write('\x05\x02\x00\x02')
else:
writer.write('\x05\x01\x00')
writer.flush()
chosen_auth = self._readall(reader, 2)
if (chosen_auth[0:1] != '\x05'):
raise GeneralProxyError('SOCKS5 proxy server sent invalid data')
if (chosen_auth[1:2] == '\x02'):
writer.write((((('\x01' + chr(len(username)).encode()) + username) + chr(len(password)).encode()) + password))
writer.flush()
auth_status = self._readall(reader, 2)
if (auth_status[0:1] != '\x01'):
raise GeneralProxyError('SOCKS5 proxy server sent invalid data')
if (auth_status[1:2] != '\x00'):
raise SOCKS5AuthError('SOCKS5 authentication failed')
elif (chosen_auth[1:2] != '\x00'):
if (chosen_auth[1:2] == '\xff'):
raise SOCKS5AuthError('All offered SOCKS5 authentication methods were rejected')
else:
raise GeneralProxyError('SOCKS5 proxy server sent invalid data')
writer.write((('\x05' + cmd) + '\x00'))
resolved = self._write_SOCKS5_address(dst, writer)
writer.flush()
resp = self._readall(reader, 3)
if (resp[0:1] != '\x05'):
raise GeneralProxyError('SOCKS5 proxy server sent invalid data')
status = ord(resp[1:2])
if (status != 0):
error = SOCKS5_ERRORS.get(status, 'Unknown error')
raise SOCKS5Error('{0:#04x}: {1}'.format(status, error))
bnd = self._read_SOCKS5_address(reader)
return (resolved, bnd)
finally:
reader.close()
writer.close()
|
'Return the host and port packed for the SOCKS5 protocol,
and the resolved address as a tuple object.'
| def _write_SOCKS5_address(self, addr, file):
| (host, port) = addr
(proxy_type, _, _, rdns, username, password) = self.proxy
family_to_byte = {socket.AF_INET: '\x01', socket.AF_INET6: '\x04'}
for family in (socket.AF_INET, socket.AF_INET6):
try:
addr_bytes = socket.inet_pton(family, host)
file.write((family_to_byte[family] + addr_bytes))
host = socket.inet_ntop(family, addr_bytes)
file.write(struct.pack('>H', port))
return (host, port)
except socket.error:
continue
if rdns:
host_bytes = host.encode('idna')
file.write((('\x03' + chr(len(host_bytes)).encode()) + host_bytes))
else:
addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
target_addr = addresses[0]
family = target_addr[0]
host = target_addr[4][0]
addr_bytes = socket.inet_pton(family, host)
file.write((family_to_byte[family] + addr_bytes))
host = socket.inet_ntop(family, addr_bytes)
file.write(struct.pack('>H', port))
return (host, port)
|
'Negotiates a connection through a SOCKS4 server.'
| def _negotiate_SOCKS4(self, dest_addr, dest_port):
| (proxy_type, addr, port, rdns, username, password) = self.proxy
writer = self.makefile('wb')
reader = self.makefile('rb', 0)
try:
remote_resolve = False
try:
addr_bytes = socket.inet_aton(dest_addr)
except socket.error:
if rdns:
addr_bytes = '\x00\x00\x00\x01'
remote_resolve = True
else:
addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr))
writer.write(struct.pack('>BBH', 4, 1, dest_port))
writer.write(addr_bytes)
if username:
writer.write(username)
writer.write('\x00')
if remote_resolve:
writer.write((dest_addr.encode('idna') + '\x00'))
writer.flush()
resp = self._readall(reader, 8)
if (resp[0:1] != '\x00'):
raise GeneralProxyError('SOCKS4 proxy server sent invalid data')
status = ord(resp[1:2])
if (status != 90):
error = SOCKS4_ERRORS.get(status, 'Unknown error')
raise SOCKS4Error('{0:#04x}: {1}'.format(status, error))
self.proxy_sockname = (socket.inet_ntoa(resp[4:]), struct.unpack('>H', resp[2:4])[0])
if remote_resolve:
self.proxy_peername = (socket.inet_ntoa(addr_bytes), dest_port)
else:
self.proxy_peername = (dest_addr, dest_port)
finally:
reader.close()
writer.close()
|
'Negotiates a connection through an HTTP server.
NOTE: This currently only supports HTTP CONNECT-style proxies.'
| def _negotiate_HTTP(self, dest_addr, dest_port):
| (proxy_type, addr, port, rdns, username, password) = self.proxy
addr = (dest_addr if rdns else socket.gethostbyname(dest_addr))
http_headers = [(((('CONNECT ' + addr.encode('idna')) + ':') + str(dest_port).encode()) + ' HTTP/1.1'), ('Host: ' + dest_addr.encode('idna'))]
if (username and password):
http_headers.append(('Proxy-Authorization: basic ' + b64encode(((username + ':') + password))))
http_headers.append('\r\n')
self.sendall('\r\n'.join(http_headers))
fobj = self.makefile()
status_line = fobj.readline()
fobj.close()
if (not status_line):
raise GeneralProxyError('Connection closed unexpectedly')
try:
(proto, status_code, status_msg) = status_line.split(' ', 2)
except ValueError:
raise GeneralProxyError('HTTP proxy server sent invalid response')
if (not proto.startswith('HTTP/')):
raise GeneralProxyError('Proxy server does not appear to be an HTTP proxy')
try:
status_code = int(status_code)
except ValueError:
raise HTTPError('HTTP proxy server did not return a valid HTTP status')
if (status_code != 200):
error = '{0}: {1}'.format(status_code, status_msg)
if (status_code in (400, 403, 405)):
error += '\n[*] Note: The HTTP proxy server may not be supported by PySocks (must be a CONNECT tunnel proxy)'
raise HTTPError(error)
self.proxy_sockname = ('0.0.0.0', 0)
self.proxy_peername = (addr, dest_port)
|
'Connects to the specified destination through a proxy.
Uses the same API as socket\'s connect().
To select the proxy server, use set_proxy().
dest_pair - 2-tuple of (IP/hostname, port).'
| def connect(self, dest_pair):
| if ((len(dest_pair) != 2) or dest_pair[0].startswith('[')):
raise socket.error("PySocks doesn't support IPv6")
(dest_addr, dest_port) = dest_pair
if (self.type == socket.SOCK_DGRAM):
if (not self._proxyconn):
self.bind(('', 0))
dest_addr = socket.gethostbyname(dest_addr)
if ((dest_addr == '0.0.0.0') and (not dest_port)):
self.proxy_peername = None
else:
self.proxy_peername = (dest_addr, dest_port)
return
(proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy
if ((not isinstance(dest_pair, (list, tuple))) or (len(dest_pair) != 2) or (not dest_addr) or (not isinstance(dest_port, int))):
raise GeneralProxyError('Invalid destination-connection (host, port) pair')
if (proxy_type is None):
self.proxy_peername = dest_pair
_BaseSocket.connect(self, (dest_addr, dest_port))
return
proxy_addr = self._proxy_addr()
try:
_BaseSocket.connect(self, proxy_addr)
except socket.error as error:
self.close()
(proxy_addr, proxy_port) = proxy_addr
proxy_server = '{0}:{1}'.format(proxy_addr, proxy_port)
printable_type = PRINTABLE_PROXY_TYPES[proxy_type]
msg = 'Error connecting to {0} proxy {1}'.format(printable_type, proxy_server)
raise ProxyConnectionError(msg, error)
else:
try:
negotiate = self._proxy_negotiators[proxy_type]
negotiate(self, dest_addr, dest_port)
except socket.error as error:
self.close()
raise GeneralProxyError('Socket error', error)
except ProxyError:
self.close()
raise
|
'Return proxy address to connect to as tuple object'
| def _proxy_addr(self):
| (proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy
proxy_port = (proxy_port or DEFAULT_PORTS.get(proxy_type))
if (not proxy_port):
raise GeneralProxyError('Invalid proxy type')
return (proxy_addr, proxy_port)
|
'prefix is ignored if add_to_http_hdrs is true.'
| def addheader(self, key, value, prefix=0, add_to_http_hdrs=0):
| lines = value.split('\r\n')
while (lines and (not lines[(-1)])):
del lines[(-1)]
while (lines and (not lines[0])):
del lines[0]
if add_to_http_hdrs:
value = ''.join(lines)
self._http_hdrs.append((key.capitalize(), value))
else:
for i in xrange(1, len(lines)):
lines[i] = (' ' + lines[i].strip())
value = ('\r\n'.join(lines) + '\r\n')
line = ((key.title() + ': ') + value)
if prefix:
self._headers.insert(0, line)
else:
self._headers.append(line)
|
'prefix is ignored if add_to_http_hdrs is true.'
| def startbody(self, ctype=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1):
| if (content_type and ctype):
for (name, value) in plist:
ctype = (ctype + (';\r\n %s=%s' % (name, value)))
self.addheader('Content-Type', ctype, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs)
self.flushheaders()
if (not add_to_http_hdrs):
self._fp.write('\r\n')
self._first_part = True
return self._fp
|
'type: string describing type of control (see the keys of the
HTMLForm.type2class dictionary for the allowable values)
name: control name
attrs: HTML attributes of control\'s HTML element'
| def __init__(self, type, name, attrs, index=None):
| raise NotImplementedError()
|
'Return list of (key, value) pairs suitable for passing to urlencode.'
| def pairs(self):
| return [(k, v) for (i, k, v) in self._totally_ordered_pairs()]
|
'Return list of (key, value, index) tuples.
Like pairs, but allows preserving correct ordering even where several
controls are involved.'
| def _totally_ordered_pairs(self):
| raise NotImplementedError()
|
'Write data for a subitem of this control to a MimeWriter.'
| def _write_mime_data(self, mw, name, value):
| mw2 = mw.nextpart()
mw2.addheader('Content-Disposition', ('form-data; name="%s"' % name), 1)
f = mw2.startbody(prefix=0)
f.write(value)
|
'Return all labels (Label instances) for this control.
If the control was surrounded by a <label> tag, that will be the first
label; all other labels, connected by \'for\' and \'id\', are in the order
that appear in the HTML.'
| def get_labels(self):
| res = []
if self._label:
res.append(self._label)
if self.id:
res.extend(self._form._id_to_labels.get(self.id, ()))
return res
|
'Return all labels (Label instances) for this item.
For items that represent radio buttons or checkboxes, if the item was
surrounded by a <label> tag, that will be the first label; all other
labels, connected by \'for\' and \'id\', are in the order that appear in
the HTML.
For items that represent select options, if the option had a label
attribute, that will be the first label. If the option has contents
(text within the option tags) and it is not the same as the label
attribute (if any), that will be a label. There is nothing in the
spec to my knowledge that makes an option with an id unable to be the
target of a label\'s for attribute, so those are included, if any, for
the sake of consistency and completeness.'
| def get_labels(self):
| res = []
res.extend(self._labels)
if self.id:
res.extend(self._control._form._id_to_labels.get(self.id, ()))
return res
|
'select_default: for RADIO and multiple-selection SELECT controls, pick
the first item as the default if no \'selected\' HTML attribute is
present'
| def __init__(self, type, name, attrs={}, select_default=False, called_as_base_class=False, index=None):
| if (not called_as_base_class):
raise NotImplementedError()
self.__dict__['type'] = type.lower()
self.__dict__['name'] = name
self._value = attrs.get('value')
self.disabled = False
self.readonly = False
self.id = attrs.get('id')
self._closed = False
self.items = []
self._form = None
self._select_default = select_default
self._clicked = False
|
'Return matching items by name or label.
For argument docs, see the docstring for .get()'
| def get_items(self, name=None, label=None, id=None, exclude_disabled=False):
| if ((name is not None) and (not isstringlike(name))):
raise TypeError('item name must be string-like')
if ((label is not None) and (not isstringlike(label))):
raise TypeError('item label must be string-like')
if ((id is not None) and (not isstringlike(id))):
raise TypeError('item id must be string-like')
items = []
compat = self._form.backwards_compat
for o in self.items:
if (exclude_disabled and o.disabled):
continue
if ((name is not None) and (o.name != name)):
continue
if (label is not None):
for l in o.get_labels():
if ((compat and (l.text == label)) or ((not compat) and (l.text.find(label) > (-1)))):
break
else:
continue
if ((id is not None) and (o.id != id)):
continue
items.append(o)
return items
|
'Return item by name or label, disambiguating if necessary with nr.
All arguments must be passed by name, with the exception of \'name\',
which may be used as a positional argument.
If name is specified, then the item must have the indicated name.
If label is specified, then the item must have a label whose
whitespace-compressed, stripped, text substring-matches the indicated
label string (eg. label="please choose" will match
" Do please choose an item ").
If id is specified, then the item must have the indicated id.
nr is an optional 0-based index of the items matching the query.
If nr is the default None value and more than item is found, raises
AmbiguityError (unless the HTMLForm instance\'s backwards_compat
attribute is true).
If no item is found, or if items are found but nr is specified and not
found, raises ItemNotFoundError.
Optionally excludes disabled items.'
| def get(self, name=None, label=None, id=None, nr=None, exclude_disabled=False):
| if ((nr is None) and self._form.backwards_compat):
nr = 0
items = self.get_items(name, label, id, exclude_disabled)
return disambiguate(items, nr, name=name, label=label, id=id)
|
'Deprecated: given a name or label and optional disambiguating index
nr, toggle the matching item\'s selection.
Selecting items follows the behavior described in the docstring of the
\'get\' method.
if the item is disabled, or this control is disabled or readonly,
raise AttributeError.'
| def toggle(self, name, by_label=False, nr=None):
| deprecation('item = control.get(...); item.selected = not item.selected')
o = self._get(name, by_label, nr)
self._set_selected_state(o, (not o.selected))
|
'Deprecated: given a name or label and optional disambiguating index
nr, set the matching item\'s selection to the bool value of selected.
Selecting items follows the behavior described in the docstring of the
\'get\' method.
if the item is disabled, or this control is disabled or readonly,
raise AttributeError.'
| def set(self, selected, name, by_label=False, nr=None):
| deprecation('control.get(...).selected = <boolean>')
self._set_selected_state(self._get(name, by_label, nr), selected)
|
'Deprecated: toggle the selection of the single item in this control.
Raises ItemCountError if the control does not contain only one item.
by_label argument is ignored, and included only for backwards
compatibility.'
| def toggle_single(self, by_label=None):
| deprecation('control.items[0].selected = not control.items[0].selected')
if (len(self.items) != 1):
raise ItemCountError(("'%s' is not a single-item control" % self.name))
item = self.items[0]
self._set_selected_state(item, (not item.selected))
|
'Deprecated: set the selection of the single item in this control.
Raises ItemCountError if the control does not contain only one item.
by_label argument is ignored, and included only for backwards
compatibility.'
| def set_single(self, selected, by_label=None):
| deprecation('control.items[0].selected = <boolean>')
if (len(self.items) != 1):
raise ItemCountError(("'%s' is not a single-item control" % self.name))
self._set_selected_state(self.items[0], selected)
|
'Get disabled state of named list item in a ListControl.'
| def get_item_disabled(self, name, by_label=False, nr=None):
| deprecation('control.get(...).disabled')
return self._get(name, by_label, nr).disabled
|
'Set disabled state of named list item in a ListControl.
disabled: boolean disabled state'
| def set_item_disabled(self, disabled, name, by_label=False, nr=None):
| deprecation('control.get(...).disabled = <boolean>')
self._get(name, by_label, nr).disabled = disabled
|
'Set disabled state of all list items in a ListControl.
disabled: boolean disabled state'
| def set_all_items_disabled(self, disabled):
| for o in self.items:
o.disabled = disabled
|
'Return dictionary of HTML attributes for a single ListControl item.
The HTML element types that describe list items are: OPTION for SELECT
controls, INPUT for the rest. These elements have HTML attributes that
you may occasionally want to know about -- for example, the "alt" HTML
attribute gives a text string describing the item (graphical browsers
usually display this as a tooltip).
The returned dictionary maps HTML attribute names to values. The names
and values are taken from the original HTML.'
| def get_item_attrs(self, name, by_label=False, nr=None):
| deprecation('control.get(...).attrs')
return self._get(name, by_label, nr).attrs
|
'ListControls are built up from component list items (which are also
ListControls) during parsing. This method should be called after all
items have been added. See ListControl.__doc__ for the reason this is
required.'
| def fixup(self):
| for o in self.items:
o.__dict__['_control'] = self
|
'Set the value of control by item labels.
value is expected to be an iterable of strings that are substrings of
the item labels that should be selected. Before substring matching is
performed, the original label text is whitespace-compressed
(consecutive whitespace characters are converted to a single space
character) and leading and trailing whitespace is stripped. Ambiguous
labels are accepted without complaint if the form\'s backwards_compat is
True; otherwise, it will not complain as long as all ambiguous labels
share the same item name (e.g. OPTION value).'
| def set_value_by_label(self, value):
| if isstringlike(value):
raise TypeError(value)
if ((not self.multiple) and (len(value) > 1)):
raise ItemCountError('single selection list, must set sequence of length 0 or 1')
items = []
for nn in value:
found = self.get_items(label=nn)
if (len(found) > 1):
if (not self._form.backwards_compat):
opt_name = found[0].name
if [o for o in found[1:] if (o.name != opt_name)]:
raise AmbiguityError(nn)
else:
found = found[:1]
for o in found:
if (self._form.backwards_compat or (o not in items)):
items.append(o)
break
else:
raise ItemNotFoundError(nn)
self.value = []
for o in items:
o.selected = True
|
'Return the value of the control as given by normalized labels.'
| def get_value_by_label(self):
| res = []
compat = self._form.backwards_compat
for o in self.items:
if (((not o.disabled) or compat) and o.selected):
for l in o.get_labels():
if l.text:
res.append(l.text)
break
else:
res.append(None)
return res
|
'Deprecated: return the names or labels of all possible items.
Includes disabled items, which may be misleading for some use cases.'
| def possible_items(self, by_label=False):
| deprecation('[item.name for item in self.items]')
if by_label:
res = []
for o in self.items:
for l in o.get_labels():
if l.text:
res.append(l.text)
break
else:
res.append(None)
return res
return [o.name for o in self.items]
|