Revision: 18740
http://sourceforge.net/p/edk2/code/18740
Author: darylm503
Date: 2015-11-07 19:33:58 +0000 (Sat, 07 Nov 2015)
Log Message:
-----------
AppPkg/Applications/Python/Python-2.7.10: Initial Checkin part 4/5.
The Lib directory from the cPython 2.7.10 distribution.
These files are unchanged and set the baseline for subsequent commits.
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Daryl McDaniel <[email protected]>
Added Paths:
-----------
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/BaseHTTPServer.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/HTMLParser.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SimpleHTTPServer.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SocketServer.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/StringIO.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/UserDict.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/_abcoll.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/_weakrefset.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/abc.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/argparse.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/ast.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/atexit.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/binhex.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/bisect.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/calendar.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/cmd.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/codecs.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/collections.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/compileall.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/copy.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/copy_reg.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/csv.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/dis.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/dummy_thread.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/aliases.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/ascii.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/base64_codec.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/big5.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/big5hkscs.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/bz2_codec.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/charmap.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp037.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1006.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1026.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1140.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1250.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1251.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1252.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1253.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1254.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1255.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1256.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1257.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp1258.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp424.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp437.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp500.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp720.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp737.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp775.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp850.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp852.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp855.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp856.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp857.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp858.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp860.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp861.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp862.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp863.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp864.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp865.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp866.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp869.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp874.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp875.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp932.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp949.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/cp950.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/euc_jis_2004.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/euc_jisx0213.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/euc_jp.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/euc_kr.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/gb18030.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/gb2312.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/gbk.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/hex_codec.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/hp_roman8.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/hz.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/idna.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso2022_jp.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso2022_jp_1.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso2022_jp_2.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso2022_jp_2004.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso2022_jp_3.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso2022_jp_ext.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso2022_kr.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_1.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_10.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_11.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_13.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_14.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_15.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_16.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_2.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_3.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_4.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_5.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_6.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_7.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_8.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/iso8859_9.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/johab.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/koi8_r.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/koi8_u.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/latin_1.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_arabic.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_centeuro.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_croatian.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_cyrillic.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_farsi.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_greek.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_iceland.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_latin2.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_roman.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_romanian.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mac_turkish.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/mbcs.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/palmos.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/ptcp154.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/punycode.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/quopri_codec.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/raw_unicode_escape.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/rot_13.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/shift_jis.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/shift_jis_2004.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/shift_jisx0213.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/string_escape.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/tis_620.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/undefined.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/unicode_escape.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/unicode_internal.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_16.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_16_be.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_16_le.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_32.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_32_be.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_32_le.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_7.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_8.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/utf_8_sig.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/uu_codec.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/encodings/zlib_codec.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/fileinput.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/fnmatch.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/formatter.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/functools.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/genericpath.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/getopt.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/gettext.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/hashlib.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/heapq.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/importlib/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/importlib/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/inspect.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/io.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/decoder.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/encoder.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/scanner.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_check_circular.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_decode.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_default.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_dump.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_encode_basestring_ascii.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_fail.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_float.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_indent.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_pass1.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_pass2.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_pass3.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_recursion.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_scanstring.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_separators.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_speedups.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_tool.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_unicode.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tool.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/keyword.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/linecache.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/locale.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/md5.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/modulefinder.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/numbers.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/opcode.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/optparse.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/pkgutil.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/platform.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/pydoc_data/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/pydoc_data/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/pydoc_data/topics.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/random.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/re.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/repr.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/runpy.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/sha.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/shutil.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/site-packages/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/site-packages/README
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/socket.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/sre.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/sre_compile.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/sre_constants.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/sre_parse.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/stat.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/string.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/struct.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/sysconfig.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/textwrap.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/token.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/tokenize.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/traceback.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/types.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/urlparse.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/warnings.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/weakref.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/NodeFilter.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/domreg.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/expatbuilder.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/minicompat.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/minidom.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/pulldom.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/dom/xmlbuilder.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/etree/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/etree/ElementInclude.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/etree/ElementPath.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/etree/ElementTree.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/etree/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/etree/cElementTree.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/parsers/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/parsers/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/parsers/expat.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/sax/
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/sax/__init__.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/sax/_exceptions.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/sax/expatreader.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/sax/handler.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/sax/saxutils.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xml/sax/xmlreader.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/xmllib.py
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/zipfile.py
Added: trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/BaseHTTPServer.py
===================================================================
--- trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/BaseHTTPServer.py
(rev 0)
+++ trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/BaseHTTPServer.py
2015-11-07 19:33:58 UTC (rev 18740)
@@ -0,0 +1,603 @@
+"""HTTP server base class.
+
+Note: the class in this module doesn't implement any HTTP request; see
+SimpleHTTPServer for simple implementations of GET, HEAD and POST
+(including CGI scripts). It does, however, optionally implement HTTP/1.1
+persistent connections, as of version 0.3.
+
+Contents:
+
+- BaseHTTPRequestHandler: HTTP request handler base class
+- test: test function
+
+XXX To do:
+
+- log requests even later (to capture byte count)
+- log user-agent header and other interesting goodies
+- send error log to separate file
+"""
+
+
+# See also:
+#
+# HTTP Working Group T. Berners-Lee
+# INTERNET-DRAFT R. T. Fielding
+# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
+# Expires September 8, 1995 March 8, 1995
+#
+# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
+#
+# and
+#
+# Network Working Group R. Fielding
+# Request for Comments: 2616 et al
+# Obsoletes: 2068 June 1999
+# Category: Standards Track
+#
+# URL: http://www.faqs.org/rfcs/rfc2616.html
+
+# Log files
+# ---------
+#
+# Here's a quote from the NCSA httpd docs about log file format.
+#
+# | The logfile format is as follows. Each line consists of:
+# |
+# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
+# |
+# | host: Either the DNS name or the IP number of the remote client
+# | rfc931: Any information returned by identd for this person,
+# | - otherwise.
+# | authuser: If user sent a userid for authentication, the user name,
+# | - otherwise.
+# | DD: Day
+# | Mon: Month (calendar name)
+# | YYYY: Year
+# | hh: hour (24-hour format, the machine's timezone)
+# | mm: minutes
+# | ss: seconds
+# | request: The first line of the HTTP request as sent by the client.
+# | ddd: the status code returned by the server, - if not available.
+# | bbbb: the total number of bytes sent,
+# | *not including the HTTP/1.0 header*, - if not available
+# |
+# | You can determine the name of the file accessed through request.
+#
+# (Actually, the latter is only true if you know the server configuration
+# at the time the request was made!)
+
+__version__ = "0.3"
+
+__all__ = ["HTTPServer", "BaseHTTPRequestHandler"]
+
+import sys
+import time
+import socket # For gethostbyaddr()
+from warnings import filterwarnings, catch_warnings
+with catch_warnings():
+ if sys.py3kwarning:
+ filterwarnings("ignore", ".*mimetools has been removed",
+ DeprecationWarning)
+ import mimetools
+import SocketServer
+
+# Default error message template
+DEFAULT_ERROR_MESSAGE = """\
+<head>
+<title>Error response</title>
+</head>
+<body>
+<h1>Error response</h1>
+<p>Error code %(code)d.
+<p>Message: %(message)s.
+<p>Error code explanation: %(code)s = %(explain)s.
+</body>
+"""
+
+DEFAULT_ERROR_CONTENT_TYPE = "text/html"
+
+def _quote_html(html):
+ return html.replace("&", "&").replace("<", "<").replace(">", ">")
+
+class HTTPServer(SocketServer.TCPServer):
+
+ allow_reuse_address = 1 # Seems to make sense in testing environment
+
+ def server_bind(self):
+ """Override server_bind to store the server name."""
+ SocketServer.TCPServer.server_bind(self)
+ host, port = self.socket.getsockname()[:2]
+ self.server_name = socket.getfqdn(host)
+ self.server_port = port
+
+
+class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
+
+ """HTTP request handler base class.
+
+ The following explanation of HTTP serves to guide you through the
+ code as well as to expose any misunderstandings I may have about
+ HTTP (so you don't need to read the code to figure out I'm wrong
+ :-).
+
+ HTTP (HyperText Transfer Protocol) is an extensible protocol on
+ top of a reliable stream transport (e.g. TCP/IP). The protocol
+ recognizes three parts to a request:
+
+ 1. One line identifying the request type and path
+ 2. An optional set of RFC-822-style headers
+ 3. An optional data part
+
+ The headers and data are separated by a blank line.
+
+ The first line of the request has the form
+
+ <command> <path> <version>
+
+ where <command> is a (case-sensitive) keyword such as GET or POST,
+ <path> is a string containing path information for the request,
+ and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
+ <path> is encoded using the URL encoding scheme (using %xx to signify
+ the ASCII character with hex code xx).
+
+ The specification specifies that lines are separated by CRLF but
+ for compatibility with the widest range of clients recommends
+ servers also handle LF. Similarly, whitespace in the request line
+ is treated sensibly (allowing multiple spaces between components
+ and allowing trailing whitespace).
+
+ Similarly, for output, lines ought to be separated by CRLF pairs
+ but most clients grok LF characters just fine.
+
+ If the first line of the request has the form
+
+ <command> <path>
+
+ (i.e. <version> is left out) then this is assumed to be an HTTP
+ 0.9 request; this form has no optional headers and data part and
+ the reply consists of just the data.
+
+ The reply form of the HTTP 1.x protocol again has three parts:
+
+ 1. One line giving the response code
+ 2. An optional set of RFC-822-style headers
+ 3. The data
+
+ Again, the headers and data are separated by a blank line.
+
+ The response code line has the form
+
+ <version> <responsecode> <responsestring>
+
+ where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
+ <responsecode> is a 3-digit response code indicating success or
+ failure of the request, and <responsestring> is an optional
+ human-readable string explaining what the response code means.
+
+ This server parses the request and the headers, and then calls a
+ function specific to the request type (<command>). Specifically,
+ a request SPAM will be handled by a method do_SPAM(). If no
+ such method exists the server sends an error response to the
+ client. If it exists, it is called with no arguments:
+
+ do_SPAM()
+
+ Note that the request name is case sensitive (i.e. SPAM and spam
+ are different requests).
+
+ The various request details are stored in instance variables:
+
+ - client_address is the client IP address in the form (host,
+ port);
+
+ - command, path and version are the broken-down request line;
+
+ - headers is an instance of mimetools.Message (or a derived
+ class) containing the header information;
+
+ - rfile is a file object open for reading positioned at the
+ start of the optional input data part;
+
+ - wfile is a file object open for writing.
+
+ IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
+
+ The first thing to be written must be the response line. Then
+ follow 0 or more header lines, then a blank line, and then the
+ actual data (if any). The meaning of the header lines depends on
+ the command executed by the server; in most cases, when data is
+ returned, there should be at least one header line of the form
+
+ Content-type: <type>/<subtype>
+
+ where <type> and <subtype> should be registered MIME types,
+ e.g. "text/html" or "text/plain".
+
+ """
+
+ # The Python system version, truncated to its first component.
+ sys_version = "Python/" + sys.version.split()[0]
+
+ # The server software version. You may want to override this.
+ # The format is multiple whitespace-separated strings,
+ # where each string is of the form name[/version].
+ server_version = "BaseHTTP/" + __version__
+
+ # The default request version. This only affects responses up until
+ # the point where the request line is parsed, so it mainly decides what
+ # the client gets back when sending a malformed request line.
+ # Most web servers default to HTTP 0.9, i.e. don't send a status line.
+ default_request_version = "HTTP/0.9"
+
+ def parse_request(self):
+ """Parse a request (internal).
+
+ The request should be stored in self.raw_requestline; the results
+ are in self.command, self.path, self.request_version and
+ self.headers.
+
+ Return True for success, False for failure; on failure, an
+ error is sent back.
+
+ """
+ self.command = None # set in case of error on the first line
+ self.request_version = version = self.default_request_version
+ self.close_connection = 1
+ requestline = self.raw_requestline
+ requestline = requestline.rstrip('\r\n')
+ self.requestline = requestline
+ words = requestline.split()
+ if len(words) == 3:
+ command, path, version = words
+ if version[:5] != 'HTTP/':
+ self.send_error(400, "Bad request version (%r)" % version)
+ return False
+ try:
+ base_version_number = version.split('/', 1)[1]
+ version_number = base_version_number.split(".")
+ # RFC 2145 section 3.1 says there can be only one "." and
+ # - major and minor numbers MUST be treated as
+ # separate integers;
+ # - HTTP/2.4 is a lower version than HTTP/2.13, which in
+ # turn is lower than HTTP/12.3;
+ # - Leading zeros MUST be ignored by recipients.
+ if len(version_number) != 2:
+ raise ValueError
+ version_number = int(version_number[0]), int(version_number[1])
+ except (ValueError, IndexError):
+ self.send_error(400, "Bad request version (%r)" % version)
+ return False
+ if version_number >= (1, 1) and self.protocol_version >=
"HTTP/1.1":
+ self.close_connection = 0
+ if version_number >= (2, 0):
+ self.send_error(505,
+ "Invalid HTTP Version (%s)" % base_version_number)
+ return False
+ elif len(words) == 2:
+ command, path = words
+ self.close_connection = 1
+ if command != 'GET':
+ self.send_error(400,
+ "Bad HTTP/0.9 request type (%r)" % command)
+ return False
+ elif not words:
+ return False
+ else:
+ self.send_error(400, "Bad request syntax (%r)" % requestline)
+ return False
+ self.command, self.path, self.request_version = command, path, version
+
+ # Examine the headers and look for a Connection directive
+ self.headers = self.MessageClass(self.rfile, 0)
+
+ conntype = self.headers.get('Connection', "")
+ if conntype.lower() == 'close':
+ self.close_connection = 1
+ elif (conntype.lower() == 'keep-alive' and
+ self.protocol_version >= "HTTP/1.1"):
+ self.close_connection = 0
+ return True
+
+ def handle_one_request(self):
+ """Handle a single HTTP request.
+
+ You normally don't need to override this method; see the class
+ __doc__ string for information on how to handle specific HTTP
+ commands such as GET and POST.
+
+ """
+ try:
+ self.raw_requestline = self.rfile.readline(65537)
+ if len(self.raw_requestline) > 65536:
+ self.requestline = ''
+ self.request_version = ''
+ self.command = ''
+ self.send_error(414)
+ return
+ if not self.raw_requestline:
+ self.close_connection = 1
+ return
+ if not self.parse_request():
+ # An error code has been sent, just exit
+ return
+ mname = 'do_' + self.command
+ if not hasattr(self, mname):
+ self.send_error(501, "Unsupported method (%r)" % self.command)
+ return
+ method = getattr(self, mname)
+ method()
+ self.wfile.flush() #actually send the response if not already done.
+ except socket.timeout, e:
+ #a read or a write timed out. Discard this connection
+ self.log_error("Request timed out: %r", e)
+ self.close_connection = 1
+ return
+
+ def handle(self):
+ """Handle multiple requests if necessary."""
+ self.close_connection = 1
+
+ self.handle_one_request()
+ while not self.close_connection:
+ self.handle_one_request()
+
+ def send_error(self, code, message=None):
+ """Send and log an error reply.
+
+ Arguments are the error code, and a detailed message.
+ The detailed message defaults to the short entry matching the
+ response code.
+
+ This sends an error response (so it must be called before any
+ output has been generated), logs the error, and finally sends
+ a piece of HTML explaining the error to the user.
+
+ """
+
+ try:
+ short, long = self.responses[code]
+ except KeyError:
+ short, long = '???', '???'
+ if message is None:
+ message = short
+ explain = long
+ self.log_error("code %d, message %s", code, message)
+ # using _quote_html to prevent Cross Site Scripting attacks (see bug
#1100201)
+ content = (self.error_message_format %
+ {'code': code, 'message': _quote_html(message), 'explain':
explain})
+ self.send_response(code, message)
+ self.send_header("Content-Type", self.error_content_type)
+ self.send_header('Connection', 'close')
+ self.end_headers()
+ if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
+ self.wfile.write(content)
+
+ error_message_format = DEFAULT_ERROR_MESSAGE
+ error_content_type = DEFAULT_ERROR_CONTENT_TYPE
+
+ def send_response(self, code, message=None):
+ """Send the response header and log the response code.
+
+ Also send two standard headers with the server software
+ version and the current date.
+
+ """
+ self.log_request(code)
+ if message is None:
+ if code in self.responses:
+ message = self.responses[code][0]
+ else:
+ message = ''
+ if self.request_version != 'HTTP/0.9':
+ self.wfile.write("%s %d %s\r\n" %
+ (self.protocol_version, code, message))
+ # print (self.protocol_version, code, message)
+ self.send_header('Server', self.version_string())
+ self.send_header('Date', self.date_time_string())
+
+ def send_header(self, keyword, value):
+ """Send a MIME header."""
+ if self.request_version != 'HTTP/0.9':
+ self.wfile.write("%s: %s\r\n" % (keyword, value))
+
+ if keyword.lower() == 'connection':
+ if value.lower() == 'close':
+ self.close_connection = 1
+ elif value.lower() == 'keep-alive':
+ self.close_connection = 0
+
+ def end_headers(self):
+ """Send the blank line ending the MIME headers."""
+ if self.request_version != 'HTTP/0.9':
+ self.wfile.write("\r\n")
+
+ def log_request(self, code='-', size='-'):
+ """Log an accepted request.
+
+ This is called by send_response().
+
+ """
+
+ self.log_message('"%s" %s %s',
+ self.requestline, str(code), str(size))
+
+ def log_error(self, format, *args):
+ """Log an error.
+
+ This is called when a request cannot be fulfilled. By
+ default it passes the message on to log_message().
+
+ Arguments are the same as for log_message().
+
+ XXX This should go to the separate error log.
+
+ """
+
+ self.log_message(format, *args)
+
+ def log_message(self, format, *args):
+ """Log an arbitrary message.
+
+ This is used by all other logging functions. Override
+ it if you have specific logging wishes.
+
+ The first argument, FORMAT, is a format string for the
+ message to be logged. If the format string contains
+ any % escapes requiring parameters, they should be
+ specified as subsequent arguments (it's just like
+ printf!).
+
+ The client ip address and current date/time are prefixed to every
+ message.
+
+ """
+
+ sys.stderr.write("%s - - [%s] %s\n" %
+ (self.client_address[0],
+ self.log_date_time_string(),
+ format%args))
+
+ def version_string(self):
+ """Return the server software version string."""
+ return self.server_version + ' ' + self.sys_version
+
+ def date_time_string(self, timestamp=None):
+ """Return the current date and time formatted for a message header."""
+ if timestamp is None:
+ timestamp = time.time()
+ year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
+ s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
+ self.weekdayname[wd],
+ day, self.monthname[month], year,
+ hh, mm, ss)
+ return s
+
+ def log_date_time_string(self):
+ """Return the current time formatted for logging."""
+ now = time.time()
+ year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
+ s = "%02d/%3s/%04d %02d:%02d:%02d" % (
+ day, self.monthname[month], year, hh, mm, ss)
+ return s
+
+ weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+
+ monthname = [None,
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
+
+ def address_string(self):
+ """Return the client address formatted for logging.
+
+ This version looks up the full hostname using gethostbyaddr(),
+ and tries to find a name that contains at least one dot.
+
+ """
+
+ host, port = self.client_address[:2]
+ return socket.getfqdn(host)
+
+ # Essentially static class variables
+
+ # The version of the HTTP protocol we support.
+ # Set this to HTTP/1.1 to enable automatic keepalive
+ protocol_version = "HTTP/1.0"
+
+ # The Message-like class used to parse headers
+ MessageClass = mimetools.Message
+
+ # Table mapping response codes to messages; entries have the
+ # form {code: (shortmessage, longmessage)}.
+ # See RFC 2616.
+ responses = {
+ 100: ('Continue', 'Request received, please continue'),
+ 101: ('Switching Protocols',
+ 'Switching to new protocol; obey Upgrade header'),
+
+ 200: ('OK', 'Request fulfilled, document follows'),
+ 201: ('Created', 'Document created, URL follows'),
+ 202: ('Accepted',
+ 'Request accepted, processing continues off-line'),
+ 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
+ 204: ('No Content', 'Request fulfilled, nothing follows'),
+ 205: ('Reset Content', 'Clear input form for further input.'),
+ 206: ('Partial Content', 'Partial content follows.'),
+
+ 300: ('Multiple Choices',
+ 'Object has several resources -- see URI list'),
+ 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
+ 302: ('Found', 'Object moved temporarily -- see URI list'),
+ 303: ('See Other', 'Object moved -- see Method and URL list'),
+ 304: ('Not Modified',
+ 'Document has not changed since given time'),
+ 305: ('Use Proxy',
+ 'You must use proxy specified in Location to access this '
+ 'resource.'),
+ 307: ('Temporary Redirect',
+ 'Object moved temporarily -- see URI list'),
+
+ 400: ('Bad Request',
+ 'Bad request syntax or unsupported method'),
+ 401: ('Unauthorized',
+ 'No permission -- see authorization schemes'),
+ 402: ('Payment Required',
+ 'No payment -- see charging schemes'),
+ 403: ('Forbidden',
+ 'Request forbidden -- authorization will not help'),
+ 404: ('Not Found', 'Nothing matches the given URI'),
+ 405: ('Method Not Allowed',
+ 'Specified method is invalid for this resource.'),
+ 406: ('Not Acceptable', 'URI not available in preferred format.'),
+ 407: ('Proxy Authentication Required', 'You must authenticate with '
+ 'this proxy before proceeding.'),
+ 408: ('Request Timeout', 'Request timed out; try again later.'),
+ 409: ('Conflict', 'Request conflict.'),
+ 410: ('Gone',
+ 'URI no longer exists and has been permanently removed.'),
+ 411: ('Length Required', 'Client must specify Content-Length.'),
+ 412: ('Precondition Failed', 'Precondition in headers is false.'),
+ 413: ('Request Entity Too Large', 'Entity is too large.'),
+ 414: ('Request-URI Too Long', 'URI is too long.'),
+ 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
+ 416: ('Requested Range Not Satisfiable',
+ 'Cannot satisfy request range.'),
+ 417: ('Expectation Failed',
+ 'Expect condition could not be satisfied.'),
+
+ 500: ('Internal Server Error', 'Server got itself in trouble'),
+ 501: ('Not Implemented',
+ 'Server does not support this operation'),
+ 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
+ 503: ('Service Unavailable',
+ 'The server cannot process the request due to a high load'),
+ 504: ('Gateway Timeout',
+ 'The gateway server did not receive a timely response'),
+ 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
+ }
+
+
+def test(HandlerClass = BaseHTTPRequestHandler,
+ ServerClass = HTTPServer, protocol="HTTP/1.0"):
+ """Test the HTTP request handler class.
+
+ This runs an HTTP server on port 8000 (or the first command line
+ argument).
+
+ """
+
+ if sys.argv[1:]:
+ port = int(sys.argv[1])
+ else:
+ port = 8000
+ server_address = ('', port)
+
+ HandlerClass.protocol_version = protocol
+ httpd = ServerClass(server_address, HandlerClass)
+
+ sa = httpd.socket.getsockname()
+ print "Serving HTTP on", sa[0], "port", sa[1], "..."
+ httpd.serve_forever()
+
+
+if __name__ == '__main__':
+ test()
Added: trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/HTMLParser.py
===================================================================
--- trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/HTMLParser.py
(rev 0)
+++ trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/HTMLParser.py
2015-11-07 19:33:58 UTC (rev 18740)
@@ -0,0 +1,475 @@
+"""A parser for HTML and XHTML."""
+
+# This file is based on sgmllib.py, but the API is slightly different.
+
+# XXX There should be a way to distinguish between PCDATA (parsed
+# character data -- the normal case), RCDATA (replaceable character
+# data -- only char and entity references and end tags are special)
+# and CDATA (character data -- only end tags are special).
+
+
+import markupbase
+import re
+
+# Regular expressions used for parsing
+
+interesting_normal = re.compile('[&<]')
+incomplete = re.compile('&[a-zA-Z#]')
+
+entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
+charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
+
+starttagopen = re.compile('<[a-zA-Z]')
+piclose = re.compile('>')
+commentclose = re.compile(r'--\s*>')
+
+# see http://www.w3.org/TR/html5/tokenization.html#tag-open-state
+# and http://www.w3.org/TR/html5/tokenization.html#tag-name-state
+# note: if you change tagfind/attrfind remember to update locatestarttagend too
+tagfind = re.compile('([a-zA-Z][^\t\n\r\f />\x00]*)(?:\s|/(?!>))*')
+# this regex is currently unused, but left for backward compatibility
+tagfind_tolerant = re.compile('[a-zA-Z][^\t\n\r\f />\x00]*')
+
+attrfind = re.compile(
+ r'((?<=[\'"\s/])[^\s/>][^\s/=>]*)(\s*=+\s*'
+ r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?(?:\s|/(?!>))*')
+
+locatestarttagend = re.compile(r"""
+ <[a-zA-Z][^\t\n\r\f />\x00]* # tag name
+ (?:[\s/]* # optional whitespace before attribute
name
+ (?:(?<=['"\s/])[^\s/>][^\s/=>]* # attribute name
+ (?:\s*=+\s* # value indicator
+ (?:'[^']*' # LITA-enclosed value
+ |"[^"]*" # LIT-enclosed value
+ |(?!['"])[^>\s]* # bare value
+ )
+ )?(?:\s|/(?!>))*
+ )*
+ )?
+ \s* # trailing whitespace
+""", re.VERBOSE)
+endendtag = re.compile('>')
+# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
+# </ and the tag name, so maybe this should be fixed
+endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
+
+
+class HTMLParseError(Exception):
+ """Exception raised for all parse errors."""
+
+ def __init__(self, msg, position=(None, None)):
+ assert msg
+ self.msg = msg
+ self.lineno = position[0]
+ self.offset = position[1]
+
+ def __str__(self):
+ result = self.msg
+ if self.lineno is not None:
+ result = result + ", at line %d" % self.lineno
+ if self.offset is not None:
+ result = result + ", column %d" % (self.offset + 1)
+ return result
+
+
+class HTMLParser(markupbase.ParserBase):
+ """Find tags and other markup and call handler functions.
+
+ Usage:
+ p = HTMLParser()
+ p.feed(data)
+ ...
+ p.close()
+
+ Start tags are handled by calling self.handle_starttag() or
+ self.handle_startendtag(); end tags by self.handle_endtag(). The
+ data between tags is passed from the parser to the derived class
+ by calling self.handle_data() with the data as argument (the data
+ may be split up in arbitrary chunks). Entity references are
+ passed by calling self.handle_entityref() with the entity
+ reference as the argument. Numeric character references are
+ passed to self.handle_charref() with the string containing the
+ reference as the argument.
+ """
+
+ CDATA_CONTENT_ELEMENTS = ("script", "style")
+
+
+ def __init__(self):
+ """Initialize and reset this instance."""
+ self.reset()
+
+ def reset(self):
+ """Reset this instance. Loses all unprocessed data."""
+ self.rawdata = ''
+ self.lasttag = '???'
+ self.interesting = interesting_normal
+ self.cdata_elem = None
+ markupbase.ParserBase.reset(self)
+
+ def feed(self, data):
+ r"""Feed data to the parser.
+
+ Call this as often as you want, with as little or as much text
+ as you want (may include '\n').
+ """
+ self.rawdata = self.rawdata + data
+ self.goahead(0)
+
+ def close(self):
+ """Handle any buffered data."""
+ self.goahead(1)
+
+ def error(self, message):
+ raise HTMLParseError(message, self.getpos())
+
+ __starttag_text = None
+
+ def get_starttag_text(self):
+ """Return full source of start tag: '<...>'."""
+ return self.__starttag_text
+
+ def set_cdata_mode(self, elem):
+ self.cdata_elem = elem.lower()
+ self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
+
+ def clear_cdata_mode(self):
+ self.interesting = interesting_normal
+ self.cdata_elem = None
+
+ # Internal -- handle data as far as reasonable. May leave state
+ # and data to be processed by a subsequent call. If 'end' is
+ # true, force handling all data as if followed by EOF marker.
+ def goahead(self, end):
+ rawdata = self.rawdata
+ i = 0
+ n = len(rawdata)
+ while i < n:
+ match = self.interesting.search(rawdata, i) # < or &
+ if match:
+ j = match.start()
+ else:
+ if self.cdata_elem:
+ break
+ j = n
+ if i < j: self.handle_data(rawdata[i:j])
+ i = self.updatepos(i, j)
+ if i == n: break
+ startswith = rawdata.startswith
+ if startswith('<', i):
+ if starttagopen.match(rawdata, i): # < + letter
+ k = self.parse_starttag(i)
+ elif startswith("</", i):
+ k = self.parse_endtag(i)
+ elif startswith("<!--", i):
+ k = self.parse_comment(i)
+ elif startswith("<?", i):
+ k = self.parse_pi(i)
+ elif startswith("<!", i):
+ k = self.parse_html_declaration(i)
+ elif (i + 1) < n:
+ self.handle_data("<")
+ k = i + 1
+ else:
+ break
+ if k < 0:
+ if not end:
+ break
+ k = rawdata.find('>', i + 1)
+ if k < 0:
+ k = rawdata.find('<', i + 1)
+ if k < 0:
+ k = i + 1
+ else:
+ k += 1
+ self.handle_data(rawdata[i:k])
+ i = self.updatepos(i, k)
+ elif startswith("&#", i):
+ match = charref.match(rawdata, i)
+ if match:
+ name = match.group()[2:-1]
+ self.handle_charref(name)
+ k = match.end()
+ if not startswith(';', k-1):
+ k = k - 1
+ i = self.updatepos(i, k)
+ continue
+ else:
+ if ";" in rawdata[i:]: # bail by consuming '&#'
+ self.handle_data(rawdata[i:i+2])
+ i = self.updatepos(i, i+2)
+ break
+ elif startswith('&', i):
+ match = entityref.match(rawdata, i)
+ if match:
+ name = match.group(1)
+ self.handle_entityref(name)
+ k = match.end()
+ if not startswith(';', k-1):
+ k = k - 1
+ i = self.updatepos(i, k)
+ continue
+ match = incomplete.match(rawdata, i)
+ if match:
+ # match.group() will contain at least 2 chars
+ if end and match.group() == rawdata[i:]:
+ self.error("EOF in middle of entity or char ref")
+ # incomplete
+ break
+ elif (i + 1) < n:
+ # not the end of the buffer, and can't be confused
+ # with some other construct
+ self.handle_data("&")
+ i = self.updatepos(i, i + 1)
+ else:
+ break
+ else:
+ assert 0, "interesting.search() lied"
+ # end while
+ if end and i < n and not self.cdata_elem:
+ self.handle_data(rawdata[i:n])
+ i = self.updatepos(i, n)
+ self.rawdata = rawdata[i:]
+
+ # Internal -- parse html declarations, return length or -1 if not
terminated
+ # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state
+ # See also parse_declaration in _markupbase
+ def parse_html_declaration(self, i):
+ rawdata = self.rawdata
+ if rawdata[i:i+2] != '<!':
+ self.error('unexpected call to parse_html_declaration()')
+ if rawdata[i:i+4] == '<!--':
+ # this case is actually already handled in goahead()
+ return self.parse_comment(i)
+ elif rawdata[i:i+3] == '<![':
+ return self.parse_marked_section(i)
+ elif rawdata[i:i+9].lower() == '<!doctype':
+ # find the closing >
+ gtpos = rawdata.find('>', i+9)
+ if gtpos == -1:
+ return -1
+ self.handle_decl(rawdata[i+2:gtpos])
+ return gtpos+1
+ else:
+ return self.parse_bogus_comment(i)
+
+ # Internal -- parse bogus comment, return length or -1 if not terminated
+ # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state
+ def parse_bogus_comment(self, i, report=1):
+ rawdata = self.rawdata
+ if rawdata[i:i+2] not in ('<!', '</'):
+ self.error('unexpected call to parse_comment()')
+ pos = rawdata.find('>', i+2)
+ if pos == -1:
+ return -1
+ if report:
+ self.handle_comment(rawdata[i+2:pos])
+ return pos + 1
+
+ # Internal -- parse processing instr, return end or -1 if not terminated
+ def parse_pi(self, i):
+ rawdata = self.rawdata
+ assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
+ match = piclose.search(rawdata, i+2) # >
+ if not match:
+ return -1
+ j = match.start()
+ self.handle_pi(rawdata[i+2: j])
+ j = match.end()
+ return j
+
+ # Internal -- handle starttag, return end or -1 if not terminated
+ def parse_starttag(self, i):
+ self.__starttag_text = None
+ endpos = self.check_for_whole_start_tag(i)
+ if endpos < 0:
+ return endpos
+ rawdata = self.rawdata
+ self.__starttag_text = rawdata[i:endpos]
+
+ # Now parse the data between i+1 and j into a tag and attrs
+ attrs = []
+ match = tagfind.match(rawdata, i+1)
+ assert match, 'unexpected call to parse_starttag()'
+ k = match.end()
+ self.lasttag = tag = match.group(1).lower()
+
+ while k < endpos:
+ m = attrfind.match(rawdata, k)
+ if not m:
+ break
+ attrname, rest, attrvalue = m.group(1, 2, 3)
+ if not rest:
+ attrvalue = None
+ elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
+ attrvalue[:1] == '"' == attrvalue[-1:]:
+ attrvalue = attrvalue[1:-1]
+ if attrvalue:
+ attrvalue = self.unescape(attrvalue)
+ attrs.append((attrname.lower(), attrvalue))
+ k = m.end()
+
+ end = rawdata[k:endpos].strip()
+ if end not in (">", "/>"):
+ lineno, offset = self.getpos()
+ if "\n" in self.__starttag_text:
+ lineno = lineno + self.__starttag_text.count("\n")
+ offset = len(self.__starttag_text) \
+ - self.__starttag_text.rfind("\n")
+ else:
+ offset = offset + len(self.__starttag_text)
+ self.handle_data(rawdata[i:endpos])
+ return endpos
+ if end.endswith('/>'):
+ # XHTML-style empty tag: <span attr="value" />
+ self.handle_startendtag(tag, attrs)
+ else:
+ self.handle_starttag(tag, attrs)
+ if tag in self.CDATA_CONTENT_ELEMENTS:
+ self.set_cdata_mode(tag)
+ return endpos
+
+ # Internal -- check to see if we have a complete starttag; return end
+ # or -1 if incomplete.
+ def check_for_whole_start_tag(self, i):
+ rawdata = self.rawdata
+ m = locatestarttagend.match(rawdata, i)
+ if m:
+ j = m.end()
+ next = rawdata[j:j+1]
+ if next == ">":
+ return j + 1
+ if next == "/":
+ if rawdata.startswith("/>", j):
+ return j + 2
+ if rawdata.startswith("/", j):
+ # buffer boundary
+ return -1
+ # else bogus input
+ self.updatepos(i, j + 1)
+ self.error("malformed empty start tag")
+ if next == "":
+ # end of input
+ return -1
+ if next in ("abcdefghijklmnopqrstuvwxyz=/"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
+ # end of input in or before attribute value, or we have the
+ # '/' from a '/>' ending
+ return -1
+ if j > i:
+ return j
+ else:
+ return i + 1
+ raise AssertionError("we should not get here!")
+
+ # Internal -- parse endtag, return end or -1 if incomplete
+ def parse_endtag(self, i):
+ rawdata = self.rawdata
+ assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
+ match = endendtag.search(rawdata, i+1) # >
+ if not match:
+ return -1
+ gtpos = match.end()
+ match = endtagfind.match(rawdata, i) # </ + tag + >
+ if not match:
+ if self.cdata_elem is not None:
+ self.handle_data(rawdata[i:gtpos])
+ return gtpos
+ # find the name: w3.org/TR/html5/tokenization.html#tag-name-state
+ namematch = tagfind.match(rawdata, i+2)
+ if not namematch:
+ # w3.org/TR/html5/tokenization.html#end-tag-open-state
+ if rawdata[i:i+3] == '</>':
+ return i+3
+ else:
+ return self.parse_bogus_comment(i)
+ tagname = namematch.group(1).lower()
+ # consume and ignore other stuff between the name and the >
+ # Note: this is not 100% correct, since we might have things like
+ # </tag attr=">">, but looking for > after tha name should cover
+ # most of the cases and is much simpler
+ gtpos = rawdata.find('>', namematch.end())
+ self.handle_endtag(tagname)
+ return gtpos+1
+
+ elem = match.group(1).lower() # script or style
+ if self.cdata_elem is not None:
+ if elem != self.cdata_elem:
+ self.handle_data(rawdata[i:gtpos])
+ return gtpos
+
+ self.handle_endtag(elem)
+ self.clear_cdata_mode()
+ return gtpos
+
+ # Overridable -- finish processing of start+end tag: <tag.../>
+ def handle_startendtag(self, tag, attrs):
+ self.handle_starttag(tag, attrs)
+ self.handle_endtag(tag)
+
+ # Overridable -- handle start tag
+ def handle_starttag(self, tag, attrs):
+ pass
+
+ # Overridable -- handle end tag
+ def handle_endtag(self, tag):
+ pass
+
+ # Overridable -- handle character reference
+ def handle_charref(self, name):
+ pass
+
+ # Overridable -- handle entity reference
+ def handle_entityref(self, name):
+ pass
+
+ # Overridable -- handle data
+ def handle_data(self, data):
+ pass
+
+ # Overridable -- handle comment
+ def handle_comment(self, data):
+ pass
+
+ # Overridable -- handle declaration
+ def handle_decl(self, decl):
+ pass
+
+ # Overridable -- handle processing instruction
+ def handle_pi(self, data):
+ pass
+
+ def unknown_decl(self, data):
+ pass
+
+ # Internal -- helper to remove special character quoting
+ entitydefs = None
+ def unescape(self, s):
+ if '&' not in s:
+ return s
+ def replaceEntities(s):
+ s = s.groups()[0]
+ try:
+ if s[0] == "#":
+ s = s[1:]
+ if s[0] in ['x','X']:
+ c = int(s[1:], 16)
+ else:
+ c = int(s)
+ return unichr(c)
+ except ValueError:
+ return '&#'+s+';'
+ else:
+ # Cannot use name2codepoint directly, because HTMLParser
supports apos,
+ # which is not part of HTML 4
+ import htmlentitydefs
+ if HTMLParser.entitydefs is None:
+ entitydefs = HTMLParser.entitydefs = {'apos':u"'"}
+ for k, v in htmlentitydefs.name2codepoint.iteritems():
+ entitydefs[k] = unichr(v)
+ try:
+ return self.entitydefs[s]
+ except KeyError:
+ return '&'+s+';'
+
+ return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities,
s)
Added:
trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SimpleHTTPServer.py
===================================================================
--- trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SimpleHTTPServer.py
(rev 0)
+++ trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SimpleHTTPServer.py
2015-11-07 19:33:58 UTC (rev 18740)
@@ -0,0 +1,235 @@
+"""Simple HTTP Server.
+
+This module builds on BaseHTTPServer by implementing the standard GET
+and HEAD requests in a fairly straightforward manner.
+
+"""
+
+
+__version__ = "0.6"
+
+__all__ = ["SimpleHTTPRequestHandler"]
+
+import os
+import posixpath
+import BaseHTTPServer
+import urllib
+import urlparse
+import cgi
+import sys
+import shutil
+import mimetypes
+try:
+ from cStringIO import StringIO
+except ImportError:
+ from StringIO import StringIO
+
+
+class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
+
+ """Simple HTTP request handler with GET and HEAD commands.
+
+ This serves files from the current directory and any of its
+ subdirectories. The MIME type for files is determined by
+ calling the .guess_type() method.
+
+ The GET and HEAD requests are identical except that the HEAD
+ request omits the actual contents of the file.
+
+ """
+
+ server_version = "SimpleHTTP/" + __version__
+
+ def do_GET(self):
+ """Serve a GET request."""
+ f = self.send_head()
+ if f:
+ try:
+ self.copyfile(f, self.wfile)
+ finally:
+ f.close()
+
+ def do_HEAD(self):
+ """Serve a HEAD request."""
+ f = self.send_head()
+ if f:
+ f.close()
+
+ def send_head(self):
+ """Common code for GET and HEAD commands.
+
+ This sends the response code and MIME headers.
+
+ Return value is either a file object (which has to be copied
+ to the outputfile by the caller unless the command was HEAD,
+ and must be closed by the caller under all circumstances), or
+ None, in which case the caller has nothing further to do.
+
+ """
+ path = self.translate_path(self.path)
+ f = None
+ if os.path.isdir(path):
+ parts = urlparse.urlsplit(self.path)
+ if not parts.path.endswith('/'):
+ # redirect browser - doing basically what apache does
+ self.send_response(301)
+ new_parts = (parts[0], parts[1], parts[2] + '/',
+ parts[3], parts[4])
+ new_url = urlparse.urlunsplit(new_parts)
+ self.send_header("Location", new_url)
+ self.end_headers()
+ return None
+ for index in "index.html", "index.htm":
+ index = os.path.join(path, index)
+ if os.path.exists(index):
+ path = index
+ break
+ else:
+ return self.list_directory(path)
+ ctype = self.guess_type(path)
+ try:
+ # Always read in binary mode. Opening files in text mode may cause
+ # newline translations, making the actual size of the content
+ # transmitted *less* than the content-length!
+ f = open(path, 'rb')
+ except IOError:
+ self.send_error(404, "File not found")
+ return None
+ try:
+ self.send_response(200)
+ self.send_header("Content-type", ctype)
+ fs = os.fstat(f.fileno())
+ self.send_header("Content-Length", str(fs[6]))
+ self.send_header("Last-Modified",
self.date_time_string(fs.st_mtime))
+ self.end_headers()
+ return f
+ except:
+ f.close()
+ raise
+
+ def list_directory(self, path):
+ """Helper to produce a directory listing (absent index.html).
+
+ Return value is either a file object, or None (indicating an
+ error). In either case, the headers are sent, making the
+ interface the same as for send_head().
+
+ """
+ try:
+ list = os.listdir(path)
+ except os.error:
+ self.send_error(404, "No permission to list directory")
+ return None
+ list.sort(key=lambda a: a.lower())
+ f = StringIO()
+ displaypath = cgi.escape(urllib.unquote(self.path))
+ f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
+ f.write("<html>\n<title>Directory listing for %s</title>\n" %
displaypath)
+ f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
+ f.write("<hr>\n<ul>\n")
+ for name in list:
+ fullname = os.path.join(path, name)
+ displayname = linkname = name
+ # Append / for directories or @ for symbolic links
+ if os.path.isdir(fullname):
+ displayname = name + "/"
+ linkname = name + "/"
+ if os.path.islink(fullname):
+ displayname = name + "@"
+ # Note: a link to a directory displays with @ and links with /
+ f.write('<li><a href="%s">%s</a>\n'
+ % (urllib.quote(linkname), cgi.escape(displayname)))
+ f.write("</ul>\n<hr>\n</body>\n</html>\n")
+ length = f.tell()
+ f.seek(0)
+ self.send_response(200)
+ encoding = sys.getfilesystemencoding()
+ self.send_header("Content-type", "text/html; charset=%s" % encoding)
+ self.send_header("Content-Length", str(length))
+ self.end_headers()
+ return f
+
+ def translate_path(self, path):
+ """Translate a /-separated PATH to the local filename syntax.
+
+ Components that mean special things to the local file system
+ (e.g. drive or directory names) are ignored. (XXX They should
+ probably be diagnosed.)
+
+ """
+ # abandon query parameters
+ path = path.split('?',1)[0]
+ path = path.split('#',1)[0]
+ # Don't forget explicit trailing slash when normalizing. Issue17324
+ trailing_slash = path.rstrip().endswith('/')
+ path = posixpath.normpath(urllib.unquote(path))
+ words = path.split('/')
+ words = filter(None, words)
+ path = os.getcwd()
+ for word in words:
+ drive, word = os.path.splitdrive(word)
+ head, word = os.path.split(word)
+ if word in (os.curdir, os.pardir): continue
+ path = os.path.join(path, word)
+ if trailing_slash:
+ path += '/'
+ return path
+
+ def copyfile(self, source, outputfile):
+ """Copy all data between two file objects.
+
+ The SOURCE argument is a file object open for reading
+ (or anything with a read() method) and the DESTINATION
+ argument is a file object open for writing (or
+ anything with a write() method).
+
+ The only reason for overriding this would be to change
+ the block size or perhaps to replace newlines by CRLF
+ -- note however that this the default server uses this
+ to copy binary data as well.
+
+ """
+ shutil.copyfileobj(source, outputfile)
+
+ def guess_type(self, path):
+ """Guess the type of a file.
+
+ Argument is a PATH (a filename).
+
+ Return value is a string of the form type/subtype,
+ usable for a MIME Content-type header.
+
+ The default implementation looks the file's extension
+ up in the table self.extensions_map, using application/octet-stream
+ as a default; however it would be permissible (if
+ slow) to look inside the data to make a better guess.
+
+ """
+
+ base, ext = posixpath.splitext(path)
+ if ext in self.extensions_map:
+ return self.extensions_map[ext]
+ ext = ext.lower()
+ if ext in self.extensions_map:
+ return self.extensions_map[ext]
+ else:
+ return self.extensions_map['']
+
+ if not mimetypes.inited:
+ mimetypes.init() # try to read system mime.types
+ extensions_map = mimetypes.types_map.copy()
+ extensions_map.update({
+ '': 'application/octet-stream', # Default
+ '.py': 'text/plain',
+ '.c': 'text/plain',
+ '.h': 'text/plain',
+ })
+
+
+def test(HandlerClass = SimpleHTTPRequestHandler,
+ ServerClass = BaseHTTPServer.HTTPServer):
+ BaseHTTPServer.test(HandlerClass, ServerClass)
+
+
+if __name__ == '__main__':
+ test()
Added: trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SocketServer.py
===================================================================
--- trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SocketServer.py
(rev 0)
+++ trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/SocketServer.py
2015-11-07 19:33:58 UTC (rev 18740)
@@ -0,0 +1,737 @@
+"""Generic socket server classes.
+
+This module tries to capture the various aspects of defining a server:
+
+For socket-based servers:
+
+- address family:
+ - AF_INET{,6}: IP (Internet Protocol) sockets (default)
+ - AF_UNIX: Unix domain sockets
+ - others, e.g. AF_DECNET are conceivable (see <socket.h>
+- socket type:
+ - SOCK_STREAM (reliable stream, e.g. TCP)
+ - SOCK_DGRAM (datagrams, e.g. UDP)
+
+For request-based servers (including socket-based):
+
+- client address verification before further looking at the request
+ (This is actually a hook for any processing that needs to look
+ at the request before anything else, e.g. logging)
+- how to handle multiple requests:
+ - synchronous (one request is handled at a time)
+ - forking (each request is handled by a new process)
+ - threading (each request is handled by a new thread)
+
+The classes in this module favor the server type that is simplest to
+write: a synchronous TCP/IP server. This is bad class design, but
+save some typing. (There's also the issue that a deep class hierarchy
+slows down method lookups.)
+
+There are five classes in an inheritance diagram, four of which represent
+synchronous servers of four types:
+
+ +------------+
+ | BaseServer |
+ +------------+
+ |
+ v
+ +-----------+ +------------------+
+ | TCPServer |------->| UnixStreamServer |
+ +-----------+ +------------------+
+ |
+ v
+ +-----------+ +--------------------+
+ | UDPServer |------->| UnixDatagramServer |
+ +-----------+ +--------------------+
+
+Note that UnixDatagramServer derives from UDPServer, not from
+UnixStreamServer -- the only difference between an IP and a Unix
+stream server is the address family, which is simply repeated in both
+unix server classes.
+
+Forking and threading versions of each type of server can be created
+using the ForkingMixIn and ThreadingMixIn mix-in classes. For
+instance, a threading UDP server class is created as follows:
+
+ class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
+
+The Mix-in class must come first, since it overrides a method defined
+in UDPServer! Setting the various member variables also changes
+the behavior of the underlying server mechanism.
+
+To implement a service, you must derive a class from
+BaseRequestHandler and redefine its handle() method. You can then run
+various versions of the service by combining one of the server classes
+with your request handler class.
+
+The request handler class must be different for datagram or stream
+services. This can be hidden by using the request handler
+subclasses StreamRequestHandler or DatagramRequestHandler.
+
+Of course, you still have to use your head!
+
+For instance, it makes no sense to use a forking server if the service
+contains state in memory that can be modified by requests (since the
+modifications in the child process would never reach the initial state
+kept in the parent process and passed to each child). In this case,
+you can use a threading server, but you will probably have to use
+locks to avoid two requests that come in nearly simultaneous to apply
+conflicting changes to the server state.
+
+On the other hand, if you are building e.g. an HTTP server, where all
+data is stored externally (e.g. in the file system), a synchronous
+class will essentially render the service "deaf" while one request is
+being handled -- which may be for a very long time if a client is slow
+to read all the data it has requested. Here a threading or forking
+server is appropriate.
+
+In some cases, it may be appropriate to process part of a request
+synchronously, but to finish processing in a forked child depending on
+the request data. This can be implemented by using a synchronous
+server and doing an explicit fork in the request handler class
+handle() method.
+
+Another approach to handling multiple simultaneous requests in an
+environment that supports neither threads nor fork (or where these are
+too expensive or inappropriate for the service) is to maintain an
+explicit table of partially finished requests and to use select() to
+decide which request to work on next (or whether to handle a new
+incoming request). This is particularly important for stream services
+where each client can potentially be connected for a long time (if
+threads or subprocesses cannot be used).
+
+Future work:
+- Standard classes for Sun RPC (which uses either UDP or TCP)
+- Standard mix-in classes to implement various authentication
+ and encryption schemes
+- Standard framework for select-based multiplexing
+
+XXX Open problems:
+- What to do with out-of-band data?
+
+BaseServer:
+- split generic "request" functionality out into BaseServer class.
+ Copyright (C) 2000 Luke Kenneth Casson Leighton <[email protected]>
+
+ example: read entries from a SQL database (requires overriding
+ get_request() to return a table entry from the database).
+ entry is processed by a RequestHandlerClass.
+
+"""
+
+# Author of the BaseServer patch: Luke Kenneth Casson Leighton
+
+# XXX Warning!
+# There is a test suite for this module, but it cannot be run by the
+# standard regression test.
+# To run it manually, run Lib/test/test_socketserver.py.
+
+__version__ = "0.4"
+
+
+import socket
+import select
+import sys
+import os
+import errno
+try:
+ import threading
+except ImportError:
+ import dummy_threading as threading
+
+__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
+ "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
+ "StreamRequestHandler","DatagramRequestHandler",
+ "ThreadingMixIn", "ForkingMixIn"]
+if hasattr(socket, "AF_UNIX"):
+ __all__.extend(["UnixStreamServer","UnixDatagramServer",
+ "ThreadingUnixStreamServer",
+ "ThreadingUnixDatagramServer"])
+
+def _eintr_retry(func, *args):
+ """restart a system call interrupted by EINTR"""
+ while True:
+ try:
+ return func(*args)
+ except (OSError, select.error) as e:
+ if e.args[0] != errno.EINTR:
+ raise
+
+class BaseServer:
+
+ """Base class for server classes.
+
+ Methods for the caller:
+
+ - __init__(server_address, RequestHandlerClass)
+ - serve_forever(poll_interval=0.5)
+ - shutdown()
+ - handle_request() # if you do not use serve_forever()
+ - fileno() -> int # for select()
+
+ Methods that may be overridden:
+
+ - server_bind()
+ - server_activate()
+ - get_request() -> request, client_address
+ - handle_timeout()
+ - verify_request(request, client_address)
+ - server_close()
+ - process_request(request, client_address)
+ - shutdown_request(request)
+ - close_request(request)
+ - handle_error()
+
+ Methods for derived classes:
+
+ - finish_request(request, client_address)
+
+ Class variables that may be overridden by derived classes or
+ instances:
+
+ - timeout
+ - address_family
+ - socket_type
+ - allow_reuse_address
+
+ Instance variables:
+
+ - RequestHandlerClass
+ - socket
+
+ """
+
+ timeout = None
+
+ def __init__(self, server_address, RequestHandlerClass):
+ """Constructor. May be extended, do not override."""
+ self.server_address = server_address
+ self.RequestHandlerClass = RequestHandlerClass
+ self.__is_shut_down = threading.Event()
+ self.__shutdown_request = False
+
+ def server_activate(self):
+ """Called by constructor to activate the server.
+
+ May be overridden.
+
+ """
+ pass
+
+ def serve_forever(self, poll_interval=0.5):
+ """Handle one request at a time until shutdown.
+
+ Polls for shutdown every poll_interval seconds. Ignores
+ self.timeout. If you need to do periodic tasks, do them in
+ another thread.
+ """
+ self.__is_shut_down.clear()
+ try:
+ while not self.__shutdown_request:
+ # XXX: Consider using another file descriptor or
+ # connecting to the socket to wake this up instead of
+ # polling. Polling reduces our responsiveness to a
+ # shutdown request and wastes cpu at all other times.
+ r, w, e = _eintr_retry(select.select, [self], [], [],
+ poll_interval)
+ if self in r:
+ self._handle_request_noblock()
+ finally:
+ self.__shutdown_request = False
+ self.__is_shut_down.set()
+
+ def shutdown(self):
+ """Stops the serve_forever loop.
+
+ Blocks until the loop has finished. This must be called while
+ serve_forever() is running in another thread, or it will
+ deadlock.
+ """
+ self.__shutdown_request = True
+ self.__is_shut_down.wait()
+
+ # The distinction between handling, getting, processing and
+ # finishing a request is fairly arbitrary. Remember:
+ #
+ # - handle_request() is the top-level call. It calls
+ # select, get_request(), verify_request() and process_request()
+ # - get_request() is different for stream or datagram sockets
+ # - process_request() is the place that may fork a new process
+ # or create a new thread to finish the request
+ # - finish_request() instantiates the request handler class;
+ # this constructor will handle the request all by itself
+
+ def handle_request(self):
+ """Handle one request, possibly blocking.
+
+ Respects self.timeout.
+ """
+ # Support people who used socket.settimeout() to escape
+ # handle_request before self.timeout was available.
+ timeout = self.socket.gettimeout()
+ if timeout is None:
+ timeout = self.timeout
+ elif self.timeout is not None:
+ timeout = min(timeout, self.timeout)
+ fd_sets = _eintr_retry(select.select, [self], [], [], timeout)
+ if not fd_sets[0]:
+ self.handle_timeout()
+ return
+ self._handle_request_noblock()
+
+ def _handle_request_noblock(self):
+ """Handle one request, without blocking.
+
+ I assume that select.select has returned that the socket is
+ readable before this function was called, so there should be
+ no risk of blocking in get_request().
+ """
+ try:
+ request, client_address = self.get_request()
+ except socket.error:
+ return
+ if self.verify_request(request, client_address):
+ try:
+ self.process_request(request, client_address)
+ except:
+ self.handle_error(request, client_address)
+ self.shutdown_request(request)
+
+ def handle_timeout(self):
+ """Called if no new request arrives within self.timeout.
+
+ Overridden by ForkingMixIn.
+ """
+ pass
+
+ def verify_request(self, request, client_address):
+ """Verify the request. May be overridden.
+
+ Return True if we should proceed with this request.
+
+ """
+ return True
+
+ def process_request(self, request, client_address):
+ """Call finish_request.
+
+ Overridden by ForkingMixIn and ThreadingMixIn.
+
+ """
+ self.finish_request(request, client_address)
+ self.shutdown_request(request)
+
+ def server_close(self):
+ """Called to clean-up the server.
+
+ May be overridden.
+
+ """
+ pass
+
+ def finish_request(self, request, client_address):
+ """Finish one request by instantiating RequestHandlerClass."""
+ self.RequestHandlerClass(request, client_address, self)
+
+ def shutdown_request(self, request):
+ """Called to shutdown and close an individual request."""
+ self.close_request(request)
+
+ def close_request(self, request):
+ """Called to clean up an individual request."""
+ pass
+
+ def handle_error(self, request, client_address):
+ """Handle an error gracefully. May be overridden.
+
+ The default is to print a traceback and continue.
+
+ """
+ print '-'*40
+ print 'Exception happened during processing of request from',
+ print client_address
+ import traceback
+ traceback.print_exc() # XXX But this goes to stderr!
+ print '-'*40
+
+
+class TCPServer(BaseServer):
+
+ """Base class for various socket-based server classes.
+
+ Defaults to synchronous IP stream (i.e., TCP).
+
+ Methods for the caller:
+
+ - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
+ - serve_forever(poll_interval=0.5)
+ - shutdown()
+ - handle_request() # if you don't use serve_forever()
+ - fileno() -> int # for select()
+
+ Methods that may be overridden:
+
+ - server_bind()
+ - server_activate()
+ - get_request() -> request, client_address
+ - handle_timeout()
+ - verify_request(request, client_address)
+ - process_request(request, client_address)
+ - shutdown_request(request)
+ - close_request(request)
+ - handle_error()
+
+ Methods for derived classes:
+
+ - finish_request(request, client_address)
+
+ Class variables that may be overridden by derived classes or
+ instances:
+
+ - timeout
+ - address_family
+ - socket_type
+ - request_queue_size (only for stream sockets)
+ - allow_reuse_address
+
+ Instance variables:
+
+ - server_address
+ - RequestHandlerClass
+ - socket
+
+ """
+
+ address_family = socket.AF_INET
+
+ socket_type = socket.SOCK_STREAM
+
+ request_queue_size = 5
+
+ allow_reuse_address = False
+
+ def __init__(self, server_address, RequestHandlerClass,
bind_and_activate=True):
+ """Constructor. May be extended, do not override."""
+ BaseServer.__init__(self, server_address, RequestHandlerClass)
+ self.socket = socket.socket(self.address_family,
+ self.socket_type)
+ if bind_and_activate:
+ try:
+ self.server_bind()
+ self.server_activate()
+ except:
+ self.server_close()
+ raise
+
+ def server_bind(self):
+ """Called by constructor to bind the socket.
+
+ May be overridden.
+
+ """
+ if self.allow_reuse_address:
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.socket.bind(self.server_address)
+ self.server_address = self.socket.getsockname()
+
+ def server_activate(self):
+ """Called by constructor to activate the server.
+
+ May be overridden.
+
+ """
+ self.socket.listen(self.request_queue_size)
+
+ def server_close(self):
+ """Called to clean-up the server.
+
+ May be overridden.
+
+ """
+ self.socket.close()
+
+ def fileno(self):
+ """Return socket file number.
+
+ Interface required by select().
+
+ """
+ return self.socket.fileno()
+
+ def get_request(self):
+ """Get the request and client address from the socket.
+
+ May be overridden.
+
+ """
+ return self.socket.accept()
+
+ def shutdown_request(self, request):
+ """Called to shutdown and close an individual request."""
+ try:
+ #explicitly shutdown. socket.close() merely releases
+ #the socket and waits for GC to perform the actual close.
+ request.shutdown(socket.SHUT_WR)
+ except socket.error:
+ pass #some platforms may raise ENOTCONN here
+ self.close_request(request)
+
+ def close_request(self, request):
+ """Called to clean up an individual request."""
+ request.close()
+
+
+class UDPServer(TCPServer):
+
+ """UDP server class."""
+
+ allow_reuse_address = False
+
+ socket_type = socket.SOCK_DGRAM
+
+ max_packet_size = 8192
+
+ def get_request(self):
+ data, client_addr = self.socket.recvfrom(self.max_packet_size)
+ return (data, self.socket), client_addr
+
+ def server_activate(self):
+ # No need to call listen() for UDP.
+ pass
+
+ def shutdown_request(self, request):
+ # No need to shutdown anything.
+ self.close_request(request)
+
+ def close_request(self, request):
+ # No need to close anything.
+ pass
+
+class ForkingMixIn:
+
+ """Mix-in class to handle each request in a new process."""
+
+ timeout = 300
+ active_children = None
+ max_children = 40
+
+ def collect_children(self):
+ """Internal routine to wait for children that have exited."""
+ if self.active_children is None:
+ return
+
+ # If we're above the max number of children, wait and reap them until
+ # we go back below threshold. Note that we use waitpid(-1) below to be
+ # able to collect children in size(<defunct children>) syscalls instead
+ # of size(<children>): the downside is that this might reap children
+ # which we didn't spawn, which is why we only resort to this when we're
+ # above max_children.
+ while len(self.active_children) >= self.max_children:
+ try:
+ pid, _ = os.waitpid(-1, 0)
+ self.active_children.discard(pid)
+ except OSError as e:
+ if e.errno == errno.ECHILD:
+ # we don't have any children, we're done
+ self.active_children.clear()
+ elif e.errno != errno.EINTR:
+ break
+
+ # Now reap all defunct children.
+ for pid in self.active_children.copy():
+ try:
+ pid, _ = os.waitpid(pid, os.WNOHANG)
+ # if the child hasn't exited yet, pid will be 0 and ignored by
+ # discard() below
+ self.active_children.discard(pid)
+ except OSError as e:
+ if e.errno == errno.ECHILD:
+ # someone else reaped it
+ self.active_children.discard(pid)
+
+ def handle_timeout(self):
+ """Wait for zombies after self.timeout seconds of inactivity.
+
+ May be extended, do not override.
+ """
+ self.collect_children()
+
+ def process_request(self, request, client_address):
+ """Fork a new subprocess to process the request."""
+ self.collect_children()
+ pid = os.fork()
+ if pid:
+ # Parent process
+ if self.active_children is None:
+ self.active_children = set()
+ self.active_children.add(pid)
+ self.close_request(request) #close handle in parent process
+ return
+ else:
+ # Child process.
+ # This must never return, hence os._exit()!
+ try:
+ self.finish_request(request, client_address)
+ self.shutdown_request(request)
+ os._exit(0)
+ except:
+ try:
+ self.handle_error(request, client_address)
+ self.shutdown_request(request)
+ finally:
+ os._exit(1)
+
+
+class ThreadingMixIn:
+ """Mix-in class to handle each request in a new thread."""
+
+ # Decides how threads will act upon termination of the
+ # main process
+ daemon_threads = False
+
+ def process_request_thread(self, request, client_address):
+ """Same as in BaseServer but as a thread.
+
+ In addition, exception handling is done here.
+
+ """
+ try:
+ self.finish_request(request, client_address)
+ self.shutdown_request(request)
+ except:
+ self.handle_error(request, client_address)
+ self.shutdown_request(request)
+
+ def process_request(self, request, client_address):
+ """Start a new thread to process the request."""
+ t = threading.Thread(target = self.process_request_thread,
+ args = (request, client_address))
+ t.daemon = self.daemon_threads
+ t.start()
+
+
+class ForkingUDPServer(ForkingMixIn, UDPServer): pass
+class ForkingTCPServer(ForkingMixIn, TCPServer): pass
+
+class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
+class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
+
+if hasattr(socket, 'AF_UNIX'):
+
+ class UnixStreamServer(TCPServer):
+ address_family = socket.AF_UNIX
+
+ class UnixDatagramServer(UDPServer):
+ address_family = socket.AF_UNIX
+
+ class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
+
+ class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
+
+class BaseRequestHandler:
+
+ """Base class for request handler classes.
+
+ This class is instantiated for each request to be handled. The
+ constructor sets the instance variables request, client_address
+ and server, and then calls the handle() method. To implement a
+ specific service, all you need to do is to derive a class which
+ defines a handle() method.
+
+ The handle() method can find the request as self.request, the
+ client address as self.client_address, and the server (in case it
+ needs access to per-server information) as self.server. Since a
+ separate instance is created for each request, the handle() method
+ can define arbitrary other instance variariables.
+
+ """
+
+ def __init__(self, request, client_address, server):
+ self.request = request
+ self.client_address = client_address
+ self.server = server
+ self.setup()
+ try:
+ self.handle()
+ finally:
+ self.finish()
+
+ def setup(self):
+ pass
+
+ def handle(self):
+ pass
+
+ def finish(self):
+ pass
+
+
+# The following two classes make it possible to use the same service
+# class for stream or datagram servers.
+# Each class sets up these instance variables:
+# - rfile: a file object from which receives the request is read
+# - wfile: a file object to which the reply is written
+# When the handle() method returns, wfile is flushed properly
+
+
+class StreamRequestHandler(BaseRequestHandler):
+
+ """Define self.rfile and self.wfile for stream sockets."""
+
+ # Default buffer sizes for rfile, wfile.
+ # We default rfile to buffered because otherwise it could be
+ # really slow for large data (a getc() call per byte); we make
+ # wfile unbuffered because (a) often after a write() we want to
+ # read and we need to flush the line; (b) big writes to unbuffered
+ # files are typically optimized by stdio even when big reads
+ # aren't.
+ rbufsize = -1
+ wbufsize = 0
+
+ # A timeout to apply to the request socket, if not None.
+ timeout = None
+
+ # Disable nagle algorithm for this socket, if True.
+ # Use only when wbufsize != 0, to avoid small packets.
+ disable_nagle_algorithm = False
+
+ def setup(self):
+ self.connection = self.request
+ if self.timeout is not None:
+ self.connection.settimeout(self.timeout)
+ if self.disable_nagle_algorithm:
+ self.connection.setsockopt(socket.IPPROTO_TCP,
+ socket.TCP_NODELAY, True)
+ self.rfile = self.connection.makefile('rb', self.rbufsize)
+ self.wfile = self.connection.makefile('wb', self.wbufsize)
+
+ def finish(self):
+ if not self.wfile.closed:
+ try:
+ self.wfile.flush()
+ except socket.error:
+ # An final socket error may have occurred here, such as
+ # the local error ECONNABORTED.
+ pass
+ self.wfile.close()
+ self.rfile.close()
+
+
+class DatagramRequestHandler(BaseRequestHandler):
+
+ # XXX Regrettably, I cannot get this working on Linux;
+ # s.recvfrom() doesn't return a meaningful client address.
+
+ """Define self.rfile and self.wfile for datagram sockets."""
+
+ def setup(self):
+ try:
+ from cStringIO import StringIO
+ except ImportError:
+ from StringIO import StringIO
+ self.packet, self.socket = self.request
+ self.rfile = StringIO(self.packet)
+ self.wfile = StringIO()
+
+ def finish(self):
+ self.socket.sendto(self.wfile.getvalue(), self.client_address)
Added: trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/StringIO.py
===================================================================
--- trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/StringIO.py
(rev 0)
+++ trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/StringIO.py
2015-11-07 19:33:58 UTC (rev 18740)
@@ -0,0 +1,324 @@
+r"""File-like objects that read from or write to a string buffer.
+
+This implements (nearly) all stdio methods.
+
+f = StringIO() # ready for writing
+f = StringIO(buf) # ready for reading
+f.close() # explicitly release resources held
+flag = f.isatty() # always false
+pos = f.tell() # get current position
+f.seek(pos) # set current position
+f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
+buf = f.read() # read until EOF
+buf = f.read(n) # read up to n bytes
+buf = f.readline() # read until end of line ('\n') or EOF
+list = f.readlines()# list of f.readline() results until EOF
+f.truncate([size]) # truncate file at to at most size (default: current pos)
+f.write(buf) # write at current position
+f.writelines(list) # for line in list: f.write(line)
+f.getvalue() # return whole file's contents as a string
+
+Notes:
+- Using a real file is often faster (but less convenient).
+- There's also a much faster implementation in C, called cStringIO, but
+ it's not subclassable.
+- fileno() is left unimplemented so that code which uses it triggers
+ an exception early.
+- Seeking far beyond EOF and then writing will insert real null
+ bytes that occupy space in the buffer.
+- There's a simple test set (see end of this file).
+"""
+try:
+ from errno import EINVAL
+except ImportError:
+ EINVAL = 22
+
+__all__ = ["StringIO"]
+
+def _complain_ifclosed(closed):
+ if closed:
+ raise ValueError, "I/O operation on closed file"
+
+class StringIO:
+ """class StringIO([buffer])
+
+ When a StringIO object is created, it can be initialized to an existing
+ string by passing the string to the constructor. If no string is given,
+ the StringIO will start empty.
+
+ The StringIO object can accept either Unicode or 8-bit strings, but
+ mixing the two may take some care. If both are used, 8-bit strings that
+ cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause
+ a UnicodeError to be raised when getvalue() is called.
+ """
+ def __init__(self, buf = ''):
+ # Force self.buf to be a string or unicode
+ if not isinstance(buf, basestring):
+ buf = str(buf)
+ self.buf = buf
+ self.len = len(buf)
+ self.buflist = []
+ self.pos = 0
+ self.closed = False
+ self.softspace = 0
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ """A file object is its own iterator, for example iter(f) returns f
+ (unless f is closed). When a file is used as an iterator, typically
+ in a for loop (for example, for line in f: print line), the next()
+ method is called repeatedly. This method returns the next input line,
+ or raises StopIteration when EOF is hit.
+ """
+ _complain_ifclosed(self.closed)
+ r = self.readline()
+ if not r:
+ raise StopIteration
+ return r
+
+ def close(self):
+ """Free the memory buffer.
+ """
+ if not self.closed:
+ self.closed = True
+ del self.buf, self.pos
+
+ def isatty(self):
+ """Returns False because StringIO objects are not connected to a
+ tty-like device.
+ """
+ _complain_ifclosed(self.closed)
+ return False
+
+ def seek(self, pos, mode = 0):
+ """Set the file's current position.
+
+ The mode argument is optional and defaults to 0 (absolute file
+ positioning); other values are 1 (seek relative to the current
+ position) and 2 (seek relative to the file's end).
+
+ There is no return value.
+ """
+ _complain_ifclosed(self.closed)
+ if self.buflist:
+ self.buf += ''.join(self.buflist)
+ self.buflist = []
+ if mode == 1:
+ pos += self.pos
+ elif mode == 2:
+ pos += self.len
+ self.pos = max(0, pos)
+
+ def tell(self):
+ """Return the file's current position."""
+ _complain_ifclosed(self.closed)
+ return self.pos
+
+ def read(self, n = -1):
+ """Read at most size bytes from the file
+ (less if the read hits EOF before obtaining size bytes).
+
+ If the size argument is negative or omitted, read all data until EOF
+ is reached. The bytes are returned as a string object. An empty
+ string is returned when EOF is encountered immediately.
+ """
+ _complain_ifclosed(self.closed)
+ if self.buflist:
+ self.buf += ''.join(self.buflist)
+ self.buflist = []
+ if n is None or n < 0:
+ newpos = self.len
+ else:
+ newpos = min(self.pos+n, self.len)
+ r = self.buf[self.pos:newpos]
+ self.pos = newpos
+ return r
+
+ def readline(self, length=None):
+ r"""Read one entire line from the file.
+
+ A trailing newline character is kept in the string (but may be absent
+ when a file ends with an incomplete line). If the size argument is
+ present and non-negative, it is a maximum byte count (including the
+ trailing newline) and an incomplete line may be returned.
+
+ An empty string is returned only when EOF is encountered immediately.
+
+ Note: Unlike stdio's fgets(), the returned string contains null
+ characters ('\0') if they occurred in the input.
+ """
+ _complain_ifclosed(self.closed)
+ if self.buflist:
+ self.buf += ''.join(self.buflist)
+ self.buflist = []
+ i = self.buf.find('\n', self.pos)
+ if i < 0:
+ newpos = self.len
+ else:
+ newpos = i+1
+ if length is not None and length >= 0:
+ if self.pos + length < newpos:
+ newpos = self.pos + length
+ r = self.buf[self.pos:newpos]
+ self.pos = newpos
+ return r
+
+ def readlines(self, sizehint = 0):
+ """Read until EOF using readline() and return a list containing the
+ lines thus read.
+
+ If the optional sizehint argument is present, instead of reading up
+ to EOF, whole lines totalling approximately sizehint bytes (or more
+ to accommodate a final whole line).
+ """
+ total = 0
+ lines = []
+ line = self.readline()
+ while line:
+ lines.append(line)
+ total += len(line)
+ if 0 < sizehint <= total:
+ break
+ line = self.readline()
+ return lines
+
+ def truncate(self, size=None):
+ """Truncate the file's size.
+
+ If the optional size argument is present, the file is truncated to
+ (at most) that size. The size defaults to the current position.
+ The current file position is not changed unless the position
+ is beyond the new file size.
+
+ If the specified size exceeds the file's current size, the
+ file remains unchanged.
+ """
+ _complain_ifclosed(self.closed)
+ if size is None:
+ size = self.pos
+ elif size < 0:
+ raise IOError(EINVAL, "Negative size not allowed")
+ elif size < self.pos:
+ self.pos = size
+ self.buf = self.getvalue()[:size]
+ self.len = size
+
+ def write(self, s):
+ """Write a string to the file.
+
+ There is no return value.
+ """
+ _complain_ifclosed(self.closed)
+ if not s: return
+ # Force s to be a string or unicode
+ if not isinstance(s, basestring):
+ s = str(s)
+ spos = self.pos
+ slen = self.len
+ if spos == slen:
+ self.buflist.append(s)
+ self.len = self.pos = spos + len(s)
+ return
+ if spos > slen:
+ self.buflist.append('\0'*(spos - slen))
+ slen = spos
+ newpos = spos + len(s)
+ if spos < slen:
+ if self.buflist:
+ self.buf += ''.join(self.buflist)
+ self.buflist = [self.buf[:spos], s, self.buf[newpos:]]
+ self.buf = ''
+ if newpos > slen:
+ slen = newpos
+ else:
+ self.buflist.append(s)
+ slen = newpos
+ self.len = slen
+ self.pos = newpos
+
+ def writelines(self, iterable):
+ """Write a sequence of strings to the file. The sequence can be any
+ iterable object producing strings, typically a list of strings. There
+ is no return value.
+
+ (The name is intended to match readlines(); writelines() does not add
+ line separators.)
+ """
+ write = self.write
+ for line in iterable:
+ write(line)
+
+ def flush(self):
+ """Flush the internal buffer
+ """
+ _complain_ifclosed(self.closed)
+
+ def getvalue(self):
+ """
+ Retrieve the entire contents of the "file" at any time before
+ the StringIO object's close() method is called.
+
+ The StringIO object can accept either Unicode or 8-bit strings,
+ but mixing the two may take some care. If both are used, 8-bit
+ strings that cannot be interpreted as 7-bit ASCII (that use the
+ 8th bit) will cause a UnicodeError to be raised when getvalue()
+ is called.
+ """
+ _complain_ifclosed(self.closed)
+ if self.buflist:
+ self.buf += ''.join(self.buflist)
+ self.buflist = []
+ return self.buf
+
+
+# A little test suite
+
+def test():
+ import sys
+ if sys.argv[1:]:
+ file = sys.argv[1]
+ else:
+ file = '/etc/passwd'
+ lines = open(file, 'r').readlines()
+ text = open(file, 'r').read()
+ f = StringIO()
+ for line in lines[:-2]:
+ f.write(line)
+ f.writelines(lines[-2:])
+ if f.getvalue() != text:
+ raise RuntimeError, 'write failed'
+ length = f.tell()
+ print 'File length =', length
+ f.seek(len(lines[0]))
+ f.write(lines[1])
+ f.seek(0)
+ print 'First line =', repr(f.readline())
+ print 'Position =', f.tell()
+ line = f.readline()
+ print 'Second line =', repr(line)
+ f.seek(-len(line), 1)
+ line2 = f.read(len(line))
+ if line != line2:
+ raise RuntimeError, 'bad result after seek back'
+ f.seek(len(line2), 1)
+ list = f.readlines()
+ line = list[-1]
+ f.seek(f.tell() - len(line))
+ line2 = f.read()
+ if line != line2:
+ raise RuntimeError, 'bad result after seek back from EOF'
+ print 'Read', len(list), 'more lines'
+ print 'File length =', f.tell()
+ if f.tell() != length:
+ raise RuntimeError, 'bad length'
+ f.truncate(length/2)
+ f.seek(0, 2)
+ print 'Truncated length =', f.tell()
+ if f.tell() != length/2:
+ raise RuntimeError, 'truncate did not adjust length'
+ f.close()
+
+if __name__ == '__main__':
+ test()
Added: trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/UserDict.py
===================================================================
--- trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/UserDict.py
(rev 0)
+++ trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/UserDict.py
2015-11-07 19:33:58 UTC (rev 18740)
@@ -0,0 +1,180 @@
+"""A more or less complete user-defined wrapper around dictionary objects."""
+
+class UserDict:
+ def __init__(self, dict=None, **kwargs):
+ self.data = {}
+ if dict is not None:
+ self.update(dict)
+ if len(kwargs):
+ self.update(kwargs)
+ def __repr__(self): return repr(self.data)
+ def __cmp__(self, dict):
+ if isinstance(dict, UserDict):
+ return cmp(self.data, dict.data)
+ else:
+ return cmp(self.data, dict)
+ __hash__ = None # Avoid Py3k warning
+ def __len__(self): return len(self.data)
+ def __getitem__(self, key):
+ if key in self.data:
+ return self.data[key]
+ if hasattr(self.__class__, "__missing__"):
+ return self.__class__.__missing__(self, key)
+ raise KeyError(key)
+ def __setitem__(self, key, item): self.data[key] = item
+ def __delitem__(self, key): del self.data[key]
+ def clear(self): self.data.clear()
+ def copy(self):
+ if self.__class__ is UserDict:
+ return UserDict(self.data.copy())
+ import copy
+ data = self.data
+ try:
+ self.data = {}
+ c = copy.copy(self)
+ finally:
+ self.data = data
+ c.update(self)
+ return c
+ def keys(self): return self.data.keys()
+ def items(self): return self.data.items()
+ def iteritems(self): return self.data.iteritems()
+ def iterkeys(self): return self.data.iterkeys()
+ def itervalues(self): return self.data.itervalues()
+ def values(self): return self.data.values()
+ def has_key(self, key): return key in self.data
+ def update(self, dict=None, **kwargs):
+ if dict is None:
+ pass
+ elif isinstance(dict, UserDict):
+ self.data.update(dict.data)
+ elif isinstance(dict, type({})) or not hasattr(dict, 'items'):
+ self.data.update(dict)
+ else:
+ for k, v in dict.items():
+ self[k] = v
+ if len(kwargs):
+ self.data.update(kwargs)
+ def get(self, key, failobj=None):
+ if key not in self:
+ return failobj
+ return self[key]
+ def setdefault(self, key, failobj=None):
+ if key not in self:
+ self[key] = failobj
+ return self[key]
+ def pop(self, key, *args):
+ return self.data.pop(key, *args)
+ def popitem(self):
+ return self.data.popitem()
+ def __contains__(self, key):
+ return key in self.data
+ @classmethod
+ def fromkeys(cls, iterable, value=None):
+ d = cls()
+ for key in iterable:
+ d[key] = value
+ return d
+
+class IterableUserDict(UserDict):
+ def __iter__(self):
+ return iter(self.data)
+
+import _abcoll
+_abcoll.MutableMapping.register(IterableUserDict)
+
+
+class DictMixin:
+ # Mixin defining all dictionary methods for classes that already have
+ # a minimum dictionary interface including getitem, setitem, delitem,
+ # and keys. Without knowledge of the subclass constructor, the mixin
+ # does not define __init__() or copy(). In addition to the four base
+ # methods, progressively more efficiency comes with defining
+ # __contains__(), __iter__(), and iteritems().
+
+ # second level definitions support higher levels
+ def __iter__(self):
+ for k in self.keys():
+ yield k
+ def has_key(self, key):
+ try:
+ self[key]
+ except KeyError:
+ return False
+ return True
+ def __contains__(self, key):
+ return self.has_key(key)
+
+ # third level takes advantage of second level definitions
+ def iteritems(self):
+ for k in self:
+ yield (k, self[k])
+ def iterkeys(self):
+ return self.__iter__()
+
+ # fourth level uses definitions from lower levels
+ def itervalues(self):
+ for _, v in self.iteritems():
+ yield v
+ def values(self):
+ return [v for _, v in self.iteritems()]
+ def items(self):
+ return list(self.iteritems())
+ def clear(self):
+ for key in self.keys():
+ del self[key]
+ def setdefault(self, key, default=None):
+ try:
+ return self[key]
+ except KeyError:
+ self[key] = default
+ return default
+ def pop(self, key, *args):
+ if len(args) > 1:
+ raise TypeError, "pop expected at most 2 arguments, got "\
+ + repr(1 + len(args))
+ try:
+ value = self[key]
+ except KeyError:
+ if args:
+ return args[0]
+ raise
+ del self[key]
+ return value
+ def popitem(self):
+ try:
+ k, v = self.iteritems().next()
+ except StopIteration:
+ raise KeyError, 'container is empty'
+ del self[k]
+ return (k, v)
+ def update(self, other=None, **kwargs):
+ # Make progressively weaker assumptions about "other"
+ if other is None:
+ pass
+ elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups
+ for k, v in other.iteritems():
+ self[k] = v
+ elif hasattr(other, 'keys'):
+ for k in other.keys():
+ self[k] = other[k]
+ else:
+ for k, v in other:
+ self[k] = v
+ if kwargs:
+ self.update(kwargs)
+ def get(self, key, default=None):
+ try:
+ return self[key]
+ except KeyError:
+ return default
+ def __repr__(self):
+ return repr(dict(self.iteritems()))
+ def __cmp__(self, other):
+ if other is None:
+ return 1
+ if isinstance(other, DictMixin):
+ other = dict(other.iteritems())
+ return cmp(dict(self.iteritems()), other)
+ def __len__(self):
+ return len(self.keys())
Added: trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/_abcoll.py
===================================================================
--- trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/_abcoll.py
(rev 0)
+++ trunk/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/_abcoll.py
2015-11-07 19:33:58 UTC (rev 18740)
@@ -0,0 +1,692 @@
+# Copyright 2007 Google, Inc. All Rights Reserved.
+# Licensed to PSF under a Contributor Agreement.
+
+"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
+
+DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
+via collections; they are defined here only to alleviate certain
+bootstrapping issues. Unit tests are in test_collections.
+"""
+
+from abc import ABCMeta, abstractmethod
+import sys
+
+__all__ = ["Hashable", "Iterable", "Iterator",
+ "Sized", "Container", "Callable",
+ "Set", "MutableSet",
+ "Mapping", "MutableMapping",
+ "MappingView", "KeysView", "ItemsView", "ValuesView",
+ "Sequence", "MutableSequence",
+ ]
+
+### ONE-TRICK PONIES ###
+
+def _hasattr(C, attr):
+ try:
+ return any(attr in B.__dict__ for B in C.__mro__)
+ except AttributeError:
+ # Old-style class
+ return hasattr(C, attr)
+
+
+class Hashable:
+ __metaclass__ = ABCMeta
+
+ @abstractmethod
+ def __hash__(self):
+ return 0
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Hashable:
+ try:
+ for B in C.__mro__:
+ if "__hash__" in B.__dict__:
+ if B.__dict__["__hash__"]:
+ return True
+ break
+ except AttributeError:
+ # Old-style class
+ if getattr(C, "__hash__", None):
+ return True
+ return NotImplemented
+
+
+class Iterable:
+ __metaclass__ = ABCMeta
+
+ @abstractmethod
+ def __iter__(self):
+ while False:
+ yield None
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Iterable:
+ if _hasattr(C, "__iter__"):
+ return True
+ return NotImplemented
+
+Iterable.register(str)
+
+
+class Iterator(Iterable):
+
+ @abstractmethod
+ def next(self):
+ 'Return the next item from the iterator. When exhausted, raise
StopIteration'
+ raise StopIteration
+
+ def __iter__(self):
+ return self
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Iterator:
+ if _hasattr(C, "next") and _hasattr(C, "__iter__"):
+ return True
+ return NotImplemented
+
+
+class Sized:
+ __metaclass__ = ABCMeta
+
+ @abstractmethod
+ def __len__(self):
+ return 0
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Sized:
+ if _hasattr(C, "__len__"):
+ return True
+ return NotImplemented
+
+
+class Container:
+ __metaclass__ = ABCMeta
+
+ @abstractmethod
+ def __contains__(self, x):
+ return False
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Container:
+ if _hasattr(C, "__contains__"):
+ return True
+ return NotImplemented
+
+
+class Callable:
+ __metaclass__ = ABCMeta
+
+ @abstractmethod
+ def __call__(self, *args, **kwds):
+ return False
+
+ @classmethod
+ def __subclasshook__(cls, C):
+ if cls is Callable:
+ if _hasattr(C, "__call__"):
+ return True
+ return NotImplemented
+
+
+### SETS ###
+
+
+class Set(Sized, Iterable, Container):
+ """A set is a finite, iterable container.
+
+ This class provides concrete generic implementations of all
+ methods except for __contains__, __iter__ and __len__.
+
+ To override the comparisons (presumably for speed, as the
+ semantics are fixed), redefine __le__ and __ge__,
+ then the other operations will automatically follow suit.
+ """
+
+ def __le__(self, other):
+ if not isinstance(other, Set):
+ return NotImplemented
+ if len(self) > len(other):
+ return False
+ for elem in self:
+ if elem not in other:
+ return False
+ return True
+
+ def __lt__(self, other):
+ if not isinstance(other, Set):
+ return NotImplemented
+ return len(self) < len(other) and self.__le__(other)
+
+ def __gt__(self, other):
+ if not isinstance(other, Set):
+ return NotImplemented
+ return len(self) > len(other) and self.__ge__(other)
+
+ def __ge__(self, other):
+ if not isinstance(other, Set):
+ return NotImplemented
+ if len(self) < len(other):
+ return False
+ for elem in other:
+ if elem not in self:
+ return False
+ return True
+
+ def __eq__(self, other):
+ if not isinstance(other, Set):
+ return NotImplemented
+ return len(self) == len(other) and self.__le__(other)
+
+ def __ne__(self, other):
+ return not (self == other)
+
+ @classmethod
+ def _from_iterable(cls, it):
+ '''Construct an instance of the class from any iterable input.
+
+ Must override this method if the class constructor signature
+ does not accept an iterable for an input.
+ '''
+ return cls(it)
+
+ def __and__(self, other):
+ if not isinstance(other, Iterable):
+ return NotImplemented
+ return self._from_iterable(value for value in other if value in self)
+
+ __rand__ = __and__
+
+ def isdisjoint(self, other):
+ 'Return True if two sets have a null intersection.'
+ for value in other:
+ if value in self:
+ return False
+ return True
+
+ def __or__(self, other):
+ if not isinstance(other, Iterable):
+ return NotImplemented
+ chain = (e for s in (self, other) for e in s)
+ return self._from_iterable(chain)
+
+ __ror__ = __or__
+
+ def __sub__(self, other):
+ if not isinstance(other, Set):
+ if not isinstance(other, Iterable):
+ return NotImplemented
+ other = self._from_iterable(other)
+ return self._from_iterable(value for value in self
+ if value not in other)
+
+ def __rsub__(self, other):
+ if not isinstance(other, Set):
+ if not isinstance(other, Iterable):
+ return NotImplemented
+ other = self._from_iterable(other)
+ return self._from_iterable(value for value in other
+ if value not in self)
+
+ def __xor__(self, other):
+ if not isinstance(other, Set):
+ if not isinstance(other, Iterable):
+ return NotImplemented
+ other = self._from_iterable(other)
+ return (self - other) | (other - self)
+
+ __rxor__ = __xor__
+
+ # Sets are not hashable by default, but subclasses can change this
+ __hash__ = None
+
+ def _hash(self):
+ """Compute the hash value of a set.
+
+ Note that we don't define __hash__: not all sets are hashable.
+ But if you define a hashable set type, its __hash__ should
+ call this function.
+
+ This must be compatible __eq__.
+
+ All sets ought to compare equal if they contain the same
+ elements, regardless of how they are implemented, and
+ regardless of the order of the elements; so there's not much
+ freedom for __eq__ or __hash__. We match the algorithm used
+ by the built-in frozenset type.
+ """
+ MAX = sys.maxint
+ MASK = 2 * MAX + 1
+ n = len(self)
+ h = 1927868237 * (n + 1)
+ h &= MASK
+ for x in self:
+ hx = hash(x)
+ h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
+ h &= MASK
+ h = h * 69069 + 907133923
+ h &= MASK
+ if h > MAX:
+ h -= MASK + 1
+ if h == -1:
+ h = 590923713
+ return h
+
+Set.register(frozenset)
+
+
+class MutableSet(Set):
+ """A mutable set is a finite, iterable container.
+
+ This class provides concrete generic implementations of all
+ methods except for __contains__, __iter__, __len__,
+ add(), and discard().
+
+ To override the comparisons (presumably for speed, as the
+ semantics are fixed), all you have to do is redefine __le__ and
+ then the other operations will automatically follow suit.
+ """
+
+ @abstractmethod
+ def add(self, value):
+ """Add an element."""
+ raise NotImplementedError
+
+ @abstractmethod
+ def discard(self, value):
+ """Remove an element. Do not raise an exception if absent."""
+ raise NotImplementedError
+
+ def remove(self, value):
+ """Remove an element. If not a member, raise a KeyError."""
+ if value not in self:
+ raise KeyError(value)
+ self.discard(value)
+
+ def pop(self):
+ """Return the popped value. Raise KeyError if empty."""
+ it = iter(self)
+ try:
+ value = next(it)
+ except StopIteration:
+ raise KeyError
+ self.discard(value)
+ return value
+
+ def clear(self):
+ """This is slow (creates N new iterators!) but effective."""
+ try:
+ while True:
+ self.pop()
+ except KeyError:
+ pass
+
+ def __ior__(self, it):
+ for value in it:
+ self.add(value)
+ return self
+
+ def __iand__(self, it):
+ for value in (self - it):
+ self.discard(value)
+ return self
+
+ def __ixor__(self, it):
+ if it is self:
+ self.clear()
+ else:
@@ Diff output truncated at 100000 characters. @@
------------------------------------------------------------------------------
_______________________________________________
edk2-commits mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/edk2-commits