summaryrefslogtreecommitdiffstats
path: root/AppPkg/Applications/Python/Python-2.7.2/Tools
diff options
context:
space:
mode:
Diffstat (limited to 'AppPkg/Applications/Python/Python-2.7.2/Tools')
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/README41
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/README9
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgen.py12
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenBuffer.py301
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGenerator.py302
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGeneratorGroup.py40
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenHeapBuffer.py145
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenModule.py94
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenObjectDefinition.py512
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenOutput.py219
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStackBuffer.py62
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStringBuffer.py67
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenType.py328
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenVariable.py112
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/macsupport.py197
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/scantools.py849
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/README.tcltk-AMD6436
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build-amd64.bat6
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build.bat7
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/buildmsi.bat20
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean-amd64.bat10
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean.bat10
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-amd64.bat20
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-common.bat45
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external.bat21
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test-amd64.bat3
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test.bat3
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/ccbench/ccbench.py609
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ACKS8
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/README18
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ast.txt104
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/astgen.py294
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/compile.py51
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py38
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/dumppyc.py46
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/regrtest.py78
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/stacktest.py43
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/README114
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqconf.py577
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqcust.py1
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqw.py33
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqwiz.py841
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/move-faqwiz.sh55
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/README.txt8
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/TODO.txt6
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/example.py126
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/__init__.py6
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/bases.py220
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/function.py173
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/member.py73
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/slots.py64
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/struct.py52
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/structparse.py46
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/template.py102
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/util.py35
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/README296
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/bkfile.py47
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions.py90
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions_win32.py188
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/extensions_win32.ini171
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/freeze.py497
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/hello.py1
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makeconfig.py60
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makefreeze.py90
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makemakefile.py29
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/parsesetup.py112
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/win32.html119
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/winmakemakefile.py147
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/gdb/libpython.py1447
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/makelocalealias.py73
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/msgfmt.py226
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/pygettext.py669
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/iobench/iobench.py539
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/README.txt25
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/crtlicense.txt44
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msi.py1398
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msilib.py692
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.c93
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.mak9
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/schema.py1007
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/sequence.py126
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uisample.py1400
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uuids.py58
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Arithmetic.py777
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Calls.py560
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/CommandLine.py634
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Constructs.py564
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Dict.py504
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Exceptions.py699
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Imports.py138
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Instances.py66
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/LICENSE25
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lists.py350
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lookups.py945
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/NewInstances.py75
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Numbers.py784
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/README368
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Setup.py43
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Strings.py562
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Tuples.py360
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Unicode.py542
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/With.py190
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/clockres.py43
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/__init__.py0
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/submodule.py0
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/pybench.py961
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/systimes.py211
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/2to35
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/README69
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/analyze_dxp.py129
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byext.py131
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byteyears.py61
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkappend.py167
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkpyc.py66
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/classfix.py190
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cleanfuture.py276
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/combinerefs.py127
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/copytime.py26
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/crlf.py23
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cvsfiles.py72
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/db2pickle.py135
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/diff.py49
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.doc54
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.py60
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/eptags.py56
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/find_recursionlimit.py117
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/finddiv.py89
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findlinksto.py43
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findnocoding.py104
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixcid.py314
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixdiv.py380
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixheader.py49
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixnotice.py113
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixps.py33
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ftpmirror.py400
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/google.py23
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/gprof2html.py79
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/h2py.py175
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/hotshotmain.py55
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/idle5
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ifdef.py112
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lfcr.py24
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/linktree.py80
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lll.py28
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/logmerge.py185
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mailerdaemon.py237
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/md5sum.py90
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/methfix.py171
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mkreal.py66
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ndiff.py133
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/nm2def.py103
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/objgraph.py215
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/parseentities.py64
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/patchcheck.py158
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pathfix.py149
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pdeps.py167
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pickle2db.py147
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pindent.py542
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ptags.py53
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydoc5
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydocgui.pyw7
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pysource.py130
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/redemo.py171
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent-rst.py14
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent.py304
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/rgrep.py64
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/serve.py35
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/setup.py20
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/suff.py30
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/svneol.py91
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texcheck.py233
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texi2html.py2078
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/treesync.py205
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/untabify.py52
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/which.py60
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/win_add2path.py57
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/xxci.py116
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/ssl/get-remote-certificate.py79
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/Makefile84
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/comparecodecs.py53
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencjkcodecs.py68
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencodec.py423
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodec.py61
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodecs.bat7
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/listcodecs.py41
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/makeunicodedata.py1135
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/mkstringprep.py425
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/CP1140.TXT291
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/KOI8-U.TXT298
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/TIS-620.TXT284
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/README41
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/_checkversion.py16
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/checkversions.py52
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/pyversioncheck.py98
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/README23
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/tktools.py366
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcgui.py456
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcmac.py7
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/webchecker.py892
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/websucker.py123
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wsgui.py240
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/world/README85
-rw-r--r--AppPkg/Applications/Python/Python-2.7.2/Tools/world/world551
203 files changed, 42616 insertions, 0 deletions
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/README
new file mode 100644
index 0000000000..619786adab
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/README
@@ -0,0 +1,41 @@
+This directory contains a number of Python programs that are useful
+while building or extending Python.
+
+bgen Generate complete extension modules from a
+ description. Still under development!
+ WARNING: bgen has been removed in 3.0.
+
+compiler Tools used to maintain the compiler package in the
+ standard library.
+
+faqwiz FAQ Wizard.
+ See http://www.python.org/cgi-bin/faqw.py
+ for a live example.
+
+freeze Create a stand-alone executable from a Python program.
+
+gdb Python code to be run inside gdb, to make it easier to
+ debug Python itself (by David Malcolm).
+
+i18n Tools for internationalization. pygettext.py
+ parses Python source code and generates .pot files,
+ and msgfmt.py generates a binary message catalog
+ from a catalog in text format.
+
+scripts A number of useful single-file programs, e.g. tabnanny.py
+ by Tim Peters, which checks for inconsistent mixing of
+ tabs and spaces, and 2to3, which converts Python 2 code
+ to Python 3 code.
+
+unicode Tools used to generate unicode database files for
+ Python 2.0 (by Fredrik Lundh).
+
+versioncheck A tool to automate checking whether you have the latest
+ version of a package (by Jack Jansen).
+
+webchecker A link checker for web sites.
+
+world Script to take a list of Internet addresses and print
+ out where in the world those addresses originate from,
+ based on the top-level domain country code found in
+ the address.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/README
new file mode 100644
index 0000000000..b69ba7168e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/README
@@ -0,0 +1,9 @@
+BGEN -- Automatic Generation of Extension Modules
+=================================================
+
+This directory contains BGEN -- a package that helps in generating
+complete source code for Python extension module. For examples of its
+use, see the Mac Python source distribution (available separately
+from the Python ftp archives). Note that BGEN is not Mac specific!
+
+WARNING: bgen has been removed in 3.0.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgen.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgen.py
new file mode 100644
index 0000000000..4b63ceb5fc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgen.py
@@ -0,0 +1,12 @@
+"Export everything in the various bgen submodules."
+
+from bgenType import *
+from bgenVariable import *
+from bgenBuffer import *
+from bgenStackBuffer import *
+from bgenHeapBuffer import *
+from bgenStringBuffer import *
+from bgenOutput import *
+from bgenGenerator import *
+from bgenModule import *
+from bgenObjectDefinition import *
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenBuffer.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenBuffer.py
new file mode 100644
index 0000000000..376dac04b1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenBuffer.py
@@ -0,0 +1,301 @@
+"""Buffers are character arrays that may contain null bytes.
+
+There are a number of variants depending on:
+- how the buffer is allocated (for output buffers), and
+- whether and how the size is passed into and/or out of the called function.
+"""
+
+
+from bgenType import Type, InputOnlyMixIn, OutputOnlyMixIn, InputOnlyType, OutputOnlyType
+from bgenOutput import *
+
+
+# Map common types to their format characters
+type2format = {
+ 'long': 'l',
+ 'int': 'i',
+ 'short': 'h',
+ 'char': 'b',
+ 'unsigned long': 'l',
+ 'unsigned int': 'i',
+ 'unsigned short': 'h',
+ 'unsigned char': 'b',
+}
+
+
+# ----- PART 1: Fixed character buffers -----
+
+
+class FixedInputOutputBufferType(InputOnlyType):
+
+ """Fixed buffer -- passed as (inbuffer, outbuffer)."""
+
+ def __init__(self, size, datatype = 'char', sizetype = 'int', sizeformat = None):
+ self.typeName = "Buffer"
+ self.size = str(size)
+ self.datatype = datatype
+ self.sizetype = sizetype
+ self.sizeformat = sizeformat or type2format[sizetype]
+ self.label_needed = 0
+
+ def getArgDeclarations(self, name, reference=False, constmode=False, outmode=False):
+ if reference:
+ raise RuntimeError, "Cannot pass buffer types by reference"
+ return (self.getBufferDeclarations(name, constmode, outmode) +
+ self.getSizeDeclarations(name, outmode))
+
+ def getBufferDeclarations(self, name, constmode=False, outmode=False):
+ return self.getInputBufferDeclarations(name, constmode) + \
+ self.getOutputBufferDeclarations(name, constmode, outmode)
+
+ def getInputBufferDeclarations(self, name, constmode=False):
+ if constmode:
+ const = "const "
+ else:
+ const = ""
+ return ["%s%s *%s__in__" % (const, self.datatype, name)]
+
+ def getOutputBufferDeclarations(self, name, constmode=False, outmode=False):
+ if constmode:
+ raise RuntimeError, "Cannot use const output buffer"
+ if outmode:
+ out = "*"
+ else:
+ out = ""
+ return ["%s%s %s__out__[%s]" % (self.datatype, out, name, self.size)]
+
+ def getSizeDeclarations(self, name, outmode=False):
+ if outmode:
+ out = "*"
+ else:
+ out = ""
+ return ["%s%s %s__len__" %(self.sizetype, out, name)]
+
+ def getAuxDeclarations(self, name):
+ return ["int %s__in_len__" %(name)]
+
+ def getargsFormat(self):
+ return "s#"
+
+ def getargsArgs(self, name):
+ return "&%s__in__, &%s__in_len__" % (name, name)
+
+ def getargsCheck(self, name):
+ Output("if (%s__in_len__ != %s)", name, self.size)
+ OutLbrace()
+ Output('PyErr_SetString(PyExc_TypeError, "buffer length should be %s");',
+ self.size)
+ Output("goto %s__error__;", name)
+ self.label_needed = 1
+ OutRbrace()
+ self.transferSize(name)
+
+ def transferSize(self, name):
+ Output("%s__len__ = %s__in_len__;", name, name)
+
+ def passOutput(self, name):
+ return "%s__in__, %s__out__" % (name, name)
+
+ def mkvalueFormat(self):
+ return "s#"
+
+ def mkvalueArgs(self, name):
+ return "%s__out__, (int)%s" % (name, self.size)
+
+ def cleanup(self, name):
+ if self.label_needed:
+ DedentLevel()
+ Output(" %s__error__: ;", name)
+ IndentLevel()
+
+
+class FixedCombinedInputOutputBufferType(FixedInputOutputBufferType):
+
+ """Like fixed buffer -- but same parameter is input and output."""
+
+ def passOutput(self, name):
+ return "(%s *)memcpy(%s__out__, %s__in__, %s)" % \
+ (self.datatype, name, name, self.size)
+
+
+class InputOnlyBufferMixIn(InputOnlyMixIn):
+
+ def getOutputBufferDeclarations(self, name, constmode=False, outmode=False):
+ return []
+
+
+class OutputOnlyBufferMixIn(OutputOnlyMixIn):
+
+ def getInputBufferDeclarations(self, name, constmode=False):
+ return []
+
+class OptionalInputBufferMixIn:
+
+ """Add to input buffers if the buffer may be omitted: pass None in Python
+ and the C code will get a NULL pointer and zero size"""
+
+ def getargsFormat(self):
+ return "z#"
+
+
+class FixedInputBufferType(InputOnlyBufferMixIn, FixedInputOutputBufferType):
+
+ """Fixed size input buffer -- passed without size information.
+
+ Instantiate with the size as parameter.
+ """
+
+ def passInput(self, name):
+ return "%s__in__" % name
+
+class OptionalFixedInputBufferType(OptionalInputBufferMixIn, FixedInputBufferType):
+ pass
+
+class FixedOutputBufferType(OutputOnlyBufferMixIn, FixedInputOutputBufferType):
+
+ """Fixed size output buffer -- passed without size information.
+
+ Instantiate with the size as parameter.
+ """
+
+ def passOutput(self, name):
+ return "%s__out__" % name
+
+
+class VarInputBufferType(FixedInputBufferType):
+
+ """Variable size input buffer -- passed as (buffer, size).
+
+ Instantiate without size parameter.
+ """
+
+ def __init__(self, datatype = 'char', sizetype = 'int', sizeformat = None):
+ FixedInputBufferType.__init__(self, "0", datatype, sizetype, sizeformat)
+
+ def getargsCheck(self, name):
+ Output("%s__len__ = %s__in_len__;", name, name)
+
+ def passInput(self, name):
+ return "%s__in__, %s__len__" % (name, name)
+
+class ReverseInputBufferMixin:
+ """ Mixin for input buffers that are passed as (size, buffer) """
+
+ def passInput(self, name):
+ return "%s__len__, %s__in__" % (name, name)
+
+class OptionalVarInputBufferType(OptionalInputBufferMixIn, VarInputBufferType):
+ pass
+
+# ----- PART 2: Structure buffers -----
+
+
+class StructInputOutputBufferType(FixedInputOutputBufferType):
+
+ """Structure buffer -- passed as a structure pointer.
+
+ Instantiate with the struct type as parameter.
+ """
+
+ def __init__(self, type):
+ FixedInputOutputBufferType.__init__(self, "sizeof(%s)" % type)
+ self.typeName = self.type = type
+
+ def getInputBufferDeclarations(self, name, constmode=False):
+ if constmode:
+ const = "const "
+ else:
+ const = ""
+ return ["%s%s *%s__in__" % (const, self.type, name)]
+
+ def getSizeDeclarations(self, name, outmode=False):
+ return []
+
+ def getAuxDeclarations(self, name):
+ return ["int %s__in_len__" % (name)]
+
+ def getOutputBufferDeclarations(self, name, constmode=False, outmode=False):
+ if constmode:
+ raise RuntimeError, "Cannot use const output buffer"
+ if outmode:
+ out = "*"
+ else:
+ out = ""
+ return ["%s%s %s__out__" % (self.type, out, name)]
+
+ def getargsArgs(self, name):
+ return "(char **)&%s__in__, &%s__in_len__" % (name, name)
+
+ def transferSize(self, name):
+ pass
+
+ def passInput(self, name):
+ return "%s__in__" % name
+
+ def passOutput(self, name):
+ return "%s__in__, &%s__out__" % (name, name)
+
+ def mkvalueArgs(self, name):
+ return "(char *)&%s__out__, (int)%s" % (name, self.size)
+
+
+class StructCombinedInputOutputBufferType(StructInputOutputBufferType):
+
+ """Like structure buffer -- but same parameter is input and output."""
+
+ def passOutput(self, name):
+ return "(%s *)memcpy((char *)%s__out__, (char *)%s__in__, %s)" % \
+ (self.type, name, name, self.size)
+
+
+class StructInputBufferType(InputOnlyBufferMixIn, StructInputOutputBufferType):
+
+ """Fixed size input buffer -- passed as a pointer to a structure.
+
+ Instantiate with the struct type as parameter.
+ """
+
+
+class StructByValueBufferType(StructInputBufferType):
+
+ """Fixed size input buffer -- passed as a structure BY VALUE.
+
+ Instantiate with the struct type as parameter.
+ """
+
+ def passInput(self, name):
+ return "*%s__in__" % name
+
+
+class StructOutputBufferType(OutputOnlyBufferMixIn, StructInputOutputBufferType):
+
+ """Fixed size output buffer -- passed as a pointer to a structure.
+
+ Instantiate with the struct type as parameter.
+ """
+
+ def getSizeDeclarations(self, name, outmode=False):
+ return []
+
+ def getAuxDeclarations(self, name):
+ return []
+
+ def passOutput(self, name):
+ return "&%s__out__" % name
+
+
+class ArrayOutputBufferType(OutputOnlyBufferMixIn, StructInputOutputBufferType):
+
+ """Fixed size output buffer -- declared as a typedef, passed as an array.
+
+ Instantiate with the struct type as parameter.
+ """
+
+ def getSizeDeclarations(self, name, outmode=False):
+ return []
+
+ def getAuxDeclarations(self, name):
+ return []
+
+ def passOutput(self, name):
+ return "%s__out__" % name
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGenerator.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGenerator.py
new file mode 100644
index 0000000000..af8e904bc9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGenerator.py
@@ -0,0 +1,302 @@
+from bgenOutput import *
+from bgenType import *
+from bgenVariable import *
+
+
+Error = "bgenGenerator.Error"
+
+DEBUG=0
+
+# Strings to specify argument transfer modes in generator calls
+IN = "in"
+OUT = "out"
+INOUT = IN_OUT = "in-out"
+
+
+class BaseFunctionGenerator:
+
+ def __init__(self, name, condition=None, callname=None, modifiers=None):
+ if DEBUG: print "<--", name
+ self.name = name
+ if callname:
+ self.callname = callname
+ else:
+ self.callname = name
+ self.prefix = name
+ self.objecttype = "PyObject" # Type of _self argument to function
+ self.condition = condition
+ self.modifiers = modifiers
+
+ def setprefix(self, prefix):
+ self.prefix = prefix
+
+ def checkgenerate(self):
+ return True
+
+ def generate(self):
+ if not self.checkgenerate():
+ return
+ if DEBUG: print "-->", self.name
+ if self.condition:
+ Output()
+ Output(self.condition)
+ self.functionheader()
+ self.functionbody()
+ self.functiontrailer()
+ if self.condition:
+ Output("#endif")
+
+ def functionheader(self):
+ Output()
+ Output("static PyObject *%s_%s(%s *_self, PyObject *_args)",
+ self.prefix, self.name, self.objecttype)
+ OutLbrace()
+ Output("PyObject *_res = NULL;")
+
+ def functionbody(self):
+ Output("/* XXX To be provided */")
+
+ def functiontrailer(self):
+ OutRbrace()
+
+ def reference(self, name = None):
+ if not self.checkgenerate():
+ return
+ if name is None:
+ name = self.name
+ docstring = self.docstring()
+ if self.condition:
+ Output()
+ Output(self.condition)
+ Output("{\"%s\", (PyCFunction)%s_%s, 1,", name, self.prefix, self.name)
+ Output(" PyDoc_STR(%s)},", stringify(docstring))
+ if self.condition:
+ Output("#endif")
+
+ def docstring(self):
+ return None
+
+ def __cmp__(self, other):
+ if not hasattr(other, 'name'):
+ return cmp(id(self), id(other))
+ return cmp(self.name, other.name)
+
+_stringify_map = {'\n': '\\n', '\t': '\\t', '\r': '\\r', '\b': '\\b',
+ '\e': '\\e', '\a': '\\a', '\f': '\\f', '"': '\\"'}
+def stringify(str):
+ if str is None: return "NULL"
+ res = '"'
+ map = _stringify_map
+ for c in str:
+ if map.has_key(c): res = res + map[c]
+ elif ' ' <= c <= '~': res = res + c
+ else: res = res + '\\%03o' % ord(c)
+ res = res + '"'
+ return res
+
+
+class ManualGenerator(BaseFunctionGenerator):
+
+ def __init__(self, name, body, condition=None):
+ BaseFunctionGenerator.__init__(self, name, condition=condition)
+ self.body = body
+
+ def functionbody(self):
+ Output("%s", self.body)
+
+ def setselftype(self, selftype, itselftype):
+ self.objecttype = selftype
+ self.itselftype = itselftype
+
+
+class FunctionGenerator(BaseFunctionGenerator):
+
+ def __init__(self, returntype, name, *argumentList, **conditionlist):
+ BaseFunctionGenerator.__init__(self, name, **conditionlist)
+ self.returntype = returntype
+ self.argumentList = []
+ self.setreturnvar()
+ self.parseArgumentList(argumentList)
+ self.prefix = "XXX" # Will be changed by setprefix() call
+ self.itselftype = None # Type of _self->ob_itself, if defined
+
+ def setreturnvar(self):
+ if self.returntype:
+ self.rv = self.makereturnvar()
+ self.argumentList.append(self.rv)
+ else:
+ self.rv = None
+
+ def makereturnvar(self):
+ return Variable(self.returntype, "_rv", OutMode)
+
+ def setselftype(self, selftype, itselftype):
+ self.objecttype = selftype
+ self.itselftype = itselftype
+
+ def parseArgumentList(self, argumentList):
+ iarg = 0
+ for type, name, mode in argumentList:
+ iarg = iarg + 1
+ if name is None: name = "_arg%d" % iarg
+ arg = Variable(type, name, mode)
+ self.argumentList.append(arg)
+
+ def docstring(self):
+ input = []
+ output = []
+ for arg in self.argumentList:
+ if arg.flags == ErrorMode or arg.flags == SelfMode:
+ continue
+ if arg.type is None:
+ str = 'void'
+ else:
+ if hasattr(arg.type, 'typeName'):
+ typeName = arg.type.typeName
+ if typeName is None: # Suppressed type
+ continue
+ else:
+ typeName = "?"
+ print "Nameless type", arg.type
+
+ str = typeName + ' ' + arg.name
+ if arg.mode in (InMode, InOutMode):
+ input.append(str)
+ if arg.mode in (InOutMode, OutMode):
+ output.append(str)
+ if not input:
+ instr = "()"
+ else:
+ instr = "(%s)" % ", ".join(input)
+ if not output or output == ["void"]:
+ outstr = "None"
+ else:
+ outstr = "(%s)" % ", ".join(output)
+ return instr + " -> " + outstr
+
+ def functionbody(self):
+ self.declarations()
+ self.precheck()
+ self.getargs()
+ self.callit()
+ self.checkit()
+ self.returnvalue()
+
+ def declarations(self):
+ for arg in self.argumentList:
+ arg.declare()
+
+ def getargs(self):
+ sep = ",\n" + ' '*len("if (!PyArg_ParseTuple(")
+ fmt, lst = self.getargsFormatArgs(sep)
+ Output("if (!PyArg_ParseTuple(_args, \"%s\"%s))", fmt, lst)
+ IndentLevel()
+ Output("return NULL;")
+ DedentLevel()
+ for arg in self.argumentList:
+ if arg.flags == SelfMode:
+ continue
+ if arg.mode in (InMode, InOutMode):
+ arg.getargsCheck()
+
+ def getargsFormatArgs(self, sep):
+ fmt = ""
+ lst = ""
+ for arg in self.argumentList:
+ if arg.flags == SelfMode:
+ continue
+ if arg.mode in (InMode, InOutMode):
+ arg.getargsPreCheck()
+ fmt = fmt + arg.getargsFormat()
+ args = arg.getargsArgs()
+ if args:
+ lst = lst + sep + args
+ return fmt, lst
+
+ def precheck(self):
+ pass
+
+ def beginallowthreads(self):
+ pass
+
+ def endallowthreads(self):
+ pass
+
+ def callit(self):
+ args = ""
+ s = "%s%s(" % (self.getrvforcallit(), self.callname)
+ sep = ",\n" + ' '*len(s)
+ for arg in self.argumentList:
+ if arg is self.rv:
+ continue
+ s = arg.passArgument()
+ if args: s = sep + s
+ args = args + s
+ self.beginallowthreads()
+ Output("%s%s(%s);",
+ self.getrvforcallit(), self.callname, args)
+ self.endallowthreads()
+
+ def getrvforcallit(self):
+ if self.rv:
+ return "%s = " % self.rv.name
+ else:
+ return ""
+
+ def checkit(self):
+ for arg in self.argumentList:
+ arg.errorCheck()
+
+ def returnvalue(self):
+ sep = ",\n" + ' '*len("return Py_BuildValue(")
+ fmt, lst = self.mkvalueFormatArgs(sep)
+ if fmt == "":
+ Output("Py_INCREF(Py_None);")
+ Output("_res = Py_None;");
+ else:
+ Output("_res = Py_BuildValue(\"%s\"%s);", fmt, lst)
+ tmp = self.argumentList[:]
+ tmp.reverse()
+ for arg in tmp:
+ if not arg: continue
+ arg.cleanup()
+ Output("return _res;")
+
+ def mkvalueFormatArgs(self, sep):
+ fmt = ""
+ lst = ""
+ for arg in self.argumentList:
+ if not arg: continue
+ if arg.flags == ErrorMode: continue
+ if arg.mode in (OutMode, InOutMode):
+ arg.mkvaluePreCheck()
+ fmt = fmt + arg.mkvalueFormat()
+ lst = lst + sep + arg.mkvalueArgs()
+ return fmt, lst
+
+class MethodGenerator(FunctionGenerator):
+
+ def parseArgumentList(self, args):
+ a0, args = args[0], args[1:]
+ t0, n0, m0 = a0
+ if m0 != InMode:
+ raise ValueError, "method's 'self' must be 'InMode'"
+ self.itself = Variable(t0, "_self->ob_itself", SelfMode)
+ self.argumentList.append(self.itself)
+ FunctionGenerator.parseArgumentList(self, args)
+
+def _test():
+ void = None
+ eggs = FunctionGenerator(void, "eggs",
+ (stringptr, 'cmd', InMode),
+ (int, 'x', InMode),
+ (double, 'y', InOutMode),
+ (int, 'status', ErrorMode),
+ )
+ eggs.setprefix("spam")
+ print "/* START */"
+ eggs.generate()
+
+
+if __name__ == "__main__":
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGeneratorGroup.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGeneratorGroup.py
new file mode 100644
index 0000000000..5b035b77e3
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenGeneratorGroup.py
@@ -0,0 +1,40 @@
+from bgenOutput import *
+
+class GeneratorGroup:
+
+ def __init__(self, prefix):
+ self.prefix = prefix
+ self.generators = []
+
+ def add(self, g, dupcheck=0):
+ if dupcheck:
+ if g in self.generators:
+ print 'DUP', g.name
+ return
+ g.setprefix(self.prefix)
+ self.generators.append(g)
+
+ def generate(self):
+ for g in self.generators:
+ g.generate()
+ Output()
+ Output("static PyMethodDef %s_methods[] = {", self.prefix)
+ IndentLevel()
+ for g in self.generators:
+ g.reference()
+ Output("{NULL, NULL, 0}")
+ DedentLevel()
+ Output("};")
+
+
+def _test():
+ void = None
+ from bgenGenerator import FunctionGenerator
+ group = GeneratorGroup("spam")
+ eggs = FunctionGenerator(void, "eggs")
+ group.add(eggs)
+ print "/* START */"
+ group.generate()
+
+if __name__ == "__main__":
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenHeapBuffer.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenHeapBuffer.py
new file mode 100644
index 0000000000..5abfca29fe
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenHeapBuffer.py
@@ -0,0 +1,145 @@
+# Buffers allocated on the heap
+
+from bgenOutput import *
+from bgenType import OutputOnlyMixIn
+from bgenBuffer import FixedInputOutputBufferType
+
+
+class HeapInputOutputBufferType(FixedInputOutputBufferType):
+
+ """Input-output buffer allocated on the heap -- passed as (inbuffer, outbuffer, size).
+
+ Instantiate without parameters.
+ Call from Python with input buffer.
+ """
+
+ def __init__(self, datatype = 'char', sizetype = 'int', sizeformat = None):
+ FixedInputOutputBufferType.__init__(self, "0", datatype, sizetype, sizeformat)
+
+ def getOutputBufferDeclarations(self, name, constmode=False, outmode=False):
+ if constmode:
+ raise RuntimeError, "Cannot use const output buffer"
+ if outmode:
+ out = "*"
+ else:
+ out = ""
+ return ["%s%s *%s__out__" % (self.datatype, out, name)]
+
+ def getargsCheck(self, name):
+ Output("if ((%s__out__ = malloc(%s__in_len__)) == NULL)", name, name)
+ OutLbrace()
+ Output('PyErr_NoMemory();')
+ Output("goto %s__error__;", name)
+ self.label_needed = 1
+ OutRbrace()
+ Output("%s__len__ = %s__in_len__;", name, name)
+
+ def passOutput(self, name):
+ return "%s__in__, %s__out__, (%s)%s__len__" % \
+ (name, name, self.sizetype, name)
+
+ def mkvalueArgs(self, name):
+ return "%s__out__, (int)%s__len__" % (name, name)
+
+ def cleanup(self, name):
+ Output("free(%s__out__);", name)
+ FixedInputOutputBufferType.cleanup(self, name)
+
+
+class VarHeapInputOutputBufferType(HeapInputOutputBufferType):
+
+ """same as base class, but passed as (inbuffer, outbuffer, &size)"""
+
+ def passOutput(self, name):
+ return "%s__in__, %s__out__, &%s__len__" % (name, name, name)
+
+
+class HeapCombinedInputOutputBufferType(HeapInputOutputBufferType):
+
+ """same as base class, but passed as (inoutbuffer, size)"""
+
+ def passOutput(self, name):
+ return "(%s *)memcpy(%s__out__, %s__in__, %s__len__)" % \
+ (self.datatype, name, name, name)
+
+
+class VarHeapCombinedInputOutputBufferType(HeapInputOutputBufferType):
+
+ """same as base class, but passed as (inoutbuffer, &size)"""
+
+ def passOutput(self, name):
+ return "(%s *)memcpy(%s__out__, %s__in__, &%s__len__)" % \
+ (self.datatype, name, name, name)
+
+
+class HeapOutputBufferType(OutputOnlyMixIn, HeapInputOutputBufferType):
+
+ """Output buffer allocated on the heap -- passed as (buffer, size).
+
+ Instantiate without parameters.
+ Call from Python with buffer size.
+ """
+
+ def getInputBufferDeclarations(self, name, constmode=False):
+ return []
+
+ def getargsFormat(self):
+ return "i"
+
+ def getargsArgs(self, name):
+ return "&%s__in_len__" % name
+
+ def passOutput(self, name):
+ return "%s__out__, %s__len__" % (name, name)
+
+
+class VarHeapOutputBufferType(HeapOutputBufferType):
+
+ """Output buffer allocated on the heap -- passed as (buffer, &size).
+
+ Instantiate without parameters.
+ Call from Python with buffer size.
+ """
+
+ def passOutput(self, name):
+ return "%s__out__, &%s__len__" % (name, name)
+
+
+class VarVarHeapOutputBufferType(VarHeapOutputBufferType):
+
+ """Output buffer allocated on the heap -- passed as (buffer, size, &size).
+
+ Instantiate without parameters.
+ Call from Python with buffer size.
+ """
+
+ def passOutput(self, name):
+ return "%s__out__, %s__len__, &%s__len__" % (name, name, name)
+
+class MallocHeapOutputBufferType(HeapOutputBufferType):
+ """Output buffer allocated by the called function -- passed as (&buffer, &size).
+
+ Instantiate without parameters.
+ Call from Python without parameters.
+ """
+
+ def getargsCheck(self, name):
+ Output("%s__out__ = NULL;", name)
+
+ def getAuxDeclarations(self, name):
+ return []
+
+ def passOutput(self, name):
+ return "&%s__out__, &%s__len__" % (name, name)
+
+ def getargsFormat(self):
+ return ""
+
+ def getargsArgs(self, name):
+ return None
+
+ def mkvalueFormat(self):
+ return "z#"
+
+ def cleanup(self, name):
+ Output("if( %s__out__ ) free(%s__out__);", name, name)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenModule.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenModule.py
new file mode 100644
index 0000000000..f8c43d9af1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenModule.py
@@ -0,0 +1,94 @@
+from bgenOutput import *
+from bgenGeneratorGroup import GeneratorGroup
+
+class Module(GeneratorGroup):
+
+ def __init__(self, name, prefix = None,
+ includestuff = None,
+ finalstuff = None,
+ initstuff = None,
+ variablestuff = None,
+ longname = None):
+ GeneratorGroup.__init__(self, prefix or name)
+ self.name = name
+ if longname:
+ self.longname = longname
+ else:
+ self.longname = name
+ self.includestuff = includestuff
+ self.initstuff = initstuff
+ self.finalstuff = finalstuff
+ self.variablestuff = variablestuff
+ self.typeobjects = []
+
+ def addobject(self, od):
+ self.generators.append(od)
+ self.typeobjects.append(od)
+ od.setmodulename(self.longname)
+
+ def generate(self):
+ OutHeader1("Module " + self.name)
+ Output("#include \"Python.h\"")
+ Output()
+
+ if self.includestuff:
+ Output()
+ Output("%s", self.includestuff)
+
+ self.declareModuleVariables()
+
+ GeneratorGroup.generate(self)
+
+ if self.finalstuff:
+ Output()
+ Output("%s", self.finalstuff)
+
+ Output()
+ Output("void init%s(void)", self.name)
+ OutLbrace()
+ Output("PyObject *m;")
+ Output("PyObject *d;")
+ Output()
+
+ if self.initstuff:
+ Output("%s", self.initstuff)
+ Output()
+
+ Output("m = Py_InitModule(\"%s\", %s_methods);",
+ self.name, self.prefix)
+ Output("d = PyModule_GetDict(m);")
+ self.createModuleVariables()
+ OutRbrace()
+ OutHeader1("End module " + self.name)
+
+ def declareModuleVariables(self):
+ self.errorname = self.prefix + "_Error"
+ Output("static PyObject *%s;", self.errorname)
+
+ def createModuleVariables(self):
+ Output("""%s = %s;""", self.errorname, self.exceptionInitializer())
+ Output("""if (%s == NULL ||""", self.errorname)
+ Output(""" PyDict_SetItemString(d, "Error", %s) != 0)""",
+ self.errorname)
+ IndentLevel()
+ Output("""return;""")
+ DedentLevel()
+ for tp in self.typeobjects:
+ tp.outputTypeObjectInitializer()
+ if self.variablestuff:
+ Output("%s", self.variablestuff)
+ Output()
+
+ def exceptionInitializer(self):
+ return """PyErr_NewException("%s.Error", NULL, NULL)""" % self.name
+
+
+def _test():
+ from bgenGenerator import FunctionGenerator
+ m = Module("spam", "", "#include <stdio.h>")
+ g = FunctionGenerator(None, "bacon")
+ m.add(g)
+ m.generate()
+
+if __name__ == "__main__":
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenObjectDefinition.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenObjectDefinition.py
new file mode 100644
index 0000000000..838369be75
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenObjectDefinition.py
@@ -0,0 +1,512 @@
+from bgenOutput import *
+from bgenGeneratorGroup import GeneratorGroup
+
+class ObjectDefinition(GeneratorGroup):
+ "Spit out code that together defines a new Python object type"
+ basechain = "NULL"
+ tp_flags = "Py_TPFLAGS_DEFAULT"
+ basetype = None
+ argref = "" # set to "*" if arg to <type>_New should be pointer
+ argconst = "" # set to "const " if arg to <type>_New should be const
+
+ def __init__(self, name, prefix, itselftype):
+ """ObjectDefinition constructor. May be extended, but do not override.
+
+ - name: the object's official name, e.g. 'SndChannel'.
+ - prefix: the prefix used for the object's functions and data, e.g. 'SndCh'.
+ - itselftype: the C type actually contained in the object, e.g. 'SndChannelPtr'.
+
+ XXX For official Python data types, rules for the 'Py' prefix are a problem.
+ """
+
+ GeneratorGroup.__init__(self, prefix or name)
+ self.name = name
+ self.itselftype = itselftype
+ self.objecttype = name + 'Object'
+ self.typename = name + '_Type'
+ self.static = "static " # set to "" to make <type>_New and <type>_Convert public
+ self.modulename = None
+ if hasattr(self, "assertions"):
+ self.assertions()
+
+ def add(self, g, dupcheck=0):
+ g.setselftype(self.objecttype, self.itselftype)
+ GeneratorGroup.add(self, g, dupcheck)
+
+ def reference(self):
+ # In case we are referenced from a module
+ pass
+
+ def setmodulename(self, name):
+ self.modulename = name
+
+ def generate(self):
+ # XXX This should use long strings and %(varname)s substitution!
+
+ OutHeader2("Object type " + self.name)
+
+ self.outputCheck()
+
+ Output("typedef struct %s {", self.objecttype)
+ IndentLevel()
+ Output("PyObject_HEAD")
+ self.outputStructMembers()
+ DedentLevel()
+ Output("} %s;", self.objecttype)
+
+ self.outputNew()
+
+ self.outputConvert()
+
+ self.outputDealloc()
+
+ GeneratorGroup.generate(self)
+
+ Output()
+ self.outputMethodChain()
+
+ self.outputGetattr()
+
+ self.outputSetattr()
+
+ self.outputCompare()
+
+ self.outputRepr()
+
+ self.outputHash()
+
+ self.outputPEP253Hooks()
+
+ self.outputTypeObject()
+
+ OutHeader2("End object type " + self.name)
+
+ def outputCheck(self):
+ sf = self.static and "static "
+ Output("%sPyTypeObject %s;", sf, self.typename)
+ Output()
+ Output("#define %s_Check(x) ((x)->ob_type == &%s || PyObject_TypeCheck((x), &%s))",
+ self.prefix, self.typename, self.typename)
+ Output()
+
+ def outputMethodChain(self):
+ Output("%sPyMethodChain %s_chain = { %s_methods, %s };",
+ self.static, self.prefix, self.prefix, self.basechain)
+
+ def outputStructMembers(self):
+ Output("%s ob_itself;", self.itselftype)
+
+ def outputNew(self):
+ Output()
+ Output("%sPyObject *%s_New(%s%s %sitself)", self.static, self.prefix,
+ self.argconst, self.itselftype, self.argref)
+ OutLbrace()
+ Output("%s *it;", self.objecttype)
+ self.outputCheckNewArg()
+ Output("it = PyObject_NEW(%s, &%s);", self.objecttype, self.typename)
+ Output("if (it == NULL) return NULL;")
+ if self.basetype:
+ Output("/* XXXX Should we tp_init or tp_new our basetype? */")
+ self.outputInitStructMembers()
+ Output("return (PyObject *)it;")
+ OutRbrace()
+
+ def outputInitStructMembers(self):
+ Output("it->ob_itself = %sitself;", self.argref)
+
+ def outputCheckNewArg(self):
+ "Override this method to apply additional checks/conversions"
+
+ def outputConvert(self):
+ Output()
+ Output("%sint %s_Convert(PyObject *v, %s *p_itself)", self.static, self.prefix,
+ self.itselftype)
+ OutLbrace()
+ self.outputCheckConvertArg()
+ Output("if (!%s_Check(v))", self.prefix)
+ OutLbrace()
+ Output('PyErr_SetString(PyExc_TypeError, "%s required");', self.name)
+ Output("return 0;")
+ OutRbrace()
+ Output("*p_itself = ((%s *)v)->ob_itself;", self.objecttype)
+ Output("return 1;")
+ OutRbrace()
+
+ def outputCheckConvertArg(self):
+ "Override this method to apply additional conversions"
+
+ def outputDealloc(self):
+ Output()
+ Output("static void %s_dealloc(%s *self)", self.prefix, self.objecttype)
+ OutLbrace()
+ self.outputCleanupStructMembers()
+ if self.basetype:
+ Output("%s.tp_dealloc((PyObject *)self);", self.basetype)
+ elif hasattr(self, 'output_tp_free'):
+ # This is a new-style object with tp_free slot
+ Output("self->ob_type->tp_free((PyObject *)self);")
+ else:
+ Output("PyObject_Free((PyObject *)self);")
+ OutRbrace()
+
+ def outputCleanupStructMembers(self):
+ self.outputFreeIt("self->ob_itself")
+
+ def outputFreeIt(self, name):
+ Output("/* Cleanup of %s goes here */", name)
+
+ def outputGetattr(self):
+ Output()
+ Output("static PyObject *%s_getattr(%s *self, char *name)", self.prefix, self.objecttype)
+ OutLbrace()
+ self.outputGetattrBody()
+ OutRbrace()
+
+ def outputGetattrBody(self):
+ self.outputGetattrHook()
+ Output("return Py_FindMethodInChain(&%s_chain, (PyObject *)self, name);",
+ self.prefix)
+
+ def outputGetattrHook(self):
+ pass
+
+ def outputSetattr(self):
+ Output()
+ Output("#define %s_setattr NULL", self.prefix)
+
+ def outputCompare(self):
+ Output()
+ Output("#define %s_compare NULL", self.prefix)
+
+ def outputRepr(self):
+ Output()
+ Output("#define %s_repr NULL", self.prefix)
+
+ def outputHash(self):
+ Output()
+ Output("#define %s_hash NULL", self.prefix)
+
+ def outputTypeObject(self):
+ sf = self.static and "static "
+ Output()
+ Output("%sPyTypeObject %s = {", sf, self.typename)
+ IndentLevel()
+ Output("PyObject_HEAD_INIT(NULL)")
+ Output("0, /*ob_size*/")
+ if self.modulename:
+ Output("\"%s.%s\", /*tp_name*/", self.modulename, self.name)
+ else:
+ Output("\"%s\", /*tp_name*/", self.name)
+ Output("sizeof(%s), /*tp_basicsize*/", self.objecttype)
+ Output("0, /*tp_itemsize*/")
+ Output("/* methods */")
+ Output("(destructor) %s_dealloc, /*tp_dealloc*/", self.prefix)
+ Output("0, /*tp_print*/")
+ Output("(getattrfunc) %s_getattr, /*tp_getattr*/", self.prefix)
+ Output("(setattrfunc) %s_setattr, /*tp_setattr*/", self.prefix)
+ Output("(cmpfunc) %s_compare, /*tp_compare*/", self.prefix)
+ Output("(reprfunc) %s_repr, /*tp_repr*/", self.prefix)
+ Output("(PyNumberMethods *)0, /* tp_as_number */")
+ Output("(PySequenceMethods *)0, /* tp_as_sequence */")
+ Output("(PyMappingMethods *)0, /* tp_as_mapping */")
+ Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix)
+ DedentLevel()
+ Output("};")
+
+ def outputTypeObjectInitializer(self):
+ Output("""%s.ob_type = &PyType_Type;""", self.typename)
+ if self.basetype:
+ Output("%s.tp_base = &%s;", self.typename, self.basetype)
+ Output("if (PyType_Ready(&%s) < 0) return;", self.typename)
+ Output("""Py_INCREF(&%s);""", self.typename)
+ Output("PyModule_AddObject(m, \"%s\", (PyObject *)&%s);", self.name, self.typename);
+ self.outputTypeObjectInitializerCompat()
+
+ def outputTypeObjectInitializerCompat(self):
+ Output("/* Backward-compatible name */")
+ Output("""Py_INCREF(&%s);""", self.typename);
+ Output("PyModule_AddObject(m, \"%sType\", (PyObject *)&%s);", self.name, self.typename);
+
+ def outputPEP253Hooks(self):
+ pass
+
+class PEP252Mixin:
+ getsetlist = []
+
+ def assertions(self):
+ # Check that various things aren't overridden. If they are it could
+ # signify a bgen-client that has been partially converted to PEP252.
+ assert self.outputGetattr.im_func == PEP252Mixin.outputGetattr.im_func
+ assert self.outputSetattr.im_func == PEP252Mixin.outputSetattr.im_func
+ assert self.outputGetattrBody == None
+ assert self.outputGetattrHook == None
+ assert self.basechain == "NULL"
+
+ def outputGetattr(self):
+ pass
+
+ outputGetattrBody = None
+
+ outputGetattrHook = None
+
+ def outputSetattr(self):
+ pass
+
+ def outputMethodChain(self):
+ # This is a good place to output the getters and setters
+ self.outputGetSetList()
+
+ def outputHook(self, name):
+ methodname = "outputHook_" + name
+ if hasattr(self, methodname):
+ func = getattr(self, methodname)
+ func()
+ else:
+ Output("0, /*%s*/", name)
+
+ def outputTypeObject(self):
+ sf = self.static and "static "
+ Output()
+ Output("%sPyTypeObject %s = {", sf, self.typename)
+ IndentLevel()
+ Output("PyObject_HEAD_INIT(NULL)")
+ Output("0, /*ob_size*/")
+ if self.modulename:
+ Output("\"%s.%s\", /*tp_name*/", self.modulename, self.name)
+ else:
+ Output("\"%s\", /*tp_name*/", self.name)
+ Output("sizeof(%s), /*tp_basicsize*/", self.objecttype)
+ Output("0, /*tp_itemsize*/")
+
+ Output("/* methods */")
+ Output("(destructor) %s_dealloc, /*tp_dealloc*/", self.prefix)
+ Output("0, /*tp_print*/")
+ Output("(getattrfunc)0, /*tp_getattr*/")
+ Output("(setattrfunc)0, /*tp_setattr*/")
+ Output("(cmpfunc) %s_compare, /*tp_compare*/", self.prefix)
+ Output("(reprfunc) %s_repr, /*tp_repr*/", self.prefix)
+
+ Output("(PyNumberMethods *)0, /* tp_as_number */")
+ Output("(PySequenceMethods *)0, /* tp_as_sequence */")
+ Output("(PyMappingMethods *)0, /* tp_as_mapping */")
+
+ Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix)
+ self.outputHook("tp_call")
+ Output("0, /*tp_str*/")
+ Output("PyObject_GenericGetAttr, /*tp_getattro*/")
+ Output("PyObject_GenericSetAttr, /*tp_setattro */")
+
+ self.outputHook("tp_as_buffer")
+ Output("%s, /* tp_flags */", self.tp_flags)
+ self.outputHook("tp_doc")
+ self.outputHook("tp_traverse")
+ self.outputHook("tp_clear")
+ self.outputHook("tp_richcompare")
+ self.outputHook("tp_weaklistoffset")
+ self.outputHook("tp_iter")
+ self.outputHook("tp_iternext")
+ Output("%s_methods, /* tp_methods */", self.prefix)
+ self.outputHook("tp_members")
+ Output("%s_getsetlist, /*tp_getset*/", self.prefix)
+ self.outputHook("tp_base")
+ self.outputHook("tp_dict")
+ self.outputHook("tp_descr_get")
+ self.outputHook("tp_descr_set")
+ self.outputHook("tp_dictoffset")
+ self.outputHook("tp_init")
+ self.outputHook("tp_alloc")
+ self.outputHook("tp_new")
+ self.outputHook("tp_free")
+ DedentLevel()
+ Output("};")
+
+ def outputGetSetList(self):
+ if self.getsetlist:
+ for name, get, set, doc in self.getsetlist:
+ if get:
+ self.outputGetter(name, get)
+ else:
+ Output("#define %s_get_%s NULL", self.prefix, name)
+ Output()
+ if set:
+ self.outputSetter(name, set)
+ else:
+ Output("#define %s_set_%s NULL", self.prefix, name)
+ Output()
+
+ Output("static PyGetSetDef %s_getsetlist[] = {", self.prefix)
+ IndentLevel()
+ for name, get, set, doc in self.getsetlist:
+ if doc:
+ doc = '"' + doc + '"'
+ else:
+ doc = "NULL"
+ Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s},",
+ name, self.prefix, name, self.prefix, name, doc)
+ Output("{NULL, NULL, NULL, NULL},")
+ DedentLevel()
+ Output("};")
+ else:
+ Output("#define %s_getsetlist NULL", self.prefix)
+ Output()
+
+ def outputGetter(self, name, code):
+ Output("static PyObject *%s_get_%s(%s *self, void *closure)",
+ self.prefix, name, self.objecttype)
+ OutLbrace()
+ Output(code)
+ OutRbrace()
+ Output()
+
+ def outputSetter(self, name, code):
+ Output("static int %s_set_%s(%s *self, PyObject *v, void *closure)",
+ self.prefix, name, self.objecttype)
+ OutLbrace()
+ Output(code)
+ Output("return 0;")
+ OutRbrace()
+ Output()
+
+class PEP253Mixin(PEP252Mixin):
+ tp_flags = "Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE"
+
+ def outputHook_tp_init(self):
+ Output("%s_tp_init, /* tp_init */", self.prefix)
+
+ def outputHook_tp_alloc(self):
+ Output("%s_tp_alloc, /* tp_alloc */", self.prefix)
+
+ def outputHook_tp_new(self):
+ Output("%s_tp_new, /* tp_new */", self.prefix)
+
+ def outputHook_tp_free(self):
+ Output("%s_tp_free, /* tp_free */", self.prefix)
+
+ def output_tp_initBody_basecall(self):
+ """If a type shares its init call with its base type set output_tp_initBody
+ to output_tp_initBody_basecall"""
+ if self.basetype:
+ Output("if (%s.tp_init)", self.basetype)
+ OutLbrace()
+ Output("if ( (*%s.tp_init)(_self, _args, _kwds) < 0) return -1;", self.basetype)
+ OutRbrace()
+
+ output_tp_initBody = None
+
+ def output_tp_init(self):
+ if self.output_tp_initBody:
+ Output("static int %s_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)", self.prefix)
+ OutLbrace()
+ self.output_tp_initBody()
+ OutRbrace()
+ else:
+ Output("#define %s_tp_init 0", self.prefix)
+ Output()
+
+ output_tp_allocBody = None
+
+ def output_tp_alloc(self):
+ if self.output_tp_allocBody:
+ Output("static PyObject *%s_tp_alloc(PyTypeObject *type, int nitems)",
+ self.prefix)
+ OutLbrace()
+ self.output_tp_allocBody()
+ OutRbrace()
+ else:
+ Output("#define %s_tp_alloc PyType_GenericAlloc", self.prefix)
+ Output()
+
+ def output_tp_newBody(self):
+ Output("PyObject *_self;");
+ Output("%s itself;", self.itselftype);
+ Output("char *kw[] = {\"itself\", 0};")
+ Output()
+ Output("if (!PyArg_ParseTupleAndKeywords(_args, _kwds, \"O&\", kw, %s_Convert, &itself)) return NULL;",
+ self.prefix);
+ if self.basetype:
+ Output("if (%s.tp_new)", self.basetype)
+ OutLbrace()
+ Output("if ( (*%s.tp_new)(type, _args, _kwds) == NULL) return NULL;", self.basetype)
+ Dedent()
+ Output("} else {")
+ Indent()
+ Output("if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;")
+ OutRbrace()
+ else:
+ Output("if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;")
+ Output("((%s *)_self)->ob_itself = itself;", self.objecttype)
+ Output("return _self;")
+
+ def output_tp_new(self):
+ if self.output_tp_newBody:
+ Output("static PyObject *%s_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)", self.prefix)
+ OutLbrace()
+ self.output_tp_newBody()
+ OutRbrace()
+ else:
+ Output("#define %s_tp_new PyType_GenericNew", self.prefix)
+ Output()
+
+ output_tp_freeBody = None
+
+ def output_tp_free(self):
+ if self.output_tp_freeBody:
+ Output("static void %s_tp_free(PyObject *self)", self.prefix)
+ OutLbrace()
+ self.output_tp_freeBody()
+ OutRbrace()
+ else:
+ Output("#define %s_tp_free PyObject_Del", self.prefix)
+ Output()
+
+ def outputPEP253Hooks(self):
+ self.output_tp_init()
+ self.output_tp_alloc()
+ self.output_tp_new()
+ self.output_tp_free()
+
+class GlobalObjectDefinition(ObjectDefinition):
+ """Like ObjectDefinition but exports some parts.
+
+ XXX Should also somehow generate a .h file for them.
+ """
+
+ def __init__(self, name, prefix = None, itselftype = None):
+ ObjectDefinition.__init__(self, name, prefix or name, itselftype or name)
+ self.static = ""
+
+class ObjectIdentityMixin:
+ """A mixin class for objects that makes the identity of ob_itself
+ govern comparisons and dictionary lookups. Useful if the C object can
+ be returned by library calls and it is difficult (or impossible) to find
+ the corresponding Python objects. With this you can create Python object
+ wrappers on the fly"""
+
+ def outputCompare(self):
+ Output()
+ Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype,
+ self.objecttype)
+ OutLbrace()
+ Output("unsigned long v, w;")
+ Output()
+ Output("if (!%s_Check((PyObject *)other))", self.prefix)
+ OutLbrace()
+ Output("v=(unsigned long)self;")
+ Output("w=(unsigned long)other;")
+ OutRbrace()
+ Output("else")
+ OutLbrace()
+ Output("v=(unsigned long)self->ob_itself;")
+ Output("w=(unsigned long)other->ob_itself;")
+ OutRbrace()
+ Output("if( v < w ) return -1;")
+ Output("if( v > w ) return 1;")
+ Output("return 0;")
+ OutRbrace()
+
+ def outputHash(self):
+ Output()
+ Output("static long %s_hash(%s *self)", self.prefix, self.objecttype)
+ OutLbrace()
+ Output("return (long)self->ob_itself;")
+ OutRbrace()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenOutput.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenOutput.py
new file mode 100644
index 0000000000..bde53f040f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenOutput.py
@@ -0,0 +1,219 @@
+"""Output primitives for the binding generator classes.
+
+This should really be a class, but then everybody would be passing
+the output object to each other. I chose for the simpler approach
+of a module with a global variable. Use SetOutputFile() or
+SetOutputFileName() to change the output file.
+"""
+
+_NeedClose = 0
+
+def SetOutputFile(file = None, needclose = 0):
+ """Call this with an open file object to make it the output file.
+
+ Call it without arguments to close the current file (if necessary)
+ and reset it to sys.stdout.
+ If the second argument is true, the new file will be explicitly closed
+ on a subsequence call.
+ """
+ global _File, _NeedClose
+ if _NeedClose:
+ tmp = _File
+ _NeedClose = 0
+ _File = None
+ tmp.close()
+ if file is None:
+ import sys
+ file = sys.stdout
+ _File = file
+ _NeedClose = file and needclose
+
+def SetOutputFileName(filename = None):
+ """Call this with a filename to make it the output file.
+
+ Call it without arguments to close the current file (if necessary)
+ and reset it to sys.stdout.
+ """
+ SetOutputFile()
+ if filename:
+ SetOutputFile(open(filename, 'w'), 1)
+
+SetOutputFile() # Initialize _File
+
+_Level = 0 # Indentation level
+
+def GetLevel():
+ """Return the current indentation level."""
+ return _Level
+
+def SetLevel(level):
+ """Set the current indentation level.
+
+ This does no type or range checking -- use at own risk.
+ """
+ global _Level
+ _Level = level
+
+def Output(format = "", *args):
+ VaOutput(format, args)
+
+def VaOutput(format, args):
+ """Call this with a format string and argument tuple for the format.
+
+ A newline is always added. Each line in the output is indented
+ to the proper indentation level -- even if the result of the
+ format expansion contains embedded newlines. Exception: lines
+ beginning with '#' are not indented -- these are assumed to be
+ C preprprocessor lines.
+ """
+ text = format % args
+ if _Level > 0:
+ indent = '\t' * _Level
+ lines = text.split('\n')
+ for i in range(len(lines)):
+ if lines[i] and lines[i][0] != '#':
+ lines[i] = indent + lines[i]
+ text = '\n'.join(lines)
+ _File.write(text + '\n')
+
+def IndentLevel(by = 1):
+ """Increment the indentation level by one.
+
+ When called with an argument, adds it to the indentation level.
+ """
+ global _Level
+ if _Level+by < 0:
+ raise Error, "indentation underflow (internal error)"
+ _Level = _Level + by
+
+def DedentLevel(by = 1):
+ """Decrement the indentation level by one.
+
+ When called with an argument, subtracts it from the indentation level.
+ """
+ IndentLevel(-by)
+
+def OutIndent(format = "", *args):
+ """Combine Output() followed by IndentLevel().
+
+ If no text is given, acts like lone IndentLevel().
+ """
+ if format: VaOutput(format, args)
+ IndentLevel()
+
+def OutDedent(format = "", *args):
+ """Combine Output() followed by DedentLevel().
+
+ If no text is given, acts like loneDedentLevel().
+ """
+ if format: VaOutput(format, args)
+ DedentLevel()
+
+def OutLbrace(format = "", *args):
+ """Like Output, but add a '{' and increase the indentation level.
+
+ If no text is given a lone '{' is output.
+ """
+ if format:
+ format = format + " {"
+ else:
+ format = "{"
+ VaOutput(format, args)
+ IndentLevel()
+
+def OutRbrace():
+ """Decrease the indentation level and output a '}' on a line by itself."""
+ DedentLevel()
+ Output("}")
+
+def OutHeader(text, dash):
+ """Output a header comment using a given dash character."""
+ n = 64 - len(text)
+ Output()
+ Output("/* %s %s %s */", dash * (n/2), text, dash * (n - n/2))
+ Output()
+
+def OutHeader1(text):
+ """Output a level 1 header comment (uses '=' dashes)."""
+ OutHeader(text, "=")
+
+def OutHeader2(text):
+ """Output a level 2 header comment (uses '-' dashes)."""
+ OutHeader(text, "-")
+
+def Out(text):
+ """Output multiline text that's internally indented.
+
+ Pass this a multiline character string. The whitespace before the
+ first nonblank line of the string will be subtracted from all lines.
+ The lines are then output using Output(), but without interpretation
+ of formatting (if you need formatting you can do it before the call).
+ Recommended use:
+
+ Out('''
+ int main(argc, argv)
+ int argc;
+ char *argv;
+ {
+ printf("Hello, world\\n");
+ exit(0);
+ }
+ ''')
+
+ Caveat: the indentation must be consistent -- if you use three tabs
+ in the first line, (up to) three tabs are removed from following lines,
+ but a line beginning with 24 spaces is not trimmed at all. Don't use
+ this as a feature.
+ """
+ # (Don't you love using triple quotes *inside* triple quotes? :-)
+
+ lines = text.split('\n')
+ indent = ""
+ for line in lines:
+ if line.strip():
+ for c in line:
+ if not c.isspace():
+ break
+ indent = indent + c
+ break
+ n = len(indent)
+ for line in lines:
+ if line[:n] == indent:
+ line = line[n:]
+ else:
+ for c in indent:
+ if line[:1] <> c: break
+ line = line[1:]
+ VaOutput("%s", line)
+
+
+def _test():
+ """Test program. Run when the module is run as a script."""
+ OutHeader1("test bgenOutput")
+ Out("""
+ #include <Python.h>
+ #include <stdio.h>
+
+ main(argc, argv)
+ int argc;
+ char **argv;
+ {
+ int i;
+ """)
+ IndentLevel()
+ Output("""\
+/* Here are a few comment lines.
+ Just to test indenting multiple lines.
+
+ End of the comment lines. */
+""")
+ Output("for (i = 0; i < argc; i++)")
+ OutLbrace()
+ Output('printf("argv[%%d] = %%s\\n", i, argv[i]);')
+ OutRbrace()
+ Output("exit(0)")
+ OutRbrace()
+ OutHeader2("end test")
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStackBuffer.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStackBuffer.py
new file mode 100644
index 0000000000..befab6b64c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStackBuffer.py
@@ -0,0 +1,62 @@
+"""Buffers allocated on the stack."""
+
+
+from bgenBuffer import FixedInputBufferType, FixedOutputBufferType
+
+
+class StackOutputBufferType(FixedOutputBufferType):
+
+ """Fixed output buffer allocated on the stack -- passed as (buffer, size).
+
+ Instantiate with the buffer size as parameter.
+ """
+
+ def passOutput(self, name):
+ return "%s__out__, %s" % (name, self.size)
+
+
+class VarStackOutputBufferType(StackOutputBufferType):
+
+ """Output buffer allocated on the stack -- passed as (buffer, &size).
+
+ Instantiate with the buffer size as parameter.
+ """
+
+ def getSizeDeclarations(self, name):
+ return []
+
+ def getAuxDeclarations(self, name):
+ return ["int %s__len__ = %s" % (name, self.size)]
+
+ def passOutput(self, name):
+ return "%s__out__, &%s__len__" % (name, name)
+
+ def mkvalueArgs(self, name):
+ return "%s__out__, (int)%s__len__" % (name, name)
+
+
+class VarVarStackOutputBufferType(VarStackOutputBufferType):
+
+ """Output buffer allocated on the stack -- passed as (buffer, size, &size).
+
+ Instantiate with the buffer size as parameter.
+ """
+
+ def passOutput(self, name):
+ return "%s__out__, %s__len__, &%s__len__" % (name, name, name)
+
+
+class ReturnVarStackOutputBufferType(VarStackOutputBufferType):
+
+ """Output buffer allocated on the stack -- passed as (buffer, size) -> size.
+
+ Instantiate with the buffer size as parameter.
+ The function's return value is the size.
+ (XXX Should have a way to suppress returning it separately, too.)
+ """
+
+ def passOutput(self, name):
+ return "%s__out__, %s__len__" % (name, name)
+
+ def mkvalueArgs(self, name):
+ return "%s__out__, (int)_rv" % name
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStringBuffer.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStringBuffer.py
new file mode 100644
index 0000000000..70b58a4241
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenStringBuffer.py
@@ -0,0 +1,67 @@
+"""Buffers used to hold null-terminated strings."""
+
+
+from bgenBuffer import FixedOutputBufferType
+from bgenStackBuffer import StackOutputBufferType
+from bgenHeapBuffer import HeapOutputBufferType
+
+
+class StringBufferMixIn:
+
+ """Mix-in class to create various string buffer types.
+
+ Strings are character arrays terminated by a null byte.
+ (For input, this is also covered by stringptr.)
+ For output, there are again three variants:
+ - Fixed: size is a constant given in the documentation; or
+ - Stack: size is passed to the C function but we decide on a size at
+ code generation time so we can still allocate on the heap); or
+ - Heap: size is passed to the C function and we let the Python caller
+ pass a size.
+ (Note that this doesn't cover output parameters in which a string
+ pointer is returned. These are actually easier (no allocation) but far
+ less common. I'll write the classes when there is demand.)
+ """
+
+ def getSizeDeclarations(self, name):
+ return []
+
+ def getAuxDeclarations(self, name):
+ return []
+
+ def getargsFormat(self):
+ return "s"
+
+ def getargsArgs(self, name):
+ return "&%s__in__" % name
+
+ def mkvalueFormat(self):
+ return "s"
+
+ def mkvalueArgs(self, name):
+ return "%s__out__" % name
+
+
+class FixedOutputStringType(StringBufferMixIn, FixedOutputBufferType):
+
+ """Null-terminated output string -- passed without size.
+
+ Instantiate with buffer size as parameter.
+ """
+
+
+class StackOutputStringType(StringBufferMixIn, StackOutputBufferType):
+
+ """Null-terminated output string -- passed as (buffer, size).
+
+ Instantiate with buffer size as parameter.
+ """
+
+
+class HeapOutputStringType(StringBufferMixIn, HeapOutputBufferType):
+
+ """Null-terminated output string -- passed as (buffer, size).
+
+ Instantiate without parameters.
+ Call from Python with buffer size.
+ """
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenType.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenType.py
new file mode 100644
index 0000000000..af6fc69944
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenType.py
@@ -0,0 +1,328 @@
+"""Type classes and a modest collection of standard types."""
+
+
+from bgenOutput import *
+
+
+class Type:
+
+ """Define the various things you can do with a C type.
+
+ Most methods are intended to be extended or overridden.
+ """
+
+ def __init__(self, typeName, fmt):
+ """Call with the C name and getargs format for the type.
+
+ Example: int = Type("int", "i")
+ """
+ self.typeName = typeName
+ self.fmt = fmt
+
+ def declare(self, name, reference=False):
+ """Declare a variable of the type with a given name.
+
+ Example: int.declare('spam') prints "int spam;"
+ """
+ for decl in self.getArgDeclarations(name, reference):
+ Output("%s;", decl)
+ for decl in self.getAuxDeclarations(name):
+ Output("%s;", decl)
+
+ def getArgDeclarations(self, name, reference=False, constmode=False, outmode=False):
+ """Return the main part of the declarations for this type: the items
+ that will be passed as arguments in the C/C++ function call."""
+ if reference:
+ ref = "&"
+ else:
+ ref = ""
+ if constmode:
+ const = "const "
+ else:
+ const = ""
+ if outmode:
+ out = "*"
+ else:
+ out = ""
+ return ["%s%s%s%s %s" % (const, self.typeName, ref, out, name)]
+
+ def getAuxDeclarations(self, name):
+ """Return any auxiliary declarations needed for implementing this
+ type, such as helper variables used to hold sizes, etc. These declarations
+ are not part of the C/C++ function call interface."""
+ return []
+
+ def getargs(self):
+ return self.getargsFormat(), self.getargsArgs()
+
+ def getargsFormat(self):
+ """Return the format for this type for use with PyArg_Parse().
+
+ Example: int.getargsFormat() returns the string "i".
+ (getargs is a very old name for PyArg_Parse, hence the name of this method).
+ """
+ return self.fmt
+
+ def getargsArgs(self, name):
+ """Return an argument for use with PyArg_Parse().
+
+ Example: int.getargsArgs("spam") returns the string "&spam".
+ """
+ return "&" + name
+
+ def getargsPreCheck(self, name):
+ """Perform any actions needed before calling getargs().
+
+ This could include declaring temporary variables and such.
+ """
+
+ def getargsCheck(self, name):
+ """Perform any needed post-[new]getargs() checks.
+
+ This is type-dependent; the default does not check for errors.
+ An example would be a check for a maximum string length, or it
+ could do post-getargs() copying or conversion."""
+
+ def passInput(self, name):
+ """Return an argument for passing a variable into a call.
+
+ Example: int.passInput("spam") returns the string "spam".
+ """
+ return name
+
+ def passOutput(self, name):
+ """Return an argument for returning a variable out of a call.
+
+ Example: int.passOutput("spam") returns the string "&spam".
+ """
+ return "&" + name
+
+ def passReference(self, name):
+ """Return an argument for C++ pass-by-reference.
+ Default is to call passInput().
+ """
+ return self.passInput(name)
+
+ def errorCheck(self, name):
+ """Check for an error returned in the variable.
+
+ This is type-dependent; the default does not check for errors.
+ An example would be a check for a NULL pointer.
+ If an error is found, the generated routine should
+ raise an exception and return NULL.
+
+ XXX There should be a way to add error clean-up code.
+ """
+ Output("/* XXX no err check for %s %s */", self.typeName, name)
+
+ def mkvalue(self):
+ return self.mkvalueFormat(), self.mkvalueArgs()
+
+ def mkvalueFormat(self):
+ """Return the format for this type for use with Py_BuildValue().
+
+ This is normally the same as getargsFormat() but it is
+ a separate function to allow future divergence.
+ (mkvalue is a very old name for Py_BuildValue, hence the name of this
+ method).
+ """
+ return self.getargsFormat()
+
+ def mkvalueArgs(self, name):
+ """Return an argument for use with Py_BuildValue().
+
+ Example: int.mkvalueArgs("spam") returns the string "spam".
+ """
+ return name
+
+ def mkvaluePreCheck(self, name):
+ """Perform any actions needed before calling mkvalue().
+
+ This could include declaring temporary variables and such.
+ """
+
+ def cleanup(self, name):
+ """Clean up if necessary.
+
+ This is normally empty; it may deallocate buffers etc.
+ """
+ pass
+
+class ByAddressType(Type):
+ "Simple type that is also passed by address for input"
+
+ def passInput(self, name):
+ return "&%s" % name
+
+
+
+# Sometimes it's useful to define a type that's only usable as input or output parameter
+
+class InputOnlyMixIn:
+
+ "Mix-in class to boobytrap passOutput"
+
+ def passOutput(self, name):
+ raise RuntimeError, "Type '%s' can only be used for input parameters" % self.typeName
+
+class InputOnlyType(InputOnlyMixIn, Type):
+
+ "Same as Type, but only usable for input parameters -- passOutput is boobytrapped"
+
+class OutputOnlyMixIn:
+
+ "Mix-in class to boobytrap passInput"
+
+ def passInput(self, name):
+ raise RuntimeError, "Type '%s' can only be used for output parameters" % self.typeName
+
+class OutputOnlyType(OutputOnlyMixIn, Type):
+
+ "Same as Type, but only usable for output parameters -- passInput is boobytrapped"
+
+
+# A modest collection of standard C types.
+void = None
+char = Type("char", "c")
+short = Type("short", "h")
+unsigned_short = Type("unsigned short", "H")
+int = Type("int", "i")
+long = Type("long", "l")
+unsigned_long = Type("unsigned long", "l")
+float = Type("float", "f")
+double = Type("double", "d")
+
+
+# The most common use of character pointers is a null-terminated string.
+# For input, this is easy. For output, and for other uses of char *,
+# see the module bgenBuffer.
+stringptr = InputOnlyType("char*", "s")
+unicodestringptr = InputOnlyType("wchar_t *", "u")
+
+
+# Some Python related types.
+objectptr = Type("PyObject*", "O")
+stringobjectptr = Type("PyStringObject*", "S")
+# Etc.
+
+
+class FakeType(InputOnlyType):
+
+ """A type that is not represented in the Python version of the interface.
+
+ Instantiate with a value to pass in the call.
+ """
+
+ def __init__(self, substitute):
+ self.substitute = substitute
+ self.typeName = None # Don't show this argument in __doc__ string
+
+ def getArgDeclarations(self, name, reference=False, constmode=False, outmode=False):
+ return []
+
+ def getAuxDeclarations(self, name, reference=False):
+ return []
+
+ def getargsFormat(self):
+ return ""
+
+ def getargsArgs(self, name):
+ return None
+
+ def passInput(self, name):
+ return self.substitute
+
+
+class OpaqueType(Type):
+
+ """A type represented by an opaque object type, always passed by address.
+
+ Instantiate with the type name and the names of the new and convert procs.
+ If fewer than three arguments are passed, the second argument is used
+ to derive the new and convert procs by appending _New and _Convert; it
+ defaults to the first argument.
+ """
+
+ def __init__(self, name, arg = None, extra = None):
+ self.typeName = name
+ if extra is None:
+ # Two arguments (name, usetype) or one (name)
+ arg = arg or name
+ self.new = arg + '_New'
+ self.convert = arg + '_Convert'
+ else:
+ # Three arguments (name, new, convert)
+ self.new = arg
+ self.convert = extra
+
+ def getargsFormat(self):
+ return "O&"
+
+ def getargsArgs(self, name):
+ return "%s, &%s" % (self.convert, name)
+
+ def passInput(self, name):
+ return "&%s" % name
+
+ def mkvalueFormat(self):
+ return "O&"
+
+ def mkvalueArgs(self, name):
+ return "%s, &%s" % (self.new, name)
+
+
+class OpaqueByValueType(OpaqueType):
+
+ """A type represented by an opaque object type, on input passed BY VALUE.
+
+ Instantiate with the type name, and optionally an object type name whose
+ New/Convert functions will be used.
+ """
+
+ def passInput(self, name):
+ return name
+
+ def mkvalueArgs(self, name):
+ return "%s, %s" % (self.new, name)
+
+class OpaqueByRefType(OpaqueType):
+ """An opaque object type, passed by reference.
+
+ Instantiate with the type name, and optionally an object type name whose
+ New/Convert functions will be used.
+ """
+
+ def passInput(self, name):
+ return name
+
+# def passOutput(self, name):
+# return name
+
+ def mkvalueFormat(self):
+ return "O"
+
+ def mkvalueArgs(self, name):
+ return "%s(%s)" % (self.new, name)
+
+class OpaqueByValueStructType(OpaqueByValueType):
+ """Similar to OpaqueByValueType, but we also pass this to mkvalue by
+ address, in stead of by value.
+ """
+
+ def mkvalueArgs(self, name):
+ return "%s, &%s" % (self.new, name)
+
+
+class OpaqueArrayType(OpaqueByValueType):
+
+ """A type represented by an opaque object type, with ARRAY passing semantics.
+
+ Instantiate with the type name, and optional an object type name whose
+ New/Convert functions will be used.
+ """
+
+ def getargsArgs(self, name):
+ return "%s, %s" % (self.convert, name)
+
+ def passOutput(self, name):
+ return name
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenVariable.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenVariable.py
new file mode 100644
index 0000000000..57059bfb8e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/bgenVariable.py
@@ -0,0 +1,112 @@
+"""Variables, arguments and argument transfer modes etc."""
+
+
+# Values to represent argument transfer modes
+InMode = 1 # input-only argument
+OutMode = 2 # output-only argument
+InOutMode = 3 # input-output argument
+ModeMask = 3 # bits to keep for mode
+
+
+# Special cases for mode/flags argument
+# XXX This is still a mess!
+SelfMode = 4+InMode # this is 'self' -- don't declare it
+ReturnMode = 8+OutMode # this is the function return value
+ErrorMode = 16+OutMode # this is an error status -- turn it into an exception
+RefMode = 32
+ConstMode = 64
+
+class Variable:
+
+ """A Variable holds a type, a name, a transfer mode and flags.
+
+ Most of its methods call the correponding type method with the
+ variable name.
+ """
+
+ def __init__(self, type, name = None, flags = InMode):
+ """Call with a type, a name and flags.
+
+ If name is None, it muse be set later.
+ flags defaults to InMode.
+ """
+ self.type = type
+ self.name = name
+ self.flags = flags
+ self.mode = flags & ModeMask
+
+ def declare(self):
+ """Declare the variable if necessary.
+
+ If it is "self", it is not declared.
+ """
+ if self.flags == ReturnMode+RefMode:
+ self.type.declare(self.name, reference=True)
+ elif self.flags != SelfMode:
+ self.type.declare(self.name)
+
+ def getArgDeclarations(self, fullmodes=False):
+ refmode = (self.flags & RefMode)
+ constmode = False
+ outmode = False
+ if fullmodes:
+ constmode = (self.flags & ConstMode)
+ outmode = (self.flags & OutMode)
+ return self.type.getArgDeclarations(self.name,
+ reference=refmode, constmode=constmode, outmode=outmode)
+
+ def getAuxDeclarations(self):
+ return self.type.getAuxDeclarations(self.name)
+
+ def getargsFormat(self):
+ """Call the type's getargsFormatmethod."""
+ return self.type.getargsFormat()
+
+ def getargsArgs(self):
+ """Call the type's getargsArgsmethod."""
+ return self.type.getargsArgs(self.name)
+
+ def getargsCheck(self):
+ return self.type.getargsCheck(self.name)
+
+ def getargsPreCheck(self):
+ return self.type.getargsPreCheck(self.name)
+
+ def passArgument(self):
+ """Return the string required to pass the variable as argument.
+
+ For "in" arguments, return the variable name.
+ For "out" and "in out" arguments,
+ return its name prefixed with "&".
+ """
+ if self.mode == InMode:
+ return self.type.passInput(self.name)
+ if self.mode & RefMode:
+ return self.type.passReference(self.name)
+ if self.mode in (OutMode, InOutMode):
+ return self.type.passOutput(self.name)
+ # XXX Shouldn't get here
+ return "/*mode?*/" + self.type.passInput(self.name)
+
+ def errorCheck(self):
+ """Check for an error if necessary.
+
+ This only generates code if the variable's mode is ErrorMode.
+ """
+ if self.flags == ErrorMode:
+ self.type.errorCheck(self.name)
+
+ def mkvalueFormat (self):
+ """Call the type's mkvalueFormat method."""
+ return self.type.mkvalueFormat()
+
+ def mkvalueArgs(self):
+ """Call the type's mkvalueArgs method."""
+ return self.type.mkvalueArgs(self.name)
+
+ def mkvaluePreCheck(self):
+ return self.type.mkvaluePreCheck(self.name)
+
+ def cleanup(self):
+ """Call the type's cleanup method."""
+ return self.type.cleanup(self.name)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/macsupport.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/macsupport.py
new file mode 100644
index 0000000000..6e2f041f4a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/macsupport.py
@@ -0,0 +1,197 @@
+"""\
+Augment the "bgen" package with definitions that are useful on the Apple Macintosh.
+
+Intended usage is "from macsupport import *" -- this implies all bgen's goodies.
+"""
+
+
+# Import everything from bgen (for ourselves as well as for re-export)
+from bgen import *
+
+
+# Simple types
+Boolean = Type("Boolean", "b")
+SignedByte = Type("SignedByte", "b")
+Size = Type("Size", "l")
+Style = Type("Style", "b")
+StyleParameter = Type("StyleParameter", "h")
+CharParameter = Type("CharParameter", "h")
+TextEncoding = Type("TextEncoding", "l")
+ByteCount = Type("ByteCount", "l")
+Duration = Type("Duration", "l")
+ByteOffset = Type("ByteOffset", "l")
+OptionBits = Type("OptionBits", "l")
+ItemCount = Type("ItemCount", "l")
+PBVersion = Type("PBVersion", "l")
+ScriptCode = Type("ScriptCode", "h")
+LangCode = Type("LangCode", "h")
+RegionCode = Type("RegionCode", "h")
+
+UInt8 = Type("UInt8", "b")
+SInt8 = Type("SInt8", "b")
+UInt16 = Type("UInt16", "H")
+SInt16 = Type("SInt16", "h")
+UInt32 = Type("UInt32", "l")
+SInt32 = Type("SInt32", "l")
+Float32 = Type("Float32", "f")
+
+wide = OpaqueByValueType("wide", "PyMac_Buildwide", "PyMac_Getwide")
+wide_ptr = OpaqueType("wide", "PyMac_Buildwide", "PyMac_Getwide")
+
+# Pascal strings
+ConstStr255Param = OpaqueArrayType("Str255", "PyMac_BuildStr255", "PyMac_GetStr255")
+Str255 = OpaqueArrayType("Str255", "PyMac_BuildStr255", "PyMac_GetStr255")
+StringPtr = OpaqueByValueType("StringPtr", "PyMac_BuildStr255", "PyMac_GetStr255")
+ConstStringPtr = StringPtr
+
+# File System Specifications
+FSSpec_ptr = OpaqueType("FSSpec", "PyMac_BuildFSSpec", "PyMac_GetFSSpec")
+FSSpec = OpaqueByValueStructType("FSSpec", "PyMac_BuildFSSpec", "PyMac_GetFSSpec")
+FSRef_ptr = OpaqueType("FSRef", "PyMac_BuildFSRef", "PyMac_GetFSRef")
+FSRef = OpaqueByValueStructType("FSRef", "PyMac_BuildFSRef", "PyMac_GetFSRef")
+
+# OSType and ResType: 4-byte character strings
+def OSTypeType(typename):
+ return OpaqueByValueType(typename, "PyMac_BuildOSType", "PyMac_GetOSType")
+OSType = OSTypeType("OSType")
+ResType = OSTypeType("ResType")
+FourCharCode = OSTypeType("FourCharCode")
+
+# Version numbers
+NumVersion = OpaqueByValueType("NumVersion", "PyMac_BuildNumVersion", "BUG")
+
+# Handles (always resources in our case)
+Handle = OpaqueByValueType("Handle", "ResObj")
+MenuHandle = OpaqueByValueType("MenuHandle", "MenuObj")
+MenuRef = MenuHandle
+ControlHandle = OpaqueByValueType("ControlHandle", "CtlObj")
+ControlRef = ControlHandle
+
+# Windows and Dialogs
+WindowPtr = OpaqueByValueType("WindowPtr", "WinObj")
+WindowRef = WindowPtr
+DialogPtr = OpaqueByValueType("DialogPtr", "DlgObj")
+DialogRef = DialogPtr
+ExistingWindowPtr = OpaqueByValueType("WindowPtr", "WinObj_WhichWindow", "BUG")
+ExistingDialogPtr = OpaqueByValueType("DialogPtr", "DlgObj_WhichDialog", "BUG")
+
+# NULL pointer passed in as optional storage -- not present in Python version
+NullStorage = FakeType("(void *)0")
+
+# More standard datatypes
+Fixed = OpaqueByValueType("Fixed", "PyMac_BuildFixed", "PyMac_GetFixed")
+
+# Quickdraw data types
+Rect = Rect_ptr = OpaqueType("Rect", "PyMac_BuildRect", "PyMac_GetRect")
+Point = OpaqueByValueType("Point", "PyMac_BuildPoint", "PyMac_GetPoint")
+Point_ptr = OpaqueType("Point", "PyMac_BuildPoint", "PyMac_GetPoint")
+
+# Event records
+EventRecord = OpaqueType("EventRecord", "PyMac_BuildEventRecord", "PyMac_GetEventRecord")
+EventRecord_ptr = EventRecord
+
+# CoreFoundation datatypes
+CFTypeRef = OpaqueByValueType("CFTypeRef", "CFTypeRefObj")
+CFStringRef = OpaqueByValueType("CFStringRef", "CFStringRefObj")
+CFMutableStringRef = OpaqueByValueType("CFMutableStringRef", "CFMutableStringRefObj")
+CFArrayRef = OpaqueByValueType("CFArrayRef", "CFArrayRefObj")
+CFMutableArrayRef = OpaqueByValueType("CFMutableArrayRef", "CFMutableArrayRefObj")
+CFDictionaryRef = OpaqueByValueType("CFDictionaryRef", "CFDictionaryRefObj")
+CFMutableDictionaryRef = OpaqueByValueType("CFMutableDictionaryRef", "CFMutableDictionaryRefObj")
+CFURLRef = OpaqueByValueType("CFURLRef", "CFURLRefObj")
+OptionalCFURLRef = OpaqueByValueType("CFURLRef", "OptionalCFURLRefObj")
+
+# OSErr is special because it is turned into an exception
+# (Could do this with less code using a variant of mkvalue("O&")?)
+class OSErrType(Type):
+ def errorCheck(self, name):
+ Output("if (%s != noErr) return PyMac_Error(%s);", name, name)
+ self.used = 1
+OSErr = OSErrType("OSErr", 'h')
+OSStatus = OSErrType("OSStatus", 'l')
+
+
+# Various buffer types
+
+InBuffer = VarInputBufferType('char', 'long', 'l') # (buf, len)
+UcharInBuffer = VarInputBufferType('unsigned char', 'long', 'l') # (buf, len)
+OptionalInBuffer = OptionalVarInputBufferType('char', 'long', 'l') # (buf, len)
+
+InOutBuffer = HeapInputOutputBufferType('char', 'long', 'l') # (inbuf, outbuf, len)
+VarInOutBuffer = VarHeapInputOutputBufferType('char', 'long', 'l') # (inbuf, outbuf, &len)
+
+OutBuffer = HeapOutputBufferType('char', 'long', 'l') # (buf, len)
+VarOutBuffer = VarHeapOutputBufferType('char', 'long', 'l') # (buf, &len)
+VarVarOutBuffer = VarVarHeapOutputBufferType('char', 'long', 'l') # (buf, len, &len)
+
+# Unicode arguments sometimes have reversed len, buffer (don't understand why Apple did this...)
+class VarUnicodeInputBufferType(VarInputBufferType):
+
+ def getargsFormat(self):
+ return "u#"
+
+class VarUnicodeReverseInputBufferType(ReverseInputBufferMixin, VarUnicodeInputBufferType):
+ pass
+
+UnicodeInBuffer = VarUnicodeInputBufferType('UniChar', 'UniCharCount', 'l')
+UnicodeReverseInBuffer = VarUnicodeReverseInputBufferType('UniChar', 'UniCharCount', 'l')
+UniChar_ptr = InputOnlyType("UniCharPtr", "u")
+
+
+# Predefine various pieces of program text to be passed to Module() later:
+
+# Stuff added immediately after the system include files
+includestuff = """
+#include "pymactoolbox.h"
+
+/* Macro to test whether a weak-loaded CFM function exists */
+#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\\
+ PyErr_SetString(PyExc_NotImplementedError, \\
+ "Not available in this shared library/OS version"); \\
+ return NULL; \\
+ }} while(0)
+
+"""
+
+# Stuff added just before the module's init function
+finalstuff = """
+"""
+
+# Stuff added inside the module's init function
+initstuff = """
+"""
+
+
+# Generator classes with a twist -- if the function returns OSErr,
+# its mode is manipulated so that it turns into an exception or disappears
+# (and its name is changed to _err, for documentation purposes).
+# This requires that the OSErr type (defined above) has a non-trivial
+# errorCheck method.
+class OSErrMixIn:
+ "Mix-in class to treat OSErr/OSStatus return values special"
+ def makereturnvar(self):
+ if self.returntype.__class__ == OSErrType:
+ return Variable(self.returntype, "_err", ErrorMode)
+ else:
+ return Variable(self.returntype, "_rv", OutMode)
+
+class OSErrFunctionGenerator(OSErrMixIn, FunctionGenerator): pass
+class OSErrMethodGenerator(OSErrMixIn, MethodGenerator): pass
+
+class WeakLinkMixIn:
+ "Mix-in to test the function actually exists (!= NULL) before calling"
+
+ def precheck(self):
+ Output('#ifndef %s', self.name)
+ Output('PyMac_PRECHECK(%s);', self.name)
+ Output('#endif')
+
+class WeakLinkFunctionGenerator(WeakLinkMixIn, FunctionGenerator): pass
+class WeakLinkMethodGenerator(WeakLinkMixIn, MethodGenerator): pass
+class OSErrWeakLinkFunctionGenerator(OSErrMixIn, WeakLinkMixIn, FunctionGenerator): pass
+class OSErrWeakLinkMethodGenerator(OSErrMixIn, WeakLinkMixIn, MethodGenerator): pass
+
+class MacModule(Module):
+ "Subclass which gets the exception initializer from macglue.c"
+ def exceptionInitializer(self):
+ return "PyMac_GetOSErrException()"
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/scantools.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/scantools.py
new file mode 100644
index 0000000000..1dd3627212
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/bgen/bgen/scantools.py
@@ -0,0 +1,849 @@
+"""\
+
+Tools for scanning header files in search of function prototypes.
+
+Often, the function prototypes in header files contain enough information
+to automatically generate (or reverse-engineer) interface specifications
+from them. The conventions used are very vendor specific, but once you've
+figured out what they are they are often a great help, and it sure beats
+manually entering the interface specifications. (These are needed to generate
+the glue used to access the functions from Python.)
+
+In order to make this class useful, almost every component can be overridden.
+The defaults are (currently) tuned to scanning Apple Macintosh header files,
+although most Mac specific details are contained in header-specific subclasses.
+"""
+
+import re
+import sys
+import os
+import fnmatch
+from types import *
+try:
+ import MacOS
+except ImportError:
+ MacOS = None
+
+try:
+ from bgenlocations import CREATOR, INCLUDEDIR
+except ImportError:
+ CREATOR = None
+ INCLUDEDIR = os.curdir
+
+Error = "scantools.Error"
+
+BEGINHTMLREPORT="""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<html>
+<head>
+<style type="text/css">
+.unmatched { }
+.commentstripping { color: grey; text-decoration: line-through }
+.comment { text-decoration: line-through }
+.notcomment { color: black }
+.incomplete { color: maroon }
+.constant { color: green }
+.pyconstant { background-color: yellow }
+.blconstant { background-color: yellow; color: red }
+.declaration { color: blue }
+.pydeclaration { background-color: yellow }
+.type { font-style: italic }
+.name { font-weight: bold }
+.value { font-style: italic }
+.arglist { text-decoration: underline }
+.blacklisted { background-color: yellow; color: red }
+</style>
+<title>Bgen scan report</title>
+</head>
+<body>
+<h1>Bgen scan report</h1>
+<h2>Legend</h2>
+<p>This scan report is intended to help you debug the regular expressions
+used by the bgen scanner. It consists of the original ".h" header file(s)
+marked up to show you what the regular expressions in the bgen parser matched
+for each line. NOTE: comments in the original source files may or may not be
+shown.</p>
+<p>The typographic conventions of this file are as follows:</p>
+<dl>
+<dt>comment stripping</dt>
+<dd><pre><span class="commentstripping"><span class="notcomment">comment stripping is </span><span class="comment">/* marked up */</span><span class="notcomment"> and the line is repeated if needed</span></span></pre>
+<p>If anything here does not appear to happen correctly look at
+<tt>comment1_pat</tt> and <tt>comment2_pat</tt>.</p>
+</dd>
+<dt>constant definitions</dt>
+<dd><pre><span class="constant">#define <span class="name">name</span> <span class="value">value</span></pre>
+<p>Highlights name and value of the constant. Governed by <tt>sym_pat</tt>.</p>
+</dd>
+<dt>function declaration</dt>
+<dd><pre><span class="declaration"><span class="type">char *</span><span class="name">rindex</span><span class="arglist">(<span class="type">const char *</span><span class="name">s</span>, <span class="type">int </span><span class="name">c</span>)</span>;</span></pre>
+<p>Highlights type, name and argument list. <tt>type_pat</tt>,
+<tt>name_pat</tt> and <tt>args_pat</tt> are combined into <tt>whole_pat</tt>, which
+is what is used here.</p></dd>
+</dd>
+<dt>incomplete match for function declaration</dt>
+<dd><pre><span class="incomplete"><span class="type">char *</span>foo;</span></pre>
+<p>The beginning of this looked promising, but it did not match a function declaration.
+In other words, it matched <tt>head_pat</tt> but not <tt>whole_pat</tt>. If the next
+declaration has also been gobbled up you need to look at <tt>end_pat</tt>.</p>
+</dd>
+<dt>unrecognized input</dt>
+<dd><pre><span class="unmatched">#include "type.h"</span></pre>
+<p>If there are function declarations the scanner has missed (i.e. things
+are in this class but you want them to be declarations) you need to adapt
+<tt>head_pat</tt>.
+</dd>
+</dl>
+<h2>Output</h2>
+<pre>
+<span class="unmatched">
+"""
+ENDHTMLREPORT="""</span>
+</pre>
+</body>
+</html>
+"""
+
+class Scanner:
+
+ # Set to 1 in subclass to debug your scanner patterns.
+ debug = 0
+
+ def __init__(self, input = None, output = None, defsoutput = None):
+ self.initsilent()
+ self.initblacklists()
+ self.initrepairinstructions()
+ self.initpaths()
+ self.initfiles()
+ self.initpatterns()
+ self.compilepatterns()
+ self.initosspecifics()
+ self.initusedtypes()
+ if output:
+ self.setoutput(output, defsoutput)
+ if input:
+ self.setinput(input)
+
+ def initusedtypes(self):
+ self.usedtypes = {}
+
+ def typeused(self, type, mode):
+ if not self.usedtypes.has_key(type):
+ self.usedtypes[type] = {}
+ self.usedtypes[type][mode] = None
+
+ def reportusedtypes(self):
+ types = self.usedtypes.keys()
+ types.sort()
+ for type in types:
+ modes = self.usedtypes[type].keys()
+ modes.sort()
+ self.report("%s %s", type, " ".join(modes))
+
+ def gentypetest(self, file):
+ fp = open(file, "w")
+ fp.write("types=[\n")
+ types = self.usedtypes.keys()
+ types.sort()
+ for type in types:
+ fp.write("\t'%s',\n"%type)
+ fp.write("]\n")
+ fp.write("""missing=0
+for t in types:
+ try:
+ tt = eval(t)
+ except NameError:
+ print "** Missing type:", t
+ missing = 1
+if missing: raise "Missing Types"
+""")
+ fp.close()
+
+ def initsilent(self):
+ self.silent = 1
+
+ def error(self, format, *args):
+ if self.silent >= 0:
+ print format%args
+
+ def report(self, format, *args):
+ if not self.silent:
+ print format%args
+
+ def writeinitialdefs(self):
+ pass
+
+ def initblacklists(self):
+ self.blacklistnames = self.makeblacklistnames()
+ self.blacklisttypes = ["unknown", "-"] + self.makeblacklisttypes()
+ self.greydictnames = self.greylist2dict(self.makegreylist())
+
+ def greylist2dict(self, list):
+ rv = {}
+ for define, namelist in list:
+ for name in namelist:
+ rv[name] = define
+ return rv
+
+ def makeblacklistnames(self):
+ return []
+
+ def makeblacklisttypes(self):
+ return []
+
+ def makegreylist(self):
+ return []
+
+ def initrepairinstructions(self):
+ self.repairinstructions = self.makerepairinstructions()
+ self.inherentpointertypes = self.makeinherentpointertypes()
+
+ def makerepairinstructions(self):
+ """Parse the repair file into repair instructions.
+
+ The file format is simple:
+ 1) use \ to split a long logical line in multiple physical lines
+ 2) everything after the first # on a line is ignored (as comment)
+ 3) empty lines are ignored
+ 4) remaining lines must have exactly 3 colon-separated fields:
+ functionpattern : argumentspattern : argumentsreplacement
+ 5) all patterns use shell style pattern matching
+ 6) an empty functionpattern means the same as *
+ 7) the other two fields are each comma-separated lists of triples
+ 8) a triple is a space-separated list of 1-3 words
+ 9) a triple with less than 3 words is padded at the end with "*" words
+ 10) when used as a pattern, a triple matches the type, name, and mode
+ of an argument, respectively
+ 11) when used as a replacement, the words of a triple specify
+ replacements for the corresponding words of the argument,
+ with "*" as a word by itself meaning leave the original word
+ (no other uses of "*" is allowed)
+ 12) the replacement need not have the same number of triples
+ as the pattern
+ """
+ f = self.openrepairfile()
+ if not f: return []
+ print "Reading repair file", repr(f.name), "..."
+ list = []
+ lineno = 0
+ while 1:
+ line = f.readline()
+ if not line: break
+ lineno = lineno + 1
+ startlineno = lineno
+ while line[-2:] == '\\\n':
+ line = line[:-2] + ' ' + f.readline()
+ lineno = lineno + 1
+ i = line.find('#')
+ if i >= 0: line = line[:i]
+ words = [s.strip() for s in line.split(':')]
+ if words == ['']: continue
+ if len(words) <> 3:
+ print "Line", startlineno,
+ print ": bad line (not 3 colon-separated fields)"
+ print repr(line)
+ continue
+ [fpat, pat, rep] = words
+ if not fpat: fpat = "*"
+ if not pat:
+ print "Line", startlineno,
+ print "Empty pattern"
+ print repr(line)
+ continue
+ patparts = [s.strip() for s in pat.split(',')]
+ repparts = [s.strip() for s in rep.split(',')]
+ patterns = []
+ for p in patparts:
+ if not p:
+ print "Line", startlineno,
+ print "Empty pattern part"
+ print repr(line)
+ continue
+ pattern = p.split()
+ if len(pattern) > 3:
+ print "Line", startlineno,
+ print "Pattern part has > 3 words"
+ print repr(line)
+ pattern = pattern[:3]
+ else:
+ while len(pattern) < 3:
+ pattern.append("*")
+ patterns.append(pattern)
+ replacements = []
+ for p in repparts:
+ if not p:
+ print "Line", startlineno,
+ print "Empty replacement part"
+ print repr(line)
+ continue
+ replacement = p.split()
+ if len(replacement) > 3:
+ print "Line", startlineno,
+ print "Pattern part has > 3 words"
+ print repr(line)
+ replacement = replacement[:3]
+ else:
+ while len(replacement) < 3:
+ replacement.append("*")
+ replacements.append(replacement)
+ list.append((fpat, patterns, replacements))
+ return list
+
+ def makeinherentpointertypes(self):
+ return []
+
+ def openrepairfile(self, filename = "REPAIR"):
+ try:
+ return open(filename, "rU")
+ except IOError, msg:
+ print repr(filename), ":", msg
+ print "Cannot open repair file -- assume no repair needed"
+ return None
+
+ def initfiles(self):
+ self.specmine = 0
+ self.defsmine = 0
+ self.scanmine = 0
+ self.htmlmine = 0
+ self.specfile = sys.stdout
+ self.defsfile = None
+ self.scanfile = sys.stdin
+ self.htmlfile = None
+ self.lineno = 0
+ self.line = ""
+
+ def initpaths(self):
+ self.includepath = [os.curdir, INCLUDEDIR]
+
+ def initpatterns(self):
+ self.head_pat = r"^EXTERN_API[^_]"
+ self.tail_pat = r"[;={}]"
+ self.type_pat = r"EXTERN_API" + \
+ r"[ \t\n]*\([ \t\n]*" + \
+ r"(?P<type>[a-zA-Z0-9_* \t]*[a-zA-Z0-9_*])" + \
+ r"[ \t\n]*\)[ \t\n]*"
+ self.name_pat = r"(?P<name>[a-zA-Z0-9_]+)[ \t\n]*"
+ self.args_pat = r"\((?P<args>([^\(;=\)]+|\([^\(;=\)]*\))*)\)"
+ self.whole_pat = self.type_pat + self.name_pat + self.args_pat
+ self.sym_pat = r"^[ \t]*(?P<name>[a-zA-Z0-9_]+)[ \t]*=" + \
+ r"[ \t]*(?P<defn>[-0-9_a-zA-Z'\"\(][^\t\n,;}]*),?"
+ self.asplit_pat = r"^(?P<type>.*[^a-zA-Z0-9_])(?P<name>[a-zA-Z0-9_]+)(?P<array>\[\])?$"
+ self.comment1_pat = r"(?P<rest>.*)//.*"
+ # note that the next pattern only removes comments that are wholly within one line
+ self.comment2_pat = r"(?P<rest1>.*)/\*.*\*/(?P<rest2>.*)"
+
+ def compilepatterns(self):
+ for name in dir(self):
+ if name[-4:] == "_pat":
+ pat = getattr(self, name)
+ prog = re.compile(pat)
+ setattr(self, name[:-4], prog)
+
+ def initosspecifics(self):
+ if MacOS and CREATOR:
+ self.filetype = 'TEXT'
+ self.filecreator = CREATOR
+ else:
+ self.filetype = self.filecreator = None
+
+ def setfiletype(self, filename):
+ if MacOS and (self.filecreator or self.filetype):
+ creator, type = MacOS.GetCreatorAndType(filename)
+ if self.filecreator: creator = self.filecreator
+ if self.filetype: type = self.filetype
+ MacOS.SetCreatorAndType(filename, creator, type)
+
+ def close(self):
+ self.closefiles()
+
+ def closefiles(self):
+ self.closespec()
+ self.closedefs()
+ self.closescan()
+ self.closehtml()
+
+ def closespec(self):
+ tmp = self.specmine and self.specfile
+ self.specfile = None
+ if tmp: tmp.close()
+
+ def closedefs(self):
+ tmp = self.defsmine and self.defsfile
+ self.defsfile = None
+ if tmp: tmp.close()
+
+ def closescan(self):
+ tmp = self.scanmine and self.scanfile
+ self.scanfile = None
+ if tmp: tmp.close()
+
+ def closehtml(self):
+ if self.htmlfile: self.htmlfile.write(ENDHTMLREPORT)
+ tmp = self.htmlmine and self.htmlfile
+ self.htmlfile = None
+ if tmp: tmp.close()
+
+ def setoutput(self, spec, defs = None):
+ self.closespec()
+ self.closedefs()
+ if spec:
+ if type(spec) == StringType:
+ file = self.openoutput(spec)
+ mine = 1
+ else:
+ file = spec
+ mine = 0
+ self.specfile = file
+ self.specmine = mine
+ if defs:
+ if type(defs) == StringType:
+ file = self.openoutput(defs)
+ mine = 1
+ else:
+ file = defs
+ mine = 0
+ self.defsfile = file
+ self.defsmine = mine
+
+ def sethtmloutput(self, htmlfile):
+ self.closehtml()
+ if htmlfile:
+ if type(htmlfile) == StringType:
+ file = self.openoutput(htmlfile)
+ mine = 1
+ else:
+ file = htmlfile
+ mine = 0
+ self.htmlfile = file
+ self.htmlmine = mine
+ self.htmlfile.write(BEGINHTMLREPORT)
+
+ def openoutput(self, filename):
+ try:
+ file = open(filename, 'w')
+ except IOError, arg:
+ raise IOError, (filename, arg)
+ self.setfiletype(filename)
+ return file
+
+ def setinput(self, scan = sys.stdin):
+ if not type(scan) in (TupleType, ListType):
+ scan = [scan]
+ self.allscaninputs = scan
+ self._nextinput()
+
+ def _nextinput(self):
+ if not self.allscaninputs:
+ return 0
+ scan = self.allscaninputs[0]
+ self.allscaninputs = self.allscaninputs[1:]
+ self.closescan()
+ if scan:
+ if type(scan) == StringType:
+ file = self.openinput(scan)
+ mine = 1
+ else:
+ file = scan
+ mine = 0
+ self.scanfile = file
+ self.scanmine = mine
+ self.lineno = 0
+ return 1
+
+ def openinput(self, filename):
+ if not os.path.isabs(filename):
+ for dir in self.includepath:
+ fullname = os.path.join(dir, filename)
+ #self.report("trying full name %r", fullname)
+ try:
+ return open(fullname, 'rU')
+ except IOError:
+ pass
+ # If not on the path, or absolute, try default open()
+ try:
+ return open(filename, 'rU')
+ except IOError, arg:
+ raise IOError, (arg, filename)
+
+ def getline(self):
+ if not self.scanfile:
+ raise Error, "input file not set"
+ self.line = self.scanfile.readline()
+ if not self.line:
+ if self._nextinput():
+ return self.getline()
+ raise EOFError
+ self.lineno = self.lineno + 1
+ return self.line
+
+ def scan(self):
+ if not self.scanfile:
+ self.error("No input file has been specified")
+ return
+ inputname = self.scanfile.name
+ self.report("scanfile = %r", inputname)
+ if not self.specfile:
+ self.report("(No interface specifications will be written)")
+ else:
+ self.report("specfile = %r", self.specfile.name)
+ self.specfile.write("# Generated from %r\n\n" % (inputname,))
+ if not self.defsfile:
+ self.report("(No symbol definitions will be written)")
+ else:
+ self.report("defsfile = %r", (self.defsfile.name,))
+ self.defsfile.write("# Generated from %r\n\n" % (os.path.split(inputname)[1],))
+ self.writeinitialdefs()
+ self.alreadydone = []
+ try:
+ while 1:
+ try: line = self.getline()
+ except EOFError: break
+ if self.debug:
+ self.report("LINE: %r" % (line,))
+ match = self.comment1.match(line)
+ if match:
+ self.htmlreport(line, klass='commentstripping', ranges=[(
+ match.start('rest'), match.end('rest'), 'notcomment')])
+ line = match.group('rest')
+ if self.debug:
+ self.report("\tafter comment1: %r" % (line,))
+ match = self.comment2.match(line)
+ while match:
+ if match:
+ self.htmlreport(line, klass='commentstripping', ranges=[
+ (match.start('rest1'), match.end('rest1'), 'notcomment'),
+ (match.start('rest2'), match.end('rest2'), 'notcomment')])
+ line = match.group('rest1')+match.group('rest2')
+ if self.debug:
+ self.report("\tafter comment2: %r" % (line,))
+ match = self.comment2.match(line)
+ if self.defsfile:
+ match = self.sym.match(line)
+ if match:
+ if self.debug:
+ self.report("\tmatches sym.")
+ self.dosymdef(match, line)
+ continue
+ match = self.head.match(line)
+ if match:
+ if self.debug:
+ self.report("\tmatches head.")
+ self.dofuncspec()
+ continue
+ self.htmlreport(line, klass='unmatched')
+ except EOFError:
+ self.error("Uncaught EOF error")
+ self.reportusedtypes()
+
+ def dosymdef(self, match, line):
+ name, defn = match.group('name', 'defn')
+ self.htmlreport(line, klass='constant', ranges=[
+ (match.start('name'), match.end('name'), 'name'),
+ (match.start('defn'), match.end('defn'), 'value')])
+ defn = escape8bit(defn)
+ if self.debug:
+ self.report("\tsym: name=%r, defn=%r" % (name, defn))
+ if not name in self.blacklistnames:
+ oline = "%s = %s\n" % (name, defn)
+ self.defsfile.write(oline)
+ self.htmlreport(oline, klass="pyconstant")
+ else:
+ self.defsfile.write("# %s = %s\n" % (name, defn))
+ self.htmlreport("** no output: name is blacklisted", klass="blconstant")
+ # XXXX No way to handle greylisted names
+
+ def dofuncspec(self):
+ raw = self.line
+ while not self.tail.search(raw):
+ line = self.getline()
+ if self.debug:
+ self.report("* CONTINUATION LINE: %r" % (line,))
+ match = self.comment1.match(line)
+ if match:
+ line = match.group('rest')
+ if self.debug:
+ self.report("\tafter comment1: %r" % (line,))
+ match = self.comment2.match(line)
+ while match:
+ line = match.group('rest1')+match.group('rest2')
+ if self.debug:
+ self.report("\tafter comment1: %r" % (line,))
+ match = self.comment2.match(line)
+ raw = raw + line
+ if self.debug:
+ self.report("* WHOLE LINE: %r" % (raw,))
+ self.processrawspec(raw)
+ return raw
+
+ def processrawspec(self, raw):
+ match = self.whole.search(raw)
+ if not match:
+ self.report("Bad raw spec: %r", raw)
+ if self.debug:
+ match = self.type.search(raw)
+ if not match:
+ self.report("(Type already doesn't match)")
+ self.htmlreport(raw, klass='incomplete', ranges=[(
+ match.start('type'), match.end('type'), 'type')])
+ else:
+ self.report("(but type matched)")
+ self.htmlreport(raw, klass='incomplete')
+ return
+ type, name, args = match.group('type', 'name', 'args')
+ ranges=[
+ (match.start('type'), match.end('type'), 'type'),
+ (match.start('name'), match.end('name'), 'name'),
+ (match.start('args'), match.end('args'), 'arglist')]
+ self.htmlreport(raw, klass='declaration', ranges=ranges)
+ modifiers = self.getmodifiers(match)
+ type = self.pythonizename(type)
+ name = self.pythonizename(name)
+ if self.checkduplicate(name):
+ self.htmlreport("*** no output generated: duplicate name", klass="blacklisted")
+ return
+ self.report("==> %s %s <==", type, name)
+ if self.blacklisted(type, name):
+ self.htmlreport("*** no output generated: function name or return type blacklisted", klass="blacklisted")
+ self.report("*** %s %s blacklisted", type, name)
+ return
+ returnlist = [(type, name, 'ReturnMode')]
+ returnlist = self.repairarglist(name, returnlist)
+ [(type, name, returnmode)] = returnlist
+ arglist = self.extractarglist(args)
+ arglist = self.repairarglist(name, arglist)
+ if self.unmanageable(type, name, arglist):
+ self.htmlreport("*** no output generated: some argument blacklisted", klass="blacklisted")
+ ##for arg in arglist:
+ ## self.report(" %r", arg)
+ self.report("*** %s %s unmanageable", type, name)
+ return
+ if modifiers:
+ self.generate(type, name, arglist, modifiers)
+ else:
+ self.generate(type, name, arglist)
+
+ def getmodifiers(self, match):
+ return []
+
+ def checkduplicate(self, name):
+ if name in self.alreadydone:
+ self.report("Name has already been defined: %r", name)
+ return True
+ self.alreadydone.append(name)
+ return False
+
+ def pythonizename(self, name):
+ name = re.sub("\*", " ptr", name)
+ name = name.strip()
+ name = re.sub("[ \t]+", "_", name)
+ return name
+
+ def extractarglist(self, args):
+ args = args.strip()
+ if not args or args == "void":
+ return []
+ parts = [s.strip() for s in args.split(",")]
+ arglist = []
+ for part in parts:
+ arg = self.extractarg(part)
+ arglist.append(arg)
+ return arglist
+
+ def extractarg(self, part):
+ mode = "InMode"
+ part = part.strip()
+ match = self.asplit.match(part)
+ if not match:
+ self.error("Indecipherable argument: %r", part)
+ return ("unknown", part, mode)
+ type, name, array = match.group('type', 'name', 'array')
+ if array:
+ # array matches an optional [] after the argument name
+ type = type + " ptr "
+ type = self.pythonizename(type)
+ return self.modifyarg(type, name, mode)
+
+ def modifyarg(self, type, name, mode):
+ if type[:6] == "const_":
+ type = type[6:]
+ elif type[-4:] == "_ptr":
+ type = type[:-4]
+ mode = "OutMode"
+ elif type in self.inherentpointertypes:
+ mode = "OutMode"
+ if type[-4:] == "_far":
+ type = type[:-4]
+ return type, name, mode
+
+ def repairarglist(self, functionname, arglist):
+ arglist = arglist[:]
+ i = 0
+ while i < len(arglist):
+ for item in self.repairinstructions:
+ if len(item) == 2:
+ pattern, replacement = item
+ functionpat = "*"
+ else:
+ functionpat, pattern, replacement = item
+ if not fnmatch.fnmatchcase(functionname, functionpat):
+ continue
+ n = len(pattern)
+ if i+n > len(arglist): continue
+ current = arglist[i:i+n]
+ for j in range(n):
+ if not self.matcharg(pattern[j], current[j]):
+ break
+ else: # All items of the pattern match
+ new = self.substituteargs(
+ pattern, replacement, current)
+ if new is not None:
+ arglist[i:i+n] = new
+ i = i+len(new) # No recursive substitutions
+ break
+ else: # No patterns match
+ i = i+1
+ return arglist
+
+ def matcharg(self, patarg, arg):
+ return len(filter(None, map(fnmatch.fnmatchcase, arg, patarg))) == 3
+
+ def substituteargs(self, pattern, replacement, old):
+ new = []
+ for k in range(len(replacement)):
+ item = replacement[k]
+ newitem = [item[0], item[1], item[2]]
+ for i in range(3):
+ if item[i] == '*':
+ newitem[i] = old[k][i]
+ elif item[i][:1] == '$':
+ index = int(item[i][1:]) - 1
+ newitem[i] = old[index][i]
+ new.append(tuple(newitem))
+ ##self.report("old: %r", old)
+ ##self.report("new: %r", new)
+ return new
+
+ def generate(self, tp, name, arglist, modifiers=[]):
+
+ self.typeused(tp, 'return')
+ if modifiers:
+ classname, listname = self.destination(tp, name, arglist, modifiers)
+ else:
+ classname, listname = self.destination(tp, name, arglist)
+ if not classname or not listname:
+ self.htmlreport("*** no output generated: self.destination() returned None", klass="blacklisted")
+ return
+ if not self.specfile:
+ self.htmlreport("*** no output generated: no output file specified", klass="blacklisted")
+ return
+ self.specfile.write("f = %s(%s, %r,\n" % (classname, tp, name))
+ for atype, aname, amode in arglist:
+ self.typeused(atype, amode)
+ self.specfile.write(" (%s, %r, %s),\n" %
+ (atype, aname, amode))
+ if self.greydictnames.has_key(name):
+ self.specfile.write(" condition=%r,\n"%(self.greydictnames[name],))
+ self.generatemodifiers(classname, name, modifiers)
+ self.specfile.write(")\n")
+ self.specfile.write("%s.append(f)\n\n" % listname)
+ if self.htmlfile:
+ oline = "Adding to %s:\n%s(returntype=%s, name=%r" % (listname, classname, tp, name)
+ for atype, aname, amode in arglist:
+ oline += ",\n (%s, %r, %s)" % (atype, aname, amode)
+ oline += ")\n"
+ self.htmlreport(oline, klass="pydeclaration")
+
+ def destination(self, type, name, arglist):
+ return "FunctionGenerator", "functions"
+
+ def generatemodifiers(self, classname, name, modifiers):
+ pass
+
+ def blacklisted(self, type, name):
+ if type in self.blacklisttypes:
+ ##self.report("return type %s is blacklisted", type)
+ return 1
+ if name in self.blacklistnames:
+ ##self.report("function name %s is blacklisted", name)
+ return 1
+ return 0
+
+ def unmanageable(self, type, name, arglist):
+ for atype, aname, amode in arglist:
+ if atype in self.blacklisttypes:
+ self.report("argument type %s is blacklisted", atype)
+ return 1
+ return 0
+
+ def htmlreport(self, line, klass=None, ranges=None):
+ if not self.htmlfile: return
+ if ranges is None:
+ ranges = []
+ if klass:
+ ranges.insert(0, (0, len(line), klass))
+ oline = ''
+ i = 0
+ for c in line:
+ for b, e, name in ranges:
+ if b == i:
+ oline += '<span class="%s">' % name
+ if e == i:
+ oline += '</span>'
+ i += 1
+
+ if c == '<': oline += '&lt;'
+ elif c == '>': oline += '&gt;'
+ else: oline += c
+ for b, e, name in ranges:
+ if b >= i:
+ oline += '<span class="%s">' % name
+ if e >= i:
+ oline += '</span>'
+ if not line or line[-1] != '\n':
+ oline += '\n'
+ self.htmlfile.write(oline)
+
+class Scanner_PreUH3(Scanner):
+ """Scanner for Universal Headers before release 3"""
+ def initpatterns(self):
+ Scanner.initpatterns(self)
+ self.head_pat = "^extern pascal[ \t]+" # XXX Mac specific!
+ self.type_pat = "pascal[ \t\n]+(?P<type>[a-zA-Z0-9_ \t]*[a-zA-Z0-9_])[ \t\n]+"
+ self.whole_pat = self.type_pat + self.name_pat + self.args_pat
+ self.sym_pat = "^[ \t]*(?P<name>[a-zA-Z0-9_]+)[ \t]*=" + \
+ "[ \t]*(?P<defn>[-0-9'\"][^\t\n,;}]*),?"
+
+class Scanner_OSX(Scanner):
+ """Scanner for modern (post UH3.3) Universal Headers """
+ def initpatterns(self):
+ Scanner.initpatterns(self)
+ self.head_pat = "^EXTERN_API(_C)?"
+ self.type_pat = "EXTERN_API(_C)?" + \
+ "[ \t\n]*\([ \t\n]*" + \
+ "(?P<type>[a-zA-Z0-9_* \t]*[a-zA-Z0-9_*])" + \
+ "[ \t\n]*\)[ \t\n]*"
+ self.whole_pat = self.type_pat + self.name_pat + self.args_pat
+ self.sym_pat = "^[ \t]*(?P<name>[a-zA-Z0-9_]+)[ \t]*=" + \
+ "[ \t]*(?P<defn>[-0-9_a-zA-Z'\"\(][^\t\n,;}]*),?"
+
+_8bit = re.compile(r"[\200-\377]")
+
+def escape8bit(s):
+ if _8bit.search(s) is not None:
+ out = []
+ for c in s:
+ o = ord(c)
+ if o >= 128:
+ out.append("\\" + hex(o)[1:])
+ else:
+ out.append(c)
+ s = "".join(out)
+ return s
+
+def test():
+ input = "D:Development:THINK C:Mac #includes:Apple #includes:AppleEvents.h"
+ output = "@aespecs.py"
+ defsoutput = "@aedefs.py"
+ s = Scanner(input, output, defsoutput)
+ s.scan()
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/README.tcltk-AMD64 b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/README.tcltk-AMD64
new file mode 100644
index 0000000000..fcc5374a03
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/README.tcltk-AMD64
@@ -0,0 +1,36 @@
+Comments on building tcl/tk for AMD64 with the MS SDK compiler
+==============================================================
+
+I did have to build tcl/tk manually.
+
+First, I had to build the nmakehlp.exe helper utility manually by executing
+ cl nmakehlp.c /link bufferoverflowU.lib
+in both the tcl8.4.12\win and tk8.4.12\win directories.
+
+Second, the AMD64 compiler refuses to compile the file
+tcl8.4.12\generic\tclExecute.c because it insists on using intrinsics
+for the 'ceil' and 'floor' functions:
+
+ ..\generic\tclExecute.c(394) : error C2099: initializer is not a constant
+ ..\generic\tclExecute.c(398) : error C2099: initializer is not a constant
+
+I did comment out these lines; an alternative would have been to use
+the /Oi- compiler flag to disable the intrinsic functions.
+The commands then used were these:
+
+ svn export http://svn.python.org/projects/external/tcl8.4.12
+ cd tcl8.4.12\win
+ REM
+ echo patch the tcl8.4.12\generic\tclExecute.c file
+ pause
+ REM
+ cl nmakehlp.c /link bufferoverflowU.lib
+ nmake -f makefile.vc MACHINE=AMD64
+ nmake -f makefile.vc INSTALLDIR=..\..\tcltk install
+ cd ..\..
+ svn export http://svn.python.org/projects/external/tk8.4.12
+ cd tk8.4.12\win
+ cl nmakehlp.c /link bufferoverflowU.lib
+ nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12 MACHINE=AMD64
+ nmake -f makefile.vc TCLDIR=..\..\tcl8.4.12 INSTALLDIR=..\..\tcltk install
+ cd ..\..
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build-amd64.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build-amd64.bat
new file mode 100644
index 0000000000..8ec332884e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build-amd64.bat
@@ -0,0 +1,6 @@
+@rem Used by the buildbot "compile" step.
+cmd /c Tools\buildbot\external-amd64.bat
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
+cmd /c Tools\buildbot\clean-amd64.bat
+vcbuild /useenv PCbuild\kill_python.vcproj "Debug|x64" && PCbuild\amd64\kill_python_d.exe
+vcbuild PCbuild\pcbuild.sln "Debug|x64"
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build.bat
new file mode 100644
index 0000000000..976ce72b0f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/build.bat
@@ -0,0 +1,7 @@
+@rem Used by the buildbot "compile" step.
+cmd /c Tools\buildbot\external.bat
+call "%VS90COMNTOOLS%vsvars32.bat"
+cmd /c Tools\buildbot\clean.bat
+vcbuild /useenv PCbuild\kill_python.vcproj "Debug|Win32" && PCbuild\kill_python_d.exe
+vcbuild /useenv PCbuild\pcbuild.sln "Debug|Win32"
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/buildmsi.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/buildmsi.bat
new file mode 100644
index 0000000000..b4f63dc847
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/buildmsi.bat
@@ -0,0 +1,20 @@
+@rem Used by the buildbot "buildmsi" step.
+
+cmd /c Tools\buildbot\external.bat
+@rem build release versions of things
+call "%VS90COMNTOOLS%vsvars32.bat"
+
+@rem build Python
+vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32"
+
+@rem build the documentation
+bash.exe -c 'cd Doc;make PYTHON=python2.5 update htmlhelp'
+"%ProgramFiles%\HTML Help Workshop\hhc.exe" Doc\build\htmlhelp\python26a3.hhp
+
+@rem build the MSI file
+cd PC
+nmake /f icons.mak
+cd ..\Tools\msi
+del *.msi
+nmake /f msisupport.mak
+%HOST_PYTHON% msi.py
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean-amd64.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean-amd64.bat
new file mode 100644
index 0000000000..0f6b3b4b07
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean-amd64.bat
@@ -0,0 +1,10 @@
+@rem Used by the buildbot "clean" step.
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
+@echo Deleting .pyc/.pyo files ...
+del /s Lib\*.pyc Lib\*.pyo
+@echo Deleting test leftovers ...
+rmdir /s /q build
+cd PCbuild
+vcbuild /clean pcbuild.sln "Release|x64"
+vcbuild /clean pcbuild.sln "Debug|x64"
+cd ..
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean.bat
new file mode 100644
index 0000000000..cf8a6b747c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/clean.bat
@@ -0,0 +1,10 @@
+@rem Used by the buildbot "clean" step.
+call "%VS90COMNTOOLS%vsvars32.bat"
+@echo Deleting .pyc/.pyo files ...
+del /s Lib\*.pyc Lib\*.pyo
+@echo Deleting test leftovers ...
+rmdir /s /q build
+cd PCbuild
+vcbuild /clean pcbuild.sln "Release|Win32"
+vcbuild /clean pcbuild.sln "Debug|Win32"
+cd ..
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-amd64.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-amd64.bat
new file mode 100644
index 0000000000..902e37a9d6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-amd64.bat
@@ -0,0 +1,20 @@
+@rem Fetches (and builds if necessary) external dependencies
+
+@rem Assume we start inside the Python source directory
+call "Tools\buildbot\external-common.bat"
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
+
+if not exist tcltk64\bin\tcl85g.dll (
+ cd tcl-8.5.2.1\win
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 install
+ cd ..\..
+)
+
+if not exist tcltk64\bin\tk85g.dll (
+ cd tk-8.5.2.0\win
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.2.1 clean
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.2.1 all
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.2.1 install
+ cd ..\..
+)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-common.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-common.bat
new file mode 100644
index 0000000000..7395db5b50
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external-common.bat
@@ -0,0 +1,45 @@
+@rem Common file shared between external.bat and external-amd64.bat. Responsible for
+@rem fetching external components into the root\.. buildbot directories.
+
+cd ..
+@rem XXX: If you need to force the buildbots to start from a fresh environment, uncomment
+@rem the following, check it in, then check it out, comment it out, then check it back in.
+@rem if exist bzip2-1.0.5 rd /s/q bzip2-1.0.5
+@rem if exist tcltk rd /s/q tcltk
+@rem if exist tcltk64 rd /s/q tcltk64
+@rem if exist tcl8.4.12 rd /s/q tcl8.4.12
+@rem if exist tcl8.4.16 rd /s/q tcl8.4.16
+@rem if exist tcl-8.4.18.1 rd /s/q tcl-8.4.18.1
+@rem if exist tk8.4.12 rd /s/q tk8.4.12
+@rem if exist tk8.4.16 rd /s/q tk8.4.16
+@rem if exist tk-8.4.18.1 rd /s/q tk-8.4.18.1
+@rem if exist db-4.4.20 rd /s/q db-4.4.20
+@rem if exist db-4.7.25.0 rd /s/q db-4.7.25.0
+@rem if exist openssl-0.9.8l rd /s/q openssl-0.9.8l
+@rem if exist sqlite-3.6.21 rd /s/q sqlite-3.6.21
+
+@rem bzip
+if not exist bzip2-1.0.5 (
+ rd /s/q bzip2-1.0.3
+ svn export http://svn.python.org/projects/external/bzip2-1.0.5
+)
+
+@rem Berkeley DB
+if exist db-4.4.20 rd /s/q db-4.4.20
+if not exist db-4.7.25.0 svn export http://svn.python.org/projects/external/db-4.7.25.0
+
+@rem OpenSSL
+if not exist openssl-0.9.8l svn export http://svn.python.org/projects/external/openssl-0.9.8l
+
+@rem tcl/tk
+if not exist tcl-8.5.2.1 (
+ rd /s/q tcltk tcltk64
+ svn export http://svn.python.org/projects/external/tcl-8.5.2.1
+)
+if not exist tk-8.5.2.0 svn export http://svn.python.org/projects/external/tk-8.5.2.0
+
+@rem sqlite3
+if not exist sqlite-3.6.21 (
+ rd /s/q sqlite-source-3.3.4
+ svn export http://svn.python.org/projects/external/sqlite-3.6.21
+)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external.bat
new file mode 100644
index 0000000000..d6b18ae78f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/external.bat
@@ -0,0 +1,21 @@
+@rem Fetches (and builds if necessary) external dependencies
+
+@rem Assume we start inside the Python source directory
+call "Tools\buildbot\external-common.bat"
+call "%VS90COMNTOOLS%\vsvars32.bat"
+
+if not exist tcltk\bin\tcl85g.dll (
+ @rem all and install need to be separate invocations, otherwise nmakehlp is not found on install
+ cd tcl-8.5.2.1\win
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 INSTALLDIR=..\..\tcltk clean all
+ nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk install
+ cd ..\..
+)
+
+if not exist tcltk\bin\tk85g.dll (
+ cd tk-8.5.2.0\win
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.2.1 clean
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.2.1 all
+ nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.2.1 install
+ cd ..\..
+)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test-amd64.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test-amd64.bat
new file mode 100644
index 0000000000..6124b51d96
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test-amd64.bat
@@ -0,0 +1,3 @@
+@rem Used by the buildbot "test" step.
+cd PCbuild
+call rt.bat -q -d -x64 -uall -rw
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test.bat
new file mode 100644
index 0000000000..cffd850e05
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/buildbot/test.bat
@@ -0,0 +1,3 @@
+@rem Used by the buildbot "test" step.
+cd PCbuild
+call rt.bat -d -q -uall -rwW
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/ccbench/ccbench.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/ccbench/ccbench.py
new file mode 100644
index 0000000000..a2cf7205b8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/ccbench/ccbench.py
@@ -0,0 +1,609 @@
+# -*- coding: utf-8 -*-
+# This file should be kept compatible with both Python 2.6 and Python >= 3.0.
+
+from __future__ import division
+from __future__ import print_function
+
+"""
+ccbench, a Python concurrency benchmark.
+"""
+
+import time
+import os
+import sys
+import functools
+import itertools
+import threading
+import subprocess
+import socket
+from optparse import OptionParser, SUPPRESS_HELP
+import platform
+
+# Compatibility
+try:
+ xrange
+except NameError:
+ xrange = range
+
+try:
+ map = itertools.imap
+except AttributeError:
+ pass
+
+
+THROUGHPUT_DURATION = 2.0
+
+LATENCY_PING_INTERVAL = 0.1
+LATENCY_DURATION = 2.0
+
+BANDWIDTH_PACKET_SIZE = 1024
+BANDWIDTH_DURATION = 2.0
+
+
+def task_pidigits():
+ """Pi calculation (Python)"""
+ _map = map
+ _count = itertools.count
+ _islice = itertools.islice
+
+ def calc_ndigits(n):
+ # From http://shootout.alioth.debian.org/
+ def gen_x():
+ return _map(lambda k: (k, 4*k + 2, 0, 2*k + 1), _count(1))
+
+ def compose(a, b):
+ aq, ar, as_, at = a
+ bq, br, bs, bt = b
+ return (aq * bq,
+ aq * br + ar * bt,
+ as_ * bq + at * bs,
+ as_ * br + at * bt)
+
+ def extract(z, j):
+ q, r, s, t = z
+ return (q*j + r) // (s*j + t)
+
+ def pi_digits():
+ z = (1, 0, 0, 1)
+ x = gen_x()
+ while 1:
+ y = extract(z, 3)
+ while y != extract(z, 4):
+ z = compose(z, next(x))
+ y = extract(z, 3)
+ z = compose((10, -10*y, 0, 1), z)
+ yield y
+
+ return list(_islice(pi_digits(), n))
+
+ return calc_ndigits, (50, )
+
+def task_regex():
+ """regular expression (C)"""
+ # XXX this task gives horrendous latency results.
+ import re
+ # Taken from the `inspect` module
+ pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)', re.MULTILINE)
+ with open(__file__, "r") as f:
+ arg = f.read(2000)
+
+ def findall(s):
+ t = time.time()
+ try:
+ return pat.findall(s)
+ finally:
+ print(time.time() - t)
+ return pat.findall, (arg, )
+
+def task_sort():
+ """list sorting (C)"""
+ def list_sort(l):
+ l = l[::-1]
+ l.sort()
+
+ return list_sort, (list(range(1000)), )
+
+def task_compress_zlib():
+ """zlib compression (C)"""
+ import zlib
+ with open(__file__, "rb") as f:
+ arg = f.read(5000) * 3
+
+ def compress(s):
+ zlib.decompress(zlib.compress(s, 5))
+ return compress, (arg, )
+
+def task_compress_bz2():
+ """bz2 compression (C)"""
+ import bz2
+ with open(__file__, "rb") as f:
+ arg = f.read(3000) * 2
+
+ def compress(s):
+ bz2.compress(s)
+ return compress, (arg, )
+
+def task_hashing():
+ """SHA1 hashing (C)"""
+ import hashlib
+ with open(__file__, "rb") as f:
+ arg = f.read(5000) * 30
+
+ def compute(s):
+ hashlib.sha1(s).digest()
+ return compute, (arg, )
+
+
+throughput_tasks = [task_pidigits, task_regex]
+for mod in 'bz2', 'hashlib':
+ try:
+ globals()[mod] = __import__(mod)
+ except ImportError:
+ globals()[mod] = None
+
+# For whatever reasons, zlib gives irregular results, so we prefer bz2 or
+# hashlib if available.
+# (NOTE: hashlib releases the GIL from 2.7 and 3.1 onwards)
+if bz2 is not None:
+ throughput_tasks.append(task_compress_bz2)
+elif hashlib is not None:
+ throughput_tasks.append(task_hashing)
+else:
+ throughput_tasks.append(task_compress_zlib)
+
+latency_tasks = throughput_tasks
+bandwidth_tasks = [task_pidigits]
+
+
+class TimedLoop:
+ def __init__(self, func, args):
+ self.func = func
+ self.args = args
+
+ def __call__(self, start_time, min_duration, end_event, do_yield=False):
+ step = 20
+ niters = 0
+ duration = 0.0
+ _time = time.time
+ _sleep = time.sleep
+ _func = self.func
+ _args = self.args
+ t1 = start_time
+ while True:
+ for i in range(step):
+ _func(*_args)
+ t2 = _time()
+ # If another thread terminated, the current measurement is invalid
+ # => return the previous one.
+ if end_event:
+ return niters, duration
+ niters += step
+ duration = t2 - start_time
+ if duration >= min_duration:
+ end_event.append(None)
+ return niters, duration
+ if t2 - t1 < 0.01:
+ # Minimize interference of measurement on overall runtime
+ step = step * 3 // 2
+ elif do_yield:
+ # OS scheduling of Python threads is sometimes so bad that we
+ # have to force thread switching ourselves, otherwise we get
+ # completely useless results.
+ _sleep(0.0001)
+ t1 = t2
+
+
+def run_throughput_test(func, args, nthreads):
+ assert nthreads >= 1
+
+ # Warm up
+ func(*args)
+
+ results = []
+ loop = TimedLoop(func, args)
+ end_event = []
+
+ if nthreads == 1:
+ # Pure single-threaded performance, without any switching or
+ # synchronization overhead.
+ start_time = time.time()
+ results.append(loop(start_time, THROUGHPUT_DURATION,
+ end_event, do_yield=False))
+ return results
+
+ started = False
+ ready_cond = threading.Condition()
+ start_cond = threading.Condition()
+ ready = []
+
+ def run():
+ with ready_cond:
+ ready.append(None)
+ ready_cond.notify()
+ with start_cond:
+ while not started:
+ start_cond.wait()
+ results.append(loop(start_time, THROUGHPUT_DURATION,
+ end_event, do_yield=True))
+
+ threads = []
+ for i in range(nthreads):
+ threads.append(threading.Thread(target=run))
+ for t in threads:
+ t.setDaemon(True)
+ t.start()
+ # We don't want measurements to include thread startup overhead,
+ # so we arrange for timing to start after all threads are ready.
+ with ready_cond:
+ while len(ready) < nthreads:
+ ready_cond.wait()
+ with start_cond:
+ start_time = time.time()
+ started = True
+ start_cond.notify(nthreads)
+ for t in threads:
+ t.join()
+
+ return results
+
+def run_throughput_tests(max_threads):
+ for task in throughput_tasks:
+ print(task.__doc__)
+ print()
+ func, args = task()
+ nthreads = 1
+ baseline_speed = None
+ while nthreads <= max_threads:
+ results = run_throughput_test(func, args, nthreads)
+ # Taking the max duration rather than average gives pessimistic
+ # results rather than optimistic.
+ speed = sum(r[0] for r in results) / max(r[1] for r in results)
+ print("threads=%d: %d" % (nthreads, speed), end="")
+ if baseline_speed is None:
+ print(" iterations/s.")
+ baseline_speed = speed
+ else:
+ print(" ( %d %%)" % (speed / baseline_speed * 100))
+ nthreads += 1
+ print()
+
+
+LAT_END = "END"
+
+def _sendto(sock, s, addr):
+ sock.sendto(s.encode('ascii'), addr)
+
+def _recv(sock, n):
+ return sock.recv(n).decode('ascii')
+
+def latency_client(addr, nb_pings, interval):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ _time = time.time
+ _sleep = time.sleep
+ def _ping():
+ _sendto(sock, "%r\n" % _time(), addr)
+ # The first ping signals the parent process that we are ready.
+ _ping()
+ # We give the parent a bit of time to notice.
+ _sleep(1.0)
+ for i in range(nb_pings):
+ _sleep(interval)
+ _ping()
+ _sendto(sock, LAT_END + "\n", addr)
+
+def run_latency_client(**kwargs):
+ cmd_line = [sys.executable, '-E', os.path.abspath(__file__)]
+ cmd_line.extend(['--latclient', repr(kwargs)])
+ return subprocess.Popen(cmd_line) #, stdin=subprocess.PIPE,
+ #stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+
+def run_latency_test(func, args, nthreads):
+ # Create a listening socket to receive the pings. We use UDP which should
+ # be painlessly cross-platform.
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.bind(("127.0.0.1", 0))
+ addr = sock.getsockname()
+
+ interval = LATENCY_PING_INTERVAL
+ duration = LATENCY_DURATION
+ nb_pings = int(duration / interval)
+
+ results = []
+ threads = []
+ end_event = []
+ start_cond = threading.Condition()
+ started = False
+ if nthreads > 0:
+ # Warm up
+ func(*args)
+
+ results = []
+ loop = TimedLoop(func, args)
+ ready = []
+ ready_cond = threading.Condition()
+
+ def run():
+ with ready_cond:
+ ready.append(None)
+ ready_cond.notify()
+ with start_cond:
+ while not started:
+ start_cond.wait()
+ loop(start_time, duration * 1.5, end_event, do_yield=False)
+
+ for i in range(nthreads):
+ threads.append(threading.Thread(target=run))
+ for t in threads:
+ t.setDaemon(True)
+ t.start()
+ # Wait for threads to be ready
+ with ready_cond:
+ while len(ready) < nthreads:
+ ready_cond.wait()
+
+ # Run the client and wait for the first ping(s) to arrive before
+ # unblocking the background threads.
+ chunks = []
+ process = run_latency_client(addr=sock.getsockname(),
+ nb_pings=nb_pings, interval=interval)
+ s = _recv(sock, 4096)
+ _time = time.time
+
+ with start_cond:
+ start_time = _time()
+ started = True
+ start_cond.notify(nthreads)
+
+ while LAT_END not in s:
+ s = _recv(sock, 4096)
+ t = _time()
+ chunks.append((t, s))
+
+ # Tell the background threads to stop.
+ end_event.append(None)
+ for t in threads:
+ t.join()
+ process.wait()
+
+ for recv_time, chunk in chunks:
+ # NOTE: it is assumed that a line sent by a client wasn't received
+ # in two chunks because the lines are very small.
+ for line in chunk.splitlines():
+ line = line.strip()
+ if line and line != LAT_END:
+ send_time = eval(line)
+ assert isinstance(send_time, float)
+ results.append((send_time, recv_time))
+
+ return results
+
+def run_latency_tests(max_threads):
+ for task in latency_tasks:
+ print("Background CPU task:", task.__doc__)
+ print()
+ func, args = task()
+ nthreads = 0
+ while nthreads <= max_threads:
+ results = run_latency_test(func, args, nthreads)
+ n = len(results)
+ # We print out milliseconds
+ lats = [1000 * (t2 - t1) for (t1, t2) in results]
+ #print(list(map(int, lats)))
+ avg = sum(lats) / n
+ dev = (sum((x - avg) ** 2 for x in lats) / n) ** 0.5
+ print("CPU threads=%d: %d ms. (std dev: %d ms.)" % (nthreads, avg, dev), end="")
+ print()
+ #print(" [... from %d samples]" % n)
+ nthreads += 1
+ print()
+
+
+BW_END = "END"
+
+def bandwidth_client(addr, packet_size, duration):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.bind(("127.0.0.1", 0))
+ local_addr = sock.getsockname()
+ _time = time.time
+ _sleep = time.sleep
+ def _send_chunk(msg):
+ _sendto(sock, ("%r#%s\n" % (local_addr, msg)).rjust(packet_size), addr)
+ # We give the parent some time to be ready.
+ _sleep(1.0)
+ try:
+ start_time = _time()
+ end_time = start_time + duration * 2.0
+ i = 0
+ while _time() < end_time:
+ _send_chunk(str(i))
+ s = _recv(sock, packet_size)
+ assert len(s) == packet_size
+ i += 1
+ _send_chunk(BW_END)
+ finally:
+ sock.close()
+
+def run_bandwidth_client(**kwargs):
+ cmd_line = [sys.executable, '-E', os.path.abspath(__file__)]
+ cmd_line.extend(['--bwclient', repr(kwargs)])
+ return subprocess.Popen(cmd_line) #, stdin=subprocess.PIPE,
+ #stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+
+def run_bandwidth_test(func, args, nthreads):
+ # Create a listening socket to receive the packets. We use UDP which should
+ # be painlessly cross-platform.
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.bind(("127.0.0.1", 0))
+ addr = sock.getsockname()
+
+ duration = BANDWIDTH_DURATION
+ packet_size = BANDWIDTH_PACKET_SIZE
+
+ results = []
+ threads = []
+ end_event = []
+ start_cond = threading.Condition()
+ started = False
+ if nthreads > 0:
+ # Warm up
+ func(*args)
+
+ results = []
+ loop = TimedLoop(func, args)
+ ready = []
+ ready_cond = threading.Condition()
+
+ def run():
+ with ready_cond:
+ ready.append(None)
+ ready_cond.notify()
+ with start_cond:
+ while not started:
+ start_cond.wait()
+ loop(start_time, duration * 1.5, end_event, do_yield=False)
+
+ for i in range(nthreads):
+ threads.append(threading.Thread(target=run))
+ for t in threads:
+ t.setDaemon(True)
+ t.start()
+ # Wait for threads to be ready
+ with ready_cond:
+ while len(ready) < nthreads:
+ ready_cond.wait()
+
+ # Run the client and wait for the first packet to arrive before
+ # unblocking the background threads.
+ process = run_bandwidth_client(addr=addr,
+ packet_size=packet_size,
+ duration=duration)
+ _time = time.time
+ # This will also wait for the parent to be ready
+ s = _recv(sock, packet_size)
+ remote_addr = eval(s.partition('#')[0])
+
+ with start_cond:
+ start_time = _time()
+ started = True
+ start_cond.notify(nthreads)
+
+ n = 0
+ first_time = None
+ while not end_event and BW_END not in s:
+ _sendto(sock, s, remote_addr)
+ s = _recv(sock, packet_size)
+ if first_time is None:
+ first_time = _time()
+ n += 1
+ end_time = _time()
+
+ end_event.append(None)
+ for t in threads:
+ t.join()
+ process.kill()
+
+ return (n - 1) / (end_time - first_time)
+
+def run_bandwidth_tests(max_threads):
+ for task in bandwidth_tasks:
+ print("Background CPU task:", task.__doc__)
+ print()
+ func, args = task()
+ nthreads = 0
+ baseline_speed = None
+ while nthreads <= max_threads:
+ results = run_bandwidth_test(func, args, nthreads)
+ speed = results
+ #speed = len(results) * 1.0 / results[-1][0]
+ print("CPU threads=%d: %.1f" % (nthreads, speed), end="")
+ if baseline_speed is None:
+ print(" packets/s.")
+ baseline_speed = speed
+ else:
+ print(" ( %d %%)" % (speed / baseline_speed * 100))
+ nthreads += 1
+ print()
+
+
+def main():
+ usage = "usage: %prog [-h|--help] [options]"
+ parser = OptionParser(usage=usage)
+ parser.add_option("-t", "--throughput",
+ action="store_true", dest="throughput", default=False,
+ help="run throughput tests")
+ parser.add_option("-l", "--latency",
+ action="store_true", dest="latency", default=False,
+ help="run latency tests")
+ parser.add_option("-b", "--bandwidth",
+ action="store_true", dest="bandwidth", default=False,
+ help="run I/O bandwidth tests")
+ parser.add_option("-i", "--interval",
+ action="store", type="int", dest="check_interval", default=None,
+ help="sys.setcheckinterval() value")
+ parser.add_option("-I", "--switch-interval",
+ action="store", type="float", dest="switch_interval", default=None,
+ help="sys.setswitchinterval() value")
+ parser.add_option("-n", "--num-threads",
+ action="store", type="int", dest="nthreads", default=4,
+ help="max number of threads in tests")
+
+ # Hidden option to run the pinging and bandwidth clients
+ parser.add_option("", "--latclient",
+ action="store", dest="latclient", default=None,
+ help=SUPPRESS_HELP)
+ parser.add_option("", "--bwclient",
+ action="store", dest="bwclient", default=None,
+ help=SUPPRESS_HELP)
+
+ options, args = parser.parse_args()
+ if args:
+ parser.error("unexpected arguments")
+
+ if options.latclient:
+ kwargs = eval(options.latclient)
+ latency_client(**kwargs)
+ return
+
+ if options.bwclient:
+ kwargs = eval(options.bwclient)
+ bandwidth_client(**kwargs)
+ return
+
+ if not options.throughput and not options.latency and not options.bandwidth:
+ options.throughput = options.latency = options.bandwidth = True
+ if options.check_interval:
+ sys.setcheckinterval(options.check_interval)
+ if options.switch_interval:
+ sys.setswitchinterval(options.switch_interval)
+
+ print("== %s %s (%s) ==" % (
+ platform.python_implementation(),
+ platform.python_version(),
+ platform.python_build()[0],
+ ))
+ # Processor identification often has repeated spaces
+ cpu = ' '.join(platform.processor().split())
+ print("== %s %s on '%s' ==" % (
+ platform.machine(),
+ platform.system(),
+ cpu,
+ ))
+ print()
+
+ if options.throughput:
+ print("--- Throughput ---")
+ print()
+ run_throughput_tests(options.nthreads)
+
+ if options.latency:
+ print("--- Latency ---")
+ print()
+ run_latency_tests(options.nthreads)
+
+ if options.bandwidth:
+ print("--- I/O bandwidth ---")
+ print()
+ run_bandwidth_tests(options.nthreads)
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ACKS b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ACKS
new file mode 100644
index 0000000000..56215a08c5
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ACKS
@@ -0,0 +1,8 @@
+Fred L. Drake, Jr.
+Mark Hammond
+Shane Hathaway
+Neil Schemenauer
+Evan Simpson
+Greg Stein
+Bill Tutt
+Moshe Zadka
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/README
new file mode 100644
index 0000000000..373678f439
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/README
@@ -0,0 +1,18 @@
+This directory contains support tools for the Python compiler package,
+which is now part of the standard library.
+
+compile.py Demo that compiles a Python module into a .pyc file
+ using the pure-Python compiler code.
+
+demo.py Prints the names of all the methods defined in a module,
+ as a demonstration of walking through the abstract syntax
+ tree produced by the parser.
+
+dumppyc.py Dumps the contents of a .pyc file, printing
+ the attributes of the code object followed by a
+ code disassembly.
+
+regrtest.py Runs the Python test suite using bytecode generated
+ by the pure-Python compiler code instead of the
+ builtin compiler.
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ast.txt b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ast.txt
new file mode 100644
index 0000000000..7cfb3ba95a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/ast.txt
@@ -0,0 +1,104 @@
+# This file describes the nodes of the AST in ast.py. The module is
+# generated by astgen.py.
+# The descriptions use the following special notation to describe
+# properties of the children:
+# * this child is not a node
+# ! this child is a sequence that contains nodes in it
+# & this child may be set to None
+# = ... a default value for the node constructor (optional args)
+#
+# If you add node types here, please be sure to update the list of
+# Node types in Doc/lib/asttable.tex.
+Module: doc*, node
+Stmt: nodes!
+Decorators: nodes!
+Function: decorators&, name*, argnames*, defaults!, flags*, doc*, code
+Lambda: argnames*, defaults!, flags*, code
+Class: name*, bases!, doc*, code, decorators& = None
+Pass:
+Break:
+Continue:
+For: assign, list, body, else_&
+While: test, body, else_&
+With: expr, vars&, body
+If: tests!, else_&
+IfExp: test, then, else_
+Exec: expr, locals&, globals&
+From: modname*, names*, level*
+Import: names*
+Raise: expr1&, expr2&, expr3&
+TryFinally: body, final
+TryExcept: body, handlers!, else_&
+Return: value
+Yield: value
+Const: value*
+Print: nodes!, dest&
+Printnl: nodes!, dest&
+Discard: expr
+AugAssign: node, op*, expr
+Assign: nodes!, expr
+AssTuple: nodes!
+AssList: nodes!
+AssName: name*, flags*
+AssAttr: expr, attrname*, flags*
+ListComp: expr, quals!
+ListCompFor: assign, list, ifs!
+ListCompIf: test
+GenExpr: code
+GenExprInner: expr, quals!
+GenExprFor: assign, iter, ifs!
+GenExprIf: test
+List: nodes!
+Dict: items!
+Not: expr
+Compare: expr, ops!
+Name: name*
+Global: names*
+Backquote: expr
+Getattr: expr, attrname*
+CallFunc: node, args!, star_args& = None, dstar_args& = None
+Keyword: name*, expr
+Subscript: expr, flags*, subs!
+Ellipsis:
+Sliceobj: nodes!
+Slice: expr, flags*, lower&, upper&
+Assert: test, fail&
+Tuple: nodes!
+Or: nodes!
+And: nodes!
+Bitor: nodes!
+Bitxor: nodes!
+Bitand: nodes!
+LeftShift: (left, right)
+RightShift: (left, right)
+Add: (left, right)
+Sub: (left, right)
+Mul: (left, right)
+Div: (left, right)
+Mod: (left, right)
+Power: (left, right)
+FloorDiv: (left, right)
+UnaryAdd: expr
+UnarySub: expr
+Invert: expr
+
+init(Function):
+ self.varargs = self.kwargs = None
+ if flags & CO_VARARGS:
+ self.varargs = 1
+ if flags & CO_VARKEYWORDS:
+ self.kwargs = 1
+
+init(Lambda):
+ self.varargs = self.kwargs = None
+ if flags & CO_VARARGS:
+ self.varargs = 1
+ if flags & CO_VARKEYWORDS:
+ self.kwargs = 1
+
+init(GenExpr):
+ self.argnames = ['.0']
+ self.varargs = self.kwargs = None
+
+init(GenExprFor):
+ self.is_outmost = False
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/astgen.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/astgen.py
new file mode 100644
index 0000000000..51f29b71fa
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/astgen.py
@@ -0,0 +1,294 @@
+"""Generate ast module from specification
+
+This script generates the ast module from a simple specification,
+which makes it easy to accomodate changes in the grammar. This
+approach would be quite reasonable if the grammar changed often.
+Instead, it is rather complex to generate the appropriate code. And
+the Node interface has changed more often than the grammar.
+"""
+
+import fileinput
+import re
+import sys
+from StringIO import StringIO
+
+SPEC = "ast.txt"
+COMMA = ", "
+
+def load_boilerplate(file):
+ f = open(file)
+ buf = f.read()
+ f.close()
+ i = buf.find('### ''PROLOGUE')
+ j = buf.find('### ''EPILOGUE')
+ pro = buf[i+12:j].strip()
+ epi = buf[j+12:].strip()
+ return pro, epi
+
+def strip_default(arg):
+ """Return the argname from an 'arg = default' string"""
+ i = arg.find('=')
+ if i == -1:
+ return arg
+ t = arg[:i].strip()
+ return t
+
+P_NODE = 1
+P_OTHER = 2
+P_NESTED = 3
+P_NONE = 4
+
+class NodeInfo:
+ """Each instance describes a specific AST node"""
+ def __init__(self, name, args):
+ self.name = name
+ self.args = args.strip()
+ self.argnames = self.get_argnames()
+ self.argprops = self.get_argprops()
+ self.nargs = len(self.argnames)
+ self.init = []
+
+ def get_argnames(self):
+ if '(' in self.args:
+ i = self.args.find('(')
+ j = self.args.rfind(')')
+ args = self.args[i+1:j]
+ else:
+ args = self.args
+ return [strip_default(arg.strip())
+ for arg in args.split(',') if arg]
+
+ def get_argprops(self):
+ """Each argument can have a property like '*' or '!'
+
+ XXX This method modifies the argnames in place!
+ """
+ d = {}
+ hardest_arg = P_NODE
+ for i in range(len(self.argnames)):
+ arg = self.argnames[i]
+ if arg.endswith('*'):
+ arg = self.argnames[i] = arg[:-1]
+ d[arg] = P_OTHER
+ hardest_arg = max(hardest_arg, P_OTHER)
+ elif arg.endswith('!'):
+ arg = self.argnames[i] = arg[:-1]
+ d[arg] = P_NESTED
+ hardest_arg = max(hardest_arg, P_NESTED)
+ elif arg.endswith('&'):
+ arg = self.argnames[i] = arg[:-1]
+ d[arg] = P_NONE
+ hardest_arg = max(hardest_arg, P_NONE)
+ else:
+ d[arg] = P_NODE
+ self.hardest_arg = hardest_arg
+
+ if hardest_arg > P_NODE:
+ self.args = self.args.replace('*', '')
+ self.args = self.args.replace('!', '')
+ self.args = self.args.replace('&', '')
+
+ return d
+
+ def gen_source(self):
+ buf = StringIO()
+ print >> buf, "class %s(Node):" % self.name
+ self._gen_init(buf)
+ print >> buf
+ self._gen_getChildren(buf)
+ print >> buf
+ self._gen_getChildNodes(buf)
+ print >> buf
+ self._gen_repr(buf)
+ buf.seek(0, 0)
+ return buf.read()
+
+ def _gen_init(self, buf):
+ if self.args:
+ argtuple = '(' in self.args
+ args = self.args if not argtuple else ''.join(self.argnames)
+ print >> buf, " def __init__(self, %s, lineno=None):" % args
+ else:
+ print >> buf, " def __init__(self, lineno=None):"
+ if self.argnames:
+ if argtuple:
+ for idx, name in enumerate(self.argnames):
+ print >> buf, " self.%s = %s[%s]" % (name, args, idx)
+ else:
+ for name in self.argnames:
+ print >> buf, " self.%s = %s" % (name, name)
+ print >> buf, " self.lineno = lineno"
+ # Copy the lines in self.init, indented four spaces. The rstrip()
+ # business is to get rid of the four spaces if line happens to be
+ # empty, so that reindent.py is happy with the output.
+ for line in self.init:
+ print >> buf, (" " + line).rstrip()
+
+ def _gen_getChildren(self, buf):
+ print >> buf, " def getChildren(self):"
+ if len(self.argnames) == 0:
+ print >> buf, " return ()"
+ else:
+ if self.hardest_arg < P_NESTED:
+ clist = COMMA.join(["self.%s" % c
+ for c in self.argnames])
+ if self.nargs == 1:
+ print >> buf, " return %s," % clist
+ else:
+ print >> buf, " return %s" % clist
+ else:
+ if len(self.argnames) == 1:
+ print >> buf, " return tuple(flatten(self.%s))" % self.argnames[0]
+ else:
+ print >> buf, " children = []"
+ template = " children.%s(%sself.%s%s)"
+ for name in self.argnames:
+ if self.argprops[name] == P_NESTED:
+ print >> buf, template % ("extend", "flatten(",
+ name, ")")
+ else:
+ print >> buf, template % ("append", "", name, "")
+ print >> buf, " return tuple(children)"
+
+ def _gen_getChildNodes(self, buf):
+ print >> buf, " def getChildNodes(self):"
+ if len(self.argnames) == 0:
+ print >> buf, " return ()"
+ else:
+ if self.hardest_arg < P_NESTED:
+ clist = ["self.%s" % c
+ for c in self.argnames
+ if self.argprops[c] == P_NODE]
+ if len(clist) == 0:
+ print >> buf, " return ()"
+ elif len(clist) == 1:
+ print >> buf, " return %s," % clist[0]
+ else:
+ print >> buf, " return %s" % COMMA.join(clist)
+ else:
+ print >> buf, " nodelist = []"
+ template = " nodelist.%s(%sself.%s%s)"
+ for name in self.argnames:
+ if self.argprops[name] == P_NONE:
+ tmp = (" if self.%s is not None:\n"
+ " nodelist.append(self.%s)")
+ print >> buf, tmp % (name, name)
+ elif self.argprops[name] == P_NESTED:
+ print >> buf, template % ("extend", "flatten_nodes(",
+ name, ")")
+ elif self.argprops[name] == P_NODE:
+ print >> buf, template % ("append", "", name, "")
+ print >> buf, " return tuple(nodelist)"
+
+ def _gen_repr(self, buf):
+ print >> buf, " def __repr__(self):"
+ if self.argnames:
+ fmt = COMMA.join(["%s"] * self.nargs)
+ if '(' in self.args:
+ fmt = '(%s)' % fmt
+ vals = ["repr(self.%s)" % name for name in self.argnames]
+ vals = COMMA.join(vals)
+ if self.nargs == 1:
+ vals = vals + ","
+ print >> buf, ' return "%s(%s)" %% (%s)' % \
+ (self.name, fmt, vals)
+ else:
+ print >> buf, ' return "%s()"' % self.name
+
+rx_init = re.compile('init\((.*)\):')
+
+def parse_spec(file):
+ classes = {}
+ cur = None
+ for line in fileinput.input(file):
+ if line.strip().startswith('#'):
+ continue
+ mo = rx_init.search(line)
+ if mo is None:
+ if cur is None:
+ # a normal entry
+ try:
+ name, args = line.split(':')
+ except ValueError:
+ continue
+ classes[name] = NodeInfo(name, args)
+ cur = None
+ else:
+ # some code for the __init__ method
+ cur.init.append(line)
+ else:
+ # some extra code for a Node's __init__ method
+ name = mo.group(1)
+ cur = classes[name]
+ return sorted(classes.values(), key=lambda n: n.name)
+
+def main():
+ prologue, epilogue = load_boilerplate(sys.argv[-1])
+ print prologue
+ print
+ classes = parse_spec(SPEC)
+ for info in classes:
+ print info.gen_source()
+ print epilogue
+
+if __name__ == "__main__":
+ main()
+ sys.exit(0)
+
+### PROLOGUE
+"""Python abstract syntax node definitions
+
+This file is automatically generated by Tools/compiler/astgen.py
+"""
+from consts import CO_VARARGS, CO_VARKEYWORDS
+
+def flatten(seq):
+ l = []
+ for elt in seq:
+ t = type(elt)
+ if t is tuple or t is list:
+ for elt2 in flatten(elt):
+ l.append(elt2)
+ else:
+ l.append(elt)
+ return l
+
+def flatten_nodes(seq):
+ return [n for n in flatten(seq) if isinstance(n, Node)]
+
+nodes = {}
+
+class Node:
+ """Abstract base class for ast nodes."""
+ def getChildren(self):
+ pass # implemented by subclasses
+ def __iter__(self):
+ for n in self.getChildren():
+ yield n
+ def asList(self): # for backwards compatibility
+ return self.getChildren()
+ def getChildNodes(self):
+ pass # implemented by subclasses
+
+class EmptyNode(Node):
+ pass
+
+class Expression(Node):
+ # Expression is an artificial node class to support "eval"
+ nodes["expression"] = "Expression"
+ def __init__(self, node):
+ self.node = node
+
+ def getChildren(self):
+ return self.node,
+
+ def getChildNodes(self):
+ return self.node,
+
+ def __repr__(self):
+ return "Expression(%s)" % (repr(self.node))
+
+### EPILOGUE
+for name, obj in globals().items():
+ if isinstance(obj, type) and issubclass(obj, Node):
+ nodes[name.lower()] = obj
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/compile.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/compile.py
new file mode 100644
index 0000000000..fa032b7725
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/compile.py
@@ -0,0 +1,51 @@
+import sys
+import getopt
+
+from compiler import compileFile, visitor
+
+import profile
+
+def main():
+ VERBOSE = 0
+ DISPLAY = 0
+ PROFILE = 0
+ CONTINUE = 0
+ opts, args = getopt.getopt(sys.argv[1:], 'vqdcp')
+ for k, v in opts:
+ if k == '-v':
+ VERBOSE = 1
+ visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1
+ if k == '-q':
+ if sys.platform[:3]=="win":
+ f = open('nul', 'wb') # /dev/null fails on Windows...
+ else:
+ f = open('/dev/null', 'wb')
+ sys.stdout = f
+ if k == '-d':
+ DISPLAY = 1
+ if k == '-c':
+ CONTINUE = 1
+ if k == '-p':
+ PROFILE = 1
+ if not args:
+ print "no files to compile"
+ else:
+ for filename in args:
+ if VERBOSE:
+ print filename
+ try:
+ if PROFILE:
+ profile.run('compileFile(%r, %r)' % (filename, DISPLAY),
+ filename + ".prof")
+ else:
+ compileFile(filename, DISPLAY)
+
+ except SyntaxError, err:
+ print err
+ if err.lineno is not None:
+ print err.lineno
+ if not CONTINUE:
+ sys.exit(-1)
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py
new file mode 100644
index 0000000000..cbdc20894e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/demo.py
@@ -0,0 +1,38 @@
+#! /usr/bin/env python
+
+"""Print names of all methods defined in module
+
+This script demonstrates use of the visitor interface of the compiler
+package.
+"""
+
+import compiler
+
+class MethodFinder:
+ """Print the names of all the methods
+
+ Each visit method takes two arguments, the node and its current
+ scope. The scope is the name of the current class or None.
+ """
+
+ def visitClass(self, node, scope=None):
+ self.visit(node.code, node.name)
+
+ def visitFunction(self, node, scope=None):
+ if scope is not None:
+ print "%s.%s" % (scope, node.name)
+ self.visit(node.code, None)
+
+def main(files):
+ mf = MethodFinder()
+ for file in files:
+ f = open(file)
+ buf = f.read()
+ f.close()
+ ast = compiler.parse(buf)
+ compiler.walk(ast, mf)
+
+if __name__ == "__main__":
+ import sys
+
+ main(sys.argv[1:])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/dumppyc.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/dumppyc.py
new file mode 100644
index 0000000000..18da30f4f9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/dumppyc.py
@@ -0,0 +1,46 @@
+#! /usr/bin/env python
+
+import marshal
+import dis
+import types
+
+def dump(obj):
+ print obj
+ for attr in dir(obj):
+ if attr.startswith('co_'):
+ val = getattr(obj, attr)
+ print "\t", attr, repr(val)
+
+def loadCode(path):
+ f = open(path)
+ f.read(8)
+ co = marshal.load(f)
+ f.close()
+ return co
+
+def walk(co, match=None):
+ if match is None or co.co_name == match:
+ dump(co)
+ print
+ dis.dis(co)
+ for obj in co.co_consts:
+ if type(obj) == types.CodeType:
+ walk(obj, match)
+
+def load(filename, codename=None):
+ co = loadCode(filename)
+ walk(co, codename)
+
+if __name__ == "__main__":
+ import sys
+ if len(sys.argv) == 3:
+ filename, codename = sys.argv[1:]
+ else:
+ filename = sys.argv[1]
+ codename = None
+ if filename.endswith('.py'):
+ buf = open(filename).read()
+ co = compile(buf, filename, "exec")
+ walk(co)
+ else:
+ load(filename, codename)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/regrtest.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/regrtest.py
new file mode 100644
index 0000000000..ca6ab5d09b
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/regrtest.py
@@ -0,0 +1,78 @@
+"""Run the Python regression test using the compiler
+
+This test runs the standard Python test suite using bytecode generated
+by this compiler instead of by the builtin compiler.
+
+The regression test is run with the interpreter in verbose mode so
+that import problems can be observed easily.
+"""
+
+from compiler import compileFile
+
+import os
+import sys
+import test
+import tempfile
+
+def copy_test_suite():
+ dest = tempfile.mkdtemp()
+ os.system("cp -r %s/* %s" % (test.__path__[0], dest))
+ print "Creating copy of test suite in", dest
+ return dest
+
+def copy_library():
+ dest = tempfile.mkdtemp()
+ libdir = os.path.split(test.__path__[0])[0]
+ print "Found standard library in", libdir
+ print "Creating copy of standard library in", dest
+ os.system("cp -r %s/* %s" % (libdir, dest))
+ return dest
+
+def compile_files(dir):
+ print "Compiling", dir, "\n\t",
+ line_len = 10
+ for file in os.listdir(dir):
+ base, ext = os.path.splitext(file)
+ if ext == '.py':
+ source = os.path.join(dir, file)
+ line_len = line_len + len(file) + 1
+ if line_len > 75:
+ print "\n\t",
+ line_len = len(source) + 9
+ print file,
+ try:
+ compileFile(source)
+ except SyntaxError, err:
+ print err
+ continue
+ # make sure the .pyc file is not over-written
+ os.chmod(source + "c", 444)
+ elif file == 'CVS':
+ pass
+ else:
+ path = os.path.join(dir, file)
+ if os.path.isdir(path):
+ print
+ print
+ compile_files(path)
+ print "\t",
+ line_len = 10
+ print
+
+def run_regrtest(lib_dir):
+ test_dir = os.path.join(lib_dir, "test")
+ os.chdir(test_dir)
+ os.system("PYTHONPATH=%s %s -v regrtest.py" % (lib_dir, sys.executable))
+
+def cleanup(dir):
+ os.system("rm -rf %s" % dir)
+
+def main():
+ lib_dir = copy_library()
+ compile_files(lib_dir)
+ run_regrtest(lib_dir)
+ raw_input("Cleanup?")
+ cleanup(lib_dir)
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/stacktest.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/stacktest.py
new file mode 100644
index 0000000000..986cd13c90
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/compiler/stacktest.py
@@ -0,0 +1,43 @@
+import compiler
+import dis
+import types
+
+def extract_code_objects(co):
+ l = [co]
+ for const in co.co_consts:
+ if type(const) == types.CodeType:
+ l.append(const)
+ return l
+
+def compare(a, b):
+ if not (a.co_name == "?" or a.co_name.startswith('<lambda')):
+ assert a.co_name == b.co_name, (a, b)
+ if a.co_stacksize != b.co_stacksize:
+ print "stack mismatch %s: %d vs. %d" % (a.co_name,
+ a.co_stacksize,
+ b.co_stacksize)
+ if a.co_stacksize > b.co_stacksize:
+ print "good code"
+ dis.dis(a)
+ print "bad code"
+ dis.dis(b)
+ assert 0
+
+def main(files):
+ for file in files:
+ print file
+ buf = open(file).read()
+ try:
+ co1 = compile(buf, file, "exec")
+ except SyntaxError:
+ print "skipped"
+ continue
+ co2 = compiler.compile(buf, file, "exec")
+ co1l = extract_code_objects(co1)
+ co2l = extract_code_objects(co2)
+ for a, b in zip(co1l, co2l):
+ compare(a, b)
+
+if __name__ == "__main__":
+ import sys
+ main(sys.argv[1:])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/README
new file mode 100644
index 0000000000..e566e79de0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/README
@@ -0,0 +1,114 @@
+FAQ Wizard
+----------
+
+Author: Guido van Rossum <guido@python.org>
+Version: 1.0
+Date: 6 April 1998
+
+
+This is a CGI program that maintains a user-editable FAQ. It uses RCS
+to keep track of changes to individual FAQ entries. It is fully
+configurable; everything you might want to change when using this
+program to maintain some other FAQ than the Python FAQ is contained in
+the configuration module, faqconf.py.
+
+Note that the bulk of the code is not an executable script; it's an
+importable module. The actual script in cgi-bin is minimal.
+
+Files:
+
+faqw.py executable script to be edited and installed in cgi-bin
+faqwiz.py main module, lives in same directory as FAQ entry files
+faqconf.py main configuration module
+faqcust.py additional local customization module (optional)
+move-faqwiz.sh Script to move faqwiz entries.
+
+
+What's New?
+-----------
+
+Version 1.0 corrects some minor bugs and uses tab-agnostic
+indentation; it is otherwise unchanged from version 0.9.0.
+
+Version 0.9.0 uses the re module (Perl style regular expressions) for
+all its regular expression needs, instead of the regex and regsub
+modules (Emacs style). This affects the syntax for regular
+expressions entered by the user as search strings (with "regular
+expression" checked), hence the version number jump.
+
+
+Setup Information
+-----------------
+
+This assumes you are familiar with Python, with your http server, and
+with running CGI scripts under your http server. You need Python 1.5
+or better.
+
+Select a place where the Python modules that constitute the FAQ wizard
+will live (the directory where you unpacked it is an obvious choice).
+This will be called the SRCDIR. This directory should not be writable
+by other users of your system (since they would be able to execute
+arbitrary code by invoking the FAQ wizard's CGI script).
+
+Create a dedicated working directory, preferably one that's not
+directly reachable from your http server. This will be called the
+FAQDIR. Create a subdirectory named RCS. Make both the working
+directory and the RCS subdirectory wrld-writable. (This is essential,
+since the FAQ wizard runs as use nobody, and needs to create
+additional files here!)
+
+Edit faqconf.py to reflect your setup. You only need to edit the top
+part, up till the line of all dashes. The comments should guide you
+in your edits. (Actually, you can also choose to add your changes to
+faqcust.py and leave faqconf.py alone. This is essential if you are
+maintaining multiple FAQs; see below.)
+
+Don't forget to edit the SECTION_TITLES variables to reflect the set
+of section titles for your FAQ!
+
+Next, edit faqw.py to reflect the pathname of your Python interpreter
+and the values for SRCDIR and FAQDIR that you just chose. Then
+install faqw.py in your cgi-bin directory. Make sure that it is
+world-executable. You should now be able to connect to the FAQ wizard
+by entering the following URL in your web client (subsituting the
+appropriate host and port for "your.web.server", and perhaps
+specifying a different directory for "cgi-bin" if local conventions so
+dictate):
+
+ http://your.web.server/cgi-bin/faqw.py
+
+If you are unable to get this working, check your server's error_log
+file. The documentation for Python's cgi module in the Python Library
+Reference Manual gives plentyu additional information about installing
+and debugging CGI scripts, including setup debugging. This
+documentation is repeated in the doc string in the cgi module; try
+``import cgi; print cgi.__doc__''.
+
+Assuming this works, you should now be able to add the first entry to
+your FAQ using the FAQ wizard interface. This creates a file
+faq01.001.htp in your working directory and an RCS revision history
+file faq01.001.htp,v in the RCS subdirectory. You can now exercise
+the other FAQ wizard features (search, index, whole FAQ, what's new,
+roulette, and so on).
+
+
+Maintaining Multiple FAQs
+-------------------------
+
+If you have multiple FAQs, you need a separate FAQDIR per FAQ, and a
+different customization file per FAQ. The easiest thing to do would
+be to have the faqcust.py for each FAQ live in the FAQDIR for that
+FAQ, but that creates some security concerns, since the FAQDIR must be
+world writable: *if* someone who breaks into your system (or a
+legitimate user) manages to edit the faqcust.py file they can get
+arbitrary code to execute through the FAQ wizard. Therefore, you will
+need a more complex setup.
+
+The best way is probably to have a directory that is only writable by
+you for each FAQ, where you place the copy of faqcust.py for that FAQ,
+and have a world-writable subdirectory DATA for the data. You then
+set FAQDIR to point to the DATA directory and change the faqw.py
+bootstrap script to add FAQDIR/.. to sys.path (in front of SRCDIR, so
+the dummy faqcust.py from SRCDIR is ignored).
+
+--Guido van Rossum (home page: http://www.python.org/~guido/)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqconf.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqconf.py
new file mode 100644
index 0000000000..915dfb4f70
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqconf.py
@@ -0,0 +1,577 @@
+"""FAQ Wizard customization module.
+
+Edit this file to customize the FAQ Wizard. For normal purposes, you
+should only have to change the FAQ section titles and the small group
+of parameters below it.
+
+"""
+
+# Titles of FAQ sections
+
+SECTION_TITLES = {
+ # SectionNumber : SectionTitle; need at least one entry
+ 1: "General information and availability",
+}
+
+# Parameters you definitely want to change
+
+SHORTNAME = "Generic" # FAQ name with "FAQ" omitted
+PASSWORD = "" # Password for editing
+OWNERNAME = "FAQ owner" # Name for feedback
+OWNEREMAIL = "nobody@anywhere.org" # Email for feedback
+HOMEURL = "http://www.python.org" # Related home page
+HOMENAME = "Python home" # Name of related home page
+RCSBINDIR = "/usr/local/bin/" # Directory containing RCS commands
+ # (must end in a slash)
+
+# Parameters you can normally leave alone
+
+MAXHITS = 10 # Max #hits to be shown directly
+COOKIE_LIFETIME = 28*24*3600 # Cookie expiration in seconds
+ # (28*24*3600 = 28 days = 4 weeks)
+PROCESS_PREFORMAT = 1 # toggle whether preformatted text
+ # will replace urls and emails with
+ # HTML links
+
+# Markers appended to title to indicate recently change
+# (may contain HTML, e.g. <IMG>); and corresponding
+
+MARK_VERY_RECENT = " **" # Changed very recently
+MARK_RECENT = " *" # Changed recently
+DT_VERY_RECENT = 24*3600 # 24 hours
+DT_RECENT = 7*24*3600 # 7 days
+
+EXPLAIN_MARKS = """
+<P>(Entries marked with ** were changed within the last 24 hours;
+entries marked with * were changed within the last 7 days.)
+<P>
+"""
+
+# Version -- don't change unless you edit faqwiz.py
+
+WIZVERSION = "1.0.4" # FAQ Wizard version
+
+import os, sys
+if os.name in ['nt',]:
+ # On NT we'll probably be running python from a batch file,
+ # so sys.argv[0] is not helpful
+ FAQCGI = 'faq.bat' # Relative URL of the FAQ cgi script
+ # LOGNAME is not typically set on NT
+ os.environ[ 'LOGNAME' ] = "FAQWizard"
+else:
+ # This parameter is normally overwritten with a dynamic value
+ FAQCGI = 'faqw.py' # Relative URL of the FAQ cgi script
+ FAQCGI = os.path.basename(sys.argv[0]) or FAQCGI
+del os, sys
+
+# Perl (re module) style regular expression to recognize FAQ entry
+# files: group(1) should be the section number, group(2) should be the
+# question number. Both should be fixed width so simple-minded
+# sorting yields the right order.
+
+OKFILENAME = r"^faq(\d\d)\.(\d\d\d)\.htp$"
+
+# Format to construct a FAQ entry file name
+
+NEWFILENAME = "faq%02d.%03d.htp"
+
+# Load local customizations on top of the previous parameters
+
+try:
+ from faqcust import *
+except ImportError:
+ pass
+
+# Calculated parameter names
+
+COOKIE_NAME = SHORTNAME + "-FAQ-Wizard" # Name used for Netscape cookie
+FAQNAME = SHORTNAME + " FAQ" # Name of the FAQ
+
+# ----------------------------------------------------------------------
+
+# Anything below this point normally needn't be changed; you would
+# change this if you were to create e.g. a French translation or if
+# you just aren't happy with the text generated by the FAQ Wizard.
+
+# Most strings here are subject to substitution (string%dictionary)
+
+# RCS commands
+
+import os
+if os.name in ['nt', ]:
+ SH_RLOG = RCSBINDIR + "rlog %(file)s < NUL"
+ SH_RLOG_H = RCSBINDIR + "rlog -h %(file)s < NUL"
+ SH_RDIFF = RCSBINDIR + "rcsdiff -r%(prev)s -r%(rev)s %(file)s < NUL"
+ SH_REVISION = RCSBINDIR + "co -p%(rev)s %(file)s < NUL"
+ ### Have to use co -l, or the file is not marked rw on NT
+ SH_LOCK = RCSBINDIR + "co -l %(file)s < NUL"
+ SH_CHECKIN = RCSBINDIR + "ci -u %(file)s < %(tfn)s"
+else:
+ SH_RLOG = RCSBINDIR + "rlog %(file)s </dev/null 2>&1"
+ SH_RLOG_H = RCSBINDIR + "rlog -h %(file)s </dev/null 2>&1"
+ SH_RDIFF = RCSBINDIR + "rcsdiff -r%(prev)s -r%(rev)s %(file)s </dev/null 2>&1"
+ SH_REVISION = RCSBINDIR + "co -p%(rev)s %(file)s </dev/null 2>&1"
+ SH_LOCK = RCSBINDIR + "rcs -l %(file)s </dev/null 2>&1"
+ SH_CHECKIN = RCSBINDIR + "ci -u %(file)s <%(tfn)s 2>&1"
+del os
+
+# Titles for various output pages (not subject to substitution)
+
+T_HOME = FAQNAME + " Wizard " + WIZVERSION
+T_ERROR = "Sorry, an error occurred"
+T_ROULETTE = FAQNAME + " Roulette"
+T_ALL = "The Whole " + FAQNAME
+T_INDEX = FAQNAME + " Index"
+T_SEARCH = FAQNAME + " Search Results"
+T_RECENT = "What's New in the " + FAQNAME
+T_SHOW = FAQNAME + " Entry"
+T_LOG = "RCS log for %s entry" % FAQNAME
+T_REVISION = "RCS revision for %s entry" % FAQNAME
+T_DIFF = "RCS diff for %s entry" % FAQNAME
+T_ADD = "Add an entry to the " + FAQNAME
+T_DELETE = "Deleting an entry from the " + FAQNAME
+T_EDIT = FAQNAME + " Edit Wizard"
+T_REVIEW = T_EDIT + " - Review Changes"
+T_COMMITTED = T_EDIT + " - Changes Committed"
+T_COMMITFAILED = T_EDIT + " - Commit Failed"
+T_CANTCOMMIT = T_EDIT + " - Commit Rejected"
+T_HELP = T_EDIT + " - Help"
+
+# Generic prologue and epilogue
+
+PROLOGUE = '''
+<HTML>
+<HEAD>
+<TITLE>%(title)s</TITLE>
+</HEAD>
+
+<BODY
+ BGCOLOR="#FFFFFF"
+ TEXT="#000000"
+ LINK="#AA0000"
+ VLINK="#906A6A">
+<H1>%(title)s</H1>
+'''
+
+EPILOGUE = '''
+<HR>
+<A HREF="%(HOMEURL)s">%(HOMENAME)s</A> /
+<A HREF="%(FAQCGI)s?req=home">%(FAQNAME)s Wizard %(WIZVERSION)s</A> /
+Feedback to <A HREF="mailto:%(OWNEREMAIL)s">%(OWNERNAME)s</A>
+
+</BODY>
+</HTML>
+'''
+
+# Home page
+
+HOME = """
+<H2>Search the %(FAQNAME)s:</H2>
+
+<BLOCKQUOTE>
+
+<FORM ACTION="%(FAQCGI)s">
+ <INPUT TYPE=text NAME=query>
+ <INPUT TYPE=submit VALUE="Search"><BR>
+ <INPUT TYPE=radio NAME=querytype VALUE=simple CHECKED>
+ Simple string
+ /
+ <INPUT TYPE=radio NAME=querytype VALUE=regex>
+ Regular expression
+ /<BR>
+ <INPUT TYPE=radio NAME=querytype VALUE=anykeywords>
+ Keywords (any)
+ /
+ <INPUT TYPE=radio NAME=querytype VALUE=allkeywords>
+ Keywords (all)
+ <BR>
+ <INPUT TYPE=radio NAME=casefold VALUE=yes CHECKED>
+ Fold case
+ /
+ <INPUT TYPE=radio NAME=casefold VALUE=no>
+ Case sensitive
+ <BR>
+ <INPUT TYPE=hidden NAME=req VALUE=search>
+</FORM>
+
+</BLOCKQUOTE>
+
+<HR>
+
+<H2>Other forms of %(FAQNAME)s access:</H2>
+
+<UL>
+<LI><A HREF="%(FAQCGI)s?req=index">FAQ index</A>
+<LI><A HREF="%(FAQCGI)s?req=all">The whole FAQ</A>
+<LI><A HREF="%(FAQCGI)s?req=recent">What's new in the FAQ?</A>
+<LI><A HREF="%(FAQCGI)s?req=roulette">FAQ roulette</A>
+<LI><A HREF="%(FAQCGI)s?req=add">Add a FAQ entry</A>
+<LI><A HREF="%(FAQCGI)s?req=delete">Delete a FAQ entry</A>
+</UL>
+"""
+
+# Index formatting
+
+INDEX_SECTION = """
+<P>
+<HR>
+<H2>%(sec)s. %(title)s</H2>
+<UL>
+"""
+
+INDEX_ADDSECTION = """
+<P>
+<LI><A HREF="%(FAQCGI)s?req=new&amp;section=%(sec)s">Add new entry</A>
+(at this point)
+"""
+
+INDEX_ENDSECTION = """
+</UL>
+"""
+
+INDEX_ENTRY = """\
+<LI><A HREF="%(FAQCGI)s?req=show&amp;file=%(file)s">%(title)s</A>
+"""
+
+LOCAL_ENTRY = """\
+<LI><A HREF="#%(sec)s.%(num)s">%(title)s</A>
+"""
+
+# Entry formatting
+
+ENTRY_HEADER1 = """
+<HR>
+<H2><A NAME="%(sec)s.%(num)s">%(title)s</A>\
+"""
+
+ENTRY_HEADER2 = """\
+</H2>
+"""
+
+ENTRY_FOOTER = """
+<A HREF="%(FAQCGI)s?req=edit&amp;file=%(file)s">Edit this entry</A> /
+<A HREF="%(FAQCGI)s?req=log&amp;file=%(file)s">Log info</A>
+"""
+
+ENTRY_LOGINFO = """
+/ Last changed on %(last_changed_date)s by
+<A HREF="mailto:%(last_changed_email)s">%(last_changed_author)s</A>
+"""
+
+# Search
+
+NO_HITS = """
+No hits.
+"""
+
+ONE_HIT = """
+Your search matched the following entry:
+"""
+
+FEW_HITS = """
+Your search matched the following %(count)s entries:
+"""
+
+MANY_HITS = """
+Your search matched more than %(MAXHITS)s entries.
+The %(count)s matching entries are presented here ordered by section:
+"""
+
+# RCS log and diff
+
+LOG = """
+Click on a revision line to see the diff between that revision and the
+previous one.
+"""
+
+REVISIONLINK = """\
+<A HREF="%(FAQCGI)s?req=revision&amp;file=%(file)s&amp;rev=%(rev)s"
+>%(line)s</A>\
+"""
+DIFFLINK = """\
+ (<A HREF="%(FAQCGI)s?req=diff&amp;file=%(file)s&amp;\
+prev=%(prev)s&amp;rev=%(rev)s"
+>diff -r%(prev)s -r%(rev)s</A>)\
+"""
+
+# Recently changed entries
+
+NO_RECENT = """
+<HR>
+No %(FAQNAME)s entries were changed in the last %(period)s.
+"""
+
+VIEW_MENU = """
+<HR>
+View entries changed in the last...
+<UL>
+<LI><A HREF="%(FAQCGI)s?req=recent&amp;days=1">24 hours</A>
+<LI><A HREF="%(FAQCGI)s?req=recent&amp;days=2">2 days</A>
+<LI><A HREF="%(FAQCGI)s?req=recent&amp;days=3">3 days</A>
+<LI><A HREF="%(FAQCGI)s?req=recent&amp;days=7">week</A>
+<LI><A HREF="%(FAQCGI)s?req=recent&amp;days=28">4 weeks</A>
+<LI><A HREF="%(FAQCGI)s?req=recent&amp;days=365250">millennium</A>
+</UL>
+"""
+
+ONE_RECENT = VIEW_MENU + """
+The following %(FAQNAME)s entry was changed in the last %(period)s:
+"""
+
+SOME_RECENT = VIEW_MENU + """
+The following %(count)s %(FAQNAME)s entries were changed
+in the last %(period)s, most recently changed shown first:
+"""
+
+TAIL_RECENT = VIEW_MENU
+
+# Last changed banner on "all" (strftime format)
+LAST_CHANGED = "Last changed on %c %Z"
+
+# "Compat" command prologue (this has no <BODY> tag)
+COMPAT = """
+<H1>The whole %(FAQNAME)s</H1>
+See also the <A HREF="%(FAQCGI)s?req=home">%(FAQNAME)s Wizard</A>.
+<P>
+"""
+
+# Editing
+
+EDITHEAD = """
+<A HREF="%(FAQCGI)s?req=help">Click for Help</A>
+"""
+
+REVIEWHEAD = EDITHEAD
+
+
+EDITFORM1 = """
+<FORM ACTION="%(FAQCGI)s" METHOD=POST>
+<INPUT TYPE=hidden NAME=req VALUE=review>
+<INPUT TYPE=hidden NAME=file VALUE=%(file)s>
+<INPUT TYPE=hidden NAME=editversion VALUE=%(editversion)s>
+<HR>
+"""
+
+EDITFORM2 = """
+Title: <INPUT TYPE=text SIZE=70 NAME=title VALUE="%(title)s"><BR>
+<TEXTAREA COLS=72 ROWS=20 NAME=body>%(body)s
+</TEXTAREA><BR>
+Log message (reason for the change):<BR>
+<TEXTAREA COLS=72 ROWS=5 NAME=log>%(log)s
+</TEXTAREA><BR>
+Please provide the following information for logging purposes:
+<TABLE FRAME=none COLS=2>
+ <TR>
+ <TD>Name:
+ <TD><INPUT TYPE=text SIZE=40 NAME=author VALUE="%(author)s">
+ <TR>
+ <TD>Email:
+ <TD><INPUT TYPE=text SIZE=40 NAME=email VALUE="%(email)s">
+ <TR>
+ <TD>Password:
+ <TD><INPUT TYPE=password SIZE=20 NAME=password VALUE="%(password)s">
+</TABLE>
+
+<INPUT TYPE=submit NAME=review VALUE="Preview Edit">
+Click this button to preview your changes.
+"""
+
+EDITFORM3 = """
+</FORM>
+"""
+
+COMMIT = """
+<INPUT TYPE=submit NAME=commit VALUE="Commit">
+Click this button to commit your changes.
+<HR>
+"""
+
+NOCOMMIT_HEAD = """
+To commit your changes, please correct the following errors in the
+form below and click the Preview Edit button.
+<UL>
+"""
+NOCOMMIT_TAIL = """
+</UL>
+<HR>
+"""
+
+CANTCOMMIT_HEAD = """
+Some required information is missing:
+<UL>
+"""
+NEED_PASSWD = "<LI>You must provide the correct password.\n"
+NEED_AUTHOR = "<LI>You must enter your name.\n"
+NEED_EMAIL = "<LI>You must enter your email address.\n"
+NEED_LOG = "<LI>You must enter a log message.\n"
+CANTCOMMIT_TAIL = """
+</UL>
+Please use your browser's Back command to correct the form and commit
+again.
+"""
+
+NEWCONFLICT = """
+<P>
+You are creating a new entry, but the entry number specified is not
+correct.
+<P>
+The two most common causes of this problem are:
+<UL>
+<LI>After creating the entry yourself, you went back in your browser,
+ edited the entry some more, and clicked Commit again.
+<LI>Someone else started creating a new entry in the same section and
+ committed before you did.
+</UL>
+(It is also possible that the last entry in the section was physically
+deleted, but this should not happen except through manual intervention
+by the FAQ maintainer.)
+<P>
+<A HREF="%(FAQCGI)s?req=new&amp;section=%(sec)s">Click here to try
+again.</A>
+<P>
+"""
+
+VERSIONCONFLICT = """
+<P>
+You edited version %(editversion)s but the current version is %(version)s.
+<P>
+The two most common causes of this problem are:
+<UL>
+<LI>After committing a change, you went back in your browser,
+ edited the entry some more, and clicked Commit again.
+<LI>Someone else started editing the same entry and committed
+ before you did.
+</UL>
+<P>
+<A HREF="%(FAQCGI)s?req=show&amp;file=%(file)s">Click here to reload
+the entry and try again.</A>
+<P>
+"""
+
+CANTWRITE = """
+Can't write file %(file)s (%(why)s).
+"""
+
+FILEHEADER = """\
+Title: %(title)s
+Last-Changed-Date: %(date)s
+Last-Changed-Author: %(author)s
+Last-Changed-Email: %(email)s
+Last-Changed-Remote-Host: %(REMOTE_HOST)s
+Last-Changed-Remote-Address: %(REMOTE_ADDR)s
+"""
+
+LOGHEADER = """\
+Last-Changed-Date: %(date)s
+Last-Changed-Author: %(author)s
+Last-Changed-Email: %(email)s
+Last-Changed-Remote-Host: %(REMOTE_HOST)s
+Last-Changed-Remote-Address: %(REMOTE_ADDR)s
+
+%(log)s
+"""
+
+COMMITTED = """
+Your changes have been committed.
+"""
+
+COMMITFAILED = """
+Exit status %(sts)s.
+"""
+
+# Add/Delete
+
+ADD_HEAD = """
+At the moment, new entries can only be added at the end of a section.
+This is because the entry numbers are also their
+unique identifiers -- it's a bad idea to renumber entries.
+<P>
+Click on the section to which you want to add a new entry:
+<UL>
+"""
+
+ADD_SECTION = """\
+<LI><A HREF="%(FAQCGI)s?req=new&amp;section=%(section)s">%(section)s. %(title)s</A>
+"""
+
+ADD_TAIL = """
+</UL>
+"""
+
+ROULETTE = """
+<P>Hit your browser's Reload button to play again.<P>
+"""
+
+DELETE = """
+At the moment, there's no direct way to delete entries.
+This is because the entry numbers are also their
+unique identifiers -- it's a bad idea to renumber entries.
+<P>
+If you really think an entry needs to be deleted,
+change the title to "(deleted)" and make the body
+empty (keep the entry number in the title though).
+"""
+
+# Help file for the FAQ Edit Wizard
+
+HELP = """
+Using the %(FAQNAME)s Edit Wizard speaks mostly for itself. Here are
+some answers to questions you are likely to ask:
+
+<P><HR>
+
+<H2>I can review an entry but I can't commit it.</H2>
+
+The commit button only appears if the following conditions are met:
+
+<UL>
+
+<LI>The Name field is not empty.
+
+<LI>The Email field contains at least an @ character.
+
+<LI>The Log message box is not empty.
+
+<LI>The Password field contains the proper password.
+
+</UL>
+
+<P><HR>
+
+<H2>What is the password?</H2>
+
+At the moment, only PSA members will be told the password. This is a
+good time to join the PSA! See <A
+HREF="http://www.python.org/psa/">the PSA home page</A>.
+
+<P><HR>
+
+<H2>Can I use HTML in the FAQ entry?</H2>
+
+Yes, if you include it in &lt;HTML&rt; and &lt;/HTML&gt; tags.
+<P>
+Also, if you include a URL or an email address in the text it will
+automatigally become an anchor of the right type. Also, *word*
+is made italic (but only for single alphabetic words).
+
+<P><HR>
+
+<H2>How do I delineate paragraphs?</H2>
+
+Use blank lines to separate paragraphs.
+
+<P><HR>
+
+<H2>How do I enter example text?</H2>
+
+Any line that begins with a space or tab is assumed to be part of
+literal text. Blocks of literal text delineated by blank lines are
+placed inside &lt;PRE&gt;...&lt;/PRE&gt;.
+"""
+
+# Load local customizations again, in case they set some other variables
+
+try:
+ from faqcust import *
+except ImportError:
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqcust.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqcust.py
new file mode 100644
index 0000000000..66c29dd0dd
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqcust.py
@@ -0,0 +1 @@
+# Add your customizations here -- modified copies of what's in faqconf.py.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqw.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqw.py
new file mode 100644
index 0000000000..b9bb3d0cae
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqw.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+"""FAQ wizard bootstrap."""
+
+# This is a longer version of the bootstrap script given at the end of
+# faqwin.py; it prints timing statistics at the end of the regular CGI
+# script's output (so you can monitor how it is doing).
+
+# This script should be placed in your cgi-bin directory and made
+# executable.
+
+# You need to edit the first line and the lines that define FAQDIR and
+# SRCDIR, below: change /usr/local/bin/python to where your Python
+# interpreter lives, change the value for FAQDIR to where your FAQ
+# lives, and change the value for SRCDIR to where your faqwiz.py
+# module lives. The faqconf.py and faqcust.py files live there, too.
+
+import os
+t1 = os.times() # If this doesn't work, just get rid of the timing code!
+try:
+ FAQDIR = "/usr/people/guido/python/FAQ"
+ SRCDIR = "/usr/people/guido/python/src/Tools/faqwiz"
+ import os, sys
+ os.chdir(FAQDIR)
+ sys.path.insert(0, SRCDIR)
+ import faqwiz
+except SystemExit, n:
+ sys.exit(n)
+except:
+ t, v, tb = sys.exc_info()
+ print
+ import cgi
+ cgi.print_exception(t, v, tb)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqwiz.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqwiz.py
new file mode 100644
index 0000000000..babb426582
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/faqwiz.py
@@ -0,0 +1,841 @@
+"""Generic FAQ Wizard.
+
+This is a CGI program that maintains a user-editable FAQ. It uses RCS
+to keep track of changes to individual FAQ entries. It is fully
+configurable; everything you might want to change when using this
+program to maintain some other FAQ than the Python FAQ is contained in
+the configuration module, faqconf.py.
+
+Note that this is not an executable script; it's an importable module.
+The actual script to place in cgi-bin is faqw.py.
+
+"""
+
+import sys, time, os, stat, re, cgi, faqconf
+from faqconf import * # This imports all uppercase names
+now = time.time()
+
+class FileError:
+ def __init__(self, file):
+ self.file = file
+
+class InvalidFile(FileError):
+ pass
+
+class NoSuchSection(FileError):
+ def __init__(self, section):
+ FileError.__init__(self, NEWFILENAME %(section, 1))
+ self.section = section
+
+class NoSuchFile(FileError):
+ def __init__(self, file, why=None):
+ FileError.__init__(self, file)
+ self.why = why
+
+def escape(s):
+ s = s.replace('&', '&amp;')
+ s = s.replace('<', '&lt;')
+ s = s.replace('>', '&gt;')
+ return s
+
+def escapeq(s):
+ s = escape(s)
+ s = s.replace('"', '&quot;')
+ return s
+
+def _interpolate(format, args, kw):
+ try:
+ quote = kw['_quote']
+ except KeyError:
+ quote = 1
+ d = (kw,) + args + (faqconf.__dict__,)
+ m = MagicDict(d, quote)
+ return format % m
+
+def interpolate(format, *args, **kw):
+ return _interpolate(format, args, kw)
+
+def emit(format, *args, **kw):
+ try:
+ f = kw['_file']
+ except KeyError:
+ f = sys.stdout
+ f.write(_interpolate(format, args, kw))
+
+translate_prog = None
+
+def translate(text, pre=0):
+ global translate_prog
+ if not translate_prog:
+ translate_prog = prog = re.compile(
+ r'\b(http|ftp|https)://\S+(\b|/)|\b[-.\w]+@[-.\w]+')
+ else:
+ prog = translate_prog
+ i = 0
+ list = []
+ while 1:
+ m = prog.search(text, i)
+ if not m:
+ break
+ j = m.start()
+ list.append(escape(text[i:j]))
+ i = j
+ url = m.group(0)
+ while url[-1] in '();:,.?\'"<>':
+ url = url[:-1]
+ i = i + len(url)
+ url = escape(url)
+ if not pre or (pre and PROCESS_PREFORMAT):
+ if ':' in url:
+ repl = '<A HREF="%s">%s</A>' % (url, url)
+ else:
+ repl = '<A HREF="mailto:%s">%s</A>' % (url, url)
+ else:
+ repl = url
+ list.append(repl)
+ j = len(text)
+ list.append(escape(text[i:j]))
+ return ''.join(list)
+
+def emphasize(line):
+ return re.sub(r'\*([a-zA-Z]+)\*', r'<I>\1</I>', line)
+
+revparse_prog = None
+
+def revparse(rev):
+ global revparse_prog
+ if not revparse_prog:
+ revparse_prog = re.compile(r'^(\d{1,3})\.(\d{1,4})$')
+ m = revparse_prog.match(rev)
+ if not m:
+ return None
+ [major, minor] = map(int, m.group(1, 2))
+ return major, minor
+
+logon = 0
+def log(text):
+ if logon:
+ logfile = open("logfile", "a")
+ logfile.write(text + "\n")
+ logfile.close()
+
+def load_cookies():
+ if not os.environ.has_key('HTTP_COOKIE'):
+ return {}
+ raw = os.environ['HTTP_COOKIE']
+ words = [s.strip() for s in raw.split(';')]
+ cookies = {}
+ for word in words:
+ i = word.find('=')
+ if i >= 0:
+ key, value = word[:i], word[i+1:]
+ cookies[key] = value
+ return cookies
+
+def load_my_cookie():
+ cookies = load_cookies()
+ try:
+ value = cookies[COOKIE_NAME]
+ except KeyError:
+ return {}
+ import urllib
+ value = urllib.unquote(value)
+ words = value.split('/')
+ while len(words) < 3:
+ words.append('')
+ author = '/'.join(words[:-2])
+ email = words[-2]
+ password = words[-1]
+ return {'author': author,
+ 'email': email,
+ 'password': password}
+
+def send_my_cookie(ui):
+ name = COOKIE_NAME
+ value = "%s/%s/%s" % (ui.author, ui.email, ui.password)
+ import urllib
+ value = urllib.quote(value)
+ then = now + COOKIE_LIFETIME
+ gmt = time.gmtime(then)
+ path = os.environ.get('SCRIPT_NAME', '/cgi-bin/')
+ print "Set-Cookie: %s=%s; path=%s;" % (name, value, path),
+ print time.strftime("expires=%a, %d-%b-%y %X GMT", gmt)
+
+class MagicDict:
+
+ def __init__(self, d, quote):
+ self.__d = d
+ self.__quote = quote
+
+ def __getitem__(self, key):
+ for d in self.__d:
+ try:
+ value = d[key]
+ if value:
+ value = str(value)
+ if self.__quote:
+ value = escapeq(value)
+ return value
+ except KeyError:
+ pass
+ return ''
+
+class UserInput:
+
+ def __init__(self):
+ self.__form = cgi.FieldStorage()
+ #log("\n\nbody: " + self.body)
+
+ def __getattr__(self, name):
+ if name[0] == '_':
+ raise AttributeError
+ try:
+ value = self.__form[name].value
+ except (TypeError, KeyError):
+ value = ''
+ else:
+ value = value.strip()
+ setattr(self, name, value)
+ return value
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+class FaqEntry:
+
+ def __init__(self, fp, file, sec_num):
+ self.file = file
+ self.sec, self.num = sec_num
+ if fp:
+ import rfc822
+ self.__headers = rfc822.Message(fp)
+ self.body = fp.read().strip()
+ else:
+ self.__headers = {'title': "%d.%d. " % sec_num}
+ self.body = ''
+
+ def __getattr__(self, name):
+ if name[0] == '_':
+ raise AttributeError
+ key = '-'.join(name.split('_'))
+ try:
+ value = self.__headers[key]
+ except KeyError:
+ value = ''
+ setattr(self, name, value)
+ return value
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+ def load_version(self):
+ command = interpolate(SH_RLOG_H, self)
+ p = os.popen(command)
+ version = ''
+ while 1:
+ line = p.readline()
+ if not line:
+ break
+ if line[:5] == 'head:':
+ version = line[5:].strip()
+ p.close()
+ self.version = version
+
+ def getmtime(self):
+ if not self.last_changed_date:
+ return 0
+ try:
+ return os.stat(self.file)[stat.ST_MTIME]
+ except os.error:
+ return 0
+
+ def emit_marks(self):
+ mtime = self.getmtime()
+ if mtime >= now - DT_VERY_RECENT:
+ emit(MARK_VERY_RECENT, self)
+ elif mtime >= now - DT_RECENT:
+ emit(MARK_RECENT, self)
+
+ def show(self, edit=1):
+ emit(ENTRY_HEADER1, self)
+ self.emit_marks()
+ emit(ENTRY_HEADER2, self)
+ pre = 0
+ raw = 0
+ for line in self.body.split('\n'):
+ # Allow the user to insert raw html into a FAQ answer
+ # (Skip Montanaro, with changes by Guido)
+ tag = line.rstrip().lower()
+ if tag == '<html>':
+ raw = 1
+ continue
+ if tag == '</html>':
+ raw = 0
+ continue
+ if raw:
+ print line
+ continue
+ if not line.strip():
+ if pre:
+ print '</PRE>'
+ pre = 0
+ else:
+ print '<P>'
+ else:
+ if not line[0].isspace():
+ if pre:
+ print '</PRE>'
+ pre = 0
+ else:
+ if not pre:
+ print '<PRE>'
+ pre = 1
+ if '/' in line or '@' in line:
+ line = translate(line, pre)
+ elif '<' in line or '&' in line:
+ line = escape(line)
+ if not pre and '*' in line:
+ line = emphasize(line)
+ print line
+ if pre:
+ print '</PRE>'
+ pre = 0
+ if edit:
+ print '<P>'
+ emit(ENTRY_FOOTER, self)
+ if self.last_changed_date:
+ emit(ENTRY_LOGINFO, self)
+ print '<P>'
+
+class FaqDir:
+
+ entryclass = FaqEntry
+
+ __okprog = re.compile(OKFILENAME)
+
+ def __init__(self, dir=os.curdir):
+ self.__dir = dir
+ self.__files = None
+
+ def __fill(self):
+ if self.__files is not None:
+ return
+ self.__files = files = []
+ okprog = self.__okprog
+ for file in os.listdir(self.__dir):
+ if self.__okprog.match(file):
+ files.append(file)
+ files.sort()
+
+ def good(self, file):
+ return self.__okprog.match(file)
+
+ def parse(self, file):
+ m = self.good(file)
+ if not m:
+ return None
+ sec, num = m.group(1, 2)
+ return int(sec), int(num)
+
+ def list(self):
+ # XXX Caller shouldn't modify result
+ self.__fill()
+ return self.__files
+
+ def open(self, file):
+ sec_num = self.parse(file)
+ if not sec_num:
+ raise InvalidFile(file)
+ try:
+ fp = open(file)
+ except IOError, msg:
+ raise NoSuchFile(file, msg)
+ try:
+ return self.entryclass(fp, file, sec_num)
+ finally:
+ fp.close()
+
+ def show(self, file, edit=1):
+ self.open(file).show(edit=edit)
+
+ def new(self, section):
+ if not SECTION_TITLES.has_key(section):
+ raise NoSuchSection(section)
+ maxnum = 0
+ for file in self.list():
+ sec, num = self.parse(file)
+ if sec == section:
+ maxnum = max(maxnum, num)
+ sec_num = (section, maxnum+1)
+ file = NEWFILENAME % sec_num
+ return self.entryclass(None, file, sec_num)
+
+class FaqWizard:
+
+ def __init__(self):
+ self.ui = UserInput()
+ self.dir = FaqDir()
+
+ def go(self):
+ print 'Content-type: text/html'
+ req = self.ui.req or 'home'
+ mname = 'do_%s' % req
+ try:
+ meth = getattr(self, mname)
+ except AttributeError:
+ self.error("Bad request type %r." % (req,))
+ else:
+ try:
+ meth()
+ except InvalidFile, exc:
+ self.error("Invalid entry file name %s" % exc.file)
+ except NoSuchFile, exc:
+ self.error("No entry with file name %s" % exc.file)
+ except NoSuchSection, exc:
+ self.error("No section number %s" % exc.section)
+ self.epilogue()
+
+ def error(self, message, **kw):
+ self.prologue(T_ERROR)
+ emit(message, kw)
+
+ def prologue(self, title, entry=None, **kw):
+ emit(PROLOGUE, entry, kwdict=kw, title=escape(title))
+
+ def epilogue(self):
+ emit(EPILOGUE)
+
+ def do_home(self):
+ self.prologue(T_HOME)
+ emit(HOME)
+
+ def do_debug(self):
+ self.prologue("FAQ Wizard Debugging")
+ form = cgi.FieldStorage()
+ cgi.print_form(form)
+ cgi.print_environ(os.environ)
+ cgi.print_directory()
+ cgi.print_arguments()
+
+ def do_search(self):
+ query = self.ui.query
+ if not query:
+ self.error("Empty query string!")
+ return
+ if self.ui.querytype == 'simple':
+ query = re.escape(query)
+ queries = [query]
+ elif self.ui.querytype in ('anykeywords', 'allkeywords'):
+ words = filter(None, re.split('\W+', query))
+ if not words:
+ self.error("No keywords specified!")
+ return
+ words = map(lambda w: r'\b%s\b' % w, words)
+ if self.ui.querytype[:3] == 'any':
+ queries = ['|'.join(words)]
+ else:
+ # Each of the individual queries must match
+ queries = words
+ else:
+ # Default to regular expression
+ queries = [query]
+ self.prologue(T_SEARCH)
+ progs = []
+ for query in queries:
+ if self.ui.casefold == 'no':
+ p = re.compile(query)
+ else:
+ p = re.compile(query, re.IGNORECASE)
+ progs.append(p)
+ hits = []
+ for file in self.dir.list():
+ try:
+ entry = self.dir.open(file)
+ except FileError:
+ constants
+ for p in progs:
+ if not p.search(entry.title) and not p.search(entry.body):
+ break
+ else:
+ hits.append(file)
+ if not hits:
+ emit(NO_HITS, self.ui, count=0)
+ elif len(hits) <= MAXHITS:
+ if len(hits) == 1:
+ emit(ONE_HIT, count=1)
+ else:
+ emit(FEW_HITS, count=len(hits))
+ self.format_all(hits, headers=0)
+ else:
+ emit(MANY_HITS, count=len(hits))
+ self.format_index(hits)
+
+ def do_all(self):
+ self.prologue(T_ALL)
+ files = self.dir.list()
+ self.last_changed(files)
+ self.format_index(files, localrefs=1)
+ self.format_all(files)
+
+ def do_compat(self):
+ files = self.dir.list()
+ emit(COMPAT)
+ self.last_changed(files)
+ self.format_index(files, localrefs=1)
+ self.format_all(files, edit=0)
+ sys.exit(0) # XXX Hack to suppress epilogue
+
+ def last_changed(self, files):
+ latest = 0
+ for file in files:
+ entry = self.dir.open(file)
+ if entry:
+ mtime = mtime = entry.getmtime()
+ if mtime > latest:
+ latest = mtime
+ print time.strftime(LAST_CHANGED, time.localtime(latest))
+ emit(EXPLAIN_MARKS)
+
+ def format_all(self, files, edit=1, headers=1):
+ sec = 0
+ for file in files:
+ try:
+ entry = self.dir.open(file)
+ except NoSuchFile:
+ continue
+ if headers and entry.sec != sec:
+ sec = entry.sec
+ try:
+ title = SECTION_TITLES[sec]
+ except KeyError:
+ title = "Untitled"
+ emit("\n<HR>\n<H1>%(sec)s. %(title)s</H1>\n",
+ sec=sec, title=title)
+ entry.show(edit=edit)
+
+ def do_index(self):
+ self.prologue(T_INDEX)
+ files = self.dir.list()
+ self.last_changed(files)
+ self.format_index(files, add=1)
+
+ def format_index(self, files, add=0, localrefs=0):
+ sec = 0
+ for file in files:
+ try:
+ entry = self.dir.open(file)
+ except NoSuchFile:
+ continue
+ if entry.sec != sec:
+ if sec:
+ if add:
+ emit(INDEX_ADDSECTION, sec=sec)
+ emit(INDEX_ENDSECTION, sec=sec)
+ sec = entry.sec
+ try:
+ title = SECTION_TITLES[sec]
+ except KeyError:
+ title = "Untitled"
+ emit(INDEX_SECTION, sec=sec, title=title)
+ if localrefs:
+ emit(LOCAL_ENTRY, entry)
+ else:
+ emit(INDEX_ENTRY, entry)
+ entry.emit_marks()
+ if sec:
+ if add:
+ emit(INDEX_ADDSECTION, sec=sec)
+ emit(INDEX_ENDSECTION, sec=sec)
+
+ def do_recent(self):
+ if not self.ui.days:
+ days = 1
+ else:
+ days = float(self.ui.days)
+ try:
+ cutoff = now - days * 24 * 3600
+ except OverflowError:
+ cutoff = 0
+ list = []
+ for file in self.dir.list():
+ entry = self.dir.open(file)
+ if not entry:
+ continue
+ mtime = entry.getmtime()
+ if mtime >= cutoff:
+ list.append((mtime, file))
+ list.sort()
+ list.reverse()
+ self.prologue(T_RECENT)
+ if days <= 1:
+ period = "%.2g hours" % (days*24)
+ else:
+ period = "%.6g days" % days
+ if not list:
+ emit(NO_RECENT, period=period)
+ elif len(list) == 1:
+ emit(ONE_RECENT, period=period)
+ else:
+ emit(SOME_RECENT, period=period, count=len(list))
+ self.format_all(map(lambda (mtime, file): file, list), headers=0)
+ emit(TAIL_RECENT)
+
+ def do_roulette(self):
+ import random
+ files = self.dir.list()
+ if not files:
+ self.error("No entries.")
+ return
+ file = random.choice(files)
+ self.prologue(T_ROULETTE)
+ emit(ROULETTE)
+ self.dir.show(file)
+
+ def do_help(self):
+ self.prologue(T_HELP)
+ emit(HELP)
+
+ def do_show(self):
+ entry = self.dir.open(self.ui.file)
+ self.prologue(T_SHOW)
+ entry.show()
+
+ def do_add(self):
+ self.prologue(T_ADD)
+ emit(ADD_HEAD)
+ sections = SECTION_TITLES.items()
+ sections.sort()
+ for section, title in sections:
+ emit(ADD_SECTION, section=section, title=title)
+ emit(ADD_TAIL)
+
+ def do_delete(self):
+ self.prologue(T_DELETE)
+ emit(DELETE)
+
+ def do_log(self):
+ entry = self.dir.open(self.ui.file)
+ self.prologue(T_LOG, entry)
+ emit(LOG, entry)
+ self.rlog(interpolate(SH_RLOG, entry), entry)
+
+ def rlog(self, command, entry=None):
+ output = os.popen(command).read()
+ sys.stdout.write('<PRE>')
+ athead = 0
+ lines = output.split('\n')
+ while lines and not lines[-1]:
+ del lines[-1]
+ if lines:
+ line = lines[-1]
+ if line[:1] == '=' and len(line) >= 40 and \
+ line == line[0]*len(line):
+ del lines[-1]
+ headrev = None
+ for line in lines:
+ if entry and athead and line[:9] == 'revision ':
+ rev = line[9:].split()
+ mami = revparse(rev)
+ if not mami:
+ print line
+ else:
+ emit(REVISIONLINK, entry, rev=rev, line=line)
+ if mami[1] > 1:
+ prev = "%d.%d" % (mami[0], mami[1]-1)
+ emit(DIFFLINK, entry, prev=prev, rev=rev)
+ if headrev:
+ emit(DIFFLINK, entry, prev=rev, rev=headrev)
+ else:
+ headrev = rev
+ print
+ athead = 0
+ else:
+ athead = 0
+ if line[:1] == '-' and len(line) >= 20 and \
+ line == len(line) * line[0]:
+ athead = 1
+ sys.stdout.write('<HR>')
+ else:
+ print line
+ print '</PRE>'
+
+ def do_revision(self):
+ entry = self.dir.open(self.ui.file)
+ rev = self.ui.rev
+ mami = revparse(rev)
+ if not mami:
+ self.error("Invalid revision number: %r." % (rev,))
+ self.prologue(T_REVISION, entry)
+ self.shell(interpolate(SH_REVISION, entry, rev=rev))
+
+ def do_diff(self):
+ entry = self.dir.open(self.ui.file)
+ prev = self.ui.prev
+ rev = self.ui.rev
+ mami = revparse(rev)
+ if not mami:
+ self.error("Invalid revision number: %r." % (rev,))
+ if prev:
+ if not revparse(prev):
+ self.error("Invalid previous revision number: %r." % (prev,))
+ else:
+ prev = '%d.%d' % (mami[0], mami[1])
+ self.prologue(T_DIFF, entry)
+ self.shell(interpolate(SH_RDIFF, entry, rev=rev, prev=prev))
+
+ def shell(self, command):
+ output = os.popen(command).read()
+ sys.stdout.write('<PRE>')
+ print escape(output)
+ print '</PRE>'
+
+ def do_new(self):
+ entry = self.dir.new(section=int(self.ui.section))
+ entry.version = '*new*'
+ self.prologue(T_EDIT)
+ emit(EDITHEAD)
+ emit(EDITFORM1, entry, editversion=entry.version)
+ emit(EDITFORM2, entry, load_my_cookie())
+ emit(EDITFORM3)
+ entry.show(edit=0)
+
+ def do_edit(self):
+ entry = self.dir.open(self.ui.file)
+ entry.load_version()
+ self.prologue(T_EDIT)
+ emit(EDITHEAD)
+ emit(EDITFORM1, entry, editversion=entry.version)
+ emit(EDITFORM2, entry, load_my_cookie())
+ emit(EDITFORM3)
+ entry.show(edit=0)
+
+ def do_review(self):
+ send_my_cookie(self.ui)
+ if self.ui.editversion == '*new*':
+ sec, num = self.dir.parse(self.ui.file)
+ entry = self.dir.new(section=sec)
+ entry.version = "*new*"
+ if entry.file != self.ui.file:
+ self.error("Commit version conflict!")
+ emit(NEWCONFLICT, self.ui, sec=sec, num=num)
+ return
+ else:
+ entry = self.dir.open(self.ui.file)
+ entry.load_version()
+ # Check that the FAQ entry number didn't change
+ if self.ui.title.split()[:1] != entry.title.split()[:1]:
+ self.error("Don't change the entry number please!")
+ return
+ # Check that the edited version is the current version
+ if entry.version != self.ui.editversion:
+ self.error("Commit version conflict!")
+ emit(VERSIONCONFLICT, entry, self.ui)
+ return
+ commit_ok = ((not PASSWORD
+ or self.ui.password == PASSWORD)
+ and self.ui.author
+ and '@' in self.ui.email
+ and self.ui.log)
+ if self.ui.commit:
+ if not commit_ok:
+ self.cantcommit()
+ else:
+ self.commit(entry)
+ return
+ self.prologue(T_REVIEW)
+ emit(REVIEWHEAD)
+ entry.body = self.ui.body
+ entry.title = self.ui.title
+ entry.show(edit=0)
+ emit(EDITFORM1, self.ui, entry)
+ if commit_ok:
+ emit(COMMIT)
+ else:
+ emit(NOCOMMIT_HEAD)
+ self.errordetail()
+ emit(NOCOMMIT_TAIL)
+ emit(EDITFORM2, self.ui, entry, load_my_cookie())
+ emit(EDITFORM3)
+
+ def cantcommit(self):
+ self.prologue(T_CANTCOMMIT)
+ print CANTCOMMIT_HEAD
+ self.errordetail()
+ print CANTCOMMIT_TAIL
+
+ def errordetail(self):
+ if PASSWORD and self.ui.password != PASSWORD:
+ emit(NEED_PASSWD)
+ if not self.ui.log:
+ emit(NEED_LOG)
+ if not self.ui.author:
+ emit(NEED_AUTHOR)
+ if not self.ui.email:
+ emit(NEED_EMAIL)
+
+ def commit(self, entry):
+ file = entry.file
+ # Normalize line endings in body
+ if '\r' in self.ui.body:
+ self.ui.body = re.sub('\r\n?', '\n', self.ui.body)
+ # Normalize whitespace in title
+ self.ui.title = ' '.join(self.ui.title.split())
+ # Check that there were any changes
+ if self.ui.body == entry.body and self.ui.title == entry.title:
+ self.error("You didn't make any changes!")
+ return
+
+ # need to lock here because otherwise the file exists and is not writable (on NT)
+ command = interpolate(SH_LOCK, file=file)
+ p = os.popen(command)
+ output = p.read()
+
+ try:
+ os.unlink(file)
+ except os.error:
+ pass
+ try:
+ f = open(file, 'w')
+ except IOError, why:
+ self.error(CANTWRITE, file=file, why=why)
+ return
+ date = time.ctime(now)
+ emit(FILEHEADER, self.ui, os.environ, date=date, _file=f, _quote=0)
+ f.write('\n')
+ f.write(self.ui.body)
+ f.write('\n')
+ f.close()
+
+ import tempfile
+ tf = tempfile.NamedTemporaryFile()
+ emit(LOGHEADER, self.ui, os.environ, date=date, _file=tf)
+ tf.flush()
+ tf.seek(0)
+
+ command = interpolate(SH_CHECKIN, file=file, tfn=tf.name)
+ log("\n\n" + command)
+ p = os.popen(command)
+ output = p.read()
+ sts = p.close()
+ log("output: " + output)
+ log("done: " + str(sts))
+ log("TempFile:\n" + tf.read() + "end")
+
+ if not sts:
+ self.prologue(T_COMMITTED)
+ emit(COMMITTED)
+ else:
+ self.error(T_COMMITFAILED)
+ emit(COMMITFAILED, sts=sts)
+ print '<PRE>%s</PRE>' % escape(output)
+
+ try:
+ os.unlink(tf.name)
+ except os.error:
+ pass
+
+ entry = self.dir.open(file)
+ entry.show()
+
+wiz = FaqWizard()
+wiz.go()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/move-faqwiz.sh b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/move-faqwiz.sh
new file mode 100644
index 0000000000..7d206c0219
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/faqwiz/move-faqwiz.sh
@@ -0,0 +1,55 @@
+#!/bin/sh
+#
+# Christian Reis <kiko@async.com.br>
+#
+# Moves
+#
+# Example:
+#
+# blackjesus:~> ./move-faqwiz.sh 2\.1 3\.2
+# Moving FAQ question 02.001 to 03.002
+
+if [ x$2 = x ]; then
+ echo "Need 2 args: original_version final_version."
+ exit 2
+fi
+
+if [ ! -d data -o ! -d data/RCS ]; then
+ echo "Run this inside the faqwiz data/ directory's parent dir."
+ exit 2
+fi
+
+cut_n_pad() {
+ t=`echo $1 | cut -d. -f $2`
+ export $3=`echo $t | awk "{ tmp = \\$0; l = length(tmp); for (i = 0; i < $2-l+1; i++) { tmp = "0".tmp } print tmp }"`
+}
+
+cut_n_pad $1 1 prefix1
+cut_n_pad $1 2 suffix1
+cut_n_pad $2 1 prefix2
+cut_n_pad $2 2 suffix2
+if which tempfile >/dev/null; then
+ tmpfile=$(tempfile -d .)
+elif [ -n "$RANDOM" ]; then
+ tmpfile=tmp$RANDOM.tmp
+else
+ tmpfile=tmp$$.tmp
+fi
+file1=faq$prefix1.$suffix1.htp
+file2=faq$prefix2.$suffix2.htp
+
+echo "Moving FAQ question $prefix1.$suffix1 to $prefix2.$suffix2"
+
+sed -e "s/$1\./$2\./g" data/$file1 > ${tmpfile}1
+sed -e "s/$1\./$2\./g" data/RCS/$file1,v > ${tmpfile}2
+
+if [ -f data/$file2 ]; then
+ echo "Target FAQ exists. Won't clobber."
+ exit 2
+fi
+
+mv ${tmpfile}1 data/$file2
+mv ${tmpfile}2 data/RCS/$file2,v
+mv data/$file1 data/$file1.orig
+mv data/RCS/$file1,v data/RCS/$file1,v.orig
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/README.txt b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/README.txt
new file mode 100644
index 0000000000..a0a7b6a1b1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/README.txt
@@ -0,0 +1,8 @@
+framer is a tool to generate boilerplate code for C extension types.
+
+The boilerplate is generated from a specification object written in
+Python. The specification uses the class statement to describe the
+extension module and any extension types it contains. From the
+specification, framer can generate all the boilerplate C code,
+including function definitions, argument handling code, and type
+objects.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/TODO.txt b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/TODO.txt
new file mode 100644
index 0000000000..fc9b53c716
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/TODO.txt
@@ -0,0 +1,6 @@
+Add spec for getsets.
+Generate a distutils setup script.
+Handle operator overloading.
+Generate traverse and clear methods for GC.
+Handle mapping, sequence, buffer protocols.
+Finish the todo list.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/example.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/example.py
new file mode 100644
index 0000000000..ccec1d841d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/example.py
@@ -0,0 +1,126 @@
+"""Generate the skeleton for cStringIO as an example of framer."""
+
+from framer.bases import Module, Type
+from framer.member import member
+
+class cStringIO(Module):
+ """A simple fast partial StringIO replacement.
+
+ This module provides a simple useful replacement for the StringIO
+ module that is written in C. It does not provide the full
+ generality of StringIO, but it provides enough for most
+ applications and is especially useful in conjunction with the
+ pickle module.
+
+ Usage:
+
+ from cStringIO import StringIO
+
+ an_output_stream = StringIO()
+ an_output_stream.write(some_stuff)
+ ...
+ value = an_output_stream.getvalue()
+
+ an_input_stream = StringIO(a_string)
+ spam = an_input_stream.readline()
+ spam = an_input_stream.read(5)
+ an_input_stream.seek(0) # OK, start over
+ spam = an_input_stream.read() # and read it all
+ """
+
+ __file__ = "cStringIO.c"
+
+ def StringIO(o):
+ """Return a StringIO-like stream for reading or writing"""
+ StringIO.pyarg = "|O"
+
+ class InputType(Type):
+ "Simple type for treating strings as input file streams"
+
+ abbrev = "input"
+
+ struct = """\
+ typedef struct {
+ PyObject_HEAD
+ char *buf;
+ int pos;
+ int size;
+ PyObject *pbuf;
+ } InputObject;
+ """
+
+ def flush(self):
+ """Does nothing"""
+
+ def getvalue(self):
+ """Get the string value.
+
+ If use_pos is specified and is a true value, then the
+ string returned will include only the text up to the
+ current file position.
+ """
+
+ def isatty(self):
+ """Always returns False"""
+
+ def read(self, s):
+ """Return s characters or the rest of the string."""
+ read.pyarg = "|i"
+
+ def readline(self):
+ """Read one line."""
+
+ def readlines(self, hint):
+ """Read all lines."""
+ readlines.pyarg = "|i"
+
+ def reset(self):
+ """Reset the file position to the beginning."""
+
+ def tell(self):
+ """Get the current position."""
+
+ def truncate(self, pos):
+ """Truncate the file at the current position."""
+ truncate.pyarg = "|i"
+
+ def seek(self, position, mode=0):
+ """Set the current position.
+
+ The optional mode argument can be 0 for absolute, 1 for relative,
+ and 2 for relative to EOF. The default is absolute.
+ """
+ seek.pyarg = "i|i"
+
+ def close(self):
+ pass
+
+ class OutputType(InputType):
+ "Simple type for output strings."
+
+ abbrev = "output"
+
+ struct = """\
+ typedef struct {
+ PyObject_HEAD
+ char *buf;
+ int pos;
+ int size;
+ int softspace;
+ } OutputObject;
+ """
+
+ softspace = member()
+
+ def close(self):
+ """Explicitly release resources."""
+
+ def write(self, s):
+ """Write a string to the file."""
+ # XXX Hack: writing None resets the buffer
+
+ def writelines(self, lines):
+ """Write each string in lines."""
+
+
+cStringIO.gen()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/__init__.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/__init__.py
new file mode 100644
index 0000000000..f28fd6115a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/__init__.py
@@ -0,0 +1,6 @@
+"""A tool to generate basic framework for C extension types.
+
+The basic ideas is the same as modulator, but the code generates code
+using many of the new features introduced in Python 2.2. It also
+takes a more declarative approach to generating code.
+"""
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/bases.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/bases.py
new file mode 100644
index 0000000000..5fd09c7a3e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/bases.py
@@ -0,0 +1,220 @@
+"""Provides the Module and Type base classes that user code inherits from."""
+
+__all__ = ["Module", "Type", "member"]
+
+from framer import struct, template
+from framer.function import Function, Method
+from framer.member import member
+from framer.slots import *
+from framer.util import cstring, unindent
+
+from types import FunctionType
+
+def sortitems(dict):
+ L = dict.items()
+ L.sort()
+ return L
+
+# The Module and Type classes are implemented using metaclasses,
+# because most of the methods are class methods. It is easier to use
+# metaclasses than the cumbersome classmethod() builtin. They have
+# class methods because they are exposed to user code as base classes.
+
+class BaseMetaclass(type):
+ """Shared infrastructure for generating modules and types."""
+
+ # just methoddef so far
+
+ def dump_methoddef(self, f, functions, vars):
+ def p(templ, vars=vars): # helper function to generate output
+ print >> f, templ % vars
+
+ if not functions:
+ return
+ p(template.methoddef_start)
+ for name, func in sortitems(functions):
+ if func.__doc__:
+ p(template.methoddef_def_doc, func.vars)
+ else:
+ p(template.methoddef_def, func.vars)
+ p(template.methoddef_end)
+
+class ModuleMetaclass(BaseMetaclass):
+ """Provides methods for Module class."""
+
+ def gen(self):
+ self.analyze()
+ self.initvars()
+ f = open(self.__filename, "w")
+ self.dump(f)
+ f.close()
+
+ def analyze(self):
+ self.name = getattr(self, "abbrev", self.__name__)
+ self.__functions = {}
+ self.__types = {}
+ self.__members = False
+
+ for name, obj in self.__dict__.iteritems():
+ if isinstance(obj, FunctionType):
+ self.__functions[name] = Function(obj, self)
+ elif isinstance(obj, TypeMetaclass):
+ obj._TypeMetaclass__module = self.name
+ obj.analyze()
+ self.__types[name] = obj
+ if obj.has_members():
+ self.__members = True
+
+ def initvars(self):
+ v = self.__vars = {}
+ filename = getattr(self, "__file__", None)
+ if filename is None:
+ filename = self.__name__ + "module.c"
+ self.__filename = v["FileName"] = filename
+ name = v["ModuleName"] = self.__name__
+ v["MethodDefName"] = "%s_methods" % name
+ v["ModuleDocstring"] = cstring(unindent(self.__doc__))
+
+ def dump(self, f):
+ def p(templ, vars=self.__vars): # helper function to generate output
+ print >> f, templ % vars
+
+ p(template.module_start)
+ if self.__members:
+ p(template.member_include)
+ print >> f
+
+ if self.__doc__:
+ p(template.module_doc)
+
+ for name, type in sortitems(self.__types):
+ type.dump(f)
+
+ for name, func in sortitems(self.__functions):
+ func.dump(f)
+
+ self.dump_methoddef(f, self.__functions, self.__vars)
+
+ p(template.module_init_start)
+ for name, type in sortitems(self.__types):
+ type.dump_init(f)
+
+ p("}")
+
+class Module:
+ __metaclass__ = ModuleMetaclass
+
+class TypeMetaclass(BaseMetaclass):
+
+ def dump(self, f):
+ self.initvars()
+
+ # defined after initvars() so that __vars is defined
+ def p(templ, vars=self.__vars):
+ print >> f, templ % vars
+
+ if self.struct is not None:
+ print >> f, unindent(self.struct, False)
+
+ if self.__doc__:
+ p(template.docstring)
+
+ for name, func in sortitems(self.__methods):
+ func.dump(f)
+
+ self.dump_methoddef(f, self.__methods, self.__vars)
+ self.dump_memberdef(f)
+ self.dump_slots(f)
+
+ def has_members(self):
+ if self.__members:
+ return True
+ else:
+ return False
+
+ def analyze(self):
+ # called by ModuleMetaclass analyze()
+ self.name = getattr(self, "abbrev", self.__name__)
+ src = getattr(self, "struct", None)
+ if src is not None:
+ self.__struct = struct.parse(src)
+ else:
+ self.__struct = None
+ self.__methods = {}
+ self.__members = {}
+ for cls in self.__mro__:
+ for k, v in cls.__dict__.iteritems():
+ if isinstance(v, FunctionType):
+ self.__methods[k] = Method(v, self)
+ if isinstance(v, member):
+ self.__members[k] = v
+ assert self.__struct is not None
+ v.register(k, self.__struct)
+ self.analyze_slots()
+
+ def analyze_slots(self):
+ self.__slots = {}
+ for s in Slots:
+ if s.special is not None:
+ meth = self.__methods.get(s.special)
+ if meth is not None:
+ self.__slots[s] = meth
+ self.__slots[TP_NAME] = '"%s.%s"' % (self.__module, self.__name__)
+ if self.__doc__:
+ self.__slots[TP_DOC] = "%s_doc" % self.name
+ if self.__struct is not None:
+ self.__slots[TP_BASICSIZE] = "sizeof(%s)" % self.__struct.name
+ self.__slots[TP_DEALLOC] = "%s_dealloc" % self.name
+ if self.__methods:
+ self.__slots[TP_METHODS] = "%s_methods" % self.name
+ if self.__members:
+ self.__slots[TP_MEMBERS] = "%s_members" % self.name
+
+ def initvars(self):
+ v = self.__vars = {}
+ v["TypeName"] = self.__name__
+ v["CTypeName"] = "Py%s_Type" % self.__name__
+ v["MethodDefName"] = self.__slots[TP_METHODS]
+ if self.__doc__:
+ v["DocstringVar"] = self.__slots[TP_DOC]
+ v["Docstring"] = cstring(unindent(self.__doc__))
+ if self.__struct is not None:
+ v["StructName"] = self.__struct.name
+ if self.__members:
+ v["MemberDefName"] = self.__slots[TP_MEMBERS]
+
+ def dump_memberdef(self, f):
+ def p(templ, vars=self.__vars):
+ print >> f, templ % vars
+
+ if not self.__members:
+ return
+ p(template.memberdef_start)
+ for name, slot in sortitems(self.__members):
+ slot.dump(f)
+ p(template.memberdef_end)
+
+ def dump_slots(self, f):
+ def p(templ, vars=self.__vars):
+ print >> f, templ % vars
+
+ if self.struct:
+ p(template.dealloc_func, {"name" : self.__slots[TP_DEALLOC]})
+
+ p(template.type_struct_start)
+ for s in Slots[:-5]: # XXX
+ val = self.__slots.get(s, s.default)
+ ntabs = 4 - (4 + len(val)) / 8
+ line = " %s,%s/* %s */" % (val, "\t" * ntabs, s.name)
+ print >> f, line
+ p(template.type_struct_end)
+
+ def dump_init(self, f):
+ def p(templ):
+ print >> f, templ % self.__vars
+
+ p(template.type_init_type)
+ p(template.module_add_type)
+
+class Type:
+ __metaclass__ = TypeMetaclass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/function.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/function.py
new file mode 100644
index 0000000000..4fe481c149
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/function.py
@@ -0,0 +1,173 @@
+"""Functions."""
+
+from framer import template
+from framer.util import cstring, unindent
+
+METH_O = "METH_O"
+METH_NOARGS = "METH_NOARGS"
+METH_VARARGS = "METH_VARARGS"
+
+def parsefmt(fmt):
+ for c in fmt:
+ if c == '|':
+ continue
+ yield c
+
+class Argument:
+
+ def __init__(self, name):
+ self.name = name
+ self.ctype = "PyObject *"
+ self.default = None
+
+ def __str__(self):
+ return "%s%s" % (self.ctype, self.name)
+
+ def setfmt(self, code):
+ self.ctype = self._codes[code]
+ if self.ctype[-1] != "*":
+ self.ctype += " "
+
+ _codes = {"O": "PyObject *",
+ "i": "int",
+ }
+
+ def decl(self):
+ if self.default is None:
+ return str(self) + ";"
+ else:
+ return "%s = %s;" % (self, self.default)
+
+class _ArgumentList(object):
+
+ # these instance variables should be initialized by subclasses
+ ml_meth = None
+ fmt = None
+
+ def __init__(self, args):
+ self.args = map(Argument, args)
+
+ def __len__(self):
+ return len(self.args)
+
+ def __getitem__(self, i):
+ return self.args[i]
+
+ def dump_decls(self, f):
+ pass
+
+class NoArgs(_ArgumentList):
+
+ def __init__(self, args):
+ assert len(args) == 0
+ super(NoArgs, self).__init__(args)
+ self.ml_meth = METH_NOARGS
+
+ def c_args(self):
+ return "PyObject *self"
+
+class OneArg(_ArgumentList):
+
+ def __init__(self, args):
+ assert len(args) == 1
+ super(OneArg, self).__init__(args)
+ self.ml_meth = METH_O
+
+ def c_args(self):
+ return "PyObject *self, %s" % self.args[0]
+
+class VarArgs(_ArgumentList):
+
+ def __init__(self, args, fmt=None):
+ super(VarArgs, self).__init__(args)
+ self.ml_meth = METH_VARARGS
+ if fmt is not None:
+ self.fmt = fmt
+ i = 0
+ for code in parsefmt(fmt):
+ self.args[i].setfmt(code)
+ i += 1
+
+ def c_args(self):
+ return "PyObject *self, PyObject *args"
+
+ def targets(self):
+ return ", ".join(["&%s" % a.name for a in self.args])
+
+ def dump_decls(self, f):
+ for a in self.args:
+ print >> f, " %s" % a.decl()
+
+def ArgumentList(func, method):
+ code = func.func_code
+ args = code.co_varnames[:code.co_argcount]
+ if method:
+ args = args[1:]
+ pyarg = getattr(func, "pyarg", None)
+ if pyarg is not None:
+ args = VarArgs(args, pyarg)
+ if func.func_defaults:
+ L = list(func.func_defaults)
+ ndefault = len(L)
+ i = len(args) - ndefault
+ while L:
+ args[i].default = L.pop(0)
+ return args
+ else:
+ if len(args) == 0:
+ return NoArgs(args)
+ elif len(args) == 1:
+ return OneArg(args)
+ else:
+ return VarArgs(args)
+
+class Function:
+
+ method = False
+
+ def __init__(self, func, parent):
+ self._func = func
+ self._parent = parent
+ self.analyze()
+ self.initvars()
+
+ def dump(self, f):
+ def p(templ, vars=None): # helper function to generate output
+ if vars is None:
+ vars = self.vars
+ print >> f, templ % vars
+
+ if self.__doc__:
+ p(template.docstring)
+
+ d = {"name" : self.vars["CName"],
+ "args" : self.args.c_args(),
+ }
+ p(template.funcdef_start, d)
+
+ self.args.dump_decls(f)
+
+ if self.args.ml_meth == METH_VARARGS:
+ p(template.varargs)
+
+ p(template.funcdef_end)
+
+ def analyze(self):
+ self.__doc__ = self._func.__doc__
+ self.args = ArgumentList(self._func, self.method)
+
+ def initvars(self):
+ v = self.vars = {}
+ v["PythonName"] = self._func.__name__
+ s = v["CName"] = "%s_%s" % (self._parent.name, self._func.__name__)
+ v["DocstringVar"] = s + "_doc"
+ v["MethType"] = self.args.ml_meth
+ if self.__doc__:
+ v["Docstring"] = cstring(unindent(self.__doc__))
+ if self.args.fmt is not None:
+ v["ArgParse"] = self.args.fmt
+ v["ArgTargets"] = self.args.targets()
+
+class Method(Function):
+
+ method = True
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/member.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/member.py
new file mode 100644
index 0000000000..05208fa716
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/member.py
@@ -0,0 +1,73 @@
+from framer import template
+from framer.util import cstring, unindent
+
+T_SHORT = "T_SHORT"
+T_INT = "T_INT"
+T_LONG = "T_LONG"
+T_FLOAT = "T_FLOAT"
+T_DOUBLE = "T_DOUBLE"
+T_STRING = "T_STRING"
+T_OBJECT = "T_OBJECT"
+T_CHAR = "T_CHAR"
+T_BYTE = "T_BYTE"
+T_UBYTE = "T_UBYTE"
+T_UINT = "T_UINT"
+T_ULONG = "T_ULONG"
+T_STRING_INPLACE = "T_STRING_INPLACE"
+T_OBJECT_EX = "T_OBJECT_EX"
+
+RO = READONLY = "READONLY"
+READ_RESTRICTED = "READ_RESTRICTED"
+WRITE_RESTRICTED = "WRITE_RESTRICTED"
+RESTRICT = "RESTRICTED"
+
+c2t = {"int" : T_INT,
+ "unsigned int" : T_UINT,
+ "long" : T_LONG,
+ "unsigned long" : T_LONG,
+ "float" : T_FLOAT,
+ "double" : T_DOUBLE,
+ "char *" : T_CHAR,
+ "PyObject *" : T_OBJECT,
+ }
+
+class member(object):
+
+ def __init__(self, cname=None, type=None, flags=None, doc=None):
+ self.type = type
+ self.flags = flags
+ self.cname = cname
+ self.doc = doc
+ self.name = None
+ self.struct = None
+
+ def register(self, name, struct):
+ self.name = name
+ self.struct = struct
+ self.initvars()
+
+ def initvars(self):
+ v = self.vars = {}
+ v["PythonName"] = self.name
+ if self.cname is not None:
+ v["CName"] = self.cname
+ else:
+ v["CName"] = self.name
+ v["Flags"] = self.flags or "0"
+ v["Type"] = self.get_type()
+ if self.doc is not None:
+ v["Docstring"] = cstring(unindent(self.doc))
+ v["StructName"] = self.struct.name
+
+ def get_type(self):
+ """Deduce type code from struct specification if not defined"""
+ if self.type is not None:
+ return self.type
+ ctype = self.struct.get_type(self.name)
+ return c2t[ctype]
+
+ def dump(self, f):
+ if self.doc is None:
+ print >> f, template.memberdef_def % self.vars
+ else:
+ print >> f, template.memberdef_def_doc % self.vars
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/slots.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/slots.py
new file mode 100644
index 0000000000..3fd3496c6e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/slots.py
@@ -0,0 +1,64 @@
+"""Descriptions of all the slots in Python's type objects."""
+
+class Slot(object):
+ def __init__(self, name, cast=None, special=None, default="0"):
+ self.name = name
+ self.cast = cast
+ self.special = special
+ self.default = default
+
+Slots = (Slot("ob_size"),
+ Slot("tp_name"),
+ Slot("tp_basicsize"),
+ Slot("tp_itemsize"),
+ Slot("tp_dealloc", "destructor"),
+ Slot("tp_print", "printfunc"),
+ Slot("tp_getattr", "getattrfunc"),
+ Slot("tp_setattr", "setattrfunc"),
+ Slot("tp_compare", "cmpfunc", "__cmp__"),
+ Slot("tp_repr", "reprfunc", "__repr__"),
+ Slot("tp_as_number"),
+ Slot("tp_as_sequence"),
+ Slot("tp_as_mapping"),
+ Slot("tp_hash", "hashfunc", "__hash__"),
+ Slot("tp_call", "ternaryfunc", "__call__"),
+ Slot("tp_str", "reprfunc", "__str__"),
+ Slot("tp_getattro", "getattrofunc", "__getattr__", # XXX
+ "PyObject_GenericGetAttr"),
+ Slot("tp_setattro", "setattrofunc", "__setattr__"),
+ Slot("tp_as_buffer"),
+ Slot("tp_flags", default="Py_TPFLAGS_DEFAULT"),
+ Slot("tp_doc"),
+ Slot("tp_traverse", "traverseprox"),
+ Slot("tp_clear", "inquiry"),
+ Slot("tp_richcompare", "richcmpfunc"),
+ Slot("tp_weaklistoffset"),
+ Slot("tp_iter", "getiterfunc", "__iter__"),
+ Slot("tp_iternext", "iternextfunc", "__next__"), # XXX
+ Slot("tp_methods"),
+ Slot("tp_members"),
+ Slot("tp_getset"),
+ Slot("tp_base"),
+ Slot("tp_dict"),
+ Slot("tp_descr_get", "descrgetfunc"),
+ Slot("tp_descr_set", "descrsetfunc"),
+ Slot("tp_dictoffset"),
+ Slot("tp_init", "initproc", "__init__"),
+ Slot("tp_alloc", "allocfunc"),
+ Slot("tp_new", "newfunc"),
+ Slot("tp_free", "freefunc"),
+ Slot("tp_is_gc", "inquiry"),
+ Slot("tp_bases"),
+ Slot("tp_mro"),
+ Slot("tp_cache"),
+ Slot("tp_subclasses"),
+ Slot("tp_weaklist"),
+ )
+
+# give some slots symbolic names
+TP_NAME = Slots[1]
+TP_BASICSIZE = Slots[2]
+TP_DEALLOC = Slots[4]
+TP_DOC = Slots[20]
+TP_METHODS = Slots[27]
+TP_MEMBERS = Slots[28]
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/struct.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/struct.py
new file mode 100644
index 0000000000..d58244f7f0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/struct.py
@@ -0,0 +1,52 @@
+"""Rudimentary parser for C struct definitions."""
+
+import re
+
+PyObject_HEAD = "PyObject_HEAD"
+PyObject_VAR_HEAD = "PyObject_VAR_HEAD"
+
+rx_name = re.compile("} (\w+);")
+
+class Struct:
+ def __init__(self, name, head, members):
+ self.name = name
+ self.head = head
+ self.members = members
+
+ def get_type(self, name):
+ for _name, type in self.members:
+ if name == _name:
+ return type
+ raise ValueError, "no member named %s" % name
+
+def parse(s):
+ """Parse a C struct definition.
+
+ The parser is very restricted in what it will accept.
+ """
+
+ lines = filter(None, s.split("\n")) # get non-empty lines
+ assert lines[0].strip() == "typedef struct {"
+ pyhead = lines[1].strip()
+ assert (pyhead.startswith("PyObject") and
+ pyhead.endswith("HEAD"))
+ members = []
+ for line in lines[2:]:
+ line = line.strip()
+ if line.startswith("}"):
+ break
+
+ assert line.endswith(";")
+ line = line[:-1]
+ words = line.split()
+ name = words[-1]
+ type = " ".join(words[:-1])
+ if name[0] == "*":
+ name = name[1:]
+ type += " *"
+ members.append((name, type))
+ name = None
+ mo = rx_name.search(line)
+ assert mo is not None
+ name = mo.group(1)
+ return Struct(name, pyhead, members)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/structparse.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/structparse.py
new file mode 100644
index 0000000000..b81a273557
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/structparse.py
@@ -0,0 +1,46 @@
+"""Rudimentary parser for C struct definitions."""
+
+import re
+
+PyObject_HEAD = "PyObject_HEAD"
+PyObject_VAR_HEAD = "PyObject_VAR_HEAD"
+
+rx_name = re.compile("} (\w+);")
+
+class Struct:
+ def __init__(self, name, head, members):
+ self.name = name
+ self.head = head
+ self.members = members
+
+def parse(s):
+ """Parse a C struct definition.
+
+ The parser is very restricted in what it will accept.
+ """
+
+ lines = filter(None, s.split("\n")) # get non-empty lines
+ assert lines[0].strip() == "typedef struct {"
+ pyhead = lines[1].strip()
+ assert (pyhead.startswith("PyObject") and
+ pyhead.endswith("HEAD"))
+ members = []
+ for line in lines[2:]:
+ line = line.strip()
+ if line.startswith("}"):
+ break
+
+ assert line.endswith(";")
+ line = line[:-1]
+ words = line.split()
+ name = words[-1]
+ type = " ".join(words[:-1])
+ if name[0] == "*":
+ name = name[1:]
+ type += " *"
+ members.append((name, type))
+ name = None
+ mo = rx_name.search(line)
+ assert mo is not None
+ name = mo.group(1)
+ return Struct(name, pyhead, members)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/template.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/template.py
new file mode 100644
index 0000000000..cad8f40f21
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/template.py
@@ -0,0 +1,102 @@
+"""framer's C code templates.
+
+Templates use the following variables:
+
+FileName: name of the file that contains the C source code
+ModuleName: name of the module, as in "import ModuleName"
+ModuleDocstring: C string containing the module doc string
+"""
+
+module_start = '#include "Python.h"'
+member_include = '#include "structmember.h"'
+
+module_doc = """\
+PyDoc_STRVAR(%(ModuleName)s_doc,
+%(ModuleDocstring)s);
+"""
+
+methoddef_start = """\
+static struct PyMethodDef %(MethodDefName)s[] = {"""
+
+methoddef_def = """\
+ {"%(PythonName)s", (PyCFunction)%(CName)s, %(MethType)s},"""
+
+methoddef_def_doc = """\
+ {"%(PythonName)s", (PyCFunction)%(CName)s, %(MethType)s,
+ %(DocstringVar)s},"""
+
+methoddef_end = """\
+ {NULL, NULL}
+};
+"""
+
+memberdef_start = """\
+#define OFF(X) offsetof(%(StructName)s, X)
+
+static struct PyMemberDef %(MemberDefName)s[] = {"""
+
+memberdef_def_doc = """\
+ {"%(PythonName)s", %(Type)s, OFF(%(CName)s), %(Flags)s,
+ %(Docstring)s},"""
+
+memberdef_def = """\
+ {"%(PythonName)s", %(Type)s, OFF(%(CName)s), %(Flags)s},"""
+
+memberdef_end = """\
+ {NULL}
+};
+
+#undef OFF
+"""
+
+dealloc_func = """static void
+%(name)s(PyObject *ob)
+{
+}
+"""
+
+docstring = """\
+PyDoc_STRVAR(%(DocstringVar)s,
+%(Docstring)s);
+"""
+
+funcdef_start = """\
+static PyObject *
+%(name)s(%(args)s)
+{"""
+
+funcdef_end = """\
+}
+"""
+
+varargs = """\
+ if (!PyArg_ParseTuple(args, \"%(ArgParse)s:%(PythonName)s\",
+ %(ArgTargets)s))
+ return NULL;"""
+
+module_init_start = """\
+PyMODINIT_FUNC
+init%(ModuleName)s(void)
+{
+ PyObject *mod;
+
+ mod = Py_InitModule3("%(ModuleName)s", %(MethodDefName)s,
+ %(ModuleName)s_doc);
+ if (mod == NULL)
+ return;
+"""
+
+type_init_type = " %(CTypeName)s.ob_type = &PyType_Type;"
+module_add_type = """\
+ if (!PyObject_SetAttrString(mod, "%(TypeName)s",
+ (PyObject *)&%(CTypeName)s))
+ return;
+"""
+
+type_struct_start = """\
+static PyTypeObject %(CTypeName)s = {
+ PyObject_HEAD_INIT(0)"""
+
+type_struct_end = """\
+};
+"""
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/util.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/util.py
new file mode 100644
index 0000000000..16077d07d2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/util.py
@@ -0,0 +1,35 @@
+def cstring(s, width=70):
+ """Return C string representation of a Python string.
+
+ width specifies the maximum width of any line of the C string.
+ """
+ L = []
+ for l in s.split("\n"):
+ if len(l) < width:
+ L.append(r'"%s\n"' % l)
+
+ return "\n".join(L)
+
+def unindent(s, skipfirst=True):
+ """Return an unindented version of a docstring.
+
+ Removes indentation on lines following the first one, using the
+ leading whitespace of the first indented line that is not blank
+ to determine the indentation.
+ """
+
+ lines = s.split("\n")
+ if skipfirst:
+ first = lines.pop(0)
+ L = [first]
+ else:
+ L = []
+ indent = None
+ for l in lines:
+ ls = l.strip()
+ if ls:
+ indent = len(l) - len(ls)
+ break
+ L += [l[indent:] for l in lines]
+
+ return "\n".join(L)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/README
new file mode 100644
index 0000000000..b309335d88
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/README
@@ -0,0 +1,296 @@
+THE FREEZE SCRIPT
+=================
+
+(Directions for Windows are at the end of this file.)
+
+
+What is Freeze?
+---------------
+
+Freeze make it possible to ship arbitrary Python programs to people
+who don't have Python. The shipped file (called a "frozen" version of
+your Python program) is an executable, so this only works if your
+platform is compatible with that on the receiving end (this is usually
+a matter of having the same major operating system revision and CPU
+type).
+
+The shipped file contains a Python interpreter and large portions of
+the Python run-time. Some measures have been taken to avoid linking
+unneeded modules, but the resulting binary is usually not small.
+
+The Python source code of your program (and of the library modules
+written in Python that it uses) is not included in the binary --
+instead, the compiled byte-code (the instruction stream used
+internally by the interpreter) is incorporated. This gives some
+protection of your Python source code, though not much -- a
+disassembler for Python byte-code is available in the standard Python
+library. At least someone running "strings" on your binary won't see
+the source.
+
+
+How does Freeze know which modules to include?
+----------------------------------------------
+
+Previous versions of Freeze used a pretty simple-minded algorithm to
+find the modules that your program uses, essentially searching for
+lines starting with the word "import". It was pretty easy to trick it
+into making mistakes, either missing valid import statements, or
+mistaking string literals (e.g. doc strings) for import statements.
+
+This has been remedied: Freeze now uses the regular Python parser to
+parse the program (and all its modules) and scans the generated byte
+code for IMPORT instructions. It may still be confused -- it will not
+know about calls to the __import__ built-in function, or about import
+statements constructed on the fly and executed using the 'exec'
+statement, and it will consider import statements even when they are
+unreachable (e.g. "if 0: import foobar").
+
+This new version of Freeze also knows about Python's new package
+import mechanism, and uses exactly the same rules to find imported
+modules and packages. One exception: if you write 'from package
+import *', Python will look into the __all__ variable of the package
+to determine which modules are to be imported, while Freeze will do a
+directory listing.
+
+One tricky issue: Freeze assumes that the Python interpreter and
+environment you're using to run Freeze is the same one that would be
+used to run your program, which should also be the same whose sources
+and installed files you will learn about in the next section. In
+particular, your PYTHONPATH setting should be the same as for running
+your program locally. (Tip: if the program doesn't run when you type
+"python hello.py" there's little chance of getting the frozen version
+to run.)
+
+
+How do I use Freeze?
+--------------------
+
+Normally, you should be able to use it as follows:
+
+ python freeze.py hello.py
+
+where hello.py is your program and freeze.py is the main file of
+Freeze (in actuality, you'll probably specify an absolute pathname
+such as /usr/joe/python/Tools/freeze/freeze.py).
+
+
+What do I do next?
+------------------
+
+Freeze creates a number of files: frozen.c, config.c and Makefile,
+plus one file for each Python module that gets included named
+M_<module>.c. To produce the frozen version of your program, you can
+simply type "make". This should produce a binary file. If the
+filename argument to Freeze was "hello.py", the binary will be called
+"hello".
+
+Note: you can use the -o option to freeze to specify an alternative
+directory where these files are created. This makes it easier to
+clean up after you've shipped the frozen binary. You should invoke
+"make" in the given directory.
+
+
+Freezing Tkinter programs
+-------------------------
+
+Unfortunately, it is currently not possible to freeze programs that
+use Tkinter without a Tcl/Tk installation. The best way to ship a
+frozen Tkinter program is to decide in advance where you are going
+to place the Tcl and Tk library files in the distributed setup, and
+then declare these directories in your frozen Python program using
+the TCL_LIBRARY, TK_LIBRARY and TIX_LIBRARY environment variables.
+
+For example, assume you will ship your frozen program in the directory
+<root>/bin/windows-x86 and will place your Tcl library files
+in <root>/lib/tcl8.2 and your Tk library files in <root>/lib/tk8.2. Then
+placing the following lines in your frozen Python script before importing
+Tkinter or Tix would set the environment correctly for Tcl/Tk/Tix:
+
+import os
+import os.path
+RootDir = os.path.dirname(os.path.dirname(os.getcwd()))
+
+import sys
+if sys.platform == "win32":
+ sys.path = ['', '..\\..\\lib\\python-2.0']
+ os.environ['TCL_LIBRARY'] = RootDir + '\\lib\\tcl8.2'
+ os.environ['TK_LIBRARY'] = RootDir + '\\lib\\tk8.2'
+ os.environ['TIX_LIBRARY'] = RootDir + '\\lib\\tix8.1'
+elif sys.platform == "linux2":
+ sys.path = ['', '../../lib/python-2.0']
+ os.environ['TCL_LIBRARY'] = RootDir + '/lib/tcl8.2'
+ os.environ['TK_LIBRARY'] = RootDir + '/lib/tk8.2'
+ os.environ['TIX_LIBRARY'] = RootDir + '/lib/tix8.1'
+elif sys.platform == "solaris":
+ sys.path = ['', '../../lib/python-2.0']
+ os.environ['TCL_LIBRARY'] = RootDir + '/lib/tcl8.2'
+ os.environ['TK_LIBRARY'] = RootDir + '/lib/tk8.2'
+ os.environ['TIX_LIBRARY'] = RootDir + '/lib/tix8.1'
+
+This also adds <root>/lib/python-2.0 to your Python path
+for any Python files such as _tkinter.pyd you may need.
+
+Note that the dynamic libraries (such as tcl82.dll tk82.dll python20.dll
+under Windows, or libtcl8.2.so and libtcl8.2.so under Unix) are required
+at program load time, and are searched by the operating system loader
+before Python can be started. Under Windows, the environment
+variable PATH is consulted, and under Unix, it may be the
+environment variable LD_LIBRARY_PATH and/or the system
+shared library cache (ld.so). An additional preferred directory for
+finding the dynamic libraries is built into the .dll or .so files at
+compile time - see the LIB_RUNTIME_DIR variable in the Tcl makefile.
+The OS must find the dynamic libraries or your frozen program won't start.
+Usually I make sure that the .so or .dll files are in the same directory
+as the executable, but this may not be foolproof.
+
+A workaround to installing your Tcl library files with your frozen
+executable would be possible, in which the Tcl/Tk library files are
+incorporated in a frozen Python module as string literals and written
+to a temporary location when the program runs; this is currently left
+as an exercise for the reader. An easier approach is to freeze the
+Tcl/Tk/Tix code into the dynamic libraries using the Tcl ET code,
+or the Tix Stand-Alone-Module code. Of course, you can also simply
+require that Tcl/Tk is required on the target installation, but be
+careful that the version corresponds.
+
+There are some caveats using frozen Tkinter applications:
+ Under Windows if you use the -s windows option, writing
+to stdout or stderr is an error.
+ The Tcl [info nameofexecutable] will be set to where the
+program was frozen, not where it is run from.
+ The global variables argc and argv do not exist.
+
+
+A warning about shared library modules
+--------------------------------------
+
+When your Python installation uses shared library modules such as
+_tkinter.pyd, these will not be incorporated in the frozen program.
+ Again, the frozen program will work when you test it, but it won't
+ work when you ship it to a site without a Python installation.
+
+Freeze prints a warning when this is the case at the end of the
+freezing process:
+
+ Warning: unknown modules remain: ...
+
+When this occurs, the best thing to do is usually to rebuild Python
+using static linking only. Or use the approach described in the previous
+section to declare a library path using sys.path, and place the modules
+such as _tkinter.pyd there.
+
+
+Troubleshooting
+---------------
+
+If you have trouble using Freeze for a large program, it's probably
+best to start playing with a really simple program first (like the file
+hello.py). If you can't get that to work there's something
+fundamentally wrong -- perhaps you haven't installed Python. To do a
+proper install, you should do "make install" in the Python root
+directory.
+
+
+Usage under Windows 95 or NT
+----------------------------
+
+Under Windows 95 or NT, you *must* use the -p option and point it to
+the top of the Python source tree.
+
+WARNING: the resulting executable is not self-contained; it requires
+the Python DLL, currently PYTHON20.DLL (it does not require the
+standard library of .py files though). It may also require one or
+more extension modules loaded from .DLL or .PYD files; the module
+names are printed in the warning message about remaining unknown
+modules.
+
+The driver script generates a Makefile that works with the Microsoft
+command line C compiler (CL). To compile, run "nmake"; this will
+build a target "hello.exe" if the source was "hello.py". Only the
+files frozenmain.c and frozen.c are used; no config.c is generated or
+used, since the standard DLL is used.
+
+In order for this to work, you must have built Python using the VC++
+(Developer Studio) 5.0 compiler. The provided project builds
+python20.lib in the subdirectory pcbuild\Release of thje Python source
+tree, and this is where the generated Makefile expects it to be. If
+this is not the case, you can edit the Makefile or (probably better)
+winmakemakefile.py (e.g., if you are using the 4.2 compiler, the
+python20.lib file is generated in the subdirectory vc40 of the Python
+source tree).
+
+It is possible to create frozen programs that don't have a console
+window, by specifying the option '-s windows'. See the Usage below.
+
+Usage
+-----
+
+Here is a list of all of the options (taken from freeze.__doc__):
+
+usage: freeze [options...] script [module]...
+
+Options:
+-p prefix: This is the prefix used when you ran ``make install''
+ in the Python build directory.
+ (If you never ran this, freeze won't work.)
+ The default is whatever sys.prefix evaluates to.
+ It can also be the top directory of the Python source
+ tree; then -P must point to the build tree.
+
+-P exec_prefix: Like -p but this is the 'exec_prefix', used to
+ install objects etc. The default is whatever sys.exec_prefix
+ evaluates to, or the -p argument if given.
+ If -p points to the Python source tree, -P must point
+ to the build tree, if different.
+
+-e extension: A directory containing additional .o files that
+ may be used to resolve modules. This directory
+ should also have a Setup file describing the .o files.
+ On Windows, the name of a .INI file describing one
+ or more extensions is passed.
+ More than one -e option may be given.
+
+-o dir: Directory where the output files are created; default '.'.
+
+-m: Additional arguments are module names instead of filenames.
+
+-a package=dir: Additional directories to be added to the package's
+ __path__. Used to simulate directories added by the
+ package at runtime (eg, by OpenGL and win32com).
+ More than one -a option may be given for each package.
+
+-l file: Pass the file to the linker (windows only)
+
+-d: Debugging mode for the module finder.
+
+-q: Make the module finder totally quiet.
+
+-h: Print this help message.
+
+-x module Exclude the specified module.
+
+-i filename: Include a file with additional command line options. Used
+ to prevent command lines growing beyond the capabilities of
+ the shell/OS. All arguments specified in filename
+ are read and the -i option replaced with the parsed
+ params (note - quoting args in this file is NOT supported)
+
+-s subsystem: Specify the subsystem (For Windows only.);
+ 'console' (default), 'windows', 'service' or 'com_dll'
+
+-w: Toggle Windows (NT or 95) behavior.
+ (For debugging only -- on a win32 platform, win32 behavior
+ is automatic.)
+
+Arguments:
+
+script: The Python script to be executed by the resulting binary.
+
+module ...: Additional Python modules (referenced by pathname)
+ that will be included in the resulting binary. These
+ may be .py or .pyc files. If -m is specified, these are
+ module names that are search in the path instead.
+
+
+
+--Guido van Rossum (home page: http://www.python.org/~guido/)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/bkfile.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/bkfile.py
new file mode 100644
index 0000000000..ae58408ee0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/bkfile.py
@@ -0,0 +1,47 @@
+_orig_open = open
+
+class _BkFile:
+ def __init__(self, file, mode, bufsize):
+ import os
+ self.__filename = file
+ self.__backup = file + '~'
+ try:
+ os.unlink(self.__backup)
+ except os.error:
+ pass
+ try:
+ os.rename(file, self.__backup)
+ except os.error:
+ self.__backup = None
+ self.__file = _orig_open(file, mode, bufsize)
+ self.closed = self.__file.closed
+ self.fileno = self.__file.fileno
+ self.flush = self.__file.flush
+ self.isatty = self.__file.isatty
+ self.mode = self.__file.mode
+ self.name = self.__file.name
+ self.read = self.__file.read
+ self.readinto = self.__file.readinto
+ self.readline = self.__file.readline
+ self.readlines = self.__file.readlines
+ self.seek = self.__file.seek
+ self.softspace = self.__file.softspace
+ self.tell = self.__file.tell
+ self.truncate = self.__file.truncate
+ self.write = self.__file.write
+ self.writelines = self.__file.writelines
+
+ def close(self):
+ self.__file.close()
+ if self.__backup is None:
+ return
+ import filecmp
+ if filecmp.cmp(self.__backup, self.__filename, shallow = 0):
+ import os
+ os.unlink(self.__filename)
+ os.rename(self.__backup, self.__filename)
+
+def open(file, mode = 'r', bufsize = -1):
+ if 'w' not in mode:
+ return _orig_open(file, mode, bufsize)
+ return _BkFile(file, mode, bufsize)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions.py
new file mode 100644
index 0000000000..20b73b9325
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions.py
@@ -0,0 +1,90 @@
+# Check for a module in a set of extension directories.
+# An extension directory should contain a Setup file
+# and one or more .o files or a lib.a file.
+
+import os
+import parsesetup
+
+def checkextensions(unknown, extensions):
+ files = []
+ modules = []
+ edict = {}
+ for e in extensions:
+ setup = os.path.join(e, 'Setup')
+ liba = os.path.join(e, 'lib.a')
+ if not os.path.isfile(liba):
+ liba = None
+ edict[e] = parsesetup.getsetupinfo(setup), liba
+ for mod in unknown:
+ for e in extensions:
+ (mods, vars), liba = edict[e]
+ if not mods.has_key(mod):
+ continue
+ modules.append(mod)
+ if liba:
+ # If we find a lib.a, use it, ignore the
+ # .o files, and use *all* libraries for
+ # *all* modules in the Setup file
+ if liba in files:
+ break
+ files.append(liba)
+ for m in mods.keys():
+ files = files + select(e, mods, vars,
+ m, 1)
+ break
+ files = files + select(e, mods, vars, mod, 0)
+ break
+ return files, modules
+
+def select(e, mods, vars, mod, skipofiles):
+ files = []
+ for w in mods[mod]:
+ w = treatword(w)
+ if not w:
+ continue
+ w = expandvars(w, vars)
+ for w in w.split():
+ if skipofiles and w[-2:] == '.o':
+ continue
+ # Assume $var expands to absolute pathname
+ if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'):
+ w = os.path.join(e, w)
+ if w[:2] in ('-L', '-R') and w[2:3] != '$':
+ w = w[:2] + os.path.join(e, w[2:])
+ files.append(w)
+ return files
+
+cc_flags = ['-I', '-D', '-U']
+cc_exts = ['.c', '.C', '.cc', '.c++']
+
+def treatword(w):
+ if w[:2] in cc_flags:
+ return None
+ if w[:1] == '-':
+ return w # Assume loader flag
+ head, tail = os.path.split(w)
+ base, ext = os.path.splitext(tail)
+ if ext in cc_exts:
+ tail = base + '.o'
+ w = os.path.join(head, tail)
+ return w
+
+def expandvars(str, vars):
+ i = 0
+ while i < len(str):
+ i = k = str.find('$', i)
+ if i < 0:
+ break
+ i = i+1
+ var = str[i:i+1]
+ i = i+1
+ if var == '(':
+ j = str.find(')', i)
+ if j < 0:
+ break
+ var = str[i:j]
+ i = j+1
+ if vars.has_key(var):
+ str = str[:k] + vars[var] + str[i:]
+ i = k
+ return str
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions_win32.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions_win32.py
new file mode 100644
index 0000000000..0fbe30143c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/checkextensions_win32.py
@@ -0,0 +1,188 @@
+"""Extension management for Windows.
+
+Under Windows it is unlikely the .obj files are of use, as special compiler options
+are needed (primarily to toggle the behavior of "public" symbols.
+
+I dont consider it worth parsing the MSVC makefiles for compiler options. Even if
+we get it just right, a specific freeze application may have specific compiler
+options anyway (eg, to enable or disable specific functionality)
+
+So my basic strategy is:
+
+* Have some Windows INI files which "describe" one or more extension modules.
+ (Freeze comes with a default one for all known modules - but you can specify
+ your own).
+* This description can include:
+ - The MSVC .dsp file for the extension. The .c source file names
+ are extraced from there.
+ - Specific compiler/linker options
+ - Flag to indicate if Unicode compilation is expected.
+
+At the moment the name and location of this INI file is hardcoded,
+but an obvious enhancement would be to provide command line options.
+"""
+
+import os, sys
+try:
+ import win32api
+except ImportError:
+ win32api = None # User has already been warned
+
+class CExtension:
+ """An abstraction of an extension implemented in C/C++
+ """
+ def __init__(self, name, sourceFiles):
+ self.name = name
+ # A list of strings defining additional compiler options.
+ self.sourceFiles = sourceFiles
+ # A list of special compiler options to be applied to
+ # all source modules in this extension.
+ self.compilerOptions = []
+ # A list of .lib files the final .EXE will need.
+ self.linkerLibs = []
+
+ def GetSourceFiles(self):
+ return self.sourceFiles
+
+ def AddCompilerOption(self, option):
+ self.compilerOptions.append(option)
+ def GetCompilerOptions(self):
+ return self.compilerOptions
+
+ def AddLinkerLib(self, lib):
+ self.linkerLibs.append(lib)
+ def GetLinkerLibs(self):
+ return self.linkerLibs
+
+def checkextensions(unknown, extra_inis, prefix):
+ # Create a table of frozen extensions
+
+ defaultMapName = os.path.join( os.path.split(sys.argv[0])[0], "extensions_win32.ini")
+ if not os.path.isfile(defaultMapName):
+ sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found\n" % defaultMapName)
+ else:
+ # must go on end, so other inis can override.
+ extra_inis.append(defaultMapName)
+
+ ret = []
+ for mod in unknown:
+ for ini in extra_inis:
+# print "Looking for", mod, "in", win32api.GetFullPathName(ini),"...",
+ defn = get_extension_defn( mod, ini, prefix )
+ if defn is not None:
+# print "Yay - found it!"
+ ret.append( defn )
+ break
+# print "Nope!"
+ else: # For not broken!
+ sys.stderr.write("No definition of module %s in any specified map file.\n" % (mod))
+
+ return ret
+
+def get_extension_defn(moduleName, mapFileName, prefix):
+ if win32api is None: return None
+ os.environ['PYTHONPREFIX'] = prefix
+ dsp = win32api.GetProfileVal(moduleName, "dsp", "", mapFileName)
+ if dsp=="":
+ return None
+
+ # We allow environment variables in the file name
+ dsp = win32api.ExpandEnvironmentStrings(dsp)
+ # If the path to the .DSP file is not absolute, assume it is relative
+ # to the description file.
+ if not os.path.isabs(dsp):
+ dsp = os.path.join( os.path.split(mapFileName)[0], dsp)
+ # Parse it to extract the source files.
+ sourceFiles = parse_dsp(dsp)
+ if sourceFiles is None:
+ return None
+
+ module = CExtension(moduleName, sourceFiles)
+ # Put the path to the DSP into the environment so entries can reference it.
+ os.environ['dsp_path'] = os.path.split(dsp)[0]
+ os.environ['ini_path'] = os.path.split(mapFileName)[0]
+
+ cl_options = win32api.GetProfileVal(moduleName, "cl", "", mapFileName)
+ if cl_options:
+ module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options))
+
+ exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName)
+ exclude = exclude.split()
+
+ if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName):
+ module.AddCompilerOption('/D UNICODE /D _UNICODE')
+
+ libs = win32api.GetProfileVal(moduleName, "libs", "", mapFileName).split()
+ for lib in libs:
+ module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib))
+
+ for exc in exclude:
+ if exc in module.sourceFiles:
+ modules.sourceFiles.remove(exc)
+
+ return module
+
+# Given an MSVC DSP file, locate C source files it uses
+# returns a list of source files.
+def parse_dsp(dsp):
+# print "Processing", dsp
+ # For now, only support
+ ret = []
+ dsp_path, dsp_name = os.path.split(dsp)
+ try:
+ lines = open(dsp, "r").readlines()
+ except IOError, msg:
+ sys.stderr.write("%s: %s\n" % (dsp, msg))
+ return None
+ for line in lines:
+ fields = line.strip().split("=", 2)
+ if fields[0]=="SOURCE":
+ if os.path.splitext(fields[1])[1].lower() in ['.cpp', '.c']:
+ ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) )
+ return ret
+
+def write_extension_table(fname, modules):
+ fp = open(fname, "w")
+ try:
+ fp.write (ext_src_header)
+ # Write fn protos
+ for module in modules:
+ # bit of a hack for .pyd's as part of packages.
+ name = module.name.split('.')[-1]
+ fp.write('extern void init%s(void);\n' % (name) )
+ # Write the table
+ fp.write (ext_tab_header)
+ for module in modules:
+ name = module.name.split('.')[-1]
+ fp.write('\t{"%s", init%s},\n' % (name, name) )
+
+ fp.write (ext_tab_footer)
+ fp.write(ext_src_footer)
+ finally:
+ fp.close()
+
+
+ext_src_header = """\
+#include "Python.h"
+"""
+
+ext_tab_header = """\
+
+static struct _inittab extensions[] = {
+"""
+
+ext_tab_footer = """\
+ /* Sentinel */
+ {0, 0}
+};
+"""
+
+ext_src_footer = """\
+extern DL_IMPORT(int) PyImport_ExtendInittab(struct _inittab *newtab);
+
+int PyInitFrozenExtensions()
+{
+ return PyImport_ExtendInittab(extensions);
+}
+
+"""
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/extensions_win32.ini b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/extensions_win32.ini
new file mode 100644
index 0000000000..12721ff522
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/extensions_win32.ini
@@ -0,0 +1,171 @@
+; This is a list of modules generally build as .pyd files.
+;
+; Each section contains enough information about a module for
+; freeze to include the module as a static, built-in module
+; in a frozen .EXE/.DLL.
+
+; This is all setup for all the win32 extension modules
+; released by Mark Hammond.
+; You must ensure that the environment variable PYTHONEX is set
+; to point to the root win32 extensions directory
+
+; PYTHONPREFIX must point to the Python build root directory
+; (the *parent* of PCbuild); normally the freeze script takes
+; care of this.
+
+
+
+
+
+;--------------------------------------------------------------
+;
+; Standard Python extension modules
+;
+
+; Here are some of the standard Python extensions modules.
+; If you need others, add them here
+
+[_socket]
+dsp=%PYTHONPREFIX%\PCBuild\_socket.dsp
+
+[_sre]
+dsp=%PYTHONPREFIX%\PCBuild\_sre.dsp
+
+[unicodedata]
+dsp=%PYTHONPREFIX%\PCBuild\unicodedata.dsp
+
+[mmap]
+dsp=%PYTHONPREFIX%\PCBuild\mmap.dsp
+
+[winsound]
+dsp=%PYTHONPREFIX%\PCBuild\winsound.dsp
+libs=winmm.lib
+
+[parser]
+dsp=%PYTHONPREFIX%\PCBuild\parser.dsp
+
+[select]
+dsp=%PYTHONPREFIX%\PCBuild\select.dsp
+
+[zlib]
+dsp=%PYTHONPREFIX%\PCBuild\zlib.dsp
+cl=/I %PYTHONPREFIX%\..\zlib-1.1.4 /D _WINDOWS /D WIN32
+libs=%PYTHONPREFIX%\..\zlib-1.1.4\zlib.lib /nodefaultlib:libc
+
+[_winreg]
+dsp=%PYTHONPREFIX%\PCBuild\winreg.dsp
+libs=advapi32.lib
+
+
+;--------------------------------------------------------------
+;
+; Win32 Projects.
+;
+[perfmon]
+dsp=%PYTHONEX%\win32\perfmon.dsp
+cl=/I %PYTHONEX%\win32\src
+Unicode=1
+
+[pywintypes]
+dsp=%PYTHONEX%\win32\pywintypes.dsp
+cl=/I %PYTHONEX%\win32\src
+libs=ole32.lib oleaut32.lib
+
+[win32api]
+dsp=%PYTHONEX%\win32\win32api.dsp
+cl=/I %PYTHONEX%\win32\src
+libs=kernel32.lib user32.lib shell32.lib advapi32.lib
+
+[win32service]
+dsp=%PYTHONEX%\win32\win32service.dsp
+cl=/I %PYTHONEX%\win32\src
+Unicode=1
+libs=advapi32.lib
+
+[win32evtlog]
+dsp=%PYTHONEX%\win32\win32evtlog.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32process]
+dsp=%PYTHONEX%\win32\win32process.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32event]
+dsp=%PYTHONEX%\win32\win32event.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32file]
+dsp=%PYTHONEX%\win32\win32file.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32net]
+dsp=%PYTHONEX%\win32\win32net.dsp
+cl=/I %PYTHONEX%\win32\src
+libs=netapi32.lib
+
+[win32pdh]
+dsp=%PYTHONEX%\win32\win32pdh.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32pipe]
+dsp=%PYTHONEX%\win32\win32pipe.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32security]
+dsp=%PYTHONEX%\win32\win32security.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32service]
+dsp=%PYTHONEX%\win32\win32service.dsp
+cl=/I %PYTHONEX%\win32\src
+
+[win32trace]
+dsp=%PYTHONEX%\win32\win32trace.dsp
+cl=/I %PYTHONEX%\win32\src
+
+;--------------------------------------------------------------
+;
+; COM Projects.
+;
+
+[pythoncom]
+dsp=%PYTHONEX%\com\win32com.dsp
+cl=/I %PYTHONEX%\com\win32com\src\include /I %PYTHONEX%\win32\src
+libs=uuid.lib
+
+[win32com.axcontrol.axcontrol]
+dsp=%PYTHONEX%\com\axcontrol.dsp
+cl=/I %PYTHONEX%\win32\src /I %PYTHONEX%\com\win32com\src\include
+
+[win32com.axscript.axscript]
+dsp=%PYTHONEX%\com\Active Scripting.dsp
+cl=/I %PYTHONEX%\win32\src /I %PYTHONEX%\com\win32com\src\include
+
+[win32com.axdebug.axdebug]
+dsp=%PYTHONEX%\com\Active Debugging.dsp
+cl=/I %PYTHONEX%\win32\src /I %PYTHONEX%\com\win32com\src\include
+
+[win32com.mapi.mapi]
+dsp=%PYTHONEX%\com\mapi.dsp
+cl=/I %PYTHONEX%\win32\src /I %PYTHONEX%\com\win32com\src\include
+libs=MBLOGON.lib ADDRLKUP.LIB mapi32.lib version.lib
+
+[win32com.mapi.exchange]
+dsp=%PYTHONEX%\com\exchange.dsp
+cl=/I %PYTHONEX%\win32\src /I %PYTHONEX%\com\win32com\src\include
+libs=MBLOGON.lib ADDRLKUP.LIB exchinst.lib EDKCFG.LIB EDKUTILS.LIB EDKMAPI.LIB mapi32.lib version.lib
+
+[win32com.mapi.exchdapi]
+dsp=%PYTHONEX%\com\exchdapi.dsp
+cl=/I %PYTHONEX%\win32\src /I %PYTHONEX%\com\win32com\src\include
+libs=DAPI.LIB
+
+[servicemanager]
+dsp=%PYTHONEX%\win32\PythonService EXE.dsp
+Unicode = 1
+
+; Pythonwin
+[win32ui]
+dsp=%PYTHONEX%\Pythonwin\win32ui.dsp
+cl=/D _AFXDLL /D FREEZE_WIN32UI /GX /I %PYTHONEX%\win32\src
+libs=mfc42.lib
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/freeze.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/freeze.py
new file mode 100644
index 0000000000..58cc6be040
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/freeze.py
@@ -0,0 +1,497 @@
+#! /usr/bin/env python
+
+"""Freeze a Python script into a binary.
+
+usage: freeze [options...] script [module]...
+
+Options:
+-p prefix: This is the prefix used when you ran ``make install''
+ in the Python build directory.
+ (If you never ran this, freeze won't work.)
+ The default is whatever sys.prefix evaluates to.
+ It can also be the top directory of the Python source
+ tree; then -P must point to the build tree.
+
+-P exec_prefix: Like -p but this is the 'exec_prefix', used to
+ install objects etc. The default is whatever sys.exec_prefix
+ evaluates to, or the -p argument if given.
+ If -p points to the Python source tree, -P must point
+ to the build tree, if different.
+
+-e extension: A directory containing additional .o files that
+ may be used to resolve modules. This directory
+ should also have a Setup file describing the .o files.
+ On Windows, the name of a .INI file describing one
+ or more extensions is passed.
+ More than one -e option may be given.
+
+-o dir: Directory where the output files are created; default '.'.
+
+-m: Additional arguments are module names instead of filenames.
+
+-a package=dir: Additional directories to be added to the package's
+ __path__. Used to simulate directories added by the
+ package at runtime (eg, by OpenGL and win32com).
+ More than one -a option may be given for each package.
+
+-l file: Pass the file to the linker (windows only)
+
+-d: Debugging mode for the module finder.
+
+-q: Make the module finder totally quiet.
+
+-h: Print this help message.
+
+-x module Exclude the specified module. It will still be imported
+ by the frozen binary if it exists on the host system.
+
+-X module Like -x, except the module can never be imported by
+ the frozen binary.
+
+-E: Freeze will fail if any modules can't be found (that
+ were not excluded using -x or -X).
+
+-i filename: Include a file with additional command line options. Used
+ to prevent command lines growing beyond the capabilities of
+ the shell/OS. All arguments specified in filename
+ are read and the -i option replaced with the parsed
+ params (note - quoting args in this file is NOT supported)
+
+-s subsystem: Specify the subsystem (For Windows only.);
+ 'console' (default), 'windows', 'service' or 'com_dll'
+
+-w: Toggle Windows (NT or 95) behavior.
+ (For debugging only -- on a win32 platform, win32 behavior
+ is automatic.)
+
+-r prefix=f: Replace path prefix.
+ Replace prefix with f in the source path references
+ contained in the resulting binary.
+
+Arguments:
+
+script: The Python script to be executed by the resulting binary.
+
+module ...: Additional Python modules (referenced by pathname)
+ that will be included in the resulting binary. These
+ may be .py or .pyc files. If -m is specified, these are
+ module names that are search in the path instead.
+
+NOTES:
+
+In order to use freeze successfully, you must have built Python and
+installed it ("make install").
+
+The script should not use modules provided only as shared libraries;
+if it does, the resulting binary is not self-contained.
+"""
+
+
+# Import standard modules
+
+import modulefinder
+import getopt
+import os
+import sys
+
+
+# Import the freeze-private modules
+
+import checkextensions
+import makeconfig
+import makefreeze
+import makemakefile
+import parsesetup
+import bkfile
+
+
+# Main program
+
+def main():
+ # overridable context
+ prefix = None # settable with -p option
+ exec_prefix = None # settable with -P option
+ extensions = []
+ exclude = [] # settable with -x option
+ addn_link = [] # settable with -l, but only honored under Windows.
+ path = sys.path[:]
+ modargs = 0
+ debug = 1
+ odir = ''
+ win = sys.platform[:3] == 'win'
+ replace_paths = [] # settable with -r option
+ error_if_any_missing = 0
+
+ # default the exclude list for each platform
+ if win: exclude = exclude + [
+ 'dos', 'dospath', 'mac', 'macpath', 'macfs', 'MACFS', 'posix',
+ 'os2', 'ce', 'riscos', 'riscosenviron', 'riscospath',
+ ]
+
+ fail_import = exclude[:]
+
+ # output files
+ frozen_c = 'frozen.c'
+ config_c = 'config.c'
+ target = 'a.out' # normally derived from script name
+ makefile = 'Makefile'
+ subsystem = 'console'
+
+ # parse command line by first replacing any "-i" options with the
+ # file contents.
+ pos = 1
+ while pos < len(sys.argv)-1:
+ # last option can not be "-i", so this ensures "pos+1" is in range!
+ if sys.argv[pos] == '-i':
+ try:
+ options = open(sys.argv[pos+1]).read().split()
+ except IOError, why:
+ usage("File name '%s' specified with the -i option "
+ "can not be read - %s" % (sys.argv[pos+1], why) )
+ # Replace the '-i' and the filename with the read params.
+ sys.argv[pos:pos+2] = options
+ pos = pos + len(options) - 1 # Skip the name and the included args.
+ pos = pos + 1
+
+ # Now parse the command line with the extras inserted.
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'r:a:dEe:hmo:p:P:qs:wX:x:l:')
+ except getopt.error, msg:
+ usage('getopt error: ' + str(msg))
+
+ # proces option arguments
+ for o, a in opts:
+ if o == '-h':
+ print __doc__
+ return
+ if o == '-d':
+ debug = debug + 1
+ if o == '-e':
+ extensions.append(a)
+ if o == '-m':
+ modargs = 1
+ if o == '-o':
+ odir = a
+ if o == '-p':
+ prefix = a
+ if o == '-P':
+ exec_prefix = a
+ if o == '-q':
+ debug = 0
+ if o == '-w':
+ win = not win
+ if o == '-s':
+ if not win:
+ usage("-s subsystem option only on Windows")
+ subsystem = a
+ if o == '-x':
+ exclude.append(a)
+ if o == '-X':
+ exclude.append(a)
+ fail_import.append(a)
+ if o == '-E':
+ error_if_any_missing = 1
+ if o == '-l':
+ addn_link.append(a)
+ if o == '-a':
+ apply(modulefinder.AddPackagePath, tuple(a.split("=", 2)))
+ if o == '-r':
+ f,r = a.split("=", 2)
+ replace_paths.append( (f,r) )
+
+ # modules that are imported by the Python runtime
+ implicits = []
+ for module in ('site', 'warnings',):
+ if module not in exclude:
+ implicits.append(module)
+
+ # default prefix and exec_prefix
+ if not exec_prefix:
+ if prefix:
+ exec_prefix = prefix
+ else:
+ exec_prefix = sys.exec_prefix
+ if not prefix:
+ prefix = sys.prefix
+
+ # determine whether -p points to the Python source tree
+ ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c'))
+
+ # locations derived from options
+ version = sys.version[:3]
+ if win:
+ extensions_c = 'frozen_extensions.c'
+ if ishome:
+ print "(Using Python source directory)"
+ binlib = exec_prefix
+ incldir = os.path.join(prefix, 'Include')
+ config_h_dir = exec_prefix
+ config_c_in = os.path.join(prefix, 'Modules', 'config.c.in')
+ frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c')
+ makefile_in = os.path.join(exec_prefix, 'Makefile')
+ if win:
+ frozendllmain_c = os.path.join(exec_prefix, 'Pc\\frozen_dllmain.c')
+ else:
+ binlib = os.path.join(exec_prefix,
+ 'lib', 'python%s' % version, 'config')
+ incldir = os.path.join(prefix, 'include', 'python%s' % version)
+ config_h_dir = os.path.join(exec_prefix, 'include',
+ 'python%s' % version)
+ config_c_in = os.path.join(binlib, 'config.c.in')
+ frozenmain_c = os.path.join(binlib, 'frozenmain.c')
+ makefile_in = os.path.join(binlib, 'Makefile')
+ frozendllmain_c = os.path.join(binlib, 'frozen_dllmain.c')
+ supp_sources = []
+ defines = []
+ includes = ['-I' + incldir, '-I' + config_h_dir]
+
+ # sanity check of directories and files
+ check_dirs = [prefix, exec_prefix, binlib, incldir]
+ if not win:
+ # These are not directories on Windows.
+ check_dirs = check_dirs + extensions
+ for dir in check_dirs:
+ if not os.path.exists(dir):
+ usage('needed directory %s not found' % dir)
+ if not os.path.isdir(dir):
+ usage('%s: not a directory' % dir)
+ if win:
+ files = supp_sources + extensions # extensions are files on Windows.
+ else:
+ files = [config_c_in, makefile_in] + supp_sources
+ for file in supp_sources:
+ if not os.path.exists(file):
+ usage('needed file %s not found' % file)
+ if not os.path.isfile(file):
+ usage('%s: not a plain file' % file)
+ if not win:
+ for dir in extensions:
+ setup = os.path.join(dir, 'Setup')
+ if not os.path.exists(setup):
+ usage('needed file %s not found' % setup)
+ if not os.path.isfile(setup):
+ usage('%s: not a plain file' % setup)
+
+ # check that enough arguments are passed
+ if not args:
+ usage('at least one filename argument required')
+
+ # check that file arguments exist
+ for arg in args:
+ if arg == '-m':
+ break
+ # if user specified -m on the command line before _any_
+ # file names, then nothing should be checked (as the
+ # very first file should be a module name)
+ if modargs:
+ break
+ if not os.path.exists(arg):
+ usage('argument %s not found' % arg)
+ if not os.path.isfile(arg):
+ usage('%s: not a plain file' % arg)
+
+ # process non-option arguments
+ scriptfile = args[0]
+ modules = args[1:]
+
+ # derive target name from script name
+ base = os.path.basename(scriptfile)
+ base, ext = os.path.splitext(base)
+ if base:
+ if base != scriptfile:
+ target = base
+ else:
+ target = base + '.bin'
+
+ # handle -o option
+ base_frozen_c = frozen_c
+ base_config_c = config_c
+ base_target = target
+ if odir and not os.path.isdir(odir):
+ try:
+ os.mkdir(odir)
+ print "Created output directory", odir
+ except os.error, msg:
+ usage('%s: mkdir failed (%s)' % (odir, str(msg)))
+ base = ''
+ if odir:
+ base = os.path.join(odir, '')
+ frozen_c = os.path.join(odir, frozen_c)
+ config_c = os.path.join(odir, config_c)
+ target = os.path.join(odir, target)
+ makefile = os.path.join(odir, makefile)
+ if win: extensions_c = os.path.join(odir, extensions_c)
+
+ # Handle special entry point requirements
+ # (on Windows, some frozen programs do not use __main__, but
+ # import the module directly. Eg, DLLs, Services, etc
+ custom_entry_point = None # Currently only used on Windows
+ python_entry_is_main = 1 # Is the entry point called __main__?
+ # handle -s option on Windows
+ if win:
+ import winmakemakefile
+ try:
+ custom_entry_point, python_entry_is_main = \
+ winmakemakefile.get_custom_entry_point(subsystem)
+ except ValueError, why:
+ usage(why)
+
+
+ # Actual work starts here...
+
+ # collect all modules of the program
+ dir = os.path.dirname(scriptfile)
+ path[0] = dir
+ mf = modulefinder.ModuleFinder(path, debug, exclude, replace_paths)
+
+ if win and subsystem=='service':
+ # If a Windows service, then add the "built-in" module.
+ mod = mf.add_module("servicemanager")
+ mod.__file__="dummy.pyd" # really built-in to the resulting EXE
+
+ for mod in implicits:
+ mf.import_hook(mod)
+ for mod in modules:
+ if mod == '-m':
+ modargs = 1
+ continue
+ if modargs:
+ if mod[-2:] == '.*':
+ mf.import_hook(mod[:-2], None, ["*"])
+ else:
+ mf.import_hook(mod)
+ else:
+ mf.load_file(mod)
+
+ # Add the main script as either __main__, or the actual module name.
+ if python_entry_is_main:
+ mf.run_script(scriptfile)
+ else:
+ mf.load_file(scriptfile)
+
+ if debug > 0:
+ mf.report()
+ print
+ dict = mf.modules
+
+ if error_if_any_missing:
+ missing = mf.any_missing()
+ if missing:
+ sys.exit("There are some missing modules: %r" % missing)
+
+ # generate output for frozen modules
+ files = makefreeze.makefreeze(base, dict, debug, custom_entry_point,
+ fail_import)
+
+ # look for unfrozen modules (builtin and of unknown origin)
+ builtins = []
+ unknown = []
+ mods = dict.keys()
+ mods.sort()
+ for mod in mods:
+ if dict[mod].__code__:
+ continue
+ if not dict[mod].__file__:
+ builtins.append(mod)
+ else:
+ unknown.append(mod)
+
+ # search for unknown modules in extensions directories (not on Windows)
+ addfiles = []
+ frozen_extensions = [] # Windows list of modules.
+ if unknown or (not win and builtins):
+ if not win:
+ addfiles, addmods = \
+ checkextensions.checkextensions(unknown+builtins,
+ extensions)
+ for mod in addmods:
+ if mod in unknown:
+ unknown.remove(mod)
+ builtins.append(mod)
+ else:
+ # Do the windows thang...
+ import checkextensions_win32
+ # Get a list of CExtension instances, each describing a module
+ # (including its source files)
+ frozen_extensions = checkextensions_win32.checkextensions(
+ unknown, extensions, prefix)
+ for mod in frozen_extensions:
+ unknown.remove(mod.name)
+
+ # report unknown modules
+ if unknown:
+ sys.stderr.write('Warning: unknown modules remain: %s\n' %
+ ' '.join(unknown))
+
+ # windows gets different treatment
+ if win:
+ # Taking a shortcut here...
+ import winmakemakefile, checkextensions_win32
+ checkextensions_win32.write_extension_table(extensions_c,
+ frozen_extensions)
+ # Create a module definition for the bootstrap C code.
+ xtras = [frozenmain_c, os.path.basename(frozen_c),
+ frozendllmain_c, os.path.basename(extensions_c)] + files
+ maindefn = checkextensions_win32.CExtension( '__main__', xtras )
+ frozen_extensions.append( maindefn )
+ outfp = open(makefile, 'w')
+ try:
+ winmakemakefile.makemakefile(outfp,
+ locals(),
+ frozen_extensions,
+ os.path.basename(target))
+ finally:
+ outfp.close()
+ return
+
+ # generate config.c and Makefile
+ builtins.sort()
+ infp = open(config_c_in)
+ outfp = bkfile.open(config_c, 'w')
+ try:
+ makeconfig.makeconfig(infp, outfp, builtins)
+ finally:
+ outfp.close()
+ infp.close()
+
+ cflags = ['$(OPT)']
+ cppflags = defines + includes
+ libs = [os.path.join(binlib, 'libpython$(VERSION).a')]
+
+ somevars = {}
+ if os.path.exists(makefile_in):
+ makevars = parsesetup.getmakevars(makefile_in)
+ for key in makevars.keys():
+ somevars[key] = makevars[key]
+
+ somevars['CFLAGS'] = ' '.join(cflags) # override
+ somevars['CPPFLAGS'] = ' '.join(cppflags) # override
+ files = [base_config_c, base_frozen_c] + \
+ files + supp_sources + addfiles + libs + \
+ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)']
+
+ outfp = bkfile.open(makefile, 'w')
+ try:
+ makemakefile.makemakefile(outfp, somevars, files, base_target)
+ finally:
+ outfp.close()
+
+ # Done!
+
+ if odir:
+ print 'Now run "make" in', odir,
+ print 'to build the target:', base_target
+ else:
+ print 'Now run "make" to build the target:', base_target
+
+
+# Print usage message and exit
+
+def usage(msg):
+ sys.stdout = sys.stderr
+ print "Error:", msg
+ print "Use ``%s -h'' for help" % sys.argv[0]
+ sys.exit(2)
+
+
+main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/hello.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/hello.py
new file mode 100644
index 0000000000..d3524d7cd4
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/hello.py
@@ -0,0 +1 @@
+print 'Hello world...'
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makeconfig.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makeconfig.py
new file mode 100644
index 0000000000..1e8f7e2535
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makeconfig.py
@@ -0,0 +1,60 @@
+import re
+import sys
+
+# Write the config.c file
+
+never = ['marshal', '__main__', '__builtin__', 'sys', 'exceptions', '_warnings']
+
+def makeconfig(infp, outfp, modules, with_ifdef=0):
+ m1 = re.compile('-- ADDMODULE MARKER 1 --')
+ m2 = re.compile('-- ADDMODULE MARKER 2 --')
+ while 1:
+ line = infp.readline()
+ if not line: break
+ outfp.write(line)
+ if m1 and m1.search(line):
+ m1 = None
+ for mod in modules:
+ if mod in never:
+ continue
+ if with_ifdef:
+ outfp.write("#ifndef init%s\n"%mod)
+ outfp.write('extern void init%s(void);\n' % mod)
+ if with_ifdef:
+ outfp.write("#endif\n")
+ elif m2 and m2.search(line):
+ m2 = None
+ for mod in modules:
+ if mod in never:
+ continue
+ outfp.write('\t{"%s", init%s},\n' %
+ (mod, mod))
+ if m1:
+ sys.stderr.write('MARKER 1 never found\n')
+ elif m2:
+ sys.stderr.write('MARKER 2 never found\n')
+
+
+# Test program.
+
+def test():
+ if not sys.argv[3:]:
+ print 'usage: python makeconfig.py config.c.in outputfile',
+ print 'modulename ...'
+ sys.exit(2)
+ if sys.argv[1] == '-':
+ infp = sys.stdin
+ else:
+ infp = open(sys.argv[1])
+ if sys.argv[2] == '-':
+ outfp = sys.stdout
+ else:
+ outfp = open(sys.argv[2], 'w')
+ makeconfig(infp, outfp, sys.argv[3:])
+ if outfp != sys.stdout:
+ outfp.close()
+ if infp != sys.stdin:
+ infp.close()
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makefreeze.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makefreeze.py
new file mode 100644
index 0000000000..3cc63179b0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makefreeze.py
@@ -0,0 +1,90 @@
+import marshal
+import bkfile
+
+
+# Write a file containing frozen code for the modules in the dictionary.
+
+header = """
+#include "Python.h"
+
+static struct _frozen _PyImport_FrozenModules[] = {
+"""
+trailer = """\
+ {0, 0, 0} /* sentinel */
+};
+"""
+
+# if __debug__ == 0 (i.e. -O option given), set Py_OptimizeFlag in frozen app.
+default_entry_point = """
+int
+main(int argc, char **argv)
+{
+ extern int Py_FrozenMain(int, char **);
+""" + ((not __debug__ and """
+ Py_OptimizeFlag++;
+""") or "") + """
+ PyImport_FrozenModules = _PyImport_FrozenModules;
+ return Py_FrozenMain(argc, argv);
+}
+
+"""
+
+def makefreeze(base, dict, debug=0, entry_point=None, fail_import=()):
+ if entry_point is None: entry_point = default_entry_point
+ done = []
+ files = []
+ mods = dict.keys()
+ mods.sort()
+ for mod in mods:
+ m = dict[mod]
+ mangled = "__".join(mod.split("."))
+ if m.__code__:
+ file = 'M_' + mangled + '.c'
+ outfp = bkfile.open(base + file, 'w')
+ files.append(file)
+ if debug:
+ print "freezing", mod, "..."
+ str = marshal.dumps(m.__code__)
+ size = len(str)
+ if m.__path__:
+ # Indicate package by negative size
+ size = -size
+ done.append((mod, mangled, size))
+ writecode(outfp, mangled, str)
+ outfp.close()
+ if debug:
+ print "generating table of frozen modules"
+ outfp = bkfile.open(base + 'frozen.c', 'w')
+ for mod, mangled, size in done:
+ outfp.write('extern unsigned char M_%s[];\n' % mangled)
+ outfp.write(header)
+ for mod, mangled, size in done:
+ outfp.write('\t{"%s", M_%s, %d},\n' % (mod, mangled, size))
+ outfp.write('\n')
+ # The following modules have a NULL code pointer, indicating
+ # that the prozen program should not search for them on the host
+ # system. Importing them will *always* raise an ImportError.
+ # The zero value size is never used.
+ for mod in fail_import:
+ outfp.write('\t{"%s", NULL, 0},\n' % (mod,))
+ outfp.write(trailer)
+ outfp.write(entry_point)
+ outfp.close()
+ return files
+
+
+
+# Write a C initializer for a module containing the frozen python code.
+# The array is called M_<mod>.
+
+def writecode(outfp, mod, str):
+ outfp.write('unsigned char M_%s[] = {' % mod)
+ for i in range(0, len(str), 16):
+ outfp.write('\n\t')
+ for c in str[i:i+16]:
+ outfp.write('%d,' % ord(c))
+ outfp.write('\n};\n')
+
+## def writecode(outfp, mod, str):
+## outfp.write('unsigned char M_%s[%d] = "%s";\n' % (mod, len(str),
+## '\\"'.join(map(lambda s: repr(s)[1:-1], str.split('"')))))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makemakefile.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makemakefile.py
new file mode 100644
index 0000000000..0b818904c4
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/makemakefile.py
@@ -0,0 +1,29 @@
+# Write the actual Makefile.
+
+import os
+
+def makemakefile(outfp, makevars, files, target):
+ outfp.write("# Makefile generated by freeze.py script\n\n")
+
+ keys = makevars.keys()
+ keys.sort()
+ for key in keys:
+ outfp.write("%s=%s\n" % (key, makevars[key]))
+ outfp.write("\nall: %s\n\n" % target)
+
+ deps = []
+ for i in range(len(files)):
+ file = files[i]
+ if file[-2:] == '.c':
+ base = os.path.basename(file)
+ dest = base[:-2] + '.o'
+ outfp.write("%s: %s\n" % (dest, file))
+ outfp.write("\t$(CC) $(CFLAGS) $(CPPFLAGS) -c %s\n" % file)
+ files[i] = dest
+ deps.append(dest)
+
+ outfp.write("\n%s: %s\n" % (target, ' '.join(deps)))
+ outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" %
+ (' '.join(files), target))
+
+ outfp.write("\nclean:\n\t-rm -f *.o %s\n" % target)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/parsesetup.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/parsesetup.py
new file mode 100644
index 0000000000..b14a6dac47
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/parsesetup.py
@@ -0,0 +1,112 @@
+# Parse Makefiles and Python Setup(.in) files.
+
+import re
+
+
+# Extract variable definitions from a Makefile.
+# Return a dictionary mapping names to values.
+# May raise IOError.
+
+makevardef = re.compile('^([a-zA-Z0-9_]+)[ \t]*=(.*)')
+
+def getmakevars(filename):
+ variables = {}
+ fp = open(filename)
+ pendingline = ""
+ try:
+ while 1:
+ line = fp.readline()
+ if pendingline:
+ line = pendingline + line
+ pendingline = ""
+ if not line:
+ break
+ if line.endswith('\\\n'):
+ pendingline = line[:-2]
+ matchobj = makevardef.match(line)
+ if not matchobj:
+ continue
+ (name, value) = matchobj.group(1, 2)
+ # Strip trailing comment
+ i = value.find('#')
+ if i >= 0:
+ value = value[:i]
+ value = value.strip()
+ variables[name] = value
+ finally:
+ fp.close()
+ return variables
+
+
+# Parse a Python Setup(.in) file.
+# Return two dictionaries, the first mapping modules to their
+# definitions, the second mapping variable names to their values.
+# May raise IOError.
+
+setupvardef = re.compile('^([a-zA-Z0-9_]+)=(.*)')
+
+def getsetupinfo(filename):
+ modules = {}
+ variables = {}
+ fp = open(filename)
+ pendingline = ""
+ try:
+ while 1:
+ line = fp.readline()
+ if pendingline:
+ line = pendingline + line
+ pendingline = ""
+ if not line:
+ break
+ # Strip comments
+ i = line.find('#')
+ if i >= 0:
+ line = line[:i]
+ if line.endswith('\\\n'):
+ pendingline = line[:-2]
+ continue
+ matchobj = setupvardef.match(line)
+ if matchobj:
+ (name, value) = matchobj.group(1, 2)
+ variables[name] = value.strip()
+ else:
+ words = line.split()
+ if words:
+ modules[words[0]] = words[1:]
+ finally:
+ fp.close()
+ return modules, variables
+
+
+# Test the above functions.
+
+def test():
+ import sys
+ import os
+ if not sys.argv[1:]:
+ print 'usage: python parsesetup.py Makefile*|Setup* ...'
+ sys.exit(2)
+ for arg in sys.argv[1:]:
+ base = os.path.basename(arg)
+ if base[:8] == 'Makefile':
+ print 'Make style parsing:', arg
+ v = getmakevars(arg)
+ prdict(v)
+ elif base[:5] == 'Setup':
+ print 'Setup style parsing:', arg
+ m, v = getsetupinfo(arg)
+ prdict(m)
+ prdict(v)
+ else:
+ print arg, 'is neither a Makefile nor a Setup file'
+ print '(name must begin with "Makefile" or "Setup")'
+
+def prdict(d):
+ keys = d.keys()
+ keys.sort()
+ for key in keys:
+ value = d[key]
+ print "%-15s" % key, str(value)
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/win32.html b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/win32.html
new file mode 100644
index 0000000000..ca62b46ecc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/win32.html
@@ -0,0 +1,119 @@
+<HTML>
+<HEAD>
+<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
+<META NAME="Generator" CONTENT="Microsoft Word 97">
+<TITLE>win32</TITLE>
+<META NAME="Version" CONTENT="8.0.3410">
+<META NAME="Date" CONTENT="10/11/96">
+<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\HTML.DOT">
+</HEAD>
+<BODY TEXT="#000000" BGCOLOR="#ffffff">
+
+<H1>Freeze for Win32</H1>
+<P>This document describes how to use Freeze for the Win32 platform. </P>
+<P>Freeze itself is a Python tool for creating stand-alone executables from Python source code. This document does not attempt to document freeze itself - only the win32 specific changes.</P>
+<H2>Frozen programs under Win32</H2>
+<P>Frozen programs under Win32 can (theoretically) freeze any type of program supported by Python on Win32 - At the moment, Console .EXE and NT Service .EXE programs are supported. GUI Python programs and COM .EXE programs are very nearly all ready to go.</P>
+<H3>Program Dependencies</H3>
+<P>The person freezing the program has control over what external DLLs are required by a frozen program. The following dependencies are supported:</P>
+<H4>Minimal frozen programs</H4>
+<P>These programs freeze only .py files in your program. All external DLLs are required at run-time. This includes all .pyd/.dll modules used by your program, Python20.dll, and msvcrt.dll. </P>
+<P>A small Python program would typically create a .EXE around 300kb.</P>
+<H4>Frozen Extension programs</H4>
+<B><I><P>Note:</B></I> For Python1.5.1, you must get a patch from Guido to import.c for this to work.</P>
+<P>These programs also freeze in the sources from all .pyd and .dll files used at runtime. This means the resulting .EXE is only dependent on Python20.dll and msvcrt.dll.</P>
+<P>A small Python program using win32api, win32con and one or 2 other win32 extensions would typically create a .EXE around 400kb.</P>
+<H4>Completely frozen programs</H4>
+<P>Completely stand-alone programs, as is the default on Unix systems. These are currently not supported, mainly as the size of a decent Python program gets very large. However, by tweaking the existing Unix support, this would not be difficult to do.</P>
+<H2>Freezing Extension Modules</H2>
+<P>By default, a file in the main "freeze" directory called "extensions_win32.ini" is used to obtain information about frozen extensions. A typical entry is:</P>
+<CODE><P>[win32api]</P>
+<P>dsp=%PYTHONEX%\win32\win32api.dsp</P>
+<P>cl=/I %PYTHONEX%\win32\src</P>
+<P>libs=kernel32.lib user32.lib shell32.lib advapi32.lib</P>
+</CODE><P>&nbsp;</P>
+<P>This entry indicates that the win32api extension module is defined in the MSVC project file "<CODE>%PYTHONEX%\win32\win32api.dsp</CODE>". Note the use of<CODE> </CODE>"<CODE>%PYTHONEX%" </CODE>- most strings are substituted with environment variables. In this case, it is assumed variable PYTHONEX points to the main "Python Extensions" source directory (which is assumed to be in the same structure as the release of the extension sources).</P>
+<P>An entry in a .INI file can also control specific compiler options, and also the .lib files necessary to be linked with the application.</P>
+<H3>Freezing Extension Module Considerations</H3>
+<P>To prevent freezing extension modules, simply exclude that module using the freeze "-x" switch.</P>
+<P>Occasionally, it will be necessary to explicitly include dependent modules. For example, many win32 modules are dependent on the "pywintypes" module - for example, the win32api module. In this case, the module may be explicitly included using the freeze "-m" option.</P>
+<H3>Freezing win32com and PythonCOM</H3>
+<P>PythonCOM.dll can be frozen as long as you are not implementing COM Servers. Ie, you can freeze programs which control other applications, but can not implement programs that are themselves controlled by other applications.</P>
+<P>If you use any of the win32com .pyd extensions (ex, axscript, mapi, internet, axcontrol), then you will need to specify an additional "-a" option to point to the win32comext directory. There is an example below.</P>
+<P>The use of the "win32com.client.gencache" module is not supported (although could be quite easily??)</P>
+<H2>Examples</H2>
+<P>Before we start, we must:</P>
+<CODE><P>D:\temp\delme&gt;set PYTHONEX=d:\src\pythonex</P>
+</CODE><H3>Helloworld.py</H3>
+<H4>Source Code</H4><DIR>
+<DIR>
+
+<CODE><P>import sys</P>
+<P>&nbsp;</P>
+<P>print " ".join( ["Hello", "world"] + sys.argv[1:] )</P></DIR>
+</DIR>
+
+</CODE><H4>Command Line used</H4><DIR>
+<DIR>
+
+<FONT FACE="Courier New" SIZE=2><P>\src\python-1.5.1\tools\freeze\freeze.py helloworld.py</P>
+<P>nmake</P></DIR>
+</DIR>
+
+</FONT><P>Resulting helloworld.exe: 114,688 bytes.</P>
+<H3>Helloworld2.py</H3>
+<P>Uses win32api. Demonstrates requirement for pywintypes, and difference between freezing extensions and not.</P>
+<H4>Source Code</H4><DIR>
+<DIR>
+
+<P>import win32api</P>
+<P>print "Hello from", win32api.GetComputerName()</P></DIR>
+</DIR>
+
+<H4>Command Line used</H4>
+<P>By default, win32api will be frozen in with the .EXE. If you do not provide the "pywintypes" inclusion, then the link step will fail looking for all the pywintypes modules.</P><DIR>
+<DIR>
+
+<FONT FACE="Courier New" SIZE=2><P>\src\python-1.5.1\tools\freeze\freeze.py helloworld2.py -m pywintypes</P>
+<P>nmake</P></DIR>
+</DIR>
+
+</FONT><P>Resulting helloworld2.exe: 167,936 bytes</P>
+<P>Simply adding win32con to the mix gives an EXE of size: 352,768 bytes.</P>
+<H4>Command Line used</H4>
+<P>Using this build, we are dependent at runtime on the win32api.pyd and pywintypes15.dll files.</P><DIR>
+<DIR>
+
+<P>\src\python-1.5.1\tools\freeze\freeze.py -x win32api helloworld.py</P></DIR>
+</DIR>
+
+<P>Resulting helloworld2.exe: 114,688</P>
+<P>Adding win32con to this build results in a size of: 252,928</P>
+<H3>Testmapi.py</H3>
+<P>Uses MAPI, a PythonCOM extension, and win32api.</P>
+<H4>Source Code</H4>
+<P>from win32com.mapi import mapi</P>
+<P>import win32api</P>
+<P>mapi.MAPIInitialize( (mapi.MAPI_INIT_VERSION, 0) )</P>
+<P>print "Hello from", win32api.GetComputerName()</P>
+<P>mapi.MAPIUninitialize()</P>
+<H4>Command Line used</H4>
+<P>As it does not import pythoncom or pywintypes itself, they must be specified. As it uses the win32comext directory, -a must be used. If you have built the win32com extensions from sources, then the second -a is required.</P><DIR>
+<DIR>
+
+<CODE><P>\src\python-1.5.1\tools\freeze\freeze.py -a win32com=%PYTHONEX%\com\win32comext -a win32com.mapi=%PYTHONEX%\com\build\release testmapi.py -m pywintypes -m pythoncom</P></DIR>
+</DIR>
+
+</CODE><P>Resulting testmapi.exe: 352,768 bytes</P>
+<H3>PipeTestService.py</H3>
+<P>This is a standard Python demo in the Win32 extensions. It can be found in the "win32\demos\service" directory.</P>
+<H4>Command Line used</H4>
+<P>This will create a native NT Service EXE, dependent only on the main Python20.dll. All other modules are built-in to the final .EXE</P><DIR>
+<DIR>
+
+<CODE><P>\src\python-1.5.1\tools\freeze\freeze.py -s service %PYTHONEX%\win32\demos\service\pipeTestService.py</P></DIR>
+</DIR>
+
+<P>Resulting pipeTestService.exe: </CODE><FONT FACE="Courier New" SIZE=2>533,504 bytes.</P></FONT></BODY>
+</HTML>
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/winmakemakefile.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/winmakemakefile.py
new file mode 100644
index 0000000000..80c073094d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/freeze/winmakemakefile.py
@@ -0,0 +1,147 @@
+import sys, os
+
+# Template used then the program is a GUI program
+WINMAINTEMPLATE = """
+#include <windows.h>
+
+int WINAPI WinMain(
+ HINSTANCE hInstance, // handle to current instance
+ HINSTANCE hPrevInstance, // handle to previous instance
+ LPSTR lpCmdLine, // pointer to command line
+ int nCmdShow // show state of window
+ )
+{
+ extern int Py_FrozenMain(int, char **);
+ PyImport_FrozenModules = _PyImport_FrozenModules;
+ return Py_FrozenMain(__argc, __argv);
+}
+"""
+
+SERVICETEMPLATE = """
+extern int PythonService_main(int, char **);
+
+int main( int argc, char **argv)
+{
+ PyImport_FrozenModules = _PyImport_FrozenModules;
+ return PythonService_main(argc, argv);
+}
+"""
+
+subsystem_details = {
+ # -s flag : (C entry point template), (is it __main__?), (is it a DLL?)
+ 'console' : (None, 1, 0),
+ 'windows' : (WINMAINTEMPLATE, 1, 0),
+ 'service' : (SERVICETEMPLATE, 0, 0),
+ 'com_dll' : ("", 0, 1),
+}
+
+def get_custom_entry_point(subsystem):
+ try:
+ return subsystem_details[subsystem][:2]
+ except KeyError:
+ raise ValueError, "The subsystem %s is not known" % subsystem
+
+
+def makemakefile(outfp, vars, files, target):
+ save = sys.stdout
+ try:
+ sys.stdout = outfp
+ realwork(vars, files, target)
+ finally:
+ sys.stdout = save
+
+def realwork(vars, moddefns, target):
+ version_suffix = "%r%r" % sys.version_info[:2]
+ print "# Makefile for Microsoft Visual C++ generated by freeze.py script"
+ print
+ print 'target = %s' % target
+ print 'pythonhome = %s' % vars['prefix']
+ print
+ print 'DEBUG=0 # Set to 1 to use the _d versions of Python.'
+ print '!IF $(DEBUG)'
+ print 'debug_suffix=_d'
+ print 'c_debug=/Zi /Od /DDEBUG /D_DEBUG'
+ print 'l_debug=/DEBUG'
+ print 'temp_dir=Build\\Debug'
+ print '!ELSE'
+ print 'debug_suffix='
+ print 'c_debug=/Ox'
+ print 'l_debug='
+ print 'temp_dir=Build\\Release'
+ print '!ENDIF'
+ print
+
+ print '# The following line assumes you have built Python using the standard instructions'
+ print '# Otherwise fix the following line to point to the library.'
+ print 'pythonlib = "$(pythonhome)/pcbuild/python%s$(debug_suffix).lib"' % version_suffix
+ print
+
+ # We only ever write one "entry point" symbol - either
+ # "main" or "WinMain". Therefore, there is no need to
+ # pass a subsystem switch to the linker as it works it
+ # out all by itself. However, the subsystem _does_ determine
+ # the file extension and additional linker flags.
+ target_link_flags = ""
+ target_ext = ".exe"
+ if subsystem_details[vars['subsystem']][2]:
+ target_link_flags = "-dll"
+ target_ext = ".dll"
+
+
+ print "# As the target uses Python%s.dll, we must use this compiler option!" % version_suffix
+ print "cdl = /MD"
+ print
+ print "all: $(target)$(debug_suffix)%s" % (target_ext)
+ print
+
+ print '$(temp_dir):'
+ print ' if not exist $(temp_dir)\. mkdir $(temp_dir)'
+ print
+
+ objects = []
+ libs = ["shell32.lib", "comdlg32.lib", "wsock32.lib", "user32.lib", "oleaut32.lib"]
+ for moddefn in moddefns:
+ print "# Module", moddefn.name
+ for file in moddefn.sourceFiles:
+ base = os.path.basename(file)
+ base, ext = os.path.splitext(base)
+ objects.append(base + ".obj")
+ print '$(temp_dir)\%s.obj: "%s"' % (base, file)
+ print "\t@$(CC) -c -nologo /Fo$* $(cdl) $(c_debug) /D BUILD_FREEZE",
+ print '"-I$(pythonhome)/Include" "-I$(pythonhome)/PC" \\'
+ print "\t\t$(cflags) $(cdebug) $(cinclude) \\"
+ extra = moddefn.GetCompilerOptions()
+ if extra:
+ print "\t\t%s \\" % (' '.join(extra),)
+ print '\t\t"%s"' % file
+ print
+
+ # Add .lib files this module needs
+ for modlib in moddefn.GetLinkerLibs():
+ if modlib not in libs:
+ libs.append(modlib)
+
+ print "ADDN_LINK_FILES=",
+ for addn in vars['addn_link']: print '"%s"' % (addn),
+ print ; print
+
+ print "OBJS=",
+ for obj in objects: print '"$(temp_dir)\%s"' % (obj),
+ print ; print
+
+ print "LIBS=",
+ for lib in libs: print '"%s"' % (lib),
+ print ; print
+
+ print "$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext)
+ print "\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags), "@<<"
+ print "\t$(OBJS)"
+ print "\t$(LIBS)"
+ print "\t$(ADDN_LINK_FILES)"
+ print "\t$(pythonlib) $(lcustom) $(l_debug)"
+ print "\t$(resources)"
+ print "<<"
+ print
+ print "clean:"
+ print "\t-rm -f *.obj"
+ print "\t-rm -f $(target).exe"
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/gdb/libpython.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/gdb/libpython.py
new file mode 100644
index 0000000000..652e07ead8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/gdb/libpython.py
@@ -0,0 +1,1447 @@
+#!/usr/bin/python
+'''
+From gdb 7 onwards, gdb's build can be configured --with-python, allowing gdb
+to be extended with Python code e.g. for library-specific data visualizations,
+such as for the C++ STL types. Documentation on this API can be seen at:
+http://sourceware.org/gdb/current/onlinedocs/gdb/Python-API.html
+
+
+This python module deals with the case when the process being debugged (the
+"inferior process" in gdb parlance) is itself python, or more specifically,
+linked against libpython. In this situation, almost every item of data is a
+(PyObject*), and having the debugger merely print their addresses is not very
+enlightening.
+
+This module embeds knowledge about the implementation details of libpython so
+that we can emit useful visualizations e.g. a string, a list, a dict, a frame
+giving file/line information and the state of local variables
+
+In particular, given a gdb.Value corresponding to a PyObject* in the inferior
+process, we can generate a "proxy value" within the gdb process. For example,
+given a PyObject* in the inferior process that is in fact a PyListObject*
+holding three PyObject* that turn out to be PyStringObject* instances, we can
+generate a proxy value within the gdb process that is a list of strings:
+ ["foo", "bar", "baz"]
+
+Doing so can be expensive for complicated graphs of objects, and could take
+some time, so we also have a "write_repr" method that writes a representation
+of the data to a file-like object. This allows us to stop the traversal by
+having the file-like object raise an exception if it gets too much data.
+
+With both "proxyval" and "write_repr" we keep track of the set of all addresses
+visited so far in the traversal, to avoid infinite recursion due to cycles in
+the graph of object references.
+
+We try to defer gdb.lookup_type() invocations for python types until as late as
+possible: for a dynamically linked python binary, when the process starts in
+the debugger, the libpython.so hasn't been dynamically loaded yet, so none of
+the type names are known to the debugger
+
+The module also extends gdb with some python-specific commands.
+'''
+from __future__ import with_statement
+import gdb
+import sys
+
+# Look up the gdb.Type for some standard types:
+_type_char_ptr = gdb.lookup_type('char').pointer() # char*
+_type_unsigned_char_ptr = gdb.lookup_type('unsigned char').pointer() # unsigned char*
+_type_void_ptr = gdb.lookup_type('void').pointer() # void*
+_type_size_t = gdb.lookup_type('size_t')
+
+SIZEOF_VOID_P = _type_void_ptr.sizeof
+
+
+Py_TPFLAGS_HEAPTYPE = (1L << 9)
+
+Py_TPFLAGS_INT_SUBCLASS = (1L << 23)
+Py_TPFLAGS_LONG_SUBCLASS = (1L << 24)
+Py_TPFLAGS_LIST_SUBCLASS = (1L << 25)
+Py_TPFLAGS_TUPLE_SUBCLASS = (1L << 26)
+Py_TPFLAGS_STRING_SUBCLASS = (1L << 27)
+Py_TPFLAGS_UNICODE_SUBCLASS = (1L << 28)
+Py_TPFLAGS_DICT_SUBCLASS = (1L << 29)
+Py_TPFLAGS_BASE_EXC_SUBCLASS = (1L << 30)
+Py_TPFLAGS_TYPE_SUBCLASS = (1L << 31)
+
+
+MAX_OUTPUT_LEN=1024
+
+class NullPyObjectPtr(RuntimeError):
+ pass
+
+
+def safety_limit(val):
+ # Given a integer value from the process being debugged, limit it to some
+ # safety threshold so that arbitrary breakage within said process doesn't
+ # break the gdb process too much (e.g. sizes of iterations, sizes of lists)
+ return min(val, 1000)
+
+
+def safe_range(val):
+ # As per range, but don't trust the value too much: cap it to a safety
+ # threshold in case the data was corrupted
+ return xrange(safety_limit(val))
+
+
+class StringTruncated(RuntimeError):
+ pass
+
+class TruncatedStringIO(object):
+ '''Similar to cStringIO, but can truncate the output by raising a
+ StringTruncated exception'''
+ def __init__(self, maxlen=None):
+ self._val = ''
+ self.maxlen = maxlen
+
+ def write(self, data):
+ if self.maxlen:
+ if len(data) + len(self._val) > self.maxlen:
+ # Truncation:
+ self._val += data[0:self.maxlen - len(self._val)]
+ raise StringTruncated()
+
+ self._val += data
+
+ def getvalue(self):
+ return self._val
+
+class PyObjectPtr(object):
+ """
+ Class wrapping a gdb.Value that's a either a (PyObject*) within the
+ inferior process, or some subclass pointer e.g. (PyStringObject*)
+
+ There will be a subclass for every refined PyObject type that we care
+ about.
+
+ Note that at every stage the underlying pointer could be NULL, point
+ to corrupt data, etc; this is the debugger, after all.
+ """
+ _typename = 'PyObject'
+
+ def __init__(self, gdbval, cast_to=None):
+ if cast_to:
+ self._gdbval = gdbval.cast(cast_to)
+ else:
+ self._gdbval = gdbval
+
+ def field(self, name):
+ '''
+ Get the gdb.Value for the given field within the PyObject, coping with
+ some python 2 versus python 3 differences.
+
+ Various libpython types are defined using the "PyObject_HEAD" and
+ "PyObject_VAR_HEAD" macros.
+
+ In Python 2, this these are defined so that "ob_type" and (for a var
+ object) "ob_size" are fields of the type in question.
+
+ In Python 3, this is defined as an embedded PyVarObject type thus:
+ PyVarObject ob_base;
+ so that the "ob_size" field is located insize the "ob_base" field, and
+ the "ob_type" is most easily accessed by casting back to a (PyObject*).
+ '''
+ if self.is_null():
+ raise NullPyObjectPtr(self)
+
+ if name == 'ob_type':
+ pyo_ptr = self._gdbval.cast(PyObjectPtr.get_gdb_type())
+ return pyo_ptr.dereference()[name]
+
+ if name == 'ob_size':
+ try:
+ # Python 2:
+ return self._gdbval.dereference()[name]
+ except RuntimeError:
+ # Python 3:
+ return self._gdbval.dereference()['ob_base'][name]
+
+ # General case: look it up inside the object:
+ return self._gdbval.dereference()[name]
+
+ def pyop_field(self, name):
+ '''
+ Get a PyObjectPtr for the given PyObject* field within this PyObject,
+ coping with some python 2 versus python 3 differences.
+ '''
+ return PyObjectPtr.from_pyobject_ptr(self.field(name))
+
+ def write_field_repr(self, name, out, visited):
+ '''
+ Extract the PyObject* field named "name", and write its representation
+ to file-like object "out"
+ '''
+ field_obj = self.pyop_field(name)
+ field_obj.write_repr(out, visited)
+
+ def get_truncated_repr(self, maxlen):
+ '''
+ Get a repr-like string for the data, but truncate it at "maxlen" bytes
+ (ending the object graph traversal as soon as you do)
+ '''
+ out = TruncatedStringIO(maxlen)
+ try:
+ self.write_repr(out, set())
+ except StringTruncated:
+ # Truncation occurred:
+ return out.getvalue() + '...(truncated)'
+
+ # No truncation occurred:
+ return out.getvalue()
+
+ def type(self):
+ return PyTypeObjectPtr(self.field('ob_type'))
+
+ def is_null(self):
+ return 0 == long(self._gdbval)
+
+ def is_optimized_out(self):
+ '''
+ Is the value of the underlying PyObject* visible to the debugger?
+
+ This can vary with the precise version of the compiler used to build
+ Python, and the precise version of gdb.
+
+ See e.g. https://bugzilla.redhat.com/show_bug.cgi?id=556975 with
+ PyEval_EvalFrameEx's "f"
+ '''
+ return self._gdbval.is_optimized_out
+
+ def safe_tp_name(self):
+ try:
+ return self.type().field('tp_name').string()
+ except NullPyObjectPtr:
+ # NULL tp_name?
+ return 'unknown'
+ except RuntimeError:
+ # Can't even read the object at all?
+ return 'unknown'
+
+ def proxyval(self, visited):
+ '''
+ Scrape a value from the inferior process, and try to represent it
+ within the gdb process, whilst (hopefully) avoiding crashes when
+ the remote data is corrupt.
+
+ Derived classes will override this.
+
+ For example, a PyIntObject* with ob_ival 42 in the inferior process
+ should result in an int(42) in this process.
+
+ visited: a set of all gdb.Value pyobject pointers already visited
+ whilst generating this value (to guard against infinite recursion when
+ visiting object graphs with loops). Analogous to Py_ReprEnter and
+ Py_ReprLeave
+ '''
+
+ class FakeRepr(object):
+ """
+ Class representing a non-descript PyObject* value in the inferior
+ process for when we don't have a custom scraper, intended to have
+ a sane repr().
+ """
+
+ def __init__(self, tp_name, address):
+ self.tp_name = tp_name
+ self.address = address
+
+ def __repr__(self):
+ # For the NULL pointer, we have no way of knowing a type, so
+ # special-case it as per
+ # http://bugs.python.org/issue8032#msg100882
+ if self.address == 0:
+ return '0x0'
+ return '<%s at remote 0x%x>' % (self.tp_name, self.address)
+
+ return FakeRepr(self.safe_tp_name(),
+ long(self._gdbval))
+
+ def write_repr(self, out, visited):
+ '''
+ Write a string representation of the value scraped from the inferior
+ process to "out", a file-like object.
+ '''
+ # Default implementation: generate a proxy value and write its repr
+ # However, this could involve a lot of work for complicated objects,
+ # so for derived classes we specialize this
+ return out.write(repr(self.proxyval(visited)))
+
+ @classmethod
+ def subclass_from_type(cls, t):
+ '''
+ Given a PyTypeObjectPtr instance wrapping a gdb.Value that's a
+ (PyTypeObject*), determine the corresponding subclass of PyObjectPtr
+ to use
+
+ Ideally, we would look up the symbols for the global types, but that
+ isn't working yet:
+ (gdb) python print gdb.lookup_symbol('PyList_Type')[0].value
+ Traceback (most recent call last):
+ File "<string>", line 1, in <module>
+ NotImplementedError: Symbol type not yet supported in Python scripts.
+ Error while executing Python code.
+
+ For now, we use tp_flags, after doing some string comparisons on the
+ tp_name for some special-cases that don't seem to be visible through
+ flags
+ '''
+ try:
+ tp_name = t.field('tp_name').string()
+ tp_flags = int(t.field('tp_flags'))
+ except RuntimeError:
+ # Handle any kind of error e.g. NULL ptrs by simply using the base
+ # class
+ return cls
+
+ #print 'tp_flags = 0x%08x' % tp_flags
+ #print 'tp_name = %r' % tp_name
+
+ name_map = {'bool': PyBoolObjectPtr,
+ 'classobj': PyClassObjectPtr,
+ 'instance': PyInstanceObjectPtr,
+ 'NoneType': PyNoneStructPtr,
+ 'frame': PyFrameObjectPtr,
+ 'set' : PySetObjectPtr,
+ 'frozenset' : PySetObjectPtr,
+ 'builtin_function_or_method' : PyCFunctionObjectPtr,
+ }
+ if tp_name in name_map:
+ return name_map[tp_name]
+
+ if tp_flags & Py_TPFLAGS_HEAPTYPE:
+ return HeapTypeObjectPtr
+
+ if tp_flags & Py_TPFLAGS_INT_SUBCLASS:
+ return PyIntObjectPtr
+ if tp_flags & Py_TPFLAGS_LONG_SUBCLASS:
+ return PyLongObjectPtr
+ if tp_flags & Py_TPFLAGS_LIST_SUBCLASS:
+ return PyListObjectPtr
+ if tp_flags & Py_TPFLAGS_TUPLE_SUBCLASS:
+ return PyTupleObjectPtr
+ if tp_flags & Py_TPFLAGS_STRING_SUBCLASS:
+ return PyStringObjectPtr
+ if tp_flags & Py_TPFLAGS_UNICODE_SUBCLASS:
+ return PyUnicodeObjectPtr
+ if tp_flags & Py_TPFLAGS_DICT_SUBCLASS:
+ return PyDictObjectPtr
+ if tp_flags & Py_TPFLAGS_BASE_EXC_SUBCLASS:
+ return PyBaseExceptionObjectPtr
+ #if tp_flags & Py_TPFLAGS_TYPE_SUBCLASS:
+ # return PyTypeObjectPtr
+
+ # Use the base class:
+ return cls
+
+ @classmethod
+ def from_pyobject_ptr(cls, gdbval):
+ '''
+ Try to locate the appropriate derived class dynamically, and cast
+ the pointer accordingly.
+ '''
+ try:
+ p = PyObjectPtr(gdbval)
+ cls = cls.subclass_from_type(p.type())
+ return cls(gdbval, cast_to=cls.get_gdb_type())
+ except RuntimeError:
+ # Handle any kind of error e.g. NULL ptrs by simply using the base
+ # class
+ pass
+ return cls(gdbval)
+
+ @classmethod
+ def get_gdb_type(cls):
+ return gdb.lookup_type(cls._typename).pointer()
+
+ def as_address(self):
+ return long(self._gdbval)
+
+
+class ProxyAlreadyVisited(object):
+ '''
+ Placeholder proxy to use when protecting against infinite recursion due to
+ loops in the object graph.
+
+ Analogous to the values emitted by the users of Py_ReprEnter and Py_ReprLeave
+ '''
+ def __init__(self, rep):
+ self._rep = rep
+
+ def __repr__(self):
+ return self._rep
+
+
+def _write_instance_repr(out, visited, name, pyop_attrdict, address):
+ '''Shared code for use by old-style and new-style classes:
+ write a representation to file-like object "out"'''
+ out.write('<')
+ out.write(name)
+
+ # Write dictionary of instance attributes:
+ if isinstance(pyop_attrdict, PyDictObjectPtr):
+ out.write('(')
+ first = True
+ for pyop_arg, pyop_val in pyop_attrdict.iteritems():
+ if not first:
+ out.write(', ')
+ first = False
+ out.write(pyop_arg.proxyval(visited))
+ out.write('=')
+ pyop_val.write_repr(out, visited)
+ out.write(')')
+ out.write(' at remote 0x%x>' % address)
+
+
+class InstanceProxy(object):
+
+ def __init__(self, cl_name, attrdict, address):
+ self.cl_name = cl_name
+ self.attrdict = attrdict
+ self.address = address
+
+ def __repr__(self):
+ if isinstance(self.attrdict, dict):
+ kwargs = ', '.join(["%s=%r" % (arg, val)
+ for arg, val in self.attrdict.iteritems()])
+ return '<%s(%s) at remote 0x%x>' % (self.cl_name,
+ kwargs, self.address)
+ else:
+ return '<%s at remote 0x%x>' % (self.cl_name,
+ self.address)
+
+def _PyObject_VAR_SIZE(typeobj, nitems):
+ return ( ( typeobj.field('tp_basicsize') +
+ nitems * typeobj.field('tp_itemsize') +
+ (SIZEOF_VOID_P - 1)
+ ) & ~(SIZEOF_VOID_P - 1)
+ ).cast(_type_size_t)
+
+class HeapTypeObjectPtr(PyObjectPtr):
+ _typename = 'PyObject'
+
+ def get_attr_dict(self):
+ '''
+ Get the PyDictObject ptr representing the attribute dictionary
+ (or None if there's a problem)
+ '''
+ try:
+ typeobj = self.type()
+ dictoffset = int_from_int(typeobj.field('tp_dictoffset'))
+ if dictoffset != 0:
+ if dictoffset < 0:
+ type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer()
+ tsize = int_from_int(self._gdbval.cast(type_PyVarObject_ptr)['ob_size'])
+ if tsize < 0:
+ tsize = -tsize
+ size = _PyObject_VAR_SIZE(typeobj, tsize)
+ dictoffset += size
+ assert dictoffset > 0
+ assert dictoffset % SIZEOF_VOID_P == 0
+
+ dictptr = self._gdbval.cast(_type_char_ptr) + dictoffset
+ PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
+ dictptr = dictptr.cast(PyObjectPtrPtr)
+ return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
+ except RuntimeError:
+ # Corrupt data somewhere; fail safe
+ pass
+
+ # Not found, or some kind of error:
+ return None
+
+ def proxyval(self, visited):
+ '''
+ Support for new-style classes.
+
+ Currently we just locate the dictionary using a transliteration to
+ python of _PyObject_GetDictPtr, ignoring descriptors
+ '''
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ return ProxyAlreadyVisited('<...>')
+ visited.add(self.as_address())
+
+ pyop_attr_dict = self.get_attr_dict()
+ if pyop_attr_dict:
+ attr_dict = pyop_attr_dict.proxyval(visited)
+ else:
+ attr_dict = {}
+ tp_name = self.safe_tp_name()
+
+ # New-style class:
+ return InstanceProxy(tp_name, attr_dict, long(self._gdbval))
+
+ def write_repr(self, out, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ out.write('<...>')
+ return
+ visited.add(self.as_address())
+
+ pyop_attrdict = self.get_attr_dict()
+ _write_instance_repr(out, visited,
+ self.safe_tp_name(), pyop_attrdict, self.as_address())
+
+class ProxyException(Exception):
+ def __init__(self, tp_name, args):
+ self.tp_name = tp_name
+ self.args = args
+
+ def __repr__(self):
+ return '%s%r' % (self.tp_name, self.args)
+
+class PyBaseExceptionObjectPtr(PyObjectPtr):
+ """
+ Class wrapping a gdb.Value that's a PyBaseExceptionObject* i.e. an exception
+ within the process being debugged.
+ """
+ _typename = 'PyBaseExceptionObject'
+
+ def proxyval(self, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ return ProxyAlreadyVisited('(...)')
+ visited.add(self.as_address())
+ arg_proxy = self.pyop_field('args').proxyval(visited)
+ return ProxyException(self.safe_tp_name(),
+ arg_proxy)
+
+ def write_repr(self, out, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ out.write('(...)')
+ return
+ visited.add(self.as_address())
+
+ out.write(self.safe_tp_name())
+ self.write_field_repr('args', out, visited)
+
+class PyBoolObjectPtr(PyObjectPtr):
+ """
+ Class wrapping a gdb.Value that's a PyBoolObject* i.e. one of the two
+ <bool> instances (Py_True/Py_False) within the process being debugged.
+ """
+ _typename = 'PyBoolObject'
+
+ def proxyval(self, visited):
+ if int_from_int(self.field('ob_ival')):
+ return True
+ else:
+ return False
+
+
+class PyClassObjectPtr(PyObjectPtr):
+ """
+ Class wrapping a gdb.Value that's a PyClassObject* i.e. a <classobj>
+ instance within the process being debugged.
+ """
+ _typename = 'PyClassObject'
+
+
+class BuiltInFunctionProxy(object):
+ def __init__(self, ml_name):
+ self.ml_name = ml_name
+
+ def __repr__(self):
+ return "<built-in function %s>" % self.ml_name
+
+class BuiltInMethodProxy(object):
+ def __init__(self, ml_name, pyop_m_self):
+ self.ml_name = ml_name
+ self.pyop_m_self = pyop_m_self
+
+ def __repr__(self):
+ return ('<built-in method %s of %s object at remote 0x%x>'
+ % (self.ml_name,
+ self.pyop_m_self.safe_tp_name(),
+ self.pyop_m_self.as_address())
+ )
+
+class PyCFunctionObjectPtr(PyObjectPtr):
+ """
+ Class wrapping a gdb.Value that's a PyCFunctionObject*
+ (see Include/methodobject.h and Objects/methodobject.c)
+ """
+ _typename = 'PyCFunctionObject'
+
+ def proxyval(self, visited):
+ m_ml = self.field('m_ml') # m_ml is a (PyMethodDef*)
+ ml_name = m_ml['ml_name'].string()
+
+ pyop_m_self = self.pyop_field('m_self')
+ if pyop_m_self.is_null():
+ return BuiltInFunctionProxy(ml_name)
+ else:
+ return BuiltInMethodProxy(ml_name, pyop_m_self)
+
+
+class PyCodeObjectPtr(PyObjectPtr):
+ """
+ Class wrapping a gdb.Value that's a PyCodeObject* i.e. a <code> instance
+ within the process being debugged.
+ """
+ _typename = 'PyCodeObject'
+
+ def addr2line(self, addrq):
+ '''
+ Get the line number for a given bytecode offset
+
+ Analogous to PyCode_Addr2Line; translated from pseudocode in
+ Objects/lnotab_notes.txt
+ '''
+ co_lnotab = self.pyop_field('co_lnotab').proxyval(set())
+
+ # Initialize lineno to co_firstlineno as per PyCode_Addr2Line
+ # not 0, as lnotab_notes.txt has it:
+ lineno = int_from_int(self.field('co_firstlineno'))
+
+ addr = 0
+ for addr_incr, line_incr in zip(co_lnotab[::2], co_lnotab[1::2]):
+ addr += ord(addr_incr)
+ if addr > addrq:
+ return lineno
+ lineno += ord(line_incr)
+ return lineno
+
+
+class PyDictObjectPtr(PyObjectPtr):
+ """
+ Class wrapping a gdb.Value that's a PyDictObject* i.e. a dict instance
+ within the process being debugged.
+ """
+ _typename = 'PyDictObject'
+
+ def iteritems(self):
+ '''
+ Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs,
+ analagous to dict.iteritems()
+ '''
+ for i in safe_range(self.field('ma_mask') + 1):
+ ep = self.field('ma_table') + i
+ pyop_value = PyObjectPtr.from_pyobject_ptr(ep['me_value'])
+ if not pyop_value.is_null():
+ pyop_key = PyObjectPtr.from_pyobject_ptr(ep['me_key'])
+ yield (pyop_key, pyop_value)
+
+ def proxyval(self, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ return ProxyAlreadyVisited('{...}')
+ visited.add(self.as_address())
+
+ result = {}
+ for pyop_key, pyop_value in self.iteritems():
+ proxy_key = pyop_key.proxyval(visited)
+ proxy_value = pyop_value.proxyval(visited)
+ result[proxy_key] = proxy_value
+ return result
+
+ def write_repr(self, out, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ out.write('{...}')
+ return
+ visited.add(self.as_address())
+
+ out.write('{')
+ first = True
+ for pyop_key, pyop_value in self.iteritems():
+ if not first:
+ out.write(', ')
+ first = False
+ pyop_key.write_repr(out, visited)
+ out.write(': ')
+ pyop_value.write_repr(out, visited)
+ out.write('}')
+
+class PyInstanceObjectPtr(PyObjectPtr):
+ _typename = 'PyInstanceObject'
+
+ def proxyval(self, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ return ProxyAlreadyVisited('<...>')
+ visited.add(self.as_address())
+
+ # Get name of class:
+ in_class = self.pyop_field('in_class')
+ cl_name = in_class.pyop_field('cl_name').proxyval(visited)
+
+ # Get dictionary of instance attributes:
+ in_dict = self.pyop_field('in_dict').proxyval(visited)
+
+ # Old-style class:
+ return InstanceProxy(cl_name, in_dict, long(self._gdbval))
+
+ def write_repr(self, out, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ out.write('<...>')
+ return
+ visited.add(self.as_address())
+
+ # Old-style class:
+
+ # Get name of class:
+ in_class = self.pyop_field('in_class')
+ cl_name = in_class.pyop_field('cl_name').proxyval(visited)
+
+ # Get dictionary of instance attributes:
+ pyop_in_dict = self.pyop_field('in_dict')
+
+ _write_instance_repr(out, visited,
+ cl_name, pyop_in_dict, self.as_address())
+
+class PyIntObjectPtr(PyObjectPtr):
+ _typename = 'PyIntObject'
+
+ def proxyval(self, visited):
+ result = int_from_int(self.field('ob_ival'))
+ return result
+
+class PyListObjectPtr(PyObjectPtr):
+ _typename = 'PyListObject'
+
+ def __getitem__(self, i):
+ # Get the gdb.Value for the (PyObject*) with the given index:
+ field_ob_item = self.field('ob_item')
+ return field_ob_item[i]
+
+ def proxyval(self, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ return ProxyAlreadyVisited('[...]')
+ visited.add(self.as_address())
+
+ result = [PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
+ for i in safe_range(int_from_int(self.field('ob_size')))]
+ return result
+
+ def write_repr(self, out, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ out.write('[...]')
+ return
+ visited.add(self.as_address())
+
+ out.write('[')
+ for i in safe_range(int_from_int(self.field('ob_size'))):
+ if i > 0:
+ out.write(', ')
+ element = PyObjectPtr.from_pyobject_ptr(self[i])
+ element.write_repr(out, visited)
+ out.write(']')
+
+class PyLongObjectPtr(PyObjectPtr):
+ _typename = 'PyLongObject'
+
+ def proxyval(self, visited):
+ '''
+ Python's Include/longobjrep.h has this declaration:
+ struct _longobject {
+ PyObject_VAR_HEAD
+ digit ob_digit[1];
+ };
+
+ with this description:
+ The absolute value of a number is equal to
+ SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
+ Negative numbers are represented with ob_size < 0;
+ zero is represented by ob_size == 0.
+
+ where SHIFT can be either:
+ #define PyLong_SHIFT 30
+ #define PyLong_SHIFT 15
+ '''
+ ob_size = long(self.field('ob_size'))
+ if ob_size == 0:
+ return 0L
+
+ ob_digit = self.field('ob_digit')
+
+ if gdb.lookup_type('digit').sizeof == 2:
+ SHIFT = 15L
+ else:
+ SHIFT = 30L
+
+ digits = [long(ob_digit[i]) * 2**(SHIFT*i)
+ for i in safe_range(abs(ob_size))]
+ result = sum(digits)
+ if ob_size < 0:
+ result = -result
+ return result
+
+
+class PyNoneStructPtr(PyObjectPtr):
+ """
+ Class wrapping a gdb.Value that's a PyObject* pointing to the
+ singleton (we hope) _Py_NoneStruct with ob_type PyNone_Type
+ """
+ _typename = 'PyObject'
+
+ def proxyval(self, visited):
+ return None
+
+
+class PyFrameObjectPtr(PyObjectPtr):
+ _typename = 'PyFrameObject'
+
+ def __init__(self, gdbval, cast_to):
+ PyObjectPtr.__init__(self, gdbval, cast_to)
+
+ if not self.is_optimized_out():
+ self.co = PyCodeObjectPtr.from_pyobject_ptr(self.field('f_code'))
+ self.co_name = self.co.pyop_field('co_name')
+ self.co_filename = self.co.pyop_field('co_filename')
+
+ self.f_lineno = int_from_int(self.field('f_lineno'))
+ self.f_lasti = int_from_int(self.field('f_lasti'))
+ self.co_nlocals = int_from_int(self.co.field('co_nlocals'))
+ self.co_varnames = PyTupleObjectPtr.from_pyobject_ptr(self.co.field('co_varnames'))
+
+ def iter_locals(self):
+ '''
+ Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
+ the local variables of this frame
+ '''
+ if self.is_optimized_out():
+ return
+
+ f_localsplus = self.field('f_localsplus')
+ for i in safe_range(self.co_nlocals):
+ pyop_value = PyObjectPtr.from_pyobject_ptr(f_localsplus[i])
+ if not pyop_value.is_null():
+ pyop_name = PyObjectPtr.from_pyobject_ptr(self.co_varnames[i])
+ yield (pyop_name, pyop_value)
+
+ def iter_globals(self):
+ '''
+ Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
+ the global variables of this frame
+ '''
+ if self.is_optimized_out():
+ return
+
+ pyop_globals = self.pyop_field('f_globals')
+ return pyop_globals.iteritems()
+
+ def iter_builtins(self):
+ '''
+ Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
+ the builtin variables
+ '''
+ if self.is_optimized_out():
+ return
+
+ pyop_builtins = self.pyop_field('f_builtins')
+ return pyop_builtins.iteritems()
+
+ def get_var_by_name(self, name):
+ '''
+ Look for the named local variable, returning a (PyObjectPtr, scope) pair
+ where scope is a string 'local', 'global', 'builtin'
+
+ If not found, return (None, None)
+ '''
+ for pyop_name, pyop_value in self.iter_locals():
+ if name == pyop_name.proxyval(set()):
+ return pyop_value, 'local'
+ for pyop_name, pyop_value in self.iter_globals():
+ if name == pyop_name.proxyval(set()):
+ return pyop_value, 'global'
+ for pyop_name, pyop_value in self.iter_builtins():
+ if name == pyop_name.proxyval(set()):
+ return pyop_value, 'builtin'
+ return None, None
+
+ def filename(self):
+ '''Get the path of the current Python source file, as a string'''
+ if self.is_optimized_out():
+ return '(frame information optimized out)'
+ return self.co_filename.proxyval(set())
+
+ def current_line_num(self):
+ '''Get current line number as an integer (1-based)
+
+ Translated from PyFrame_GetLineNumber and PyCode_Addr2Line
+
+ See Objects/lnotab_notes.txt
+ '''
+ if self.is_optimized_out():
+ return None
+ f_trace = self.field('f_trace')
+ if long(f_trace) != 0:
+ # we have a non-NULL f_trace:
+ return self.f_lineno
+ else:
+ #try:
+ return self.co.addr2line(self.f_lasti)
+ #except ValueError:
+ # return self.f_lineno
+
+ def current_line(self):
+ '''Get the text of the current source line as a string, with a trailing
+ newline character'''
+ if self.is_optimized_out():
+ return '(frame information optimized out)'
+ with open(self.filename(), 'r') as f:
+ all_lines = f.readlines()
+ # Convert from 1-based current_line_num to 0-based list offset:
+ return all_lines[self.current_line_num()-1]
+
+ def write_repr(self, out, visited):
+ if self.is_optimized_out():
+ out.write('(frame information optimized out)')
+ return
+ out.write('Frame 0x%x, for file %s, line %i, in %s ('
+ % (self.as_address(),
+ self.co_filename,
+ self.current_line_num(),
+ self.co_name))
+ first = True
+ for pyop_name, pyop_value in self.iter_locals():
+ if not first:
+ out.write(', ')
+ first = False
+
+ out.write(pyop_name.proxyval(visited))
+ out.write('=')
+ pyop_value.write_repr(out, visited)
+
+ out.write(')')
+
+class PySetObjectPtr(PyObjectPtr):
+ _typename = 'PySetObject'
+
+ def proxyval(self, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ return ProxyAlreadyVisited('%s(...)' % self.safe_tp_name())
+ visited.add(self.as_address())
+
+ members = []
+ table = self.field('table')
+ for i in safe_range(self.field('mask')+1):
+ setentry = table[i]
+ key = setentry['key']
+ if key != 0:
+ key_proxy = PyObjectPtr.from_pyobject_ptr(key).proxyval(visited)
+ if key_proxy != '<dummy key>':
+ members.append(key_proxy)
+ if self.safe_tp_name() == 'frozenset':
+ return frozenset(members)
+ else:
+ return set(members)
+
+ def write_repr(self, out, visited):
+ out.write(self.safe_tp_name())
+
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ out.write('(...)')
+ return
+ visited.add(self.as_address())
+
+ out.write('([')
+ first = True
+ table = self.field('table')
+ for i in safe_range(self.field('mask')+1):
+ setentry = table[i]
+ key = setentry['key']
+ if key != 0:
+ pyop_key = PyObjectPtr.from_pyobject_ptr(key)
+ key_proxy = pyop_key.proxyval(visited) # FIXME!
+ if key_proxy != '<dummy key>':
+ if not first:
+ out.write(', ')
+ first = False
+ pyop_key.write_repr(out, visited)
+ out.write('])')
+
+
+class PyStringObjectPtr(PyObjectPtr):
+ _typename = 'PyStringObject'
+
+ def __str__(self):
+ field_ob_size = self.field('ob_size')
+ field_ob_sval = self.field('ob_sval')
+ char_ptr = field_ob_sval.address.cast(_type_unsigned_char_ptr)
+ return ''.join([chr(char_ptr[i]) for i in safe_range(field_ob_size)])
+
+ def proxyval(self, visited):
+ return str(self)
+
+class PyTupleObjectPtr(PyObjectPtr):
+ _typename = 'PyTupleObject'
+
+ def __getitem__(self, i):
+ # Get the gdb.Value for the (PyObject*) with the given index:
+ field_ob_item = self.field('ob_item')
+ return field_ob_item[i]
+
+ def proxyval(self, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ return ProxyAlreadyVisited('(...)')
+ visited.add(self.as_address())
+
+ result = tuple([PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
+ for i in safe_range(int_from_int(self.field('ob_size')))])
+ return result
+
+ def write_repr(self, out, visited):
+ # Guard against infinite loops:
+ if self.as_address() in visited:
+ out.write('(...)')
+ return
+ visited.add(self.as_address())
+
+ out.write('(')
+ for i in safe_range(int_from_int(self.field('ob_size'))):
+ if i > 0:
+ out.write(', ')
+ element = PyObjectPtr.from_pyobject_ptr(self[i])
+ element.write_repr(out, visited)
+ if self.field('ob_size') == 1:
+ out.write(',)')
+ else:
+ out.write(')')
+
+class PyTypeObjectPtr(PyObjectPtr):
+ _typename = 'PyTypeObject'
+
+
+if sys.maxunicode >= 0x10000:
+ _unichr = unichr
+else:
+ # Needed for proper surrogate support if sizeof(Py_UNICODE) is 2 in gdb
+ def _unichr(x):
+ if x < 0x10000:
+ return unichr(x)
+ x -= 0x10000
+ ch1 = 0xD800 | (x >> 10)
+ ch2 = 0xDC00 | (x & 0x3FF)
+ return unichr(ch1) + unichr(ch2)
+
+class PyUnicodeObjectPtr(PyObjectPtr):
+ _typename = 'PyUnicodeObject'
+
+ def char_width(self):
+ _type_Py_UNICODE = gdb.lookup_type('Py_UNICODE')
+ return _type_Py_UNICODE.sizeof
+
+ def proxyval(self, visited):
+ # From unicodeobject.h:
+ # Py_ssize_t length; /* Length of raw Unicode data in buffer */
+ # Py_UNICODE *str; /* Raw Unicode buffer */
+ field_length = long(self.field('length'))
+ field_str = self.field('str')
+
+ # Gather a list of ints from the Py_UNICODE array; these are either
+ # UCS-2 or UCS-4 code points:
+ if self.char_width() > 2:
+ Py_UNICODEs = [int(field_str[i]) for i in safe_range(field_length)]
+ else:
+ # A more elaborate routine if sizeof(Py_UNICODE) is 2 in the
+ # inferior process: we must join surrogate pairs.
+ Py_UNICODEs = []
+ i = 0
+ limit = safety_limit(field_length)
+ while i < limit:
+ ucs = int(field_str[i])
+ i += 1
+ if ucs < 0xD800 or ucs >= 0xDC00 or i == field_length:
+ Py_UNICODEs.append(ucs)
+ continue
+ # This could be a surrogate pair.
+ ucs2 = int(field_str[i])
+ if ucs2 < 0xDC00 or ucs2 > 0xDFFF:
+ continue
+ code = (ucs & 0x03FF) << 10
+ code |= ucs2 & 0x03FF
+ code += 0x00010000
+ Py_UNICODEs.append(code)
+ i += 1
+
+ # Convert the int code points to unicode characters, and generate a
+ # local unicode instance.
+ # This splits surrogate pairs if sizeof(Py_UNICODE) is 2 here (in gdb).
+ result = u''.join([_unichr(ucs) for ucs in Py_UNICODEs])
+ return result
+
+
+def int_from_int(gdbval):
+ return int(str(gdbval))
+
+
+def stringify(val):
+ # TODO: repr() puts everything on one line; pformat can be nicer, but
+ # can lead to v.long results; this function isolates the choice
+ if True:
+ return repr(val)
+ else:
+ from pprint import pformat
+ return pformat(val)
+
+
+class PyObjectPtrPrinter:
+ "Prints a (PyObject*)"
+
+ def __init__ (self, gdbval):
+ self.gdbval = gdbval
+
+ def to_string (self):
+ pyop = PyObjectPtr.from_pyobject_ptr(self.gdbval)
+ if True:
+ return pyop.get_truncated_repr(MAX_OUTPUT_LEN)
+ else:
+ # Generate full proxy value then stringify it.
+ # Doing so could be expensive
+ proxyval = pyop.proxyval(set())
+ return stringify(proxyval)
+
+def pretty_printer_lookup(gdbval):
+ type = gdbval.type.unqualified()
+ if type.code == gdb.TYPE_CODE_PTR:
+ type = type.target().unqualified()
+ t = str(type)
+ if t in ("PyObject", "PyFrameObject"):
+ return PyObjectPtrPrinter(gdbval)
+
+"""
+During development, I've been manually invoking the code in this way:
+(gdb) python
+
+import sys
+sys.path.append('/home/david/coding/python-gdb')
+import libpython
+end
+
+then reloading it after each edit like this:
+(gdb) python reload(libpython)
+
+The following code should ensure that the prettyprinter is registered
+if the code is autoloaded by gdb when visiting libpython.so, provided
+that this python file is installed to the same path as the library (or its
+.debug file) plus a "-gdb.py" suffix, e.g:
+ /usr/lib/libpython2.6.so.1.0-gdb.py
+ /usr/lib/debug/usr/lib/libpython2.6.so.1.0.debug-gdb.py
+"""
+def register (obj):
+ if obj == None:
+ obj = gdb
+
+ # Wire up the pretty-printer
+ obj.pretty_printers.append(pretty_printer_lookup)
+
+register (gdb.current_objfile ())
+
+
+
+# Unfortunately, the exact API exposed by the gdb module varies somewhat
+# from build to build
+# See http://bugs.python.org/issue8279?#msg102276
+
+class Frame(object):
+ '''
+ Wrapper for gdb.Frame, adding various methods
+ '''
+ def __init__(self, gdbframe):
+ self._gdbframe = gdbframe
+
+ def older(self):
+ older = self._gdbframe.older()
+ if older:
+ return Frame(older)
+ else:
+ return None
+
+ def newer(self):
+ newer = self._gdbframe.newer()
+ if newer:
+ return Frame(newer)
+ else:
+ return None
+
+ def select(self):
+ '''If supported, select this frame and return True; return False if unsupported
+
+ Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
+ onwards, but absent on Ubuntu buildbot'''
+ if not hasattr(self._gdbframe, 'select'):
+ print ('Unable to select frame: '
+ 'this build of gdb does not expose a gdb.Frame.select method')
+ return False
+ self._gdbframe.select()
+ return True
+
+ def get_index(self):
+ '''Calculate index of frame, starting at 0 for the newest frame within
+ this thread'''
+ index = 0
+ # Go down until you reach the newest frame:
+ iter_frame = self
+ while iter_frame.newer():
+ index += 1
+ iter_frame = iter_frame.newer()
+ return index
+
+ def is_evalframeex(self):
+ '''Is this a PyEval_EvalFrameEx frame?'''
+ if self._gdbframe.name() == 'PyEval_EvalFrameEx':
+ '''
+ I believe we also need to filter on the inline
+ struct frame_id.inline_depth, only regarding frames with
+ an inline depth of 0 as actually being this function
+
+ So we reject those with type gdb.INLINE_FRAME
+ '''
+ if self._gdbframe.type() == gdb.NORMAL_FRAME:
+ # We have a PyEval_EvalFrameEx frame:
+ return True
+
+ return False
+
+ def get_pyop(self):
+ try:
+ f = self._gdbframe.read_var('f')
+ return PyFrameObjectPtr.from_pyobject_ptr(f)
+ except ValueError:
+ return None
+
+ @classmethod
+ def get_selected_frame(cls):
+ _gdbframe = gdb.selected_frame()
+ if _gdbframe:
+ return Frame(_gdbframe)
+ return None
+
+ @classmethod
+ def get_selected_python_frame(cls):
+ '''Try to obtain the Frame for the python code in the selected frame,
+ or None'''
+ frame = cls.get_selected_frame()
+
+ while frame:
+ if frame.is_evalframeex():
+ return frame
+ frame = frame.older()
+
+ # Not found:
+ return None
+
+ def print_summary(self):
+ if self.is_evalframeex():
+ pyop = self.get_pyop()
+ if pyop:
+ sys.stdout.write('#%i %s\n' % (self.get_index(), pyop.get_truncated_repr(MAX_OUTPUT_LEN)))
+ sys.stdout.write(pyop.current_line())
+ else:
+ sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())
+ else:
+ sys.stdout.write('#%i\n' % self.get_index())
+
+class PyList(gdb.Command):
+ '''List the current Python source code, if any
+
+ Use
+ py-list START
+ to list at a different line number within the python source.
+
+ Use
+ py-list START, END
+ to list a specific range of lines within the python source.
+ '''
+
+ def __init__(self):
+ gdb.Command.__init__ (self,
+ "py-list",
+ gdb.COMMAND_FILES,
+ gdb.COMPLETE_NONE)
+
+
+ def invoke(self, args, from_tty):
+ import re
+
+ start = None
+ end = None
+
+ m = re.match(r'\s*(\d+)\s*', args)
+ if m:
+ start = int(m.group(0))
+ end = start + 10
+
+ m = re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
+ if m:
+ start, end = map(int, m.groups())
+
+ frame = Frame.get_selected_python_frame()
+ if not frame:
+ print 'Unable to locate python frame'
+ return
+
+ pyop = frame.get_pyop()
+ if not pyop:
+ print 'Unable to read information on python frame'
+ return
+
+ filename = pyop.filename()
+ lineno = pyop.current_line_num()
+
+ if start is None:
+ start = lineno - 5
+ end = lineno + 5
+
+ if start<1:
+ start = 1
+
+ with open(filename, 'r') as f:
+ all_lines = f.readlines()
+ # start and end are 1-based, all_lines is 0-based;
+ # so [start-1:end] as a python slice gives us [start, end] as a
+ # closed interval
+ for i, line in enumerate(all_lines[start-1:end]):
+ linestr = str(i+start)
+ # Highlight current line:
+ if i + start == lineno:
+ linestr = '>' + linestr
+ sys.stdout.write('%4s %s' % (linestr, line))
+
+
+# ...and register the command:
+PyList()
+
+def move_in_stack(move_up):
+ '''Move up or down the stack (for the py-up/py-down command)'''
+ frame = Frame.get_selected_python_frame()
+ while frame:
+ if move_up:
+ iter_frame = frame.older()
+ else:
+ iter_frame = frame.newer()
+
+ if not iter_frame:
+ break
+
+ if iter_frame.is_evalframeex():
+ # Result:
+ if iter_frame.select():
+ iter_frame.print_summary()
+ return
+
+ frame = iter_frame
+
+ if move_up:
+ print 'Unable to find an older python frame'
+ else:
+ print 'Unable to find a newer python frame'
+
+class PyUp(gdb.Command):
+ 'Select and print the python stack frame that called this one (if any)'
+ def __init__(self):
+ gdb.Command.__init__ (self,
+ "py-up",
+ gdb.COMMAND_STACK,
+ gdb.COMPLETE_NONE)
+
+
+ def invoke(self, args, from_tty):
+ move_in_stack(move_up=True)
+
+class PyDown(gdb.Command):
+ 'Select and print the python stack frame called by this one (if any)'
+ def __init__(self):
+ gdb.Command.__init__ (self,
+ "py-down",
+ gdb.COMMAND_STACK,
+ gdb.COMPLETE_NONE)
+
+
+ def invoke(self, args, from_tty):
+ move_in_stack(move_up=False)
+
+# Not all builds of gdb have gdb.Frame.select
+if hasattr(gdb.Frame, 'select'):
+ PyUp()
+ PyDown()
+
+class PyBacktrace(gdb.Command):
+ 'Display the current python frame and all the frames within its call stack (if any)'
+ def __init__(self):
+ gdb.Command.__init__ (self,
+ "py-bt",
+ gdb.COMMAND_STACK,
+ gdb.COMPLETE_NONE)
+
+
+ def invoke(self, args, from_tty):
+ frame = Frame.get_selected_python_frame()
+ while frame:
+ if frame.is_evalframeex():
+ frame.print_summary()
+ frame = frame.older()
+
+PyBacktrace()
+
+class PyPrint(gdb.Command):
+ 'Look up the given python variable name, and print it'
+ def __init__(self):
+ gdb.Command.__init__ (self,
+ "py-print",
+ gdb.COMMAND_DATA,
+ gdb.COMPLETE_NONE)
+
+
+ def invoke(self, args, from_tty):
+ name = str(args)
+
+ frame = Frame.get_selected_python_frame()
+ if not frame:
+ print 'Unable to locate python frame'
+ return
+
+ pyop_frame = frame.get_pyop()
+ if not pyop_frame:
+ print 'Unable to read information on python frame'
+ return
+
+ pyop_var, scope = pyop_frame.get_var_by_name(name)
+
+ if pyop_var:
+ print ('%s %r = %s'
+ % (scope,
+ name,
+ pyop_var.get_truncated_repr(MAX_OUTPUT_LEN)))
+ else:
+ print '%r not found' % name
+
+PyPrint()
+
+class PyLocals(gdb.Command):
+ 'Look up the given python variable name, and print it'
+ def __init__(self):
+ gdb.Command.__init__ (self,
+ "py-locals",
+ gdb.COMMAND_DATA,
+ gdb.COMPLETE_NONE)
+
+
+ def invoke(self, args, from_tty):
+ name = str(args)
+
+ frame = Frame.get_selected_python_frame()
+ if not frame:
+ print 'Unable to locate python frame'
+ return
+
+ pyop_frame = frame.get_pyop()
+ if not pyop_frame:
+ print 'Unable to read information on python frame'
+ return
+
+ for pyop_name, pyop_value in pyop_frame.iter_locals():
+ print ('%s = %s'
+ % (pyop_name.proxyval(set()),
+ pyop_value.get_truncated_repr(MAX_OUTPUT_LEN)))
+
+PyLocals()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/makelocalealias.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/makelocalealias.py
new file mode 100644
index 0000000000..7585a101ec
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/makelocalealias.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+"""
+ Convert the X11 locale.alias file into a mapping dictionary suitable
+ for locale.py.
+
+ Written by Marc-Andre Lemburg <mal@genix.com>, 2004-12-10.
+
+"""
+import locale
+
+# Location of the alias file
+LOCALE_ALIAS = '/usr/share/X11/locale/locale.alias'
+
+def parse(filename):
+
+ f = open(filename)
+ lines = f.read().splitlines()
+ data = {}
+ for line in lines:
+ line = line.strip()
+ if not line:
+ continue
+ if line[:1] == '#':
+ continue
+ locale, alias = line.split()
+ # Strip ':'
+ if locale[-1] == ':':
+ locale = locale[:-1]
+ # Lower-case locale
+ locale = locale.lower()
+ # Ignore one letter locale mappings (except for 'c')
+ if len(locale) == 1 and locale != 'c':
+ continue
+ # Normalize encoding, if given
+ if '.' in locale:
+ lang, encoding = locale.split('.')[:2]
+ encoding = encoding.replace('-', '')
+ encoding = encoding.replace('_', '')
+ locale = lang + '.' + encoding
+ if encoding.lower() == 'utf8':
+ # Ignore UTF-8 mappings - this encoding should be
+ # available for all locales
+ continue
+ data[locale] = alias
+ return data
+
+def pprint(data):
+
+ items = data.items()
+ items.sort()
+ for k,v in items:
+ print ' %-40s%r,' % ('%r:' % k, v)
+
+def print_differences(data, olddata):
+
+ items = olddata.items()
+ items.sort()
+ for k, v in items:
+ if not data.has_key(k):
+ print '# removed %r' % k
+ elif olddata[k] != data[k]:
+ print '# updated %r -> %r to %r' % \
+ (k, olddata[k], data[k])
+ # Additions are not mentioned
+
+if __name__ == '__main__':
+ data = locale.locale_alias.copy()
+ data.update(parse(LOCALE_ALIAS))
+ print_differences(data, locale.locale_alias)
+ print
+ print 'locale_alias = {'
+ pprint(data)
+ print '}'
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/msgfmt.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/msgfmt.py
new file mode 100644
index 0000000000..25795d7702
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/msgfmt.py
@@ -0,0 +1,226 @@
+#! /usr/bin/env python
+# -*- coding: iso-8859-1 -*-
+# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
+
+"""Generate binary message catalog from textual translation description.
+
+This program converts a textual Uniforum-style message catalog (.po file) into
+a binary GNU catalog (.mo file). This is essentially the same function as the
+GNU msgfmt program, however, it is a simpler implementation.
+
+Usage: msgfmt.py [OPTIONS] filename.po
+
+Options:
+ -o file
+ --output-file=file
+ Specify the output file to write to. If omitted, output will go to a
+ file named filename.mo (based off the input file name).
+
+ -h
+ --help
+ Print this message and exit.
+
+ -V
+ --version
+ Display version information and exit.
+"""
+
+import sys
+import os
+import getopt
+import struct
+import array
+
+__version__ = "1.1"
+
+MESSAGES = {}
+
+
+
+def usage(code, msg=''):
+ print >> sys.stderr, __doc__
+ if msg:
+ print >> sys.stderr, msg
+ sys.exit(code)
+
+
+
+def add(id, str, fuzzy):
+ "Add a non-fuzzy translation to the dictionary."
+ global MESSAGES
+ if not fuzzy and str:
+ MESSAGES[id] = str
+
+
+
+def generate():
+ "Return the generated output."
+ global MESSAGES
+ keys = MESSAGES.keys()
+ # the keys are sorted in the .mo file
+ keys.sort()
+ offsets = []
+ ids = strs = ''
+ for id in keys:
+ # For each string, we need size and file offset. Each string is NUL
+ # terminated; the NUL does not count into the size.
+ offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
+ ids += id + '\0'
+ strs += MESSAGES[id] + '\0'
+ output = ''
+ # The header is 7 32-bit unsigned integers. We don't use hash tables, so
+ # the keys start right after the index tables.
+ # translated string.
+ keystart = 7*4+16*len(keys)
+ # and the values start after the keys
+ valuestart = keystart + len(ids)
+ koffsets = []
+ voffsets = []
+ # The string table first has the list of keys, then the list of values.
+ # Each entry has first the size of the string, then the file offset.
+ for o1, l1, o2, l2 in offsets:
+ koffsets += [l1, o1+keystart]
+ voffsets += [l2, o2+valuestart]
+ offsets = koffsets + voffsets
+ output = struct.pack("Iiiiiii",
+ 0x950412deL, # Magic
+ 0, # Version
+ len(keys), # # of entries
+ 7*4, # start of key index
+ 7*4+len(keys)*8, # start of value index
+ 0, 0) # size and offset of hash table
+ output += array.array("i", offsets).tostring()
+ output += ids
+ output += strs
+ return output
+
+
+
+def make(filename, outfile):
+ ID = 1
+ STR = 2
+
+ # Compute .mo name from .po name and arguments
+ if filename.endswith('.po'):
+ infile = filename
+ else:
+ infile = filename + '.po'
+ if outfile is None:
+ outfile = os.path.splitext(infile)[0] + '.mo'
+
+ try:
+ lines = open(infile).readlines()
+ except IOError, msg:
+ print >> sys.stderr, msg
+ sys.exit(1)
+
+ section = None
+ fuzzy = 0
+
+ # Parse the catalog
+ lno = 0
+ for l in lines:
+ lno += 1
+ # If we get a comment line after a msgstr, this is a new entry
+ if l[0] == '#' and section == STR:
+ add(msgid, msgstr, fuzzy)
+ section = None
+ fuzzy = 0
+ # Record a fuzzy mark
+ if l[:2] == '#,' and 'fuzzy' in l:
+ fuzzy = 1
+ # Skip comments
+ if l[0] == '#':
+ continue
+ # Now we are in a msgid section, output previous section
+ if l.startswith('msgid') and not l.startswith('msgid_plural'):
+ if section == STR:
+ add(msgid, msgstr, fuzzy)
+ section = ID
+ l = l[5:]
+ msgid = msgstr = ''
+ is_plural = False
+ # This is a message with plural forms
+ elif l.startswith('msgid_plural'):
+ if section != ID:
+ print >> sys.stderr, 'msgid_plural not preceeded by msgid on %s:%d' %\
+ (infile, lno)
+ sys.exit(1)
+ l = l[12:]
+ msgid += '\0' # separator of singular and plural
+ is_plural = True
+ # Now we are in a msgstr section
+ elif l.startswith('msgstr'):
+ section = STR
+ if l.startswith('msgstr['):
+ if not is_plural:
+ print >> sys.stderr, 'plural without msgid_plural on %s:%d' %\
+ (infile, lno)
+ sys.exit(1)
+ l = l.split(']', 1)[1]
+ if msgstr:
+ msgstr += '\0' # Separator of the various plural forms
+ else:
+ if is_plural:
+ print >> sys.stderr, 'indexed msgstr required for plural on %s:%d' %\
+ (infile, lno)
+ sys.exit(1)
+ l = l[6:]
+ # Skip empty lines
+ l = l.strip()
+ if not l:
+ continue
+ # XXX: Does this always follow Python escape semantics?
+ l = eval(l)
+ if section == ID:
+ msgid += l
+ elif section == STR:
+ msgstr += l
+ else:
+ print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
+ 'before:'
+ print >> sys.stderr, l
+ sys.exit(1)
+ # Add last entry
+ if section == STR:
+ add(msgid, msgstr, fuzzy)
+
+ # Compute output
+ output = generate()
+
+ try:
+ open(outfile,"wb").write(output)
+ except IOError,msg:
+ print >> sys.stderr, msg
+
+
+
+def main():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
+ ['help', 'version', 'output-file='])
+ except getopt.error, msg:
+ usage(1, msg)
+
+ outfile = None
+ # parse options
+ for opt, arg in opts:
+ if opt in ('-h', '--help'):
+ usage(0)
+ elif opt in ('-V', '--version'):
+ print >> sys.stderr, "msgfmt.py", __version__
+ sys.exit(0)
+ elif opt in ('-o', '--output-file'):
+ outfile = arg
+ # do it
+ if not args:
+ print >> sys.stderr, 'No input file given'
+ print >> sys.stderr, "Try `msgfmt --help' for more information."
+ return
+
+ for filename in args:
+ make(filename, outfile)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/pygettext.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/pygettext.py
new file mode 100644
index 0000000000..1cf01cb8e5
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/i18n/pygettext.py
@@ -0,0 +1,669 @@
+#! /usr/bin/env python
+# -*- coding: iso-8859-1 -*-
+# Originally written by Barry Warsaw <barry@zope.com>
+#
+# Minimally patched to make it even more xgettext compatible
+# by Peter Funk <pf@artcom-gmbh.de>
+#
+# 2002-11-22 Jürgen Hermann <jh@web.de>
+# Added checks that _() only contains string literals, and
+# command line args are resolved to module lists, i.e. you
+# can now pass a filename, a module or package name, or a
+# directory (including globbing chars, important for Win32).
+# Made docstring fit in 80 chars wide displays using pydoc.
+#
+
+# for selftesting
+try:
+ import fintl
+ _ = fintl.gettext
+except ImportError:
+ _ = lambda s: s
+
+__doc__ = _("""pygettext -- Python equivalent of xgettext(1)
+
+Many systems (Solaris, Linux, Gnu) provide extensive tools that ease the
+internationalization of C programs. Most of these tools are independent of
+the programming language and can be used from within Python programs.
+Martin von Loewis' work[1] helps considerably in this regard.
+
+There's one problem though; xgettext is the program that scans source code
+looking for message strings, but it groks only C (or C++). Python
+introduces a few wrinkles, such as dual quoting characters, triple quoted
+strings, and raw strings. xgettext understands none of this.
+
+Enter pygettext, which uses Python's standard tokenize module to scan
+Python source code, generating .pot files identical to what GNU xgettext[2]
+generates for C and C++ code. From there, the standard GNU tools can be
+used.
+
+A word about marking Python strings as candidates for translation. GNU
+xgettext recognizes the following keywords: gettext, dgettext, dcgettext,
+and gettext_noop. But those can be a lot of text to include all over your
+code. C and C++ have a trick: they use the C preprocessor. Most
+internationalized C source includes a #define for gettext() to _() so that
+what has to be written in the source is much less. Thus these are both
+translatable strings:
+
+ gettext("Translatable String")
+ _("Translatable String")
+
+Python of course has no preprocessor so this doesn't work so well. Thus,
+pygettext searches only for _() by default, but see the -k/--keyword flag
+below for how to augment this.
+
+ [1] http://www.python.org/workshops/1997-10/proceedings/loewis.html
+ [2] http://www.gnu.org/software/gettext/gettext.html
+
+NOTE: pygettext attempts to be option and feature compatible with GNU
+xgettext where ever possible. However some options are still missing or are
+not fully implemented. Also, xgettext's use of command line switches with
+option arguments is broken, and in these cases, pygettext just defines
+additional switches.
+
+Usage: pygettext [options] inputfile ...
+
+Options:
+
+ -a
+ --extract-all
+ Extract all strings.
+
+ -d name
+ --default-domain=name
+ Rename the default output file from messages.pot to name.pot.
+
+ -E
+ --escape
+ Replace non-ASCII characters with octal escape sequences.
+
+ -D
+ --docstrings
+ Extract module, class, method, and function docstrings. These do
+ not need to be wrapped in _() markers, and in fact cannot be for
+ Python to consider them docstrings. (See also the -X option).
+
+ -h
+ --help
+ Print this help message and exit.
+
+ -k word
+ --keyword=word
+ Keywords to look for in addition to the default set, which are:
+ %(DEFAULTKEYWORDS)s
+
+ You can have multiple -k flags on the command line.
+
+ -K
+ --no-default-keywords
+ Disable the default set of keywords (see above). Any keywords
+ explicitly added with the -k/--keyword option are still recognized.
+
+ --no-location
+ Do not write filename/lineno location comments.
+
+ -n
+ --add-location
+ Write filename/lineno location comments indicating where each
+ extracted string is found in the source. These lines appear before
+ each msgid. The style of comments is controlled by the -S/--style
+ option. This is the default.
+
+ -o filename
+ --output=filename
+ Rename the default output file from messages.pot to filename. If
+ filename is `-' then the output is sent to standard out.
+
+ -p dir
+ --output-dir=dir
+ Output files will be placed in directory dir.
+
+ -S stylename
+ --style stylename
+ Specify which style to use for location comments. Two styles are
+ supported:
+
+ Solaris # File: filename, line: line-number
+ GNU #: filename:line
+
+ The style name is case insensitive. GNU style is the default.
+
+ -v
+ --verbose
+ Print the names of the files being processed.
+
+ -V
+ --version
+ Print the version of pygettext and exit.
+
+ -w columns
+ --width=columns
+ Set width of output to columns.
+
+ -x filename
+ --exclude-file=filename
+ Specify a file that contains a list of strings that are not be
+ extracted from the input files. Each string to be excluded must
+ appear on a line by itself in the file.
+
+ -X filename
+ --no-docstrings=filename
+ Specify a file that contains a list of files (one per line) that
+ should not have their docstrings extracted. This is only useful in
+ conjunction with the -D option above.
+
+If `inputfile' is -, standard input is read.
+""")
+
+import os
+import imp
+import sys
+import glob
+import time
+import getopt
+import token
+import tokenize
+import operator
+
+__version__ = '1.5'
+
+default_keywords = ['_']
+DEFAULTKEYWORDS = ', '.join(default_keywords)
+
+EMPTYSTRING = ''
+
+
+
+# The normal pot-file header. msgmerge and Emacs's po-mode work better if it's
+# there.
+pot_header = _('''\
+# SOME DESCRIPTIVE TITLE.
+# Copyright (C) YEAR ORGANIZATION
+# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: PACKAGE VERSION\\n"
+"POT-Creation-Date: %(time)s\\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
+"Language-Team: LANGUAGE <LL@li.org>\\n"
+"MIME-Version: 1.0\\n"
+"Content-Type: text/plain; charset=CHARSET\\n"
+"Content-Transfer-Encoding: ENCODING\\n"
+"Generated-By: pygettext.py %(version)s\\n"
+
+''')
+
+
+def usage(code, msg=''):
+ print >> sys.stderr, __doc__ % globals()
+ if msg:
+ print >> sys.stderr, msg
+ sys.exit(code)
+
+
+
+escapes = []
+
+def make_escapes(pass_iso8859):
+ global escapes
+ if pass_iso8859:
+ # Allow iso-8859 characters to pass through so that e.g. 'msgid
+ # "Höhe"' would result not result in 'msgid "H\366he"'. Otherwise we
+ # escape any character outside the 32..126 range.
+ mod = 128
+ else:
+ mod = 256
+ for i in range(256):
+ if 32 <= (i % mod) <= 126:
+ escapes.append(chr(i))
+ else:
+ escapes.append("\\%03o" % i)
+ escapes[ord('\\')] = '\\\\'
+ escapes[ord('\t')] = '\\t'
+ escapes[ord('\r')] = '\\r'
+ escapes[ord('\n')] = '\\n'
+ escapes[ord('\"')] = '\\"'
+
+
+def escape(s):
+ global escapes
+ s = list(s)
+ for i in range(len(s)):
+ s[i] = escapes[ord(s[i])]
+ return EMPTYSTRING.join(s)
+
+
+def safe_eval(s):
+ # unwrap quotes, safely
+ return eval(s, {'__builtins__':{}}, {})
+
+
+def normalize(s):
+ # This converts the various Python string types into a format that is
+ # appropriate for .po files, namely much closer to C style.
+ lines = s.split('\n')
+ if len(lines) == 1:
+ s = '"' + escape(s) + '"'
+ else:
+ if not lines[-1]:
+ del lines[-1]
+ lines[-1] = lines[-1] + '\n'
+ for i in range(len(lines)):
+ lines[i] = escape(lines[i])
+ lineterm = '\\n"\n"'
+ s = '""\n"' + lineterm.join(lines) + '"'
+ return s
+
+
+def containsAny(str, set):
+ """Check whether 'str' contains ANY of the chars in 'set'"""
+ return 1 in [c in str for c in set]
+
+
+def _visit_pyfiles(list, dirname, names):
+ """Helper for getFilesForName()."""
+ # get extension for python source files
+ if not globals().has_key('_py_ext'):
+ global _py_ext
+ _py_ext = [triple[0] for triple in imp.get_suffixes()
+ if triple[2] == imp.PY_SOURCE][0]
+
+ # don't recurse into CVS directories
+ if 'CVS' in names:
+ names.remove('CVS')
+
+ # add all *.py files to list
+ list.extend(
+ [os.path.join(dirname, file) for file in names
+ if os.path.splitext(file)[1] == _py_ext]
+ )
+
+
+def _get_modpkg_path(dotted_name, pathlist=None):
+ """Get the filesystem path for a module or a package.
+
+ Return the file system path to a file for a module, and to a directory for
+ a package. Return None if the name is not found, or is a builtin or
+ extension module.
+ """
+ # split off top-most name
+ parts = dotted_name.split('.', 1)
+
+ if len(parts) > 1:
+ # we have a dotted path, import top-level package
+ try:
+ file, pathname, description = imp.find_module(parts[0], pathlist)
+ if file: file.close()
+ except ImportError:
+ return None
+
+ # check if it's indeed a package
+ if description[2] == imp.PKG_DIRECTORY:
+ # recursively handle the remaining name parts
+ pathname = _get_modpkg_path(parts[1], [pathname])
+ else:
+ pathname = None
+ else:
+ # plain name
+ try:
+ file, pathname, description = imp.find_module(
+ dotted_name, pathlist)
+ if file:
+ file.close()
+ if description[2] not in [imp.PY_SOURCE, imp.PKG_DIRECTORY]:
+ pathname = None
+ except ImportError:
+ pathname = None
+
+ return pathname
+
+
+def getFilesForName(name):
+ """Get a list of module files for a filename, a module or package name,
+ or a directory.
+ """
+ if not os.path.exists(name):
+ # check for glob chars
+ if containsAny(name, "*?[]"):
+ files = glob.glob(name)
+ list = []
+ for file in files:
+ list.extend(getFilesForName(file))
+ return list
+
+ # try to find module or package
+ name = _get_modpkg_path(name)
+ if not name:
+ return []
+
+ if os.path.isdir(name):
+ # find all python files in directory
+ list = []
+ os.path.walk(name, _visit_pyfiles, list)
+ return list
+ elif os.path.exists(name):
+ # a single file
+ return [name]
+
+ return []
+
+
+class TokenEater:
+ def __init__(self, options):
+ self.__options = options
+ self.__messages = {}
+ self.__state = self.__waiting
+ self.__data = []
+ self.__lineno = -1
+ self.__freshmodule = 1
+ self.__curfile = None
+
+ def __call__(self, ttype, tstring, stup, etup, line):
+ # dispatch
+## import token
+## print >> sys.stderr, 'ttype:', token.tok_name[ttype], \
+## 'tstring:', tstring
+ self.__state(ttype, tstring, stup[0])
+
+ def __waiting(self, ttype, tstring, lineno):
+ opts = self.__options
+ # Do docstring extractions, if enabled
+ if opts.docstrings and not opts.nodocstrings.get(self.__curfile):
+ # module docstring?
+ if self.__freshmodule:
+ if ttype == tokenize.STRING:
+ self.__addentry(safe_eval(tstring), lineno, isdocstring=1)
+ self.__freshmodule = 0
+ elif ttype not in (tokenize.COMMENT, tokenize.NL):
+ self.__freshmodule = 0
+ return
+ # class docstring?
+ if ttype == tokenize.NAME and tstring in ('class', 'def'):
+ self.__state = self.__suiteseen
+ return
+ if ttype == tokenize.NAME and tstring in opts.keywords:
+ self.__state = self.__keywordseen
+
+ def __suiteseen(self, ttype, tstring, lineno):
+ # ignore anything until we see the colon
+ if ttype == tokenize.OP and tstring == ':':
+ self.__state = self.__suitedocstring
+
+ def __suitedocstring(self, ttype, tstring, lineno):
+ # ignore any intervening noise
+ if ttype == tokenize.STRING:
+ self.__addentry(safe_eval(tstring), lineno, isdocstring=1)
+ self.__state = self.__waiting
+ elif ttype not in (tokenize.NEWLINE, tokenize.INDENT,
+ tokenize.COMMENT):
+ # there was no class docstring
+ self.__state = self.__waiting
+
+ def __keywordseen(self, ttype, tstring, lineno):
+ if ttype == tokenize.OP and tstring == '(':
+ self.__data = []
+ self.__lineno = lineno
+ self.__state = self.__openseen
+ else:
+ self.__state = self.__waiting
+
+ def __openseen(self, ttype, tstring, lineno):
+ if ttype == tokenize.OP and tstring == ')':
+ # We've seen the last of the translatable strings. Record the
+ # line number of the first line of the strings and update the list
+ # of messages seen. Reset state for the next batch. If there
+ # were no strings inside _(), then just ignore this entry.
+ if self.__data:
+ self.__addentry(EMPTYSTRING.join(self.__data))
+ self.__state = self.__waiting
+ elif ttype == tokenize.STRING:
+ self.__data.append(safe_eval(tstring))
+ elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
+ token.NEWLINE, tokenize.NL]:
+ # warn if we see anything else than STRING or whitespace
+ print >> sys.stderr, _(
+ '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"'
+ ) % {
+ 'token': tstring,
+ 'file': self.__curfile,
+ 'lineno': self.__lineno
+ }
+ self.__state = self.__waiting
+
+ def __addentry(self, msg, lineno=None, isdocstring=0):
+ if lineno is None:
+ lineno = self.__lineno
+ if not msg in self.__options.toexclude:
+ entry = (self.__curfile, lineno)
+ self.__messages.setdefault(msg, {})[entry] = isdocstring
+
+ def set_filename(self, filename):
+ self.__curfile = filename
+ self.__freshmodule = 1
+
+ def write(self, fp):
+ options = self.__options
+ timestamp = time.strftime('%Y-%m-%d %H:%M+%Z')
+ # The time stamp in the header doesn't have the same format as that
+ # generated by xgettext...
+ print >> fp, pot_header % {'time': timestamp, 'version': __version__}
+ # Sort the entries. First sort each particular entry's keys, then
+ # sort all the entries by their first item.
+ reverse = {}
+ for k, v in self.__messages.items():
+ keys = v.keys()
+ keys.sort()
+ reverse.setdefault(tuple(keys), []).append((k, v))
+ rkeys = reverse.keys()
+ rkeys.sort()
+ for rkey in rkeys:
+ rentries = reverse[rkey]
+ rentries.sort()
+ for k, v in rentries:
+ isdocstring = 0
+ # If the entry was gleaned out of a docstring, then add a
+ # comment stating so. This is to aid translators who may wish
+ # to skip translating some unimportant docstrings.
+ if reduce(operator.__add__, v.values()):
+ isdocstring = 1
+ # k is the message string, v is a dictionary-set of (filename,
+ # lineno) tuples. We want to sort the entries in v first by
+ # file name and then by line number.
+ v = v.keys()
+ v.sort()
+ if not options.writelocations:
+ pass
+ # location comments are different b/w Solaris and GNU:
+ elif options.locationstyle == options.SOLARIS:
+ for filename, lineno in v:
+ d = {'filename': filename, 'lineno': lineno}
+ print >>fp, _(
+ '# File: %(filename)s, line: %(lineno)d') % d
+ elif options.locationstyle == options.GNU:
+ # fit as many locations on one line, as long as the
+ # resulting line length doesn't exceeds 'options.width'
+ locline = '#:'
+ for filename, lineno in v:
+ d = {'filename': filename, 'lineno': lineno}
+ s = _(' %(filename)s:%(lineno)d') % d
+ if len(locline) + len(s) <= options.width:
+ locline = locline + s
+ else:
+ print >> fp, locline
+ locline = "#:" + s
+ if len(locline) > 2:
+ print >> fp, locline
+ if isdocstring:
+ print >> fp, '#, docstring'
+ print >> fp, 'msgid', normalize(k)
+ print >> fp, 'msgstr ""\n'
+
+
+
+def main():
+ global default_keywords
+ try:
+ opts, args = getopt.getopt(
+ sys.argv[1:],
+ 'ad:DEhk:Kno:p:S:Vvw:x:X:',
+ ['extract-all', 'default-domain=', 'escape', 'help',
+ 'keyword=', 'no-default-keywords',
+ 'add-location', 'no-location', 'output=', 'output-dir=',
+ 'style=', 'verbose', 'version', 'width=', 'exclude-file=',
+ 'docstrings', 'no-docstrings',
+ ])
+ except getopt.error, msg:
+ usage(1, msg)
+
+ # for holding option values
+ class Options:
+ # constants
+ GNU = 1
+ SOLARIS = 2
+ # defaults
+ extractall = 0 # FIXME: currently this option has no effect at all.
+ escape = 0
+ keywords = []
+ outpath = ''
+ outfile = 'messages.pot'
+ writelocations = 1
+ locationstyle = GNU
+ verbose = 0
+ width = 78
+ excludefilename = ''
+ docstrings = 0
+ nodocstrings = {}
+
+ options = Options()
+ locations = {'gnu' : options.GNU,
+ 'solaris' : options.SOLARIS,
+ }
+
+ # parse options
+ for opt, arg in opts:
+ if opt in ('-h', '--help'):
+ usage(0)
+ elif opt in ('-a', '--extract-all'):
+ options.extractall = 1
+ elif opt in ('-d', '--default-domain'):
+ options.outfile = arg + '.pot'
+ elif opt in ('-E', '--escape'):
+ options.escape = 1
+ elif opt in ('-D', '--docstrings'):
+ options.docstrings = 1
+ elif opt in ('-k', '--keyword'):
+ options.keywords.append(arg)
+ elif opt in ('-K', '--no-default-keywords'):
+ default_keywords = []
+ elif opt in ('-n', '--add-location'):
+ options.writelocations = 1
+ elif opt in ('--no-location',):
+ options.writelocations = 0
+ elif opt in ('-S', '--style'):
+ options.locationstyle = locations.get(arg.lower())
+ if options.locationstyle is None:
+ usage(1, _('Invalid value for --style: %s') % arg)
+ elif opt in ('-o', '--output'):
+ options.outfile = arg
+ elif opt in ('-p', '--output-dir'):
+ options.outpath = arg
+ elif opt in ('-v', '--verbose'):
+ options.verbose = 1
+ elif opt in ('-V', '--version'):
+ print _('pygettext.py (xgettext for Python) %s') % __version__
+ sys.exit(0)
+ elif opt in ('-w', '--width'):
+ try:
+ options.width = int(arg)
+ except ValueError:
+ usage(1, _('--width argument must be an integer: %s') % arg)
+ elif opt in ('-x', '--exclude-file'):
+ options.excludefilename = arg
+ elif opt in ('-X', '--no-docstrings'):
+ fp = open(arg)
+ try:
+ while 1:
+ line = fp.readline()
+ if not line:
+ break
+ options.nodocstrings[line[:-1]] = 1
+ finally:
+ fp.close()
+
+ # calculate escapes
+ make_escapes(options.escape)
+
+ # calculate all keywords
+ options.keywords.extend(default_keywords)
+
+ # initialize list of strings to exclude
+ if options.excludefilename:
+ try:
+ fp = open(options.excludefilename)
+ options.toexclude = fp.readlines()
+ fp.close()
+ except IOError:
+ print >> sys.stderr, _(
+ "Can't read --exclude-file: %s") % options.excludefilename
+ sys.exit(1)
+ else:
+ options.toexclude = []
+
+ # resolve args to module lists
+ expanded = []
+ for arg in args:
+ if arg == '-':
+ expanded.append(arg)
+ else:
+ expanded.extend(getFilesForName(arg))
+ args = expanded
+
+ # slurp through all the files
+ eater = TokenEater(options)
+ for filename in args:
+ if filename == '-':
+ if options.verbose:
+ print _('Reading standard input')
+ fp = sys.stdin
+ closep = 0
+ else:
+ if options.verbose:
+ print _('Working on %s') % filename
+ fp = open(filename)
+ closep = 1
+ try:
+ eater.set_filename(filename)
+ try:
+ tokenize.tokenize(fp.readline, eater)
+ except tokenize.TokenError, e:
+ print >> sys.stderr, '%s: %s, line %d, column %d' % (
+ e[0], filename, e[1][0], e[1][1])
+ finally:
+ if closep:
+ fp.close()
+
+ # write the output
+ if options.outfile == '-':
+ fp = sys.stdout
+ closep = 0
+ else:
+ if options.outpath:
+ options.outfile = os.path.join(options.outpath, options.outfile)
+ fp = open(options.outfile, 'w')
+ closep = 1
+ try:
+ eater.write(fp)
+ finally:
+ if closep:
+ fp.close()
+
+
+if __name__ == '__main__':
+ main()
+ # some more test strings
+ _(u'a unicode string')
+ # this one creates a warning
+ _('*** Seen unexpected token "%(token)s"') % {'token': 'test'}
+ _('more' 'than' 'one' 'string')
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/iobench/iobench.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/iobench/iobench.py
new file mode 100644
index 0000000000..801e53abb5
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/iobench/iobench.py
@@ -0,0 +1,539 @@
+# -*- coding: utf-8 -*-
+# This file should be kept compatible with both Python 2.6 and Python >= 3.0.
+
+import time
+import os
+import re
+import sys
+import hashlib
+import functools
+import itertools
+from optparse import OptionParser
+
+out = sys.stdout
+
+TEXT_ENCODING = 'utf8'
+NEWLINES = 'lf'
+
+# Compatibility
+try:
+ xrange
+except NameError:
+ xrange = range
+
+def text_open(fn, mode, encoding=None):
+ try:
+ return open(fn, mode, encoding=encoding or TEXT_ENCODING)
+ except TypeError:
+ return open(fn, mode)
+
+def get_file_sizes():
+ for s in ['20 KB', '400 KB', '10 MB']:
+ size, unit = s.split()
+ size = int(size) * {'KB': 1024, 'MB': 1024 ** 2}[unit]
+ yield s.replace(' ', ''), size
+
+def get_binary_files():
+ return ((name + ".bin", size) for name, size in get_file_sizes())
+
+def get_text_files():
+ return (("%s-%s-%s.txt" % (name, TEXT_ENCODING, NEWLINES), size)
+ for name, size in get_file_sizes())
+
+def with_open_mode(mode):
+ def decorate(f):
+ f.file_open_mode = mode
+ return f
+ return decorate
+
+def with_sizes(*sizes):
+ def decorate(f):
+ f.file_sizes = sizes
+ return f
+ return decorate
+
+
+# Here begin the tests
+
+@with_open_mode("r")
+@with_sizes("medium")
+def read_bytewise(f):
+ """ read one unit at a time """
+ f.seek(0)
+ while f.read(1):
+ pass
+
+@with_open_mode("r")
+@with_sizes("medium")
+def read_small_chunks(f):
+ """ read 20 units at a time """
+ f.seek(0)
+ while f.read(20):
+ pass
+
+@with_open_mode("r")
+@with_sizes("medium")
+def read_big_chunks(f):
+ """ read 4096 units at a time """
+ f.seek(0)
+ while f.read(4096):
+ pass
+
+@with_open_mode("r")
+@with_sizes("small", "medium", "large")
+def read_whole_file(f):
+ """ read whole contents at once """
+ f.seek(0)
+ while f.read():
+ pass
+
+@with_open_mode("rt")
+@with_sizes("medium")
+def read_lines(f):
+ """ read one line at a time """
+ f.seek(0)
+ for line in f:
+ pass
+
+@with_open_mode("r")
+@with_sizes("medium")
+def seek_forward_bytewise(f):
+ """ seek forward one unit at a time """
+ f.seek(0, 2)
+ size = f.tell()
+ f.seek(0, 0)
+ for i in xrange(0, size - 1):
+ f.seek(i, 0)
+
+@with_open_mode("r")
+@with_sizes("medium")
+def seek_forward_blockwise(f):
+ """ seek forward 1000 units at a time """
+ f.seek(0, 2)
+ size = f.tell()
+ f.seek(0, 0)
+ for i in xrange(0, size - 1, 1000):
+ f.seek(i, 0)
+
+@with_open_mode("rb")
+@with_sizes("medium")
+def read_seek_bytewise(f):
+ """ alternate read & seek one unit """
+ f.seek(0)
+ while f.read(1):
+ f.seek(1, 1)
+
+@with_open_mode("rb")
+@with_sizes("medium")
+def read_seek_blockwise(f):
+ """ alternate read & seek 1000 units """
+ f.seek(0)
+ while f.read(1000):
+ f.seek(1000, 1)
+
+
+@with_open_mode("w")
+@with_sizes("small")
+def write_bytewise(f, source):
+ """ write one unit at a time """
+ for i in xrange(0, len(source)):
+ f.write(source[i:i+1])
+
+@with_open_mode("w")
+@with_sizes("medium")
+def write_small_chunks(f, source):
+ """ write 20 units at a time """
+ for i in xrange(0, len(source), 20):
+ f.write(source[i:i+20])
+
+@with_open_mode("w")
+@with_sizes("medium")
+def write_medium_chunks(f, source):
+ """ write 4096 units at a time """
+ for i in xrange(0, len(source), 4096):
+ f.write(source[i:i+4096])
+
+@with_open_mode("w")
+@with_sizes("large")
+def write_large_chunks(f, source):
+ """ write 1e6 units at a time """
+ for i in xrange(0, len(source), 1000000):
+ f.write(source[i:i+1000000])
+
+
+@with_open_mode("w+")
+@with_sizes("small")
+def modify_bytewise(f, source):
+ """ modify one unit at a time """
+ f.seek(0)
+ for i in xrange(0, len(source)):
+ f.write(source[i:i+1])
+
+@with_open_mode("w+")
+@with_sizes("medium")
+def modify_small_chunks(f, source):
+ """ modify 20 units at a time """
+ f.seek(0)
+ for i in xrange(0, len(source), 20):
+ f.write(source[i:i+20])
+
+@with_open_mode("w+")
+@with_sizes("medium")
+def modify_medium_chunks(f, source):
+ """ modify 4096 units at a time """
+ f.seek(0)
+ for i in xrange(0, len(source), 4096):
+ f.write(source[i:i+4096])
+
+@with_open_mode("wb+")
+@with_sizes("medium")
+def modify_seek_forward_bytewise(f, source):
+ """ alternate write & seek one unit """
+ f.seek(0)
+ for i in xrange(0, len(source), 2):
+ f.write(source[i:i+1])
+ f.seek(i+2)
+
+@with_open_mode("wb+")
+@with_sizes("medium")
+def modify_seek_forward_blockwise(f, source):
+ """ alternate write & seek 1000 units """
+ f.seek(0)
+ for i in xrange(0, len(source), 2000):
+ f.write(source[i:i+1000])
+ f.seek(i+2000)
+
+# XXX the 2 following tests don't work with py3k's text IO
+@with_open_mode("wb+")
+@with_sizes("medium")
+def read_modify_bytewise(f, source):
+ """ alternate read & write one unit """
+ f.seek(0)
+ for i in xrange(0, len(source), 2):
+ f.read(1)
+ f.write(source[i+1:i+2])
+
+@with_open_mode("wb+")
+@with_sizes("medium")
+def read_modify_blockwise(f, source):
+ """ alternate read & write 1000 units """
+ f.seek(0)
+ for i in xrange(0, len(source), 2000):
+ f.read(1000)
+ f.write(source[i+1000:i+2000])
+
+
+read_tests = [
+ read_bytewise, read_small_chunks, read_lines, read_big_chunks,
+ None, read_whole_file, None,
+ seek_forward_bytewise, seek_forward_blockwise,
+ read_seek_bytewise, read_seek_blockwise,
+]
+
+write_tests = [
+ write_bytewise, write_small_chunks, write_medium_chunks, write_large_chunks,
+]
+
+modify_tests = [
+ modify_bytewise, modify_small_chunks, modify_medium_chunks,
+ None,
+ modify_seek_forward_bytewise, modify_seek_forward_blockwise,
+ read_modify_bytewise, read_modify_blockwise,
+]
+
+def run_during(duration, func):
+ _t = time.time
+ n = 0
+ start = os.times()
+ start_timestamp = _t()
+ real_start = start[4] or start_timestamp
+ while True:
+ func()
+ n += 1
+ if _t() - start_timestamp > duration:
+ break
+ end = os.times()
+ real = (end[4] if start[4] else time.time()) - real_start
+ return n, real, sum(end[0:2]) - sum(start[0:2])
+
+def warm_cache(filename):
+ with open(filename, "rb") as f:
+ f.read()
+
+
+def run_all_tests(options):
+ def print_label(filename, func):
+ name = re.split(r'[-.]', filename)[0]
+ out.write(
+ ("[%s] %s... "
+ % (name.center(7), func.__doc__.strip())
+ ).ljust(52))
+ out.flush()
+
+ def print_results(size, n, real, cpu):
+ bw = n * float(size) / 1024 ** 2 / real
+ bw = ("%4d MB/s" if bw > 100 else "%.3g MB/s") % bw
+ out.write(bw.rjust(12) + "\n")
+ if cpu < 0.90 * real:
+ out.write(" warning: test above used only %d%% CPU, "
+ "result may be flawed!\n" % (100.0 * cpu / real))
+
+ def run_one_test(name, size, open_func, test_func, *args):
+ mode = test_func.file_open_mode
+ print_label(name, test_func)
+ if "w" not in mode or "+" in mode:
+ warm_cache(name)
+ with open_func(name) as f:
+ n, real, cpu = run_during(1.5, lambda: test_func(f, *args))
+ print_results(size, n, real, cpu)
+
+ def run_test_family(tests, mode_filter, files, open_func, *make_args):
+ for test_func in tests:
+ if test_func is None:
+ out.write("\n")
+ continue
+ if mode_filter in test_func.file_open_mode:
+ continue
+ for s in test_func.file_sizes:
+ name, size = files[size_names[s]]
+ #name += file_ext
+ args = tuple(f(name, size) for f in make_args)
+ run_one_test(name, size,
+ open_func, test_func, *args)
+
+ size_names = {
+ "small": 0,
+ "medium": 1,
+ "large": 2,
+ }
+
+ binary_files = list(get_binary_files())
+ text_files = list(get_text_files())
+ if "b" in options:
+ print("Binary unit = one byte")
+ if "t" in options:
+ print("Text unit = one character (%s-decoded)" % TEXT_ENCODING)
+
+ # Binary reads
+ if "b" in options and "r" in options:
+ print("\n** Binary input **\n")
+ run_test_family(read_tests, "t", binary_files, lambda fn: open(fn, "rb"))
+
+ # Text reads
+ if "t" in options and "r" in options:
+ print("\n** Text input **\n")
+ run_test_family(read_tests, "b", text_files, lambda fn: text_open(fn, "r"))
+
+ # Binary writes
+ if "b" in options and "w" in options:
+ print("\n** Binary append **\n")
+ def make_test_source(name, size):
+ with open(name, "rb") as f:
+ return f.read()
+ run_test_family(write_tests, "t", binary_files,
+ lambda fn: open(os.devnull, "wb"), make_test_source)
+
+ # Text writes
+ if "t" in options and "w" in options:
+ print("\n** Text append **\n")
+ def make_test_source(name, size):
+ with text_open(name, "r") as f:
+ return f.read()
+ run_test_family(write_tests, "b", text_files,
+ lambda fn: text_open(os.devnull, "w"), make_test_source)
+
+ # Binary overwrites
+ if "b" in options and "w" in options:
+ print("\n** Binary overwrite **\n")
+ def make_test_source(name, size):
+ with open(name, "rb") as f:
+ return f.read()
+ run_test_family(modify_tests, "t", binary_files,
+ lambda fn: open(fn, "r+b"), make_test_source)
+
+ # Text overwrites
+ if "t" in options and "w" in options:
+ print("\n** Text overwrite **\n")
+ def make_test_source(name, size):
+ with text_open(name, "r") as f:
+ return f.read()
+ run_test_family(modify_tests, "b", text_files,
+ lambda fn: open(fn, "r+"), make_test_source)
+
+
+def prepare_files():
+ print("Preparing files...")
+ # Binary files
+ for name, size in get_binary_files():
+ if os.path.isfile(name) and os.path.getsize(name) == size:
+ continue
+ with open(name, "wb") as f:
+ f.write(os.urandom(size))
+ # Text files
+ chunk = []
+ with text_open(__file__, "rU", encoding='utf8') as f:
+ for line in f:
+ if line.startswith("# <iobench text chunk marker>"):
+ break
+ else:
+ raise RuntimeError(
+ "Couldn't find chunk marker in %s !" % __file__)
+ if NEWLINES == "all":
+ it = itertools.cycle(["\n", "\r", "\r\n"])
+ else:
+ it = itertools.repeat(
+ {"cr": "\r", "lf": "\n", "crlf": "\r\n"}[NEWLINES])
+ chunk = "".join(line.replace("\n", next(it)) for line in f)
+ if isinstance(chunk, bytes):
+ chunk = chunk.decode('utf8')
+ chunk = chunk.encode(TEXT_ENCODING)
+ for name, size in get_text_files():
+ if os.path.isfile(name) and os.path.getsize(name) == size:
+ continue
+ head = chunk * (size // len(chunk))
+ tail = chunk[:size % len(chunk)]
+ # Adjust tail to end on a character boundary
+ while True:
+ try:
+ tail.decode(TEXT_ENCODING)
+ break
+ except UnicodeDecodeError:
+ tail = tail[:-1]
+ with open(name, "wb") as f:
+ f.write(head)
+ f.write(tail)
+
+def main():
+ global TEXT_ENCODING, NEWLINES
+
+ usage = "usage: %prog [-h|--help] [options]"
+ parser = OptionParser(usage=usage)
+ parser.add_option("-b", "--binary",
+ action="store_true", dest="binary", default=False,
+ help="run binary I/O tests")
+ parser.add_option("-t", "--text",
+ action="store_true", dest="text", default=False,
+ help="run text I/O tests")
+ parser.add_option("-r", "--read",
+ action="store_true", dest="read", default=False,
+ help="run read tests")
+ parser.add_option("-w", "--write",
+ action="store_true", dest="write", default=False,
+ help="run write & modify tests")
+ parser.add_option("-E", "--encoding",
+ action="store", dest="encoding", default=None,
+ help="encoding for text tests (default: %s)" % TEXT_ENCODING)
+ parser.add_option("-N", "--newlines",
+ action="store", dest="newlines", default='lf',
+ help="line endings for text tests "
+ "(one of: {lf (default), cr, crlf, all})")
+ options, args = parser.parse_args()
+ if args:
+ parser.error("unexpected arguments")
+ NEWLINES = options.newlines.lower()
+ if NEWLINES not in ('lf', 'cr', 'crlf', 'all'):
+ parser.error("invalid 'newlines' option: %r" % NEWLINES)
+
+ test_options = ""
+ if options.read:
+ test_options += "r"
+ if options.write:
+ test_options += "w"
+ elif not options.read:
+ test_options += "rw"
+ if options.text:
+ test_options += "t"
+ if options.binary:
+ test_options += "b"
+ elif not options.text:
+ test_options += "tb"
+
+ if options.encoding:
+ TEXT_ENCODING = options.encoding
+
+ prepare_files()
+ run_all_tests(test_options)
+
+if __name__ == "__main__":
+ main()
+
+
+# -- This part to exercise text reading. Don't change anything! --
+# <iobench text chunk marker>
+
+"""
+1.
+Gáttir allar,
+áðr gangi fram,
+um skoðask skyli,
+um skyggnast skyli,
+því at óvíst er at vita,
+hvar óvinir
+sitja á fleti fyrir.
+
+2.
+Gefendr heilir!
+Gestr er inn kominn,
+hvar skal sitja sjá?
+Mjök er bráðr,
+sá er á bröndum skal
+síns of freista frama.
+
+3.
+Elds er þörf,
+þeims inn er kominn
+ok á kné kalinn;
+matar ok váða
+er manni þörf,
+þeim er hefr um fjall farit.
+
+4.
+Vatns er þörf,
+þeim er til verðar kemr,
+þerru ok þjóðlaðar,
+góðs of æðis,
+ef sér geta mætti,
+orðs ok endrþögu.
+
+5.
+Vits er þörf,
+þeim er víða ratar;
+dælt er heima hvat;
+at augabragði verðr,
+sá er ekki kann
+ok með snotrum sitr.
+
+6.
+At hyggjandi sinni
+skyli-t maðr hræsinn vera,
+heldr gætinn at geði;
+þá er horskr ok þögull
+kemr heimisgarða til,
+sjaldan verðr víti vörum,
+því at óbrigðra vin
+fær maðr aldregi
+en mannvit mikit.
+
+7.
+Inn vari gestr,
+er til verðar kemr,
+þunnu hljóði þegir,
+eyrum hlýðir,
+en augum skoðar;
+svá nýsisk fróðra hverr fyrir.
+
+8.
+Hinn er sæll,
+er sér of getr
+lof ok líknstafi;
+ódælla er við þat,
+er maðr eiga skal
+annars brjóstum í.
+"""
+
+"""
+C'est revenir tard, je le sens, sur un sujet trop rebattu et déjà presque oublié. Mon état, qui ne me permet plus aucun travail suivi, mon aversion pour le genre polémique, ont causé ma lenteur à écrire et ma répugnance à publier. J'aurais même tout à fait supprimé ces Lettres, ou plutôt je lie les aurais point écrites, s'il n'eût été question que de moi : Mais ma patrie ne m'est pas tellement devenue étrangère que je puisse voir tranquillement opprimer ses citoyens, surtout lorsqu'ils n'ont compromis leurs droits qu'en défendant ma cause. Je serais le dernier des hommes si dans une telle occasion j'écoutais un sentiment qui n'est plus ni douceur ni patience, mais faiblesse et lâcheté, dans celui qu'il empêche de remplir son devoir.
+Rien de moins important pour le public, j'en conviens, que la matière de ces lettres. La constitution d'une petite République, le sort d'un petit particulier, l'exposé de quelques injustices, la réfutation de quelques sophismes ; tout cela n'a rien en soi d'assez considérable pour mériter beaucoup de lecteurs : mais si mes sujets sont petits mes objets sont grands, et dignes de l'attention de tout honnête homme. Laissons Genève à sa place, et Rousseau dans sa dépression ; mais la religion, mais la liberté, la justice ! voilà, qui que vous soyez, ce qui n'est pas au-dessous de vous.
+Qu'on ne cherche pas même ici dans le style le dédommagement de l'aridité de la matière. Ceux que quelques traits heureux de ma plume ont si fort irrités trouveront de quoi s'apaiser dans ces lettres, L'honneur de défendre un opprimé eût enflammé mon coeur si j'avais parlé pour un autre. Réduit au triste emploi de me défendre moi-même, j'ai dû me borner à raisonner ; m'échauffer eût été m'avilir. J'aurai donc trouvé grâce en ce point devant ceux qui s'imaginent qu'il est essentiel à la vérité d'être dite froidement ; opinion que pourtant j'ai peine à comprendre. Lorsqu'une vive persuasion nous anime, le moyen d'employer un langage glacé ? Quand Archimède tout transporté courait nu dans les rues de Syracuse, en avait-il moins trouvé la vérité parce qu'il se passionnait pour elle ? Tout au contraire, celui qui la sent ne peut s'abstenir de l'adorer ; celui qui demeure froid ne l'a pas vue.
+Quoi qu'il en soit, je prie les lecteurs de vouloir bien mettre à part mon beau style, et d'examiner seulement si je raisonne bien ou mal ; car enfin, de cela seul qu'un auteur s'exprime en bons termes, je ne vois pas comment il peut s'ensuivre que cet auteur ne sait ce qu'il dit.
+"""
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/README.txt b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/README.txt
new file mode 100644
index 0000000000..1a6961c050
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/README.txt
@@ -0,0 +1,25 @@
+Packaging Python as a Microsoft Installer Package (MSI)
+=======================================================
+
+Using this library, Python can be packaged as a MS-Windows
+MSI file. To generate an installer package, you need
+a build tree. By default, the build tree root directory
+is assumed to be in "../..". This location can be changed
+by adding a file config.py; see the beginning of msi.py
+for additional customization options.
+
+The packaging process assumes that binaries have been
+generated according to the instructions in PCBuild/README.txt,
+and that you have either Visual Studio or the Platform SDK
+installed. In addition, you need the Python COM extensions,
+either from PythonWin, or from ActivePython.
+
+To invoke the script, open a cmd.exe window which has
+cabarc.exe in its PATH (e.g. "Visual Studio .NET 2003
+Command Prompt"). Then invoke
+
+<path-to-python.exe> msi.py
+
+If everything succeeds, pythonX.Y.Z.msi is generated
+in the current directory.
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/crtlicense.txt b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/crtlicense.txt
new file mode 100644
index 0000000000..79294f2a3f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/crtlicense.txt
@@ -0,0 +1,44 @@
+
+
+Additional Conditions for this Windows binary build
+---------------------------------------------------
+
+This program is linked with and uses Microsoft Distributable Code,
+copyrighted by Microsoft Corporation. The Microsoft Distributable Code
+includes the following files:
+
+msvcr90.dll
+msvcp90.dll
+msvcm90.dll
+
+If you further distribute programs that include the Microsoft
+Distributable Code, you must comply with the restrictions on
+distribution specified by Microsoft. In particular, you must require
+distributors and external end users to agree to terms that protect the
+Microsoft Distributable Code at least as much as Microsoft's own
+requirements for the Distributable Code. See Microsoft's documentation
+(included in its developer tools and on its website at microsoft.com)
+for specific details.
+
+Redistribution of the Windows binary build of the Python interpreter
+complies with this agreement, provided that you do not:
+
+- alter any copyright, trademark or patent notice in Microsoft's
+Distributable Code;
+
+- use Microsoft's trademarks in your programs' names or in a way that
+suggests your programs come from or are endorsed by Microsoft;
+
+- distribute Microsoft's Distributable Code to run on a platform other
+than Microsoft operating systems, run-time technologies or application
+platforms; or
+
+- include Microsoft Distributable Code in malicious, deceptive or
+unlawful programs.
+
+These restrictions apply only to the Microsoft Distributable Code as
+defined above, not to Python itself or any programs running on the
+Python interpreter. The redistribution of the Python interpreter and
+libraries is governed by the Python Software License included with this
+file, or by other licenses as marked.
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msi.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msi.py
new file mode 100644
index 0000000000..c5bf6ec4f9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msi.py
@@ -0,0 +1,1398 @@
+# Python MSI Generator
+# (C) 2003 Martin v. Loewis
+# See "FOO" in comments refers to MSDN sections with the title FOO.
+import msilib, schema, sequence, os, glob, time, re, shutil, zipfile
+from msilib import Feature, CAB, Directory, Dialog, Binary, add_data
+import uisample
+from win32com.client import constants
+from distutils.spawn import find_executable
+from uuids import product_codes
+import tempfile
+
+# Settings can be overridden in config.py below
+# 0 for official python.org releases
+# 1 for intermediate releases by anybody, with
+# a new product code for every package.
+snapshot = 1
+# 1 means that file extension is px, not py,
+# and binaries start with x
+testpackage = 0
+# Location of build tree
+srcdir = os.path.abspath("../..")
+# Text to be displayed as the version in dialogs etc.
+# goes into file name and ProductCode. Defaults to
+# current_version.day for Snapshot, current_version otherwise
+full_current_version = None
+# Is Tcl available at all?
+have_tcl = True
+# path to PCbuild directory
+PCBUILD="PCbuild"
+# msvcrt version
+MSVCR = "90"
+# Name of certificate in default store to sign MSI with
+certname = None
+# Make a zip file containing the PDB files for this build?
+pdbzip = True
+
+try:
+ from config import *
+except ImportError:
+ pass
+
+# Extract current version from Include/patchlevel.h
+lines = open(srcdir + "/Include/patchlevel.h").readlines()
+major = minor = micro = level = serial = None
+levels = {
+ 'PY_RELEASE_LEVEL_ALPHA':0xA,
+ 'PY_RELEASE_LEVEL_BETA': 0xB,
+ 'PY_RELEASE_LEVEL_GAMMA':0xC,
+ 'PY_RELEASE_LEVEL_FINAL':0xF
+ }
+for l in lines:
+ if not l.startswith("#define"):
+ continue
+ l = l.split()
+ if len(l) != 3:
+ continue
+ _, name, value = l
+ if name == 'PY_MAJOR_VERSION': major = value
+ if name == 'PY_MINOR_VERSION': minor = value
+ if name == 'PY_MICRO_VERSION': micro = value
+ if name == 'PY_RELEASE_LEVEL': level = levels[value]
+ if name == 'PY_RELEASE_SERIAL': serial = value
+
+short_version = major+"."+minor
+# See PC/make_versioninfo.c
+FIELD3 = 1000*int(micro) + 10*level + int(serial)
+current_version = "%s.%d" % (short_version, FIELD3)
+
+# This should never change. The UpgradeCode of this package can be
+# used in the Upgrade table of future packages to make the future
+# package replace this one. See "UpgradeCode Property".
+# upgrade_code gets set to upgrade_code_64 when we have determined
+# that the target is Win64.
+upgrade_code_snapshot='{92A24481-3ECB-40FC-8836-04B7966EC0D5}'
+upgrade_code='{65E6DE48-A358-434D-AA4F-4AF72DB4718F}'
+upgrade_code_64='{6A965A0C-6EE6-4E3A-9983-3263F56311EC}'
+
+if snapshot:
+ current_version = "%s.%s.%s" % (major, minor, int(time.time()/3600/24))
+ product_code = msilib.gen_uuid()
+else:
+ product_code = product_codes[current_version]
+
+if full_current_version is None:
+ full_current_version = current_version
+
+extensions = [
+ 'bz2.pyd',
+ 'pyexpat.pyd',
+ 'select.pyd',
+ 'unicodedata.pyd',
+ 'winsound.pyd',
+ '_elementtree.pyd',
+ '_bsddb.pyd',
+ '_socket.pyd',
+ '_ssl.pyd',
+ '_testcapi.pyd',
+ '_tkinter.pyd',
+ '_msi.pyd',
+ '_ctypes.pyd',
+ '_ctypes_test.pyd',
+ '_sqlite3.pyd',
+ '_hashlib.pyd',
+ '_multiprocessing.pyd'
+]
+
+# Well-known component UUIDs
+# These are needed for SharedDLLs reference counter; if
+# a different UUID was used for each incarnation of, say,
+# python24.dll, an upgrade would set the reference counter
+# from 1 to 2 (due to what I consider a bug in MSI)
+# Using the same UUID is fine since these files are versioned,
+# so Installer will always keep the newest version.
+# NOTE: All uuids are self generated.
+pythondll_uuid = {
+ "24":"{9B81E618-2301-4035-AC77-75D9ABEB7301}",
+ "25":"{2e41b118-38bd-4c1b-a840-6977efd1b911}",
+ "26":"{34ebecac-f046-4e1c-b0e3-9bac3cdaacfa}",
+ "27":"{4fe21c76-1760-437b-a2f2-99909130a175}",
+ } [major+minor]
+
+# Compute the name that Sphinx gives to the docfile
+docfile = ""
+if int(micro):
+ docfile = micro
+if level < 0xf:
+ if level == 0xC:
+ docfile += "rc%s" % (serial,)
+ else:
+ docfile += '%x%s' % (level, serial)
+docfile = 'python%s%s%s.chm' % (major, minor, docfile)
+
+# Build the mingw import library, libpythonXY.a
+# This requires 'nm' and 'dlltool' executables on your PATH
+def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib):
+ warning = "WARNING: %s - libpythonXX.a not built"
+ nm = find_executable('nm')
+ dlltool = find_executable('dlltool')
+
+ if not nm or not dlltool:
+ print warning % "nm and/or dlltool were not found"
+ return False
+
+ nm_command = '%s -Cs %s' % (nm, lib_file)
+ dlltool_command = "%s --dllname %s --def %s --output-lib %s" % \
+ (dlltool, dll_file, def_file, mingw_lib)
+ export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match
+
+ f = open(def_file,'w')
+ print >>f, "LIBRARY %s" % dll_file
+ print >>f, "EXPORTS"
+
+ nm_pipe = os.popen(nm_command)
+ for line in nm_pipe.readlines():
+ m = export_match(line)
+ if m:
+ print >>f, m.group(1)
+ f.close()
+ exit = nm_pipe.close()
+
+ if exit:
+ print warning % "nm did not run successfully"
+ return False
+
+ if os.system(dlltool_command) != 0:
+ print warning % "dlltool did not run successfully"
+ return False
+
+ return True
+
+# Target files (.def and .a) go in PCBuild directory
+lib_file = os.path.join(srcdir, PCBUILD, "python%s%s.lib" % (major, minor))
+def_file = os.path.join(srcdir, PCBUILD, "python%s%s.def" % (major, minor))
+dll_file = "python%s%s.dll" % (major, minor)
+mingw_lib = os.path.join(srcdir, PCBUILD, "libpython%s%s.a" % (major, minor))
+
+have_mingw = build_mingw_lib(lib_file, def_file, dll_file, mingw_lib)
+
+# Determine the target architecture
+dll_path = os.path.join(srcdir, PCBUILD, dll_file)
+msilib.set_arch_from_file(dll_path)
+if msilib.pe_type(dll_path) != msilib.pe_type("msisupport.dll"):
+ raise SystemError, "msisupport.dll for incorrect architecture"
+if msilib.Win64:
+ upgrade_code = upgrade_code_64
+ # Bump the last digit of the code by one, so that 32-bit and 64-bit
+ # releases get separate product codes
+ digit = hex((int(product_code[-2],16)+1)%16)[-1]
+ product_code = product_code[:-2] + digit + '}'
+
+if testpackage:
+ ext = 'px'
+ testprefix = 'x'
+else:
+ ext = 'py'
+ testprefix = ''
+
+if msilib.Win64:
+ SystemFolderName = "[System64Folder]"
+ registry_component = 4|256
+else:
+ SystemFolderName = "[SystemFolder]"
+ registry_component = 4
+
+msilib.reset()
+
+# condition in which to install pythonxy.dll in system32:
+# a) it is Windows 9x or
+# b) it is NT, the user is privileged, and has chosen per-machine installation
+sys32cond = "(Windows9x or (Privileged and ALLUSERS))"
+
+def build_database():
+ """Generate an empty database, with just the schema and the
+ Summary information stream."""
+ if snapshot:
+ uc = upgrade_code_snapshot
+ else:
+ uc = upgrade_code
+ if msilib.Win64:
+ productsuffix = " (64-bit)"
+ else:
+ productsuffix = ""
+ # schema represents the installer 2.0 database schema.
+ # sequence is the set of standard sequences
+ # (ui/execute, admin/advt/install)
+ msiname = "python-%s%s.msi" % (full_current_version, msilib.arch_ext)
+ db = msilib.init_database(msiname,
+ schema, ProductName="Python "+full_current_version+productsuffix,
+ ProductCode=product_code,
+ ProductVersion=current_version,
+ Manufacturer=u"Python Software Foundation",
+ request_uac = True)
+ # The default sequencing of the RemoveExistingProducts action causes
+ # removal of files that got just installed. Place it after
+ # InstallInitialize, so we first uninstall everything, but still roll
+ # back in case the installation is interrupted
+ msilib.change_sequence(sequence.InstallExecuteSequence,
+ "RemoveExistingProducts", 1510)
+ msilib.add_tables(db, sequence)
+ # We cannot set ALLUSERS in the property table, as this cannot be
+ # reset if the user choses a per-user installation. Instead, we
+ # maintain WhichUsers, which can be "ALL" or "JUSTME". The UI manages
+ # this property, and when the execution starts, ALLUSERS is set
+ # accordingly.
+ add_data(db, "Property", [("UpgradeCode", uc),
+ ("WhichUsers", "ALL"),
+ ("ProductLine", "Python%s%s" % (major, minor)),
+ ])
+ db.Commit()
+ return db, msiname
+
+def remove_old_versions(db):
+ "Fill the upgrade table."
+ start = "%s.%s.0" % (major, minor)
+ # This requests that feature selection states of an older
+ # installation should be forwarded into this one. Upgrading
+ # requires that both the old and the new installation are
+ # either both per-machine or per-user.
+ migrate_features = 1
+ # See "Upgrade Table". We remove releases with the same major and
+ # minor version. For an snapshot, we remove all earlier snapshots. For
+ # a release, we remove all snapshots, and all earlier releases.
+ if snapshot:
+ add_data(db, "Upgrade",
+ [(upgrade_code_snapshot, start,
+ current_version,
+ None, # Ignore language
+ migrate_features,
+ None, # Migrate ALL features
+ "REMOVEOLDSNAPSHOT")])
+ props = "REMOVEOLDSNAPSHOT"
+ else:
+ add_data(db, "Upgrade",
+ [(upgrade_code, start, current_version,
+ None, migrate_features, None, "REMOVEOLDVERSION"),
+ (upgrade_code_snapshot, start, "%s.%d.0" % (major, int(minor)+1),
+ None, migrate_features, None, "REMOVEOLDSNAPSHOT")])
+ props = "REMOVEOLDSNAPSHOT;REMOVEOLDVERSION"
+
+ props += ";TARGETDIR;DLLDIR"
+ # Installer collects the product codes of the earlier releases in
+ # these properties. In order to allow modification of the properties,
+ # they must be declared as secure. See "SecureCustomProperties Property"
+ add_data(db, "Property", [("SecureCustomProperties", props)])
+
+class PyDialog(Dialog):
+ """Dialog class with a fixed layout: controls at the top, then a ruler,
+ then a list of buttons: back, next, cancel. Optionally a bitmap at the
+ left."""
+ def __init__(self, *args, **kw):
+ """Dialog(database, name, x, y, w, h, attributes, title, first,
+ default, cancel, bitmap=true)"""
+ Dialog.__init__(self, *args)
+ ruler = self.h - 36
+ bmwidth = 152*ruler/328
+ if kw.get("bitmap", True):
+ self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
+ self.line("BottomLine", 0, ruler, self.w, 0)
+
+ def title(self, title):
+ "Set the title text of the dialog at the top."
+ # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix,
+ # text, in VerdanaBold10
+ self.text("Title", 135, 10, 220, 60, 0x30003,
+ r"{\VerdanaBold10}%s" % title)
+
+ def back(self, title, next, name = "Back", active = 1):
+ """Add a back button with a given title, the tab-next button,
+ its name in the Control table, possibly initially disabled.
+
+ Return the button, so that events can be associated"""
+ if active:
+ flags = 3 # Visible|Enabled
+ else:
+ flags = 1 # Visible
+ return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next)
+
+ def cancel(self, title, next, name = "Cancel", active = 1):
+ """Add a cancel button with a given title, the tab-next button,
+ its name in the Control table, possibly initially disabled.
+
+ Return the button, so that events can be associated"""
+ if active:
+ flags = 3 # Visible|Enabled
+ else:
+ flags = 1 # Visible
+ return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next)
+
+ def next(self, title, next, name = "Next", active = 1):
+ """Add a Next button with a given title, the tab-next button,
+ its name in the Control table, possibly initially disabled.
+
+ Return the button, so that events can be associated"""
+ if active:
+ flags = 3 # Visible|Enabled
+ else:
+ flags = 1 # Visible
+ return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next)
+
+ def xbutton(self, name, title, next, xpos):
+ """Add a button with a given title, the tab-next button,
+ its name in the Control table, giving its x position; the
+ y-position is aligned with the other buttons.
+
+ Return the button, so that events can be associated"""
+ return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next)
+
+def add_ui(db):
+ x = y = 50
+ w = 370
+ h = 300
+ title = "[ProductName] Setup"
+
+ # see "Dialog Style Bits"
+ modal = 3 # visible | modal
+ modeless = 1 # visible
+ track_disk_space = 32
+
+ add_data(db, 'ActionText', uisample.ActionText)
+ add_data(db, 'UIText', uisample.UIText)
+
+ # Bitmaps
+ if not os.path.exists(srcdir+r"\PC\python_icon.exe"):
+ raise "Run icons.mak in PC directory"
+ add_data(db, "Binary",
+ [("PythonWin", msilib.Binary(r"%s\PCbuild\installer.bmp" % srcdir)), # 152x328 pixels
+ ("py.ico",msilib.Binary(srcdir+r"\PC\py.ico")),
+ ])
+ add_data(db, "Icon",
+ [("python_icon.exe", msilib.Binary(srcdir+r"\PC\python_icon.exe"))])
+
+ # Scripts
+ # CheckDir sets TargetExists if TARGETDIR exists.
+ # UpdateEditIDLE sets the REGISTRY.tcl component into
+ # the installed/uninstalled state according to both the
+ # Extensions and TclTk features.
+ if os.system("nmake /nologo /c /f msisupport.mak") != 0:
+ raise "'nmake /f msisupport.mak' failed"
+ add_data(db, "Binary", [("Script", msilib.Binary("msisupport.dll"))])
+ # See "Custom Action Type 1"
+ if msilib.Win64:
+ CheckDir = "CheckDir"
+ UpdateEditIDLE = "UpdateEditIDLE"
+ else:
+ CheckDir = "_CheckDir@4"
+ UpdateEditIDLE = "_UpdateEditIDLE@4"
+ add_data(db, "CustomAction",
+ [("CheckDir", 1, "Script", CheckDir)])
+ if have_tcl:
+ add_data(db, "CustomAction",
+ [("UpdateEditIDLE", 1, "Script", UpdateEditIDLE)])
+
+ # UI customization properties
+ add_data(db, "Property",
+ # See "DefaultUIFont Property"
+ [("DefaultUIFont", "DlgFont8"),
+ # See "ErrorDialog Style Bit"
+ ("ErrorDialog", "ErrorDlg"),
+ ("Progress1", "Install"), # modified in maintenance type dlg
+ ("Progress2", "installs"),
+ ("MaintenanceForm_Action", "Repair")])
+
+ # Fonts, see "TextStyle Table"
+ add_data(db, "TextStyle",
+ [("DlgFont8", "Tahoma", 9, None, 0),
+ ("DlgFontBold8", "Tahoma", 8, None, 1), #bold
+ ("VerdanaBold10", "Verdana", 10, None, 1),
+ ("VerdanaRed9", "Verdana", 9, 255, 0),
+ ])
+
+ compileargs = r'-Wi "[TARGETDIR]Lib\compileall.py" -f -x "bad_coding|badsyntax|site-packages|py3_" "[TARGETDIR]Lib"'
+ lib2to3args = r'-c "import lib2to3.pygram, lib2to3.patcomp;lib2to3.patcomp.PatternCompiler()"'
+ # See "CustomAction Table"
+ add_data(db, "CustomAction", [
+ # msidbCustomActionTypeFirstSequence + msidbCustomActionTypeTextData + msidbCustomActionTypeProperty
+ # See "Custom Action Type 51",
+ # "Custom Action Execution Scheduling Options"
+ ("InitialTargetDir", 307, "TARGETDIR",
+ "[WindowsVolume]Python%s%s" % (major, minor)),
+ ("SetDLLDirToTarget", 307, "DLLDIR", "[TARGETDIR]"),
+ ("SetDLLDirToSystem32", 307, "DLLDIR", SystemFolderName),
+ # msidbCustomActionTypeExe + msidbCustomActionTypeSourceFile
+ # See "Custom Action Type 18"
+ ("CompilePyc", 18, "python.exe", compileargs),
+ ("CompilePyo", 18, "python.exe", "-O "+compileargs),
+ ("CompileGrammar", 18, "python.exe", lib2to3args),
+ ])
+
+ # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table"
+ # Numbers indicate sequence; see sequence.py for how these action integrate
+ add_data(db, "InstallUISequence",
+ [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140),
+ ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141),
+ ("InitialTargetDir", 'TARGETDIR=""', 750),
+ # In the user interface, assume all-users installation if privileged.
+ ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751),
+ ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752),
+ ("SelectDirectoryDlg", "Not Installed", 1230),
+ # XXX no support for resume installations yet
+ #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240),
+ ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250),
+ ("ProgressDlg", None, 1280)])
+ add_data(db, "AdminUISequence",
+ [("InitialTargetDir", 'TARGETDIR=""', 750),
+ ("SetDLLDirToTarget", 'DLLDIR=""', 751),
+ ])
+
+ # Execute Sequences
+ add_data(db, "InstallExecuteSequence",
+ [("InitialTargetDir", 'TARGETDIR=""', 750),
+ ("SetDLLDirToSystem32", 'DLLDIR="" and ' + sys32cond, 751),
+ ("SetDLLDirToTarget", 'DLLDIR="" and not ' + sys32cond, 752),
+ ("UpdateEditIDLE", None, 1050),
+ ("CompilePyc", "COMPILEALL", 6800),
+ ("CompilePyo", "COMPILEALL", 6801),
+ ("CompileGrammar", "COMPILEALL", 6802),
+ ])
+ add_data(db, "AdminExecuteSequence",
+ [("InitialTargetDir", 'TARGETDIR=""', 750),
+ ("SetDLLDirToTarget", 'DLLDIR=""', 751),
+ ("CompilePyc", "COMPILEALL", 6800),
+ ("CompilePyo", "COMPILEALL", 6801),
+ ("CompileGrammar", "COMPILEALL", 6802),
+ ])
+
+ #####################################################################
+ # Standard dialogs: FatalError, UserExit, ExitDialog
+ fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title,
+ "Finish", "Finish", "Finish")
+ fatal.title("[ProductName] Installer ended prematurely")
+ fatal.back("< Back", "Finish", active = 0)
+ fatal.cancel("Cancel", "Back", active = 0)
+ fatal.text("Description1", 135, 70, 220, 80, 0x30003,
+ "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.")
+ fatal.text("Description2", 135, 155, 220, 20, 0x30003,
+ "Click the Finish button to exit the Installer.")
+ c=fatal.next("Finish", "Cancel", name="Finish")
+ # See "ControlEvent Table". Parameters are the event, the parameter
+ # to the action, and optionally the condition for the event, and the order
+ # of events.
+ c.event("EndDialog", "Exit")
+
+ user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title,
+ "Finish", "Finish", "Finish")
+ user_exit.title("[ProductName] Installer was interrupted")
+ user_exit.back("< Back", "Finish", active = 0)
+ user_exit.cancel("Cancel", "Back", active = 0)
+ user_exit.text("Description1", 135, 70, 220, 80, 0x30003,
+ "[ProductName] setup was interrupted. Your system has not been modified. "
+ "To install this program at a later time, please run the installation again.")
+ user_exit.text("Description2", 135, 155, 220, 20, 0x30003,
+ "Click the Finish button to exit the Installer.")
+ c = user_exit.next("Finish", "Cancel", name="Finish")
+ c.event("EndDialog", "Exit")
+
+ exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title,
+ "Finish", "Finish", "Finish")
+ exit_dialog.title("Completing the [ProductName] Installer")
+ exit_dialog.back("< Back", "Finish", active = 0)
+ exit_dialog.cancel("Cancel", "Back", active = 0)
+ exit_dialog.text("Acknowledgements", 135, 95, 220, 120, 0x30003,
+ "Special Windows thanks to:\n"
+ " Mark Hammond, without whose years of freely \n"
+ " shared Windows expertise, Python for Windows \n"
+ " would still be Python for DOS.")
+
+ c = exit_dialog.text("warning", 135, 200, 220, 40, 0x30003,
+ "{\\VerdanaRed9}Warning: Python 3.3.0 is the last "
+ "Python release for Windows 2000.")
+ c.condition("Hide", "VersionNT > 500")
+
+ exit_dialog.text("Description", 135, 235, 220, 20, 0x30003,
+ "Click the Finish button to exit the Installer.")
+ c = exit_dialog.next("Finish", "Cancel", name="Finish")
+ c.event("EndDialog", "Return")
+
+ #####################################################################
+ # Required dialog: FilesInUse, ErrorDlg
+ inuse = PyDialog(db, "FilesInUse",
+ x, y, w, h,
+ 19, # KeepModeless|Modal|Visible
+ title,
+ "Retry", "Retry", "Retry", bitmap=False)
+ inuse.text("Title", 15, 6, 200, 15, 0x30003,
+ r"{\DlgFontBold8}Files in Use")
+ inuse.text("Description", 20, 23, 280, 20, 0x30003,
+ "Some files that need to be updated are currently in use.")
+ inuse.text("Text", 20, 55, 330, 50, 3,
+ "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.")
+ inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess",
+ None, None, None)
+ c=inuse.back("Exit", "Ignore", name="Exit")
+ c.event("EndDialog", "Exit")
+ c=inuse.next("Ignore", "Retry", name="Ignore")
+ c.event("EndDialog", "Ignore")
+ c=inuse.cancel("Retry", "Exit", name="Retry")
+ c.event("EndDialog","Retry")
+
+
+ # See "Error Dialog". See "ICE20" for the required names of the controls.
+ error = Dialog(db, "ErrorDlg",
+ 50, 10, 330, 101,
+ 65543, # Error|Minimize|Modal|Visible
+ title,
+ "ErrorText", None, None)
+ error.text("ErrorText", 50,9,280,48,3, "")
+ error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None)
+ error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo")
+ error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes")
+ error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort")
+ error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel")
+ error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore")
+ error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk")
+ error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry")
+
+ #####################################################################
+ # Global "Query Cancel" dialog
+ cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title,
+ "No", "No", "No")
+ cancel.text("Text", 48, 15, 194, 30, 3,
+ "Are you sure you want to cancel [ProductName] installation?")
+ cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None,
+ "py.ico", None, None)
+ c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No")
+ c.event("EndDialog", "Exit")
+
+ c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes")
+ c.event("EndDialog", "Return")
+
+ #####################################################################
+ # Global "Wait for costing" dialog
+ costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title,
+ "Return", "Return", "Return")
+ costing.text("Text", 48, 15, 194, 30, 3,
+ "Please wait while the installer finishes determining your disk space requirements.")
+ costing.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None,
+ "py.ico", None, None)
+ c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None)
+ c.event("EndDialog", "Exit")
+
+ #####################################################################
+ # Preparation dialog: no user input except cancellation
+ prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title,
+ "Cancel", "Cancel", "Cancel")
+ prep.text("Description", 135, 70, 220, 40, 0x30003,
+ "Please wait while the Installer prepares to guide you through the installation.")
+ prep.title("Welcome to the [ProductName] Installer")
+ c=prep.text("ActionText", 135, 110, 220, 20, 0x30003, "Pondering...")
+ c.mapping("ActionText", "Text")
+ c=prep.text("ActionData", 135, 135, 220, 30, 0x30003, None)
+ c.mapping("ActionData", "Text")
+ prep.back("Back", None, active=0)
+ prep.next("Next", None, active=0)
+ c=prep.cancel("Cancel", None)
+ c.event("SpawnDialog", "CancelDlg")
+
+ #####################################################################
+ # Target directory selection
+ seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title,
+ "Next", "Next", "Cancel")
+ seldlg.title("Select Destination Directory")
+ c = seldlg.text("Existing", 135, 25, 235, 30, 0x30003,
+ "{\VerdanaRed9}This update will replace your existing [ProductLine] installation.")
+ c.condition("Hide", 'REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""')
+ seldlg.text("Description", 135, 50, 220, 40, 0x30003,
+ "Please select a directory for the [ProductName] files.")
+
+ seldlg.back("< Back", None, active=0)
+ c = seldlg.next("Next >", "Cancel")
+ c.event("DoAction", "CheckDir", "TargetExistsOk<>1", order=1)
+ # If the target exists, but we found that we are going to remove old versions, don't bother
+ # confirming that the target directory exists. Strictly speaking, we should determine that
+ # the target directory is indeed the target of the product that we are going to remove, but
+ # I don't know how to do that.
+ c.event("SpawnDialog", "ExistingDirectoryDlg", 'TargetExists=1 and REMOVEOLDVERSION="" and REMOVEOLDSNAPSHOT=""', 2)
+ c.event("SetTargetPath", "TARGETDIR", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 3)
+ c.event("SpawnWaitDialog", "WaitForCostingDlg", "CostingComplete=1", 4)
+ c.event("NewDialog", "SelectFeaturesDlg", 'TargetExists=0 or REMOVEOLDVERSION<>"" or REMOVEOLDSNAPSHOT<>""', 5)
+
+ c = seldlg.cancel("Cancel", "DirectoryCombo")
+ c.event("SpawnDialog", "CancelDlg")
+
+ seldlg.control("DirectoryCombo", "DirectoryCombo", 135, 70, 172, 80, 393219,
+ "TARGETDIR", None, "DirectoryList", None)
+ seldlg.control("DirectoryList", "DirectoryList", 135, 90, 208, 136, 3, "TARGETDIR",
+ None, "PathEdit", None)
+ seldlg.control("PathEdit", "PathEdit", 135, 230, 206, 16, 3, "TARGETDIR", None, "Next", None)
+ c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None)
+ c.event("DirectoryListUp", "0")
+ c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None)
+ c.event("DirectoryListNew", "0")
+
+ #####################################################################
+ # SelectFeaturesDlg
+ features = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal|track_disk_space,
+ title, "Tree", "Next", "Cancel")
+ features.title("Customize [ProductName]")
+ features.text("Description", 135, 35, 220, 15, 0x30003,
+ "Select the way you want features to be installed.")
+ features.text("Text", 135,45,220,30, 3,
+ "Click on the icons in the tree below to change the way features will be installed.")
+
+ c=features.back("< Back", "Next")
+ c.event("NewDialog", "SelectDirectoryDlg")
+
+ c=features.next("Next >", "Cancel")
+ c.mapping("SelectionNoItems", "Enabled")
+ c.event("SpawnDialog", "DiskCostDlg", "OutOfDiskSpace=1", order=1)
+ c.event("EndDialog", "Return", "OutOfDiskSpace<>1", order=2)
+
+ c=features.cancel("Cancel", "Tree")
+ c.event("SpawnDialog", "CancelDlg")
+
+ # The browse property is not used, since we have only a single target path (selected already)
+ features.control("Tree", "SelectionTree", 135, 75, 220, 95, 7, "_BrowseProperty",
+ "Tree of selections", "Back", None)
+
+ #c=features.pushbutton("Reset", 42, 243, 56, 17, 3, "Reset", "DiskCost")
+ #c.mapping("SelectionNoItems", "Enabled")
+ #c.event("Reset", "0")
+
+ features.control("Box", "GroupBox", 135, 170, 225, 90, 1, None, None, None, None)
+
+ c=features.xbutton("DiskCost", "Disk &Usage", None, 0.10)
+ c.mapping("SelectionNoItems","Enabled")
+ c.event("SpawnDialog", "DiskCostDlg")
+
+ c=features.xbutton("Advanced", "Advanced", None, 0.30)
+ c.event("SpawnDialog", "AdvancedDlg")
+
+ c=features.text("ItemDescription", 140, 180, 210, 30, 3,
+ "Multiline description of the currently selected item.")
+ c.mapping("SelectionDescription","Text")
+
+ c=features.text("ItemSize", 140, 210, 210, 45, 3,
+ "The size of the currently selected item.")
+ c.mapping("SelectionSize", "Text")
+
+ #####################################################################
+ # Disk cost
+ cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title,
+ "OK", "OK", "OK", bitmap=False)
+ cost.text("Title", 15, 6, 200, 15, 0x30003,
+ "{\DlgFontBold8}Disk Space Requirements")
+ cost.text("Description", 20, 20, 280, 20, 0x30003,
+ "The disk space required for the installation of the selected features.")
+ cost.text("Text", 20, 53, 330, 60, 3,
+ "The highlighted volumes (if any) do not have enough disk space "
+ "available for the currently selected features. You can either "
+ "remove some files from the highlighted volumes, or choose to "
+ "install less features onto local drive(s), or select different "
+ "destination drive(s).")
+ cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223,
+ None, "{120}{70}{70}{70}{70}", None, None)
+ cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return")
+
+ #####################################################################
+ # WhichUsers Dialog. Only available on NT, and for privileged users.
+ # This must be run before FindRelatedProducts, because that will
+ # take into account whether the previous installation was per-user
+ # or per-machine. We currently don't support going back to this
+ # dialog after "Next" was selected; to support this, we would need to
+ # find how to reset the ALLUSERS property, and how to re-run
+ # FindRelatedProducts.
+ # On Windows9x, the ALLUSERS property is ignored on the command line
+ # and in the Property table, but installer fails according to the documentation
+ # if a dialog attempts to set ALLUSERS.
+ whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title,
+ "AdminInstall", "Next", "Cancel")
+ whichusers.title("Select whether to install [ProductName] for all users of this computer.")
+ # A radio group with two options: allusers, justme
+ g = whichusers.radiogroup("AdminInstall", 135, 60, 235, 80, 3,
+ "WhichUsers", "", "Next")
+ g.condition("Disable", "VersionNT=600") # Not available on Vista and Windows 2008
+ g.add("ALL", 0, 5, 150, 20, "Install for all users")
+ g.add("JUSTME", 0, 25, 235, 20, "Install just for me (not available on Windows Vista)")
+
+ whichusers.back("Back", None, active=0)
+
+ c = whichusers.next("Next >", "Cancel")
+ c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1)
+ c.event("EndDialog", "Return", order = 2)
+
+ c = whichusers.cancel("Cancel", "AdminInstall")
+ c.event("SpawnDialog", "CancelDlg")
+
+ #####################################################################
+ # Advanced Dialog.
+ advanced = PyDialog(db, "AdvancedDlg", x, y, w, h, modal, title,
+ "CompilePyc", "Ok", "Ok")
+ advanced.title("Advanced Options for [ProductName]")
+ # A radio group with two options: allusers, justme
+ advanced.checkbox("CompilePyc", 135, 60, 230, 50, 3,
+ "COMPILEALL", "Compile .py files to byte code after installation", "Ok")
+
+ c = advanced.cancel("Ok", "CompilePyc", name="Ok") # Button just has location of cancel button.
+ c.event("EndDialog", "Return")
+
+ #####################################################################
+ # Existing Directory dialog
+ dlg = Dialog(db, "ExistingDirectoryDlg", 50, 30, 200, 80, modal, title,
+ "No", "No", "No")
+ dlg.text("Title", 10, 20, 180, 40, 3,
+ "[TARGETDIR] exists. Are you sure you want to overwrite existing files?")
+ c=dlg.pushbutton("Yes", 30, 60, 55, 17, 3, "Yes", "No")
+ c.event("[TargetExists]", "0", order=1)
+ c.event("[TargetExistsOk]", "1", order=2)
+ c.event("EndDialog", "Return", order=3)
+ c=dlg.pushbutton("No", 115, 60, 55, 17, 3, "No", "Yes")
+ c.event("EndDialog", "Return")
+
+ #####################################################################
+ # Installation Progress dialog (modeless)
+ progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title,
+ "Cancel", "Cancel", "Cancel", bitmap=False)
+ progress.text("Title", 20, 15, 200, 15, 0x30003,
+ "{\DlgFontBold8}[Progress1] [ProductName]")
+ progress.text("Text", 35, 65, 300, 30, 3,
+ "Please wait while the Installer [Progress2] [ProductName]. "
+ "This may take several minutes.")
+ progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:")
+
+ c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...")
+ c.mapping("ActionText", "Text")
+
+ #c=progress.text("ActionData", 35, 140, 300, 20, 3, None)
+ #c.mapping("ActionData", "Text")
+
+ c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537,
+ None, "Progress done", None, None)
+ c.mapping("SetProgress", "Progress")
+
+ progress.back("< Back", "Next", active=False)
+ progress.next("Next >", "Cancel", active=False)
+ progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg")
+
+ # Maintenance type: repair/uninstall
+ maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title,
+ "Next", "Next", "Cancel")
+ maint.title("Welcome to the [ProductName] Setup Wizard")
+ maint.text("BodyText", 135, 63, 230, 42, 3,
+ "Select whether you want to repair or remove [ProductName].")
+ g=maint.radiogroup("RepairRadioGroup", 135, 108, 230, 60, 3,
+ "MaintenanceForm_Action", "", "Next")
+ g.add("Change", 0, 0, 200, 17, "&Change [ProductName]")
+ g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]")
+ g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]")
+
+ maint.back("< Back", None, active=False)
+ c=maint.next("Finish", "Cancel")
+ # Change installation: Change progress dialog to "Change", then ask
+ # for feature selection
+ c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1)
+ c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2)
+
+ # Reinstall: Change progress dialog to "Repair", then invoke reinstall
+ # Also set list of reinstalled features to "ALL"
+ c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5)
+ c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6)
+ c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7)
+ c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8)
+
+ # Uninstall: Change progress to "Remove", then invoke uninstall
+ # Also set list of removed features to "ALL"
+ c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11)
+ c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12)
+ c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13)
+ c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14)
+
+ # Close dialog when maintenance action scheduled
+ c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20)
+ c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21)
+
+ maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg")
+
+
+# See "Feature Table". The feature level is 1 for all features,
+# and the feature attributes are 0 for the DefaultFeature, and
+# FollowParent for all other features. The numbers are the Display
+# column.
+def add_features(db):
+ # feature attributes:
+ # msidbFeatureAttributesFollowParent == 2
+ # msidbFeatureAttributesDisallowAdvertise == 8
+ # Features that need to be installed with together with the main feature
+ # (i.e. additional Python libraries) need to follow the parent feature.
+ # Features that have no advertisement trigger (e.g. the test suite)
+ # must not support advertisement
+ global default_feature, tcltk, htmlfiles, tools, testsuite, ext_feature, private_crt
+ default_feature = Feature(db, "DefaultFeature", "Python",
+ "Python Interpreter and Libraries",
+ 1, directory = "TARGETDIR")
+ shared_crt = Feature(db, "SharedCRT", "MSVCRT", "C Run-Time (system-wide)", 0,
+ level=0)
+ private_crt = Feature(db, "PrivateCRT", "MSVCRT", "C Run-Time (private)", 0,
+ level=0)
+ add_data(db, "Condition", [("SharedCRT", 1, sys32cond),
+ ("PrivateCRT", 1, "not "+sys32cond)])
+ # We don't support advertisement of extensions
+ ext_feature = Feature(db, "Extensions", "Register Extensions",
+ "Make this Python installation the default Python installation", 3,
+ parent = default_feature, attributes=2|8)
+ if have_tcl:
+ tcltk = Feature(db, "TclTk", "Tcl/Tk", "Tkinter, IDLE, pydoc", 5,
+ parent = default_feature, attributes=2)
+ htmlfiles = Feature(db, "Documentation", "Documentation",
+ "Python HTMLHelp File", 7, parent = default_feature)
+ tools = Feature(db, "Tools", "Utility Scripts",
+ "Python utility scripts (Tools/", 9,
+ parent = default_feature, attributes=2)
+ testsuite = Feature(db, "Testsuite", "Test suite",
+ "Python test suite (Lib/test/)", 11,
+ parent = default_feature, attributes=2|8)
+
+def extract_msvcr90():
+ # Find the redistributable files
+ if msilib.Win64:
+ arch = "amd64"
+ else:
+ arch = "x86"
+ dir = os.path.join(os.environ['VS90COMNTOOLS'], r"..\..\VC\redist\%s\Microsoft.VC90.CRT" % arch)
+
+ result = []
+ installer = msilib.MakeInstaller()
+ # omit msvcm90 and msvcp90, as they aren't really needed
+ files = ["Microsoft.VC90.CRT.manifest", "msvcr90.dll"]
+ for f in files:
+ path = os.path.join(dir, f)
+ kw = {'src':path}
+ if f.endswith('.dll'):
+ kw['version'] = installer.FileVersion(path, 0)
+ kw['language'] = installer.FileVersion(path, 1)
+ result.append((f, kw))
+ return result
+
+def generate_license():
+ import shutil, glob
+ out = open("LICENSE.txt", "w")
+ shutil.copyfileobj(open(os.path.join(srcdir, "LICENSE")), out)
+ shutil.copyfileobj(open("crtlicense.txt"), out)
+ for name, pat, file in (("bzip2","bzip2-*", "LICENSE"),
+ ("Berkeley DB", "db-*", "LICENSE"),
+ ("openssl", "openssl-*", "LICENSE"),
+ ("Tcl", "tcl8*", "license.terms"),
+ ("Tk", "tk8*", "license.terms"),
+ ("Tix", "tix-*", "license.terms")):
+ out.write("\nThis copy of Python includes a copy of %s, which is licensed under the following terms:\n\n" % name)
+ dirs = glob.glob(srcdir+"/../"+pat)
+ if not dirs:
+ raise ValueError, "Could not find "+srcdir+"/../"+pat
+ if len(dirs) > 2:
+ raise ValueError, "Multiple copies of "+pat
+ dir = dirs[0]
+ shutil.copyfileobj(open(os.path.join(dir, file)), out)
+ out.close()
+
+
+class PyDirectory(Directory):
+ """By default, all components in the Python installer
+ can run from source."""
+ def __init__(self, *args, **kw):
+ if not kw.has_key("componentflags"):
+ kw['componentflags'] = 2 #msidbComponentAttributesOptional
+ Directory.__init__(self, *args, **kw)
+
+# See "File Table", "Component Table", "Directory Table",
+# "FeatureComponents Table"
+def add_files(db):
+ cab = CAB("python")
+ tmpfiles = []
+ # Add all executables, icons, text files into the TARGETDIR component
+ root = PyDirectory(db, cab, None, srcdir, "TARGETDIR", "SourceDir")
+ default_feature.set_current()
+ if not msilib.Win64:
+ root.add_file("%s/w9xpopen.exe" % PCBUILD)
+ root.add_file("README.txt", src="README")
+ root.add_file("NEWS.txt", src="Misc/NEWS")
+ generate_license()
+ root.add_file("LICENSE.txt", src=os.path.abspath("LICENSE.txt"))
+ root.start_component("python.exe", keyfile="python.exe")
+ root.add_file("%s/python.exe" % PCBUILD)
+ root.start_component("pythonw.exe", keyfile="pythonw.exe")
+ root.add_file("%s/pythonw.exe" % PCBUILD)
+
+ # msidbComponentAttributesSharedDllRefCount = 8, see "Component Table"
+ dlldir = PyDirectory(db, cab, root, srcdir, "DLLDIR", ".")
+
+ pydll = "python%s%s.dll" % (major, minor)
+ pydllsrc = os.path.join(srcdir, PCBUILD, pydll)
+ dlldir.start_component("DLLDIR", flags = 8, keyfile = pydll, uuid = pythondll_uuid)
+ installer = msilib.MakeInstaller()
+ pyversion = installer.FileVersion(pydllsrc, 0)
+ if not snapshot:
+ # For releases, the Python DLL has the same version as the
+ # installer package.
+ assert pyversion.split(".")[:3] == current_version.split(".")
+ dlldir.add_file("%s/python%s%s.dll" % (PCBUILD, major, minor),
+ version=pyversion,
+ language=installer.FileVersion(pydllsrc, 1))
+ DLLs = PyDirectory(db, cab, root, srcdir + "/" + PCBUILD, "DLLs", "DLLS|DLLs")
+
+ # msvcr90.dll: Need to place the DLL and the manifest into the root directory,
+ # plus another copy of the manifest in the DLLs directory, with the manifest
+ # pointing to the root directory
+ root.start_component("msvcr90", feature=private_crt)
+ # Results are ID,keyword pairs
+ manifest, crtdll = extract_msvcr90()
+ root.add_file(manifest[0], **manifest[1])
+ root.add_file(crtdll[0], **crtdll[1])
+ # Copy the manifest
+ # Actually, don't do that anymore - no DLL in DLLs should have a manifest
+ # dependency on msvcr90.dll anymore, so this should not be necessary
+ #manifest_dlls = manifest[0]+".root"
+ #open(manifest_dlls, "w").write(open(manifest[1]['src']).read().replace("msvcr","../msvcr"))
+ #DLLs.start_component("msvcr90_dlls", feature=private_crt)
+ #DLLs.add_file(manifest[0], src=os.path.abspath(manifest_dlls))
+
+ # Now start the main component for the DLLs directory;
+ # no regular files have been added to the directory yet.
+ DLLs.start_component()
+
+ # Check if _ctypes.pyd exists
+ have_ctypes = os.path.exists(srcdir+"/%s/_ctypes.pyd" % PCBUILD)
+ if not have_ctypes:
+ print "WARNING: _ctypes.pyd not found, ctypes will not be included"
+ extensions.remove("_ctypes.pyd")
+
+ # Add all .py files in Lib, except lib-tk, test
+ dirs={}
+ pydirs = [(root,"Lib")]
+ while pydirs:
+ # Commit every now and then, or else installer will complain
+ db.Commit()
+ parent, dir = pydirs.pop()
+ if dir == ".svn" or dir.startswith("plat-"):
+ continue
+ elif dir in ["lib-tk", "idlelib", "Icons"]:
+ if not have_tcl:
+ continue
+ tcltk.set_current()
+ elif dir in ['test', 'tests', 'data', 'output']:
+ # test: Lib, Lib/email, Lib/bsddb, Lib/ctypes, Lib/sqlite3
+ # tests: Lib/distutils
+ # data: Lib/email/test
+ # output: Lib/test
+ testsuite.set_current()
+ elif not have_ctypes and dir == "ctypes":
+ continue
+ else:
+ default_feature.set_current()
+ lib = PyDirectory(db, cab, parent, dir, dir, "%s|%s" % (parent.make_short(dir), dir))
+ # Add additional files
+ dirs[dir]=lib
+ lib.glob("*.txt")
+ if dir=='site-packages':
+ lib.add_file("README.txt", src="README")
+ continue
+ files = lib.glob("*.py")
+ files += lib.glob("*.pyw")
+ if files:
+ # Add an entry to the RemoveFile table to remove bytecode files.
+ lib.remove_pyc()
+ if dir.endswith('.egg-info'):
+ lib.add_file('entry_points.txt')
+ lib.add_file('PKG-INFO')
+ lib.add_file('top_level.txt')
+ lib.add_file('zip-safe')
+ continue
+ if dir=='test' and parent.physical=='Lib':
+ lib.add_file("185test.db")
+ lib.add_file("audiotest.au")
+ lib.add_file("cfgparser.1")
+ lib.add_file("sgml_input.html")
+ lib.add_file("testtar.tar")
+ lib.add_file("test_difflib_expect.html")
+ lib.add_file("check_soundcard.vbs")
+ lib.add_file("empty.vbs")
+ lib.add_file("Sine-1000Hz-300ms.aif")
+ lib.glob("*.uue")
+ lib.glob("*.pem")
+ lib.glob("*.pck")
+ lib.add_file("zipdir.zip")
+ if dir=='tests' and parent.physical=='distutils':
+ lib.add_file("Setup.sample")
+ if dir=='decimaltestdata':
+ lib.glob("*.decTest")
+ if dir=='xmltestdata':
+ lib.glob("*.xml")
+ lib.add_file("test.xml.out")
+ if dir=='output':
+ lib.glob("test_*")
+ if dir=='idlelib':
+ lib.glob("*.def")
+ lib.add_file("idle.bat")
+ if dir=="Icons":
+ lib.glob("*.gif")
+ lib.add_file("idle.icns")
+ if dir=="command" and parent.physical=="distutils":
+ lib.glob("wininst*.exe")
+ if dir=="setuptools":
+ lib.add_file("cli.exe")
+ lib.add_file("gui.exe")
+ if dir=="lib2to3":
+ lib.removefile("pickle", "*.pickle")
+ if dir=="data" and parent.physical=="test" and parent.basedir.physical=="email":
+ # This should contain all non-.svn files listed in subversion
+ for f in os.listdir(lib.absolute):
+ if f.endswith(".txt") or f==".svn":continue
+ if f.endswith(".au") or f.endswith(".gif"):
+ lib.add_file(f)
+ else:
+ print "WARNING: New file %s in email/test/data" % f
+ for f in os.listdir(lib.absolute):
+ if os.path.isdir(os.path.join(lib.absolute, f)):
+ pydirs.append((lib, f))
+ # Add DLLs
+ default_feature.set_current()
+ lib = DLLs
+ lib.add_file("py.ico", src=srcdir+"/PC/py.ico")
+ lib.add_file("pyc.ico", src=srcdir+"/PC/pyc.ico")
+ dlls = []
+ tclfiles = []
+ for f in extensions:
+ if f=="_tkinter.pyd":
+ continue
+ if not os.path.exists(srcdir + "/" + PCBUILD + "/" + f):
+ print "WARNING: Missing extension", f
+ continue
+ dlls.append(f)
+ lib.add_file(f)
+ # Add sqlite
+ if msilib.msi_type=="Intel64;1033":
+ sqlite_arch = "/ia64"
+ elif msilib.msi_type=="x64;1033":
+ sqlite_arch = "/amd64"
+ tclsuffix = "64"
+ else:
+ sqlite_arch = ""
+ tclsuffix = ""
+ lib.add_file("sqlite3.dll")
+ if have_tcl:
+ if not os.path.exists("%s/%s/_tkinter.pyd" % (srcdir, PCBUILD)):
+ print "WARNING: Missing _tkinter.pyd"
+ else:
+ lib.start_component("TkDLLs", tcltk)
+ lib.add_file("_tkinter.pyd")
+ dlls.append("_tkinter.pyd")
+ tcldir = os.path.normpath(srcdir+("/../tcltk%s/bin" % tclsuffix))
+ for f in glob.glob1(tcldir, "*.dll"):
+ lib.add_file(f, src=os.path.join(tcldir, f))
+ # check whether there are any unknown extensions
+ for f in glob.glob1(srcdir+"/"+PCBUILD, "*.pyd"):
+ if f.endswith("_d.pyd"): continue # debug version
+ if f in dlls: continue
+ print "WARNING: Unknown extension", f
+
+ # Add headers
+ default_feature.set_current()
+ lib = PyDirectory(db, cab, root, "include", "include", "INCLUDE|include")
+ lib.glob("*.h")
+ lib.add_file("pyconfig.h", src="../PC/pyconfig.h")
+ # Add import libraries
+ lib = PyDirectory(db, cab, root, PCBUILD, "libs", "LIBS|libs")
+ for f in dlls:
+ lib.add_file(f.replace('pyd','lib'))
+ lib.add_file('python%s%s.lib' % (major, minor))
+ # Add the mingw-format library
+ if have_mingw:
+ lib.add_file('libpython%s%s.a' % (major, minor))
+ if have_tcl:
+ # Add Tcl/Tk
+ tcldirs = [(root, '../tcltk%s/lib' % tclsuffix, 'tcl')]
+ tcltk.set_current()
+ while tcldirs:
+ parent, phys, dir = tcldirs.pop()
+ lib = PyDirectory(db, cab, parent, phys, dir, "%s|%s" % (parent.make_short(dir), dir))
+ if not os.path.exists(lib.absolute):
+ continue
+ for f in os.listdir(lib.absolute):
+ if os.path.isdir(os.path.join(lib.absolute, f)):
+ tcldirs.append((lib, f, f))
+ else:
+ lib.add_file(f)
+ # Add tools
+ tools.set_current()
+ tooldir = PyDirectory(db, cab, root, "Tools", "Tools", "TOOLS|Tools")
+ for f in ['i18n', 'pynche', 'Scripts', 'versioncheck', 'webchecker']:
+ lib = PyDirectory(db, cab, tooldir, f, f, "%s|%s" % (tooldir.make_short(f), f))
+ lib.glob("*.py")
+ lib.glob("*.pyw", exclude=['pydocgui.pyw'])
+ lib.remove_pyc()
+ lib.glob("*.txt")
+ if f == "pynche":
+ x = PyDirectory(db, cab, lib, "X", "X", "X|X")
+ x.glob("*.txt")
+ if os.path.exists(os.path.join(lib.absolute, "README")):
+ lib.add_file("README.txt", src="README")
+ if f == 'Scripts':
+ lib.add_file("2to3.py", src="2to3")
+ if have_tcl:
+ lib.start_component("pydocgui.pyw", tcltk, keyfile="pydocgui.pyw")
+ lib.add_file("pydocgui.pyw")
+ # Add documentation
+ htmlfiles.set_current()
+ lib = PyDirectory(db, cab, root, "Doc", "Doc", "DOC|Doc")
+ lib.start_component("documentation", keyfile=docfile)
+ lib.add_file(docfile, src="build/htmlhelp/"+docfile)
+
+ cab.commit(db)
+
+ for f in tmpfiles:
+ os.unlink(f)
+
+# See "Registry Table", "Component Table"
+def add_registry(db):
+ # File extensions, associated with the REGISTRY.def component
+ # IDLE verbs depend on the tcltk feature.
+ # msidbComponentAttributesRegistryKeyPath = 4
+ # -1 for Root specifies "dependent on ALLUSERS property"
+ tcldata = []
+ if have_tcl:
+ tcldata = [
+ ("REGISTRY.tcl", msilib.gen_uuid(), "TARGETDIR", registry_component, None,
+ "py.IDLE")]
+ add_data(db, "Component",
+ # msidbComponentAttributesRegistryKeyPath = 4
+ [("REGISTRY", msilib.gen_uuid(), "TARGETDIR", registry_component, None,
+ "InstallPath"),
+ ("REGISTRY.doc", msilib.gen_uuid(), "TARGETDIR", registry_component, None,
+ "Documentation"),
+ ("REGISTRY.def", msilib.gen_uuid(), "TARGETDIR", registry_component,
+ None, None)] + tcldata)
+ # See "FeatureComponents Table".
+ # The association between TclTk and pythonw.exe is necessary to make ICE59
+ # happy, because the installer otherwise believes that the IDLE and PyDoc
+ # shortcuts might get installed without pythonw.exe being install. This
+ # is not true, since installing TclTk will install the default feature, which
+ # will cause pythonw.exe to be installed.
+ # REGISTRY.tcl is not associated with any feature, as it will be requested
+ # through a custom action
+ tcldata = []
+ if have_tcl:
+ tcldata = [(tcltk.id, "pythonw.exe")]
+ add_data(db, "FeatureComponents",
+ [(default_feature.id, "REGISTRY"),
+ (htmlfiles.id, "REGISTRY.doc"),
+ (ext_feature.id, "REGISTRY.def")] +
+ tcldata
+ )
+ # Extensions are not advertised. For advertised extensions,
+ # we would need separate binaries that install along with the
+ # extension.
+ pat = r"Software\Classes\%sPython.%sFile\shell\%s\command"
+ ewi = "Edit with IDLE"
+ pat2 = r"Software\Classes\%sPython.%sFile\DefaultIcon"
+ pat3 = r"Software\Classes\%sPython.%sFile"
+ pat4 = r"Software\Classes\%sPython.%sFile\shellex\DropHandler"
+ tcl_verbs = []
+ if have_tcl:
+ tcl_verbs=[
+ ("py.IDLE", -1, pat % (testprefix, "", ewi), "",
+ r'"[TARGETDIR]pythonw.exe" "[TARGETDIR]Lib\idlelib\idle.pyw" -e "%1"',
+ "REGISTRY.tcl"),
+ ("pyw.IDLE", -1, pat % (testprefix, "NoCon", ewi), "",
+ r'"[TARGETDIR]pythonw.exe" "[TARGETDIR]Lib\idlelib\idle.pyw" -e "%1"',
+ "REGISTRY.tcl"),
+ ]
+ add_data(db, "Registry",
+ [# Extensions
+ ("py.ext", -1, r"Software\Classes\."+ext, "",
+ "Python.File", "REGISTRY.def"),
+ ("pyw.ext", -1, r"Software\Classes\."+ext+'w', "",
+ "Python.NoConFile", "REGISTRY.def"),
+ ("pyc.ext", -1, r"Software\Classes\."+ext+'c', "",
+ "Python.CompiledFile", "REGISTRY.def"),
+ ("pyo.ext", -1, r"Software\Classes\."+ext+'o', "",
+ "Python.CompiledFile", "REGISTRY.def"),
+ # MIME types
+ ("py.mime", -1, r"Software\Classes\."+ext, "Content Type",
+ "text/plain", "REGISTRY.def"),
+ ("pyw.mime", -1, r"Software\Classes\."+ext+'w', "Content Type",
+ "text/plain", "REGISTRY.def"),
+ #Verbs
+ ("py.open", -1, pat % (testprefix, "", "open"), "",
+ r'"[TARGETDIR]python.exe" "%1" %*', "REGISTRY.def"),
+ ("pyw.open", -1, pat % (testprefix, "NoCon", "open"), "",
+ r'"[TARGETDIR]pythonw.exe" "%1" %*', "REGISTRY.def"),
+ ("pyc.open", -1, pat % (testprefix, "Compiled", "open"), "",
+ r'"[TARGETDIR]python.exe" "%1" %*', "REGISTRY.def"),
+ ] + tcl_verbs + [
+ #Icons
+ ("py.icon", -1, pat2 % (testprefix, ""), "",
+ r'[DLLs]py.ico', "REGISTRY.def"),
+ ("pyw.icon", -1, pat2 % (testprefix, "NoCon"), "",
+ r'[DLLs]py.ico', "REGISTRY.def"),
+ ("pyc.icon", -1, pat2 % (testprefix, "Compiled"), "",
+ r'[DLLs]pyc.ico', "REGISTRY.def"),
+ # Descriptions
+ ("py.txt", -1, pat3 % (testprefix, ""), "",
+ "Python File", "REGISTRY.def"),
+ ("pyw.txt", -1, pat3 % (testprefix, "NoCon"), "",
+ "Python File (no console)", "REGISTRY.def"),
+ ("pyc.txt", -1, pat3 % (testprefix, "Compiled"), "",
+ "Compiled Python File", "REGISTRY.def"),
+ # Drop Handler
+ ("py.drop", -1, pat4 % (testprefix, ""), "",
+ "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"),
+ ("pyw.drop", -1, pat4 % (testprefix, "NoCon"), "",
+ "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"),
+ ("pyc.drop", -1, pat4 % (testprefix, "Compiled"), "",
+ "{60254CA5-953B-11CF-8C96-00AA00B8708C}", "REGISTRY.def"),
+ ])
+
+ # Registry keys
+ prefix = r"Software\%sPython\PythonCore\%s" % (testprefix, short_version)
+ add_data(db, "Registry",
+ [("InstallPath", -1, prefix+r"\InstallPath", "", "[TARGETDIR]", "REGISTRY"),
+ ("InstallGroup", -1, prefix+r"\InstallPath\InstallGroup", "",
+ "Python %s" % short_version, "REGISTRY"),
+ ("PythonPath", -1, prefix+r"\PythonPath", "",
+ r"[TARGETDIR]Lib;[TARGETDIR]DLLs;[TARGETDIR]Lib\lib-tk", "REGISTRY"),
+ ("Documentation", -1, prefix+r"\Help\Main Python Documentation", "",
+ "[TARGETDIR]Doc\\"+docfile , "REGISTRY.doc"),
+ ("Modules", -1, prefix+r"\Modules", "+", None, "REGISTRY"),
+ ("AppPaths", -1, r"Software\Microsoft\Windows\CurrentVersion\App Paths\Python.exe",
+ "", r"[TARGETDIR]Python.exe", "REGISTRY.def"),
+ ("DisplayIcon", -1,
+ r"Software\Microsoft\Windows\CurrentVersion\Uninstall\%s" % product_code,
+ "DisplayIcon", "[TARGETDIR]python.exe", "REGISTRY")
+ ])
+ # Shortcuts, see "Shortcut Table"
+ add_data(db, "Directory",
+ [("ProgramMenuFolder", "TARGETDIR", "."),
+ ("MenuDir", "ProgramMenuFolder", "PY%s%s|%sPython %s.%s" % (major,minor,testprefix,major,minor))])
+ add_data(db, "RemoveFile",
+ [("MenuDir", "TARGETDIR", None, "MenuDir", 2)])
+ tcltkshortcuts = []
+ if have_tcl:
+ tcltkshortcuts = [
+ ("IDLE", "MenuDir", "IDLE|IDLE (Python GUI)", "pythonw.exe",
+ tcltk.id, r'"[TARGETDIR]Lib\idlelib\idle.pyw"', None, None, "python_icon.exe", 0, None, "TARGETDIR"),
+ ("PyDoc", "MenuDir", "MODDOCS|Module Docs", "pythonw.exe",
+ tcltk.id, r'"[TARGETDIR]Tools\scripts\pydocgui.pyw"', None, None, "python_icon.exe", 0, None, "TARGETDIR"),
+ ]
+ add_data(db, "Shortcut",
+ tcltkshortcuts +
+ [# Advertised shortcuts: targets are features, not files
+ ("Python", "MenuDir", "PYTHON|Python (command line)", "python.exe",
+ default_feature.id, None, None, None, "python_icon.exe", 2, None, "TARGETDIR"),
+ # Advertising the Manual breaks on (some?) Win98, and the shortcut lacks an
+ # icon first.
+ #("Manual", "MenuDir", "MANUAL|Python Manuals", "documentation",
+ # htmlfiles.id, None, None, None, None, None, None, None),
+ ## Non-advertised shortcuts: must be associated with a registry component
+ ("Manual", "MenuDir", "MANUAL|Python Manuals", "REGISTRY.doc",
+ "[#%s]" % docfile, None,
+ None, None, None, None, None, None),
+ ("Uninstall", "MenuDir", "UNINST|Uninstall Python", "REGISTRY",
+ SystemFolderName+"msiexec", "/x%s" % product_code,
+ None, None, None, None, None, None),
+ ])
+ db.Commit()
+
+def build_pdbzip():
+ pdbexclude = ['kill_python.pdb', 'make_buildinfo.pdb',
+ 'make_versioninfo.pdb']
+ path = "python-%s%s-pdb.zip" % (full_current_version, msilib.arch_ext)
+ pdbzip = zipfile.ZipFile(path, 'w')
+ for f in glob.glob1(os.path.join(srcdir, PCBUILD), "*.pdb"):
+ if f not in pdbexclude and not f.endswith('_d.pdb'):
+ pdbzip.write(os.path.join(srcdir, PCBUILD, f), f)
+ pdbzip.close()
+
+db,msiname = build_database()
+try:
+ add_features(db)
+ add_ui(db)
+ add_files(db)
+ add_registry(db)
+ remove_old_versions(db)
+ db.Commit()
+finally:
+ del db
+
+# Merge CRT into MSI file. This requires the database to be closed.
+mod_dir = os.path.join(os.environ["ProgramFiles"], "Common Files", "Merge Modules")
+if msilib.Win64:
+ modules = ["Microsoft_VC90_CRT_x86_x64.msm", "policy_9_0_Microsoft_VC90_CRT_x86_x64.msm"]
+else:
+ modules = ["Microsoft_VC90_CRT_x86.msm","policy_9_0_Microsoft_VC90_CRT_x86.msm"]
+
+for i, n in enumerate(modules):
+ modules[i] = os.path.join(mod_dir, n)
+
+def merge(msi, feature, rootdir, modules):
+ cab_and_filecount = []
+ # Step 1: Merge databases, extract cabfiles
+ m = msilib.MakeMerge2()
+ m.OpenLog("merge.log")
+ m.OpenDatabase(msi)
+ for module in modules:
+ print module
+ m.OpenModule(module,0)
+ m.Merge(feature, rootdir)
+ print "Errors:"
+ for e in m.Errors:
+ print e.Type, e.ModuleTable, e.DatabaseTable
+ print " Modkeys:",
+ for s in e.ModuleKeys: print s,
+ print
+ print " DBKeys:",
+ for s in e.DatabaseKeys: print s,
+ print
+ cabname = tempfile.mktemp(suffix=".cab")
+ m.ExtractCAB(cabname)
+ cab_and_filecount.append((cabname, len(m.ModuleFiles)))
+ m.CloseModule()
+ m.CloseDatabase(True)
+ m.CloseLog()
+
+ # Step 2: Add CAB files
+ i = msilib.MakeInstaller()
+ db = i.OpenDatabase(msi, constants.msiOpenDatabaseModeTransact)
+
+ v = db.OpenView("SELECT LastSequence FROM Media")
+ v.Execute(None)
+ maxmedia = -1
+ while 1:
+ r = v.Fetch()
+ if not r: break
+ seq = r.IntegerData(1)
+ if seq > maxmedia:
+ maxmedia = seq
+ print "Start of Media", maxmedia
+
+ for cabname, count in cab_and_filecount:
+ stream = "merged%d" % maxmedia
+ msilib.add_data(db, "Media",
+ [(maxmedia+1, maxmedia+count, None, "#"+stream, None, None)])
+ msilib.add_stream(db, stream, cabname)
+ os.unlink(cabname)
+ maxmedia += count
+ # The merge module sets ALLUSERS to 1 in the property table.
+ # This is undesired; delete that
+ v = db.OpenView("DELETE FROM Property WHERE Property='ALLUSERS'")
+ v.Execute(None)
+ v.Close()
+ db.Commit()
+
+merge(msiname, "SharedCRT", "TARGETDIR", modules)
+
+# certname (from config.py) should be (a substring of)
+# the certificate subject, e.g. "Python Software Foundation"
+if certname:
+ os.system('signtool sign /n "%s" /t http://timestamp.verisign.com/scripts/timestamp.dll %s' % (certname, msiname))
+
+if pdbzip:
+ build_pdbzip()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msilib.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msilib.py
new file mode 100644
index 0000000000..d904b21e68
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msilib.py
@@ -0,0 +1,692 @@
+# Microsoft Installer Library
+# (C) 2003 Martin v. Loewis
+
+import win32com.client.gencache
+import win32com.client
+import pythoncom, pywintypes
+from win32com.client import constants
+import re, string, os, sets, glob, subprocess, sys, _winreg, struct
+
+try:
+ basestring
+except NameError:
+ basestring = (str, unicode)
+
+# Partially taken from Wine
+datasizemask= 0x00ff
+type_valid= 0x0100
+type_localizable= 0x0200
+
+typemask= 0x0c00
+type_long= 0x0000
+type_short= 0x0400
+type_string= 0x0c00
+type_binary= 0x0800
+
+type_nullable= 0x1000
+type_key= 0x2000
+# XXX temporary, localizable?
+knownbits = datasizemask | type_valid | type_localizable | \
+ typemask | type_nullable | type_key
+
+# Summary Info Property IDs
+PID_CODEPAGE=1
+PID_TITLE=2
+PID_SUBJECT=3
+PID_AUTHOR=4
+PID_KEYWORDS=5
+PID_COMMENTS=6
+PID_TEMPLATE=7
+PID_LASTAUTHOR=8
+PID_REVNUMBER=9
+PID_LASTPRINTED=11
+PID_CREATE_DTM=12
+PID_LASTSAVE_DTM=13
+PID_PAGECOUNT=14
+PID_WORDCOUNT=15
+PID_CHARCOUNT=16
+PID_APPNAME=18
+PID_SECURITY=19
+
+def reset():
+ global _directories
+ _directories = sets.Set()
+
+def EnsureMSI():
+ win32com.client.gencache.EnsureModule('{000C1092-0000-0000-C000-000000000046}', 1033, 1, 0)
+
+def EnsureMSM():
+ try:
+ win32com.client.gencache.EnsureModule('{0ADDA82F-2C26-11D2-AD65-00A0C9AF11A6}', 0, 1, 0)
+ except pywintypes.com_error:
+ win32com.client.gencache.EnsureModule('{0ADDA82F-2C26-11D2-AD65-00A0C9AF11A6}', 0, 2, 0)
+
+_Installer=None
+def MakeInstaller():
+ global _Installer
+ if _Installer is None:
+ EnsureMSI()
+ _Installer = win32com.client.Dispatch('WindowsInstaller.Installer',
+ resultCLSID='{000C1090-0000-0000-C000-000000000046}')
+ return _Installer
+
+_Merge=None
+def MakeMerge2():
+ global _Merge
+ if _Merge is None:
+ EnsureMSM()
+ _Merge = win32com.client.Dispatch("Msm.Merge2.1")
+ return _Merge
+
+class Table:
+ def __init__(self, name):
+ self.name = name
+ self.fields = []
+
+ def add_field(self, index, name, type):
+ self.fields.append((index,name,type))
+
+ def sql(self):
+ fields = []
+ keys = []
+ self.fields.sort()
+ fields = [None]*len(self.fields)
+ for index, name, type in self.fields:
+ index -= 1
+ unk = type & ~knownbits
+ if unk:
+ print "%s.%s unknown bits %x" % (self.name, name, unk)
+ size = type & datasizemask
+ dtype = type & typemask
+ if dtype == type_string:
+ if size:
+ tname="CHAR(%d)" % size
+ else:
+ tname="CHAR"
+ elif dtype == type_short:
+ assert size==2
+ tname = "SHORT"
+ elif dtype == type_long:
+ assert size==4
+ tname="LONG"
+ elif dtype == type_binary:
+ assert size==0
+ tname="OBJECT"
+ else:
+ tname="unknown"
+ print "%s.%sunknown integer type %d" % (self.name, name, size)
+ if type & type_nullable:
+ flags = ""
+ else:
+ flags = " NOT NULL"
+ if type & type_localizable:
+ flags += " LOCALIZABLE"
+ fields[index] = "`%s` %s%s" % (name, tname, flags)
+ if type & type_key:
+ keys.append("`%s`" % name)
+ fields = ", ".join(fields)
+ keys = ", ".join(keys)
+ return "CREATE TABLE %s (%s PRIMARY KEY %s)" % (self.name, fields, keys)
+
+ def create(self, db):
+ v = db.OpenView(self.sql())
+ v.Execute(None)
+ v.Close()
+
+class Binary:
+ def __init__(self, fname):
+ self.name = fname
+ def __repr__(self):
+ return 'msilib.Binary(os.path.join(dirname,"%s"))' % self.name
+
+def gen_schema(destpath, schemapath):
+ d = MakeInstaller()
+ schema = d.OpenDatabase(schemapath,
+ win32com.client.constants.msiOpenDatabaseModeReadOnly)
+
+ # XXX ORBER BY
+ v=schema.OpenView("SELECT * FROM _Columns")
+ curtable=None
+ tables = []
+ v.Execute(None)
+ f = open(destpath, "wt")
+ f.write("from msilib import Table\n")
+ while 1:
+ r=v.Fetch()
+ if not r:break
+ name=r.StringData(1)
+ if curtable != name:
+ f.write("\n%s = Table('%s')\n" % (name,name))
+ curtable = name
+ tables.append(name)
+ f.write("%s.add_field(%d,'%s',%d)\n" %
+ (name, r.IntegerData(2), r.StringData(3), r.IntegerData(4)))
+ v.Close()
+
+ f.write("\ntables=[%s]\n\n" % (", ".join(tables)))
+
+ # Fill the _Validation table
+ f.write("_Validation_records = [\n")
+ v = schema.OpenView("SELECT * FROM _Validation")
+ v.Execute(None)
+ while 1:
+ r = v.Fetch()
+ if not r:break
+ # Table, Column, Nullable
+ f.write("(%s,%s,%s," %
+ (`r.StringData(1)`, `r.StringData(2)`, `r.StringData(3)`))
+ def put_int(i):
+ if r.IsNull(i):f.write("None, ")
+ else:f.write("%d," % r.IntegerData(i))
+ def put_str(i):
+ if r.IsNull(i):f.write("None, ")
+ else:f.write("%s," % `r.StringData(i)`)
+ put_int(4) # MinValue
+ put_int(5) # MaxValue
+ put_str(6) # KeyTable
+ put_int(7) # KeyColumn
+ put_str(8) # Category
+ put_str(9) # Set
+ put_str(10)# Description
+ f.write("),\n")
+ f.write("]\n\n")
+
+ f.close()
+
+def gen_sequence(destpath, msipath):
+ dir = os.path.dirname(destpath)
+ d = MakeInstaller()
+ seqmsi = d.OpenDatabase(msipath,
+ win32com.client.constants.msiOpenDatabaseModeReadOnly)
+
+ v = seqmsi.OpenView("SELECT * FROM _Tables");
+ v.Execute(None)
+ f = open(destpath, "w")
+ print >>f, "import msilib,os;dirname=os.path.dirname(__file__)"
+ tables = []
+ while 1:
+ r = v.Fetch()
+ if not r:break
+ table = r.StringData(1)
+ tables.append(table)
+ f.write("%s = [\n" % table)
+ v1 = seqmsi.OpenView("SELECT * FROM `%s`" % table)
+ v1.Execute(None)
+ info = v1.ColumnInfo(constants.msiColumnInfoTypes)
+ while 1:
+ r = v1.Fetch()
+ if not r:break
+ rec = []
+ for i in range(1,r.FieldCount+1):
+ if r.IsNull(i):
+ rec.append(None)
+ elif info.StringData(i)[0] in "iI":
+ rec.append(r.IntegerData(i))
+ elif info.StringData(i)[0] in "slSL":
+ rec.append(r.StringData(i))
+ elif info.StringData(i)[0]=="v":
+ size = r.DataSize(i)
+ bytes = r.ReadStream(i, size, constants.msiReadStreamBytes)
+ bytes = bytes.encode("latin-1") # binary data represented "as-is"
+ if table == "Binary":
+ fname = rec[0]+".bin"
+ open(os.path.join(dir,fname),"wb").write(bytes)
+ rec.append(Binary(fname))
+ else:
+ rec.append(bytes)
+ else:
+ raise "Unsupported column type", info.StringData(i)
+ f.write(repr(tuple(rec))+",\n")
+ v1.Close()
+ f.write("]\n\n")
+ v.Close()
+ f.write("tables=%s\n" % repr(map(str,tables)))
+ f.close()
+
+class _Unspecified:pass
+def change_sequence(seq, action, seqno=_Unspecified, cond = _Unspecified):
+ "Change the sequence number of an action in a sequence list"
+ for i in range(len(seq)):
+ if seq[i][0] == action:
+ if cond is _Unspecified:
+ cond = seq[i][1]
+ if seqno is _Unspecified:
+ seqno = seq[i][2]
+ seq[i] = (action, cond, seqno)
+ return
+ raise ValueError, "Action not found in sequence"
+
+def add_data(db, table, values):
+ d = MakeInstaller()
+ v = db.OpenView("SELECT * FROM `%s`" % table)
+ count = v.ColumnInfo(0).FieldCount
+ r = d.CreateRecord(count)
+ for value in values:
+ assert len(value) == count, value
+ for i in range(count):
+ field = value[i]
+ if isinstance(field, (int, long)):
+ r.SetIntegerData(i+1,field)
+ elif isinstance(field, basestring):
+ r.SetStringData(i+1,field)
+ elif field is None:
+ pass
+ elif isinstance(field, Binary):
+ r.SetStream(i+1, field.name)
+ else:
+ raise TypeError, "Unsupported type %s" % field.__class__.__name__
+ v.Modify(win32com.client.constants.msiViewModifyInsert, r)
+ r.ClearData()
+ v.Close()
+
+def add_stream(db, name, path):
+ d = MakeInstaller()
+ v = db.OpenView("INSERT INTO _Streams (Name, Data) VALUES ('%s', ?)" % name)
+ r = d.CreateRecord(1)
+ r.SetStream(1, path)
+ v.Execute(r)
+ v.Close()
+
+def init_database(name, schema,
+ ProductName, ProductCode, ProductVersion,
+ Manufacturer,
+ request_uac = False):
+ try:
+ os.unlink(name)
+ except OSError:
+ pass
+ ProductCode = ProductCode.upper()
+ d = MakeInstaller()
+ # Create the database
+ db = d.OpenDatabase(name,
+ win32com.client.constants.msiOpenDatabaseModeCreate)
+ # Create the tables
+ for t in schema.tables:
+ t.create(db)
+ # Fill the validation table
+ add_data(db, "_Validation", schema._Validation_records)
+ # Initialize the summary information, allowing atmost 20 properties
+ si = db.GetSummaryInformation(20)
+ si.SetProperty(PID_TITLE, "Installation Database")
+ si.SetProperty(PID_SUBJECT, ProductName)
+ si.SetProperty(PID_AUTHOR, Manufacturer)
+ si.SetProperty(PID_TEMPLATE, msi_type)
+ si.SetProperty(PID_REVNUMBER, gen_uuid())
+ if request_uac:
+ wc = 2 # long file names, compressed, original media
+ else:
+ wc = 2 | 8 # +never invoke UAC
+ si.SetProperty(PID_WORDCOUNT, wc)
+ si.SetProperty(PID_PAGECOUNT, 200)
+ si.SetProperty(PID_APPNAME, "Python MSI Library")
+ # XXX more properties
+ si.Persist()
+ add_data(db, "Property", [
+ ("ProductName", ProductName),
+ ("ProductCode", ProductCode),
+ ("ProductVersion", ProductVersion),
+ ("Manufacturer", Manufacturer),
+ ("ProductLanguage", "1033")])
+ db.Commit()
+ return db
+
+def add_tables(db, module):
+ for table in module.tables:
+ add_data(db, table, getattr(module, table))
+
+def make_id(str):
+ #str = str.replace(".", "_") # colons are allowed
+ str = str.replace(" ", "_")
+ str = str.replace("-", "_")
+ str = str.replace("+", "_")
+ if str[0] in string.digits:
+ str = "_"+str
+ assert re.match("^[A-Za-z_][A-Za-z0-9_.]*$", str), "FILE"+str
+ return str
+
+def gen_uuid():
+ return str(pythoncom.CreateGuid())
+
+class CAB:
+ def __init__(self, name):
+ self.name = name
+ self.file = open(name+".txt", "wt")
+ self.filenames = sets.Set()
+ self.index = 0
+
+ def gen_id(self, dir, file):
+ logical = _logical = make_id(file)
+ pos = 1
+ while logical in self.filenames:
+ logical = "%s.%d" % (_logical, pos)
+ pos += 1
+ self.filenames.add(logical)
+ return logical
+
+ def append(self, full, file, logical = None):
+ if os.path.isdir(full):
+ return
+ if not logical:
+ logical = self.gen_id(dir, file)
+ self.index += 1
+ if full.find(" ")!=-1:
+ print >>self.file, '"%s" %s' % (full, logical)
+ else:
+ print >>self.file, '%s %s' % (full, logical)
+ return self.index, logical
+
+ def commit(self, db):
+ self.file.close()
+ try:
+ os.unlink(self.name+".cab")
+ except OSError:
+ pass
+ for k, v in [(r"Software\Microsoft\VisualStudio\7.1\Setup\VS", "VS7CommonBinDir"),
+ (r"Software\Microsoft\VisualStudio\8.0\Setup\VS", "VS7CommonBinDir"),
+ (r"Software\Microsoft\VisualStudio\9.0\Setup\VS", "VS7CommonBinDir"),
+ (r"Software\Microsoft\Win32SDK\Directories", "Install Dir"),
+ ]:
+ try:
+ key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, k)
+ dir = _winreg.QueryValueEx(key, v)[0]
+ _winreg.CloseKey(key)
+ except (WindowsError, IndexError):
+ continue
+ cabarc = os.path.join(dir, r"Bin", "cabarc.exe")
+ if not os.path.exists(cabarc):
+ continue
+ break
+ else:
+ print "WARNING: cabarc.exe not found in registry"
+ cabarc = "cabarc.exe"
+ cmd = r'"%s" -m lzx:21 n %s.cab @%s.txt' % (cabarc, self.name, self.name)
+ p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ for line in p.stdout:
+ if line.startswith(" -- adding "):
+ sys.stdout.write(".")
+ else:
+ sys.stdout.write(line)
+ sys.stdout.flush()
+ if not os.path.exists(self.name+".cab"):
+ raise IOError, "cabarc failed"
+ add_data(db, "Media",
+ [(1, self.index, None, "#"+self.name, None, None)])
+ add_stream(db, self.name, self.name+".cab")
+ os.unlink(self.name+".txt")
+ os.unlink(self.name+".cab")
+ db.Commit()
+
+_directories = sets.Set()
+class Directory:
+ def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None):
+ """Create a new directory in the Directory table. There is a current component
+ at each point in time for the directory, which is either explicitly created
+ through start_component, or implicitly when files are added for the first
+ time. Files are added into the current component, and into the cab file.
+ To create a directory, a base directory object needs to be specified (can be
+ None), the path to the physical directory, and a logical directory name.
+ Default specifies the DefaultDir slot in the directory table. componentflags
+ specifies the default flags that new components get."""
+ index = 1
+ _logical = make_id(_logical)
+ logical = _logical
+ while logical in _directories:
+ logical = "%s%d" % (_logical, index)
+ index += 1
+ _directories.add(logical)
+ self.db = db
+ self.cab = cab
+ self.basedir = basedir
+ self.physical = physical
+ self.logical = logical
+ self.component = None
+ self.short_names = sets.Set()
+ self.ids = sets.Set()
+ self.keyfiles = {}
+ self.componentflags = componentflags
+ if basedir:
+ self.absolute = os.path.join(basedir.absolute, physical)
+ blogical = basedir.logical
+ else:
+ self.absolute = physical
+ blogical = None
+ add_data(db, "Directory", [(logical, blogical, default)])
+
+ def start_component(self, component = None, feature = None, flags = None, keyfile = None, uuid=None):
+ """Add an entry to the Component table, and make this component the current for this
+ directory. If no component name is given, the directory name is used. If no feature
+ is given, the current feature is used. If no flags are given, the directory's default
+ flags are used. If no keyfile is given, the KeyPath is left null in the Component
+ table."""
+ if flags is None:
+ flags = self.componentflags
+ if uuid is None:
+ uuid = gen_uuid()
+ else:
+ uuid = uuid.upper()
+ if component is None:
+ component = self.logical
+ self.component = component
+ if Win64:
+ flags |= 256
+ if keyfile:
+ keyid = self.cab.gen_id(self.absolute, keyfile)
+ self.keyfiles[keyfile] = keyid
+ else:
+ keyid = None
+ add_data(self.db, "Component",
+ [(component, uuid, self.logical, flags, None, keyid)])
+ if feature is None:
+ feature = current_feature
+ add_data(self.db, "FeatureComponents",
+ [(feature.id, component)])
+
+ def make_short(self, file):
+ file = re.sub(r'[\?|><:/*"+,;=\[\]]', '_', file) # restrictions on short names
+ parts = file.split(".")
+ if len(parts)>1:
+ suffix = parts[-1].upper()
+ else:
+ suffix = None
+ prefix = parts[0].upper()
+ if len(prefix) <= 8 and (not suffix or len(suffix)<=3):
+ if suffix:
+ file = prefix+"."+suffix
+ else:
+ file = prefix
+ assert file not in self.short_names
+ else:
+ prefix = prefix[:6]
+ if suffix:
+ suffix = suffix[:3]
+ pos = 1
+ while 1:
+ if suffix:
+ file = "%s~%d.%s" % (prefix, pos, suffix)
+ else:
+ file = "%s~%d" % (prefix, pos)
+ if file not in self.short_names: break
+ pos += 1
+ assert pos < 10000
+ if pos in (10, 100, 1000):
+ prefix = prefix[:-1]
+ self.short_names.add(file)
+ return file
+
+ def add_file(self, file, src=None, version=None, language=None):
+ """Add a file to the current component of the directory, starting a new one
+ one if there is no current component. By default, the file name in the source
+ and the file table will be identical. If the src file is specified, it is
+ interpreted relative to the current directory. Optionally, a version and a
+ language can be specified for the entry in the File table."""
+ if not self.component:
+ self.start_component(self.logical, current_feature)
+ if not src:
+ # Allow relative paths for file if src is not specified
+ src = file
+ file = os.path.basename(file)
+ absolute = os.path.join(self.absolute, src)
+ assert not re.search(r'[\?|><:/*]"', file) # restrictions on long names
+ if self.keyfiles.has_key(file):
+ logical = self.keyfiles[file]
+ else:
+ logical = None
+ sequence, logical = self.cab.append(absolute, file, logical)
+ assert logical not in self.ids
+ self.ids.add(logical)
+ short = self.make_short(file)
+ full = "%s|%s" % (short, file)
+ filesize = os.stat(absolute).st_size
+ # constants.msidbFileAttributesVital
+ # Compressed omitted, since it is the database default
+ # could add r/o, system, hidden
+ attributes = 512
+ add_data(self.db, "File",
+ [(logical, self.component, full, filesize, version,
+ language, attributes, sequence)])
+ if not version:
+ # Add hash if the file is not versioned
+ filehash = MakeInstaller().FileHash(absolute, 0)
+ add_data(self.db, "MsiFileHash",
+ [(logical, 0, filehash.IntegerData(1),
+ filehash.IntegerData(2), filehash.IntegerData(3),
+ filehash.IntegerData(4))])
+ # Automatically remove .pyc/.pyo files on uninstall (2)
+ # XXX: adding so many RemoveFile entries makes installer unbelievably
+ # slow. So instead, we have to use wildcard remove entries
+ # if file.endswith(".py"):
+ # add_data(self.db, "RemoveFile",
+ # [(logical+"c", self.component, "%sC|%sc" % (short, file),
+ # self.logical, 2),
+ # (logical+"o", self.component, "%sO|%so" % (short, file),
+ # self.logical, 2)])
+
+ def glob(self, pattern, exclude = None):
+ """Add a list of files to the current component as specified in the
+ glob pattern. Individual files can be excluded in the exclude list."""
+ files = glob.glob1(self.absolute, pattern)
+ for f in files:
+ if exclude and f in exclude: continue
+ self.add_file(f)
+ return files
+
+ def remove_pyc(self):
+ "Remove .pyc/.pyo files on uninstall"
+ add_data(self.db, "RemoveFile",
+ [(self.component+"c", self.component, "*.pyc", self.logical, 2),
+ (self.component+"o", self.component, "*.pyo", self.logical, 2)])
+
+ def removefile(self, key, pattern):
+ "Add a RemoveFile entry"
+ add_data(self.db, "RemoveFile", [(self.component+key, self.component, pattern, self.logical, 2)])
+
+
+class Feature:
+ def __init__(self, db, id, title, desc, display, level = 1,
+ parent=None, directory = None, attributes=0):
+ self.id = id
+ if parent:
+ parent = parent.id
+ add_data(db, "Feature",
+ [(id, parent, title, desc, display,
+ level, directory, attributes)])
+ def set_current(self):
+ global current_feature
+ current_feature = self
+
+class Control:
+ def __init__(self, dlg, name):
+ self.dlg = dlg
+ self.name = name
+
+ def event(self, ev, arg, cond = "1", order = None):
+ add_data(self.dlg.db, "ControlEvent",
+ [(self.dlg.name, self.name, ev, arg, cond, order)])
+
+ def mapping(self, ev, attr):
+ add_data(self.dlg.db, "EventMapping",
+ [(self.dlg.name, self.name, ev, attr)])
+
+ def condition(self, action, condition):
+ add_data(self.dlg.db, "ControlCondition",
+ [(self.dlg.name, self.name, action, condition)])
+
+class RadioButtonGroup(Control):
+ def __init__(self, dlg, name, property):
+ self.dlg = dlg
+ self.name = name
+ self.property = property
+ self.index = 1
+
+ def add(self, name, x, y, w, h, text, value = None):
+ if value is None:
+ value = name
+ add_data(self.dlg.db, "RadioButton",
+ [(self.property, self.index, value,
+ x, y, w, h, text, None)])
+ self.index += 1
+
+class Dialog:
+ def __init__(self, db, name, x, y, w, h, attr, title, first, default, cancel):
+ self.db = db
+ self.name = name
+ self.x, self.y, self.w, self.h = x,y,w,h
+ add_data(db, "Dialog", [(name, x,y,w,h,attr,title,first,default,cancel)])
+
+ def control(self, name, type, x, y, w, h, attr, prop, text, next, help):
+ add_data(self.db, "Control",
+ [(self.name, name, type, x, y, w, h, attr, prop, text, next, help)])
+ return Control(self, name)
+
+ def text(self, name, x, y, w, h, attr, text):
+ return self.control(name, "Text", x, y, w, h, attr, None,
+ text, None, None)
+
+ def bitmap(self, name, x, y, w, h, text):
+ return self.control(name, "Bitmap", x, y, w, h, 1, None, text, None, None)
+
+ def line(self, name, x, y, w, h):
+ return self.control(name, "Line", x, y, w, h, 1, None, None, None, None)
+
+ def pushbutton(self, name, x, y, w, h, attr, text, next):
+ return self.control(name, "PushButton", x, y, w, h, attr, None, text, next, None)
+
+ def radiogroup(self, name, x, y, w, h, attr, prop, text, next):
+ add_data(self.db, "Control",
+ [(self.name, name, "RadioButtonGroup",
+ x, y, w, h, attr, prop, text, next, None)])
+ return RadioButtonGroup(self, name, prop)
+
+ def checkbox(self, name, x, y, w, h, attr, prop, text, next):
+ return self.control(name, "CheckBox", x, y, w, h, attr, prop, text, next, None)
+
+def pe_type(path):
+ header = open(path, "rb").read(1000)
+ # offset of PE header is at offset 0x3c
+ pe_offset = struct.unpack("<i", header[0x3c:0x40])[0]
+ assert header[pe_offset:pe_offset+4] == "PE\0\0"
+ machine = struct.unpack("<H", header[pe_offset+4:pe_offset+6])[0]
+ return machine
+
+def set_arch_from_file(path):
+ global msi_type, Win64, arch_ext
+ machine = pe_type(path)
+ if machine == 0x14c:
+ # i386
+ msi_type = "Intel"
+ Win64 = 0
+ arch_ext = ''
+ elif machine == 0x200:
+ # Itanium
+ msi_type = "Intel64"
+ Win64 = 1
+ arch_ext = '.ia64'
+ elif machine == 0x8664:
+ # AMD64
+ msi_type = "x64"
+ Win64 = 1
+ arch_ext = '.amd64'
+ else:
+ raise ValueError, "Unsupported architecture"
+ msi_type += ";1033"
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.c b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.c
new file mode 100644
index 0000000000..87a4e6b1ec
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.c
@@ -0,0 +1,93 @@
+#include "windows.h"
+#include "msiquery.h"
+
+/* Print a debug message to the installer log file.
+ * To see the debug messages, install with
+ * msiexec /i pythonxy.msi /l*v python.log
+ */
+static UINT debug(MSIHANDLE hInstall, LPCSTR msg)
+{
+ MSIHANDLE hRec = MsiCreateRecord(1);
+ if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) {
+ return ERROR_INSTALL_FAILURE;
+ }
+ MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec);
+ MsiCloseHandle(hRec);
+ return ERROR_SUCCESS;
+}
+
+/* Check whether the TARGETDIR exists and is a directory.
+ * Set TargetExists appropriately.
+ */
+UINT __declspec(dllexport) __stdcall CheckDir(MSIHANDLE hInstall)
+{
+#define PSIZE 1024
+ WCHAR wpath[PSIZE];
+ char path[PSIZE];
+ UINT result;
+ DWORD size = PSIZE;
+ DWORD attributes;
+
+
+ result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size);
+ if (result != ERROR_SUCCESS)
+ return result;
+ wpath[size] = L'\0';
+ path[size] = L'\0';
+
+ attributes = GetFileAttributesW(wpath);
+ if (attributes == INVALID_FILE_ATTRIBUTES ||
+ !(attributes & FILE_ATTRIBUTE_DIRECTORY))
+ {
+ return MsiSetPropertyA(hInstall, "TargetExists", "0");
+ } else {
+ return MsiSetPropertyA(hInstall, "TargetExists", "1");
+ }
+}
+
+/* Update the state of the REGISTRY.tcl component according to the
+ * Extension and TclTk features. REGISTRY.tcl must be installed
+ * if both features are installed, and must be absent otherwise.
+ */
+UINT __declspec(dllexport) __stdcall UpdateEditIDLE(MSIHANDLE hInstall)
+{
+ INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new;
+ UINT result;
+
+ result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new);
+ if (result != ERROR_SUCCESS)
+ return result;
+ result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new);
+ if (result != ERROR_SUCCESS)
+ return result;
+
+ /* If the current state is Absent, and the user did not select
+ the feature in the UI, Installer apparently sets the "selected"
+ state to unknown. Update it to the current value, then. */
+ if (ext_new == INSTALLSTATE_UNKNOWN)
+ ext_new = ext_old;
+ if (tcl_new == INSTALLSTATE_UNKNOWN)
+ tcl_new = tcl_old;
+
+ // XXX consider current state of REGISTRY.tcl?
+ if (((tcl_new == INSTALLSTATE_LOCAL) ||
+ (tcl_new == INSTALLSTATE_SOURCE) ||
+ (tcl_new == INSTALLSTATE_DEFAULT)) &&
+ ((ext_new == INSTALLSTATE_LOCAL) ||
+ (ext_new == INSTALLSTATE_SOURCE) ||
+ (ext_new == INSTALLSTATE_DEFAULT))) {
+ reg_new = INSTALLSTATE_SOURCE;
+ } else {
+ reg_new = INSTALLSTATE_ABSENT;
+ }
+ result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new);
+ return result;
+}
+
+BOOL APIENTRY DllMain(HANDLE hModule,
+ DWORD ul_reason_for_call,
+ LPVOID lpReserved)
+{
+ return TRUE;
+}
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.mak b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.mak
new file mode 100644
index 0000000000..f6e2b02c23
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/msisupport.mak
@@ -0,0 +1,9 @@
+# /OPT: REF and ICF are added by VS.NET by default
+msisupport.dll: msisupport.obj
+ link.exe /OUT:msisupport.dll /INCREMENTAL:NO /NOLOGO /DLL /SUBSYSTEM:WINDOWS /OPT:REF /OPT:ICF msisupport.obj msi.lib kernel32.lib
+
+# We request a static CRT, so that there will be no CRT dependencies
+# for the target system. We cannot do without a CRT, since it provides
+# the DLL entry point.
+msisupport.obj: msisupport.c
+ cl /O2 /D WIN32 /D NDEBUG /D _WINDOWS /MT /W3 /c msisupport.c
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/schema.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/schema.py
new file mode 100644
index 0000000000..f99b4406a4
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/schema.py
@@ -0,0 +1,1007 @@
+from msilib import Table
+
+_Validation = Table('_Validation')
+_Validation.add_field(1,'Table',11552)
+_Validation.add_field(2,'Column',11552)
+_Validation.add_field(3,'Nullable',3332)
+_Validation.add_field(4,'MinValue',4356)
+_Validation.add_field(5,'MaxValue',4356)
+_Validation.add_field(6,'KeyTable',7679)
+_Validation.add_field(7,'KeyColumn',5378)
+_Validation.add_field(8,'Category',7456)
+_Validation.add_field(9,'Set',7679)
+_Validation.add_field(10,'Description',7679)
+
+ActionText = Table('ActionText')
+ActionText.add_field(1,'Action',11592)
+ActionText.add_field(2,'Description',7936)
+ActionText.add_field(3,'Template',7936)
+
+AdminExecuteSequence = Table('AdminExecuteSequence')
+AdminExecuteSequence.add_field(1,'Action',0x2DFF)
+AdminExecuteSequence.add_field(2,'Condition',7679)
+AdminExecuteSequence.add_field(3,'Sequence',5378)
+
+Condition = Table('Condition')
+Condition.add_field(1,'Feature_',11558)
+Condition.add_field(2,'Level',9474)
+Condition.add_field(3,'Condition',7679)
+
+AdminUISequence = Table('AdminUISequence')
+AdminUISequence.add_field(1,'Action',0x2DFF)
+AdminUISequence.add_field(2,'Condition',7679)
+AdminUISequence.add_field(3,'Sequence',5378)
+
+AdvtExecuteSequence = Table('AdvtExecuteSequence')
+AdvtExecuteSequence.add_field(1,'Action',0x2DFF)
+AdvtExecuteSequence.add_field(2,'Condition',7679)
+AdvtExecuteSequence.add_field(3,'Sequence',5378)
+
+AdvtUISequence = Table('AdvtUISequence')
+AdvtUISequence.add_field(1,'Action',11592)
+AdvtUISequence.add_field(2,'Condition',7679)
+AdvtUISequence.add_field(3,'Sequence',5378)
+
+AppId = Table('AppId')
+AppId.add_field(1,'AppId',11558)
+AppId.add_field(2,'RemoteServerName',7679)
+AppId.add_field(3,'LocalService',7679)
+AppId.add_field(4,'ServiceParameters',7679)
+AppId.add_field(5,'DllSurrogate',7679)
+AppId.add_field(6,'ActivateAtStorage',5378)
+AppId.add_field(7,'RunAsInteractiveUser',5378)
+
+AppSearch = Table('AppSearch')
+AppSearch.add_field(1,'Property',11592)
+AppSearch.add_field(2,'Signature_',11592)
+
+Property = Table('Property')
+Property.add_field(1,'Property',11592)
+Property.add_field(2,'Value',3840)
+
+BBControl = Table('BBControl')
+BBControl.add_field(1,'Billboard_',11570)
+BBControl.add_field(2,'BBControl',11570)
+BBControl.add_field(3,'Type',3378)
+BBControl.add_field(4,'X',1282)
+BBControl.add_field(5,'Y',1282)
+BBControl.add_field(6,'Width',1282)
+BBControl.add_field(7,'Height',1282)
+BBControl.add_field(8,'Attributes',4356)
+BBControl.add_field(9,'Text',7986)
+
+Billboard = Table('Billboard')
+Billboard.add_field(1,'Billboard',11570)
+Billboard.add_field(2,'Feature_',3366)
+Billboard.add_field(3,'Action',7474)
+Billboard.add_field(4,'Ordering',5378)
+
+Feature = Table('Feature')
+Feature.add_field(1,'Feature',11558)
+Feature.add_field(2,'Feature_Parent',7462)
+Feature.add_field(3,'Title',8000)
+Feature.add_field(4,'Description',8191)
+Feature.add_field(5,'Display',5378)
+Feature.add_field(6,'Level',1282)
+Feature.add_field(7,'Directory_',0x1DFF)
+Feature.add_field(8,'Attributes',1282)
+
+Binary = Table('Binary')
+Binary.add_field(1,'Name',11592)
+Binary.add_field(2,'Data',2304)
+
+BindImage = Table('BindImage')
+BindImage.add_field(1,'File_',0x2DFF)
+BindImage.add_field(2,'Path',7679)
+
+File = Table('File')
+File.add_field(1,'File',0x2DFF)
+File.add_field(2,'Component_',0xDFF)
+File.add_field(3,'FileName',4095)
+File.add_field(4,'FileSize',260)
+File.add_field(5,'Version',0x1DFF)
+File.add_field(6,'Language',7444)
+File.add_field(7,'Attributes',5378)
+File.add_field(8,'Sequence',1282)
+
+CCPSearch = Table('CCPSearch')
+CCPSearch.add_field(1,'Signature_',11592)
+
+CheckBox = Table('CheckBox')
+CheckBox.add_field(1,'Property',11592)
+CheckBox.add_field(2,'Value',7488)
+
+Class = Table('Class')
+Class.add_field(1,'CLSID',11558)
+Class.add_field(2,'Context',11552)
+Class.add_field(3,'Component_',0x2DFF)
+Class.add_field(4,'ProgId_Default',7679)
+Class.add_field(5,'Description',8191)
+Class.add_field(6,'AppId_',7462)
+Class.add_field(7,'FileTypeMask',7679)
+Class.add_field(8,'Icon_',7496)
+Class.add_field(9,'IconIndex',5378)
+Class.add_field(10,'DefInprocHandler',7456)
+Class.add_field(11,'Argument',7679)
+Class.add_field(12,'Feature_',3366)
+Class.add_field(13,'Attributes',5378)
+
+Component = Table('Component')
+Component.add_field(1,'Component',0x2DFF)
+Component.add_field(2,'ComponentId',7462)
+Component.add_field(3,'Directory_',0xDFF)
+Component.add_field(4,'Attributes',1282)
+Component.add_field(5,'Condition',7679)
+Component.add_field(6,'KeyPath',0x1DFF)
+
+Icon = Table('Icon')
+Icon.add_field(1,'Name',11592)
+Icon.add_field(2,'Data',2304)
+
+ProgId = Table('ProgId')
+ProgId.add_field(1,'ProgId',11775)
+ProgId.add_field(2,'ProgId_Parent',7679)
+ProgId.add_field(3,'Class_',7462)
+ProgId.add_field(4,'Description',8191)
+ProgId.add_field(5,'Icon_',7496)
+ProgId.add_field(6,'IconIndex',5378)
+
+ComboBox = Table('ComboBox')
+ComboBox.add_field(1,'Property',11592)
+ComboBox.add_field(2,'Order',9474)
+ComboBox.add_field(3,'Value',3392)
+ComboBox.add_field(4,'Text',8000)
+
+CompLocator = Table('CompLocator')
+CompLocator.add_field(1,'Signature_',11592)
+CompLocator.add_field(2,'ComponentId',3366)
+CompLocator.add_field(3,'Type',5378)
+
+Complus = Table('Complus')
+Complus.add_field(1,'Component_',0x2DFF)
+Complus.add_field(2,'ExpType',13570)
+
+Directory = Table('Directory')
+Directory.add_field(1,'Directory',0x2DFF)
+Directory.add_field(2,'Directory_Parent',0x1DFF)
+Directory.add_field(3,'DefaultDir',4095)
+
+Control = Table('Control')
+Control.add_field(1,'Dialog_',11592)
+Control.add_field(2,'Control',11570)
+Control.add_field(3,'Type',3348)
+Control.add_field(4,'X',1282)
+Control.add_field(5,'Y',1282)
+Control.add_field(6,'Width',1282)
+Control.add_field(7,'Height',1282)
+Control.add_field(8,'Attributes',4356)
+Control.add_field(9,'Property',7474)
+Control.add_field(10,'Text',7936)
+Control.add_field(11,'Control_Next',7474)
+Control.add_field(12,'Help',7986)
+
+Dialog = Table('Dialog')
+Dialog.add_field(1,'Dialog',11592)
+Dialog.add_field(2,'HCentering',1282)
+Dialog.add_field(3,'VCentering',1282)
+Dialog.add_field(4,'Width',1282)
+Dialog.add_field(5,'Height',1282)
+Dialog.add_field(6,'Attributes',4356)
+Dialog.add_field(7,'Title',8064)
+Dialog.add_field(8,'Control_First',3378)
+Dialog.add_field(9,'Control_Default',7474)
+Dialog.add_field(10,'Control_Cancel',7474)
+
+ControlCondition = Table('ControlCondition')
+ControlCondition.add_field(1,'Dialog_',11592)
+ControlCondition.add_field(2,'Control_',11570)
+ControlCondition.add_field(3,'Action',11570)
+ControlCondition.add_field(4,'Condition',11775)
+
+ControlEvent = Table('ControlEvent')
+ControlEvent.add_field(1,'Dialog_',11592)
+ControlEvent.add_field(2,'Control_',11570)
+ControlEvent.add_field(3,'Event',11570)
+ControlEvent.add_field(4,'Argument',11775)
+ControlEvent.add_field(5,'Condition',15871)
+ControlEvent.add_field(6,'Ordering',5378)
+
+CreateFolder = Table('CreateFolder')
+CreateFolder.add_field(1,'Directory_',0x2DFF)
+CreateFolder.add_field(2,'Component_',0x2DFF)
+
+CustomAction = Table('CustomAction')
+CustomAction.add_field(1,'Action',0x2DFF)
+CustomAction.add_field(2,'Type',1282)
+CustomAction.add_field(3,'Source',0x1DFF)
+CustomAction.add_field(4,'Target',7679)
+
+DrLocator = Table('DrLocator')
+DrLocator.add_field(1,'Signature_',11592)
+DrLocator.add_field(2,'Parent',15688)
+DrLocator.add_field(3,'Path',15871)
+DrLocator.add_field(4,'Depth',5378)
+
+DuplicateFile = Table('DuplicateFile')
+DuplicateFile.add_field(1,'FileKey',11592)
+DuplicateFile.add_field(2,'Component_',0xDFF)
+DuplicateFile.add_field(3,'File_',0xDFF)
+DuplicateFile.add_field(4,'DestName',8191)
+DuplicateFile.add_field(5,'DestFolder',7496)
+
+Environment = Table('Environment')
+Environment.add_field(1,'Environment',11592)
+Environment.add_field(2,'Name',4095)
+Environment.add_field(3,'Value',8191)
+Environment.add_field(4,'Component_',0xDFF)
+
+Error = Table('Error')
+Error.add_field(1,'Error',9474)
+Error.add_field(2,'Message',7936)
+
+EventMapping = Table('EventMapping')
+EventMapping.add_field(1,'Dialog_',11592)
+EventMapping.add_field(2,'Control_',11570)
+EventMapping.add_field(3,'Event',11570)
+EventMapping.add_field(4,'Attribute',3378)
+
+Extension = Table('Extension')
+Extension.add_field(1,'Extension',11775)
+Extension.add_field(2,'Component_',0x2DFF)
+Extension.add_field(3,'ProgId_',7679)
+Extension.add_field(4,'MIME_',7488)
+Extension.add_field(5,'Feature_',3366)
+
+MIME = Table('MIME')
+MIME.add_field(1,'ContentType',11584)
+MIME.add_field(2,'Extension_',3583)
+MIME.add_field(3,'CLSID',7462)
+
+FeatureComponents = Table('FeatureComponents')
+FeatureComponents.add_field(1,'Feature_',11558)
+FeatureComponents.add_field(2,'Component_',0x2DFF)
+
+FileSFPCatalog = Table('FileSFPCatalog')
+FileSFPCatalog.add_field(1,'File_',0x2DFF)
+FileSFPCatalog.add_field(2,'SFPCatalog_',11775)
+
+SFPCatalog = Table('SFPCatalog')
+SFPCatalog.add_field(1,'SFPCatalog',11775)
+SFPCatalog.add_field(2,'Catalog',2304)
+SFPCatalog.add_field(3,'Dependency',7424)
+
+Font = Table('Font')
+Font.add_field(1,'File_',0x2DFF)
+Font.add_field(2,'FontTitle',7552)
+
+IniFile = Table('IniFile')
+IniFile.add_field(1,'IniFile',11592)
+IniFile.add_field(2,'FileName',4095)
+IniFile.add_field(3,'DirProperty',7496)
+IniFile.add_field(4,'Section',3936)
+IniFile.add_field(5,'Key',3968)
+IniFile.add_field(6,'Value',4095)
+IniFile.add_field(7,'Action',1282)
+IniFile.add_field(8,'Component_',0xDFF)
+
+IniLocator = Table('IniLocator')
+IniLocator.add_field(1,'Signature_',11592)
+IniLocator.add_field(2,'FileName',3583)
+IniLocator.add_field(3,'Section',3424)
+IniLocator.add_field(4,'Key',3456)
+IniLocator.add_field(5,'Field',5378)
+IniLocator.add_field(6,'Type',5378)
+
+InstallExecuteSequence = Table('InstallExecuteSequence')
+InstallExecuteSequence.add_field(1,'Action',0x2DFF)
+InstallExecuteSequence.add_field(2,'Condition',7679)
+InstallExecuteSequence.add_field(3,'Sequence',5378)
+
+InstallUISequence = Table('InstallUISequence')
+InstallUISequence.add_field(1,'Action',0x2DFF)
+InstallUISequence.add_field(2,'Condition',7679)
+InstallUISequence.add_field(3,'Sequence',5378)
+
+IsolatedComponent = Table('IsolatedComponent')
+IsolatedComponent.add_field(1,'Component_Shared',0x2DFF)
+IsolatedComponent.add_field(2,'Component_Application',0x2DFF)
+
+LaunchCondition = Table('LaunchCondition')
+LaunchCondition.add_field(1,'Condition',11775)
+LaunchCondition.add_field(2,'Description',4095)
+
+ListBox = Table('ListBox')
+ListBox.add_field(1,'Property',11592)
+ListBox.add_field(2,'Order',9474)
+ListBox.add_field(3,'Value',3392)
+ListBox.add_field(4,'Text',8000)
+
+ListView = Table('ListView')
+ListView.add_field(1,'Property',11592)
+ListView.add_field(2,'Order',9474)
+ListView.add_field(3,'Value',3392)
+ListView.add_field(4,'Text',8000)
+ListView.add_field(5,'Binary_',7496)
+
+LockPermissions = Table('LockPermissions')
+LockPermissions.add_field(1,'LockObject',11592)
+LockPermissions.add_field(2,'Table',11552)
+LockPermissions.add_field(3,'Domain',15871)
+LockPermissions.add_field(4,'User',11775)
+LockPermissions.add_field(5,'Permission',4356)
+
+Media = Table('Media')
+Media.add_field(1,'DiskId',9474)
+Media.add_field(2,'LastSequence',1282)
+Media.add_field(3,'DiskPrompt',8000)
+Media.add_field(4,'Cabinet',7679)
+Media.add_field(5,'VolumeLabel',7456)
+Media.add_field(6,'Source',7496)
+
+MoveFile = Table('MoveFile')
+MoveFile.add_field(1,'FileKey',11592)
+MoveFile.add_field(2,'Component_',0xDFF)
+MoveFile.add_field(3,'SourceName',8191)
+MoveFile.add_field(4,'DestName',8191)
+MoveFile.add_field(5,'SourceFolder',7496)
+MoveFile.add_field(6,'DestFolder',3400)
+MoveFile.add_field(7,'Options',1282)
+
+MsiAssembly = Table('MsiAssembly')
+MsiAssembly.add_field(1,'Component_',0x2DFF)
+MsiAssembly.add_field(2,'Feature_',3366)
+MsiAssembly.add_field(3,'File_Manifest',0x1DFF)
+MsiAssembly.add_field(4,'File_Application',0x1DFF)
+MsiAssembly.add_field(5,'Attributes',5378)
+
+MsiAssemblyName = Table('MsiAssemblyName')
+MsiAssemblyName.add_field(1,'Component_',0x2DFF)
+MsiAssemblyName.add_field(2,'Name',11775)
+MsiAssemblyName.add_field(3,'Value',3583)
+
+MsiDigitalCertificate = Table('MsiDigitalCertificate')
+MsiDigitalCertificate.add_field(1,'DigitalCertificate',11592)
+MsiDigitalCertificate.add_field(2,'CertData',2304)
+
+MsiDigitalSignature = Table('MsiDigitalSignature')
+MsiDigitalSignature.add_field(1,'Table',11552)
+MsiDigitalSignature.add_field(2,'SignObject',11592)
+MsiDigitalSignature.add_field(3,'DigitalCertificate_',3400)
+MsiDigitalSignature.add_field(4,'Hash',6400)
+
+MsiFileHash = Table('MsiFileHash')
+MsiFileHash.add_field(1,'File_',0x2DFF)
+MsiFileHash.add_field(2,'Options',1282)
+MsiFileHash.add_field(3,'HashPart1',260)
+MsiFileHash.add_field(4,'HashPart2',260)
+MsiFileHash.add_field(5,'HashPart3',260)
+MsiFileHash.add_field(6,'HashPart4',260)
+
+MsiPatchHeaders = Table('MsiPatchHeaders')
+MsiPatchHeaders.add_field(1,'StreamRef',11558)
+MsiPatchHeaders.add_field(2,'Header',2304)
+
+ODBCAttribute = Table('ODBCAttribute')
+ODBCAttribute.add_field(1,'Driver_',11592)
+ODBCAttribute.add_field(2,'Attribute',11560)
+ODBCAttribute.add_field(3,'Value',8191)
+
+ODBCDriver = Table('ODBCDriver')
+ODBCDriver.add_field(1,'Driver',11592)
+ODBCDriver.add_field(2,'Component_',0xDFF)
+ODBCDriver.add_field(3,'Description',3583)
+ODBCDriver.add_field(4,'File_',0xDFF)
+ODBCDriver.add_field(5,'File_Setup',0x1DFF)
+
+ODBCDataSource = Table('ODBCDataSource')
+ODBCDataSource.add_field(1,'DataSource',0x2DFF)
+ODBCDataSource.add_field(2,'Component_',0xDFF)
+ODBCDataSource.add_field(3,'Description',3583)
+ODBCDataSource.add_field(4,'DriverDescription',3583)
+ODBCDataSource.add_field(5,'Registration',1282)
+
+ODBCSourceAttribute = Table('ODBCSourceAttribute')
+ODBCSourceAttribute.add_field(1,'DataSource_',11592)
+ODBCSourceAttribute.add_field(2,'Attribute',11552)
+ODBCSourceAttribute.add_field(3,'Value',8191)
+
+ODBCTranslator = Table('ODBCTranslator')
+ODBCTranslator.add_field(1,'Translator',11592)
+ODBCTranslator.add_field(2,'Component_',0xDFF)
+ODBCTranslator.add_field(3,'Description',3583)
+ODBCTranslator.add_field(4,'File_',0xDFF)
+ODBCTranslator.add_field(5,'File_Setup',0x1DFF)
+
+Patch = Table('Patch')
+Patch.add_field(1,'File_',11592)
+Patch.add_field(2,'Sequence',9474)
+Patch.add_field(3,'PatchSize',260)
+Patch.add_field(4,'Attributes',1282)
+Patch.add_field(5,'Header',6400)
+Patch.add_field(6,'StreamRef_',7462)
+
+PatchPackage = Table('PatchPackage')
+PatchPackage.add_field(1,'PatchId',11558)
+PatchPackage.add_field(2,'Media_',1282)
+
+PublishComponent = Table('PublishComponent')
+PublishComponent.add_field(1,'ComponentId',11558)
+PublishComponent.add_field(2,'Qualifier',11775)
+PublishComponent.add_field(3,'Component_',0x2DFF)
+PublishComponent.add_field(4,'AppData',8191)
+PublishComponent.add_field(5,'Feature_',3366)
+
+RadioButton = Table('RadioButton')
+RadioButton.add_field(1,'Property',11592)
+RadioButton.add_field(2,'Order',9474)
+RadioButton.add_field(3,'Value',3392)
+RadioButton.add_field(4,'X',1282)
+RadioButton.add_field(5,'Y',1282)
+RadioButton.add_field(6,'Width',1282)
+RadioButton.add_field(7,'Height',1282)
+RadioButton.add_field(8,'Text',8000)
+RadioButton.add_field(9,'Help',7986)
+
+Registry = Table('Registry')
+Registry.add_field(1,'Registry',0x2DFF)
+Registry.add_field(2,'Root',1282)
+Registry.add_field(3,'Key',4095)
+Registry.add_field(4,'Name',8191)
+Registry.add_field(5,'Value',7936)
+Registry.add_field(6,'Component_',0xDFF)
+
+RegLocator = Table('RegLocator')
+RegLocator.add_field(1,'Signature_',11592)
+RegLocator.add_field(2,'Root',1282)
+RegLocator.add_field(3,'Key',3583)
+RegLocator.add_field(4,'Name',7679)
+RegLocator.add_field(5,'Type',5378)
+
+RemoveFile = Table('RemoveFile')
+RemoveFile.add_field(1,'FileKey',11592)
+RemoveFile.add_field(2,'Component_',0xDFF)
+RemoveFile.add_field(3,'FileName',8191)
+RemoveFile.add_field(4,'DirProperty',3400)
+RemoveFile.add_field(5,'InstallMode',1282)
+
+RemoveIniFile = Table('RemoveIniFile')
+RemoveIniFile.add_field(1,'RemoveIniFile',11592)
+RemoveIniFile.add_field(2,'FileName',4095)
+RemoveIniFile.add_field(3,'DirProperty',7496)
+RemoveIniFile.add_field(4,'Section',3936)
+RemoveIniFile.add_field(5,'Key',3968)
+RemoveIniFile.add_field(6,'Value',8191)
+RemoveIniFile.add_field(7,'Action',1282)
+RemoveIniFile.add_field(8,'Component_',0xDFF)
+
+RemoveRegistry = Table('RemoveRegistry')
+RemoveRegistry.add_field(1,'RemoveRegistry',11592)
+RemoveRegistry.add_field(2,'Root',1282)
+RemoveRegistry.add_field(3,'Key',4095)
+RemoveRegistry.add_field(4,'Name',8191)
+RemoveRegistry.add_field(5,'Component_',0xDFF)
+
+ReserveCost = Table('ReserveCost')
+ReserveCost.add_field(1,'ReserveKey',11592)
+ReserveCost.add_field(2,'Component_',0xDFF)
+ReserveCost.add_field(3,'ReserveFolder',7496)
+ReserveCost.add_field(4,'ReserveLocal',260)
+ReserveCost.add_field(5,'ReserveSource',260)
+
+SelfReg = Table('SelfReg')
+SelfReg.add_field(1,'File_',0x2DFF)
+SelfReg.add_field(2,'Cost',5378)
+
+ServiceControl = Table('ServiceControl')
+ServiceControl.add_field(1,'ServiceControl',11592)
+ServiceControl.add_field(2,'Name',4095)
+ServiceControl.add_field(3,'Event',1282)
+ServiceControl.add_field(4,'Arguments',8191)
+ServiceControl.add_field(5,'Wait',5378)
+ServiceControl.add_field(6,'Component_',0xDFF)
+
+ServiceInstall = Table('ServiceInstall')
+ServiceInstall.add_field(1,'ServiceInstall',11592)
+ServiceInstall.add_field(2,'Name',3583)
+ServiceInstall.add_field(3,'DisplayName',8191)
+ServiceInstall.add_field(4,'ServiceType',260)
+ServiceInstall.add_field(5,'StartType',260)
+ServiceInstall.add_field(6,'ErrorControl',260)
+ServiceInstall.add_field(7,'LoadOrderGroup',7679)
+ServiceInstall.add_field(8,'Dependencies',7679)
+ServiceInstall.add_field(9,'StartName',7679)
+ServiceInstall.add_field(10,'Password',7679)
+ServiceInstall.add_field(11,'Arguments',7679)
+ServiceInstall.add_field(12,'Component_',0xDFF)
+ServiceInstall.add_field(13,'Description',8191)
+
+Shortcut = Table('Shortcut')
+Shortcut.add_field(1,'Shortcut',11592)
+Shortcut.add_field(2,'Directory_',0xDFF)
+Shortcut.add_field(3,'Name',3968)
+Shortcut.add_field(4,'Component_',0xDFF)
+Shortcut.add_field(5,'Target',3400)
+Shortcut.add_field(6,'Arguments',7679)
+Shortcut.add_field(7,'Description',8191)
+Shortcut.add_field(8,'Hotkey',5378)
+Shortcut.add_field(9,'Icon_',7496)
+Shortcut.add_field(10,'IconIndex',5378)
+Shortcut.add_field(11,'ShowCmd',5378)
+Shortcut.add_field(12,'WkDir',7496)
+
+Signature = Table('Signature')
+Signature.add_field(1,'Signature',11592)
+Signature.add_field(2,'FileName',3583)
+Signature.add_field(3,'MinVersion',7444)
+Signature.add_field(4,'MaxVersion',7444)
+Signature.add_field(5,'MinSize',4356)
+Signature.add_field(6,'MaxSize',4356)
+Signature.add_field(7,'MinDate',4356)
+Signature.add_field(8,'MaxDate',4356)
+Signature.add_field(9,'Languages',7679)
+
+TextStyle = Table('TextStyle')
+TextStyle.add_field(1,'TextStyle',11592)
+TextStyle.add_field(2,'FaceName',3360)
+TextStyle.add_field(3,'Size',1282)
+TextStyle.add_field(4,'Color',4356)
+TextStyle.add_field(5,'StyleBits',5378)
+
+TypeLib = Table('TypeLib')
+TypeLib.add_field(1,'LibID',11558)
+TypeLib.add_field(2,'Language',9474)
+TypeLib.add_field(3,'Component_',0x2DFF)
+TypeLib.add_field(4,'Version',4356)
+TypeLib.add_field(5,'Description',8064)
+TypeLib.add_field(6,'Directory_',0x1DFF)
+TypeLib.add_field(7,'Feature_',3366)
+TypeLib.add_field(8,'Cost',4356)
+
+UIText = Table('UIText')
+UIText.add_field(1,'Key',11592)
+UIText.add_field(2,'Text',8191)
+
+Upgrade = Table('Upgrade')
+Upgrade.add_field(1,'UpgradeCode',11558)
+Upgrade.add_field(2,'VersionMin',15636)
+Upgrade.add_field(3,'VersionMax',15636)
+Upgrade.add_field(4,'Language',15871)
+Upgrade.add_field(5,'Attributes',8452)
+Upgrade.add_field(6,'Remove',7679)
+Upgrade.add_field(7,'ActionProperty',3400)
+
+Verb = Table('Verb')
+Verb.add_field(1,'Extension_',11775)
+Verb.add_field(2,'Verb',11552)
+Verb.add_field(3,'Sequence',5378)
+Verb.add_field(4,'Command',8191)
+Verb.add_field(5,'Argument',8191)
+
+tables=[_Validation, ActionText, AdminExecuteSequence, Condition, AdminUISequence, AdvtExecuteSequence, AdvtUISequence, AppId, AppSearch, Property, BBControl, Billboard, Feature, Binary, BindImage, File, CCPSearch, CheckBox, Class, Component, Icon, ProgId, ComboBox, CompLocator, Complus, Directory, Control, Dialog, ControlCondition, ControlEvent, CreateFolder, CustomAction, DrLocator, DuplicateFile, Environment, Error, EventMapping, Extension, MIME, FeatureComponents, FileSFPCatalog, SFPCatalog, Font, IniFile, IniLocator, InstallExecuteSequence, InstallUISequence, IsolatedComponent, LaunchCondition, ListBox, ListView, LockPermissions, Media, MoveFile, MsiAssembly, MsiAssemblyName, MsiDigitalCertificate, MsiDigitalSignature, MsiFileHash, MsiPatchHeaders, ODBCAttribute, ODBCDriver, ODBCDataSource, ODBCSourceAttribute, ODBCTranslator, Patch, PatchPackage, PublishComponent, RadioButton, Registry, RegLocator, RemoveFile, RemoveIniFile, RemoveRegistry, ReserveCost, SelfReg, ServiceControl, ServiceInstall, Shortcut, Signature, TextStyle, TypeLib, UIText, Upgrade, Verb]
+
+_Validation_records = [
+(u'_Validation',u'Table',u'N',None, None, None, None, u'Identifier',None, u'Name of table',),
+(u'_Validation',u'Column',u'N',None, None, None, None, u'Identifier',None, u'Name of column',),
+(u'_Validation',u'Description',u'Y',None, None, None, None, u'Text',None, u'Description of column',),
+(u'_Validation',u'Set',u'Y',None, None, None, None, u'Text',None, u'Set of values that are permitted',),
+(u'_Validation',u'Category',u'Y',None, None, None, None, None, u'Text;Formatted;Template;Condition;Guid;Path;Version;Language;Identifier;Binary;UpperCase;LowerCase;Filename;Paths;AnyPath;WildCardFilename;RegPath;KeyFormatted;CustomSource;Property;Cabinet;Shortcut;URL',u'String category',),
+(u'_Validation',u'KeyColumn',u'Y',1,32,None, None, None, None, u'Column to which foreign key connects',),
+(u'_Validation',u'KeyTable',u'Y',None, None, None, None, u'Identifier',None, u'For foreign key, Name of table to which data must link',),
+(u'_Validation',u'MaxValue',u'Y',-2147483647,2147483647,None, None, None, None, u'Maximum value allowed',),
+(u'_Validation',u'MinValue',u'Y',-2147483647,2147483647,None, None, None, None, u'Minimum value allowed',),
+(u'_Validation',u'Nullable',u'N',None, None, None, None, None, u'Y;N;@',u'Whether the column is nullable',),
+(u'ActionText',u'Description',u'Y',None, None, None, None, u'Text',None, u'Localized description displayed in progress dialog and log when action is executing.',),
+(u'ActionText',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Name of action to be described.',),
+(u'ActionText',u'Template',u'Y',None, None, None, None, u'Template',None, u'Optional localized format template used to format action data records for display during action execution.',),
+(u'AdminExecuteSequence',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Name of action to invoke, either in the engine or the handler DLL.',),
+(u'AdminExecuteSequence',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.',),
+(u'AdminExecuteSequence',u'Sequence',u'Y',-4,32767,None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.',),
+(u'Condition',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'Expression evaluated to determine if Level in the Feature table is to change.',),
+(u'Condition',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'Reference to a Feature entry in Feature table.',),
+(u'Condition',u'Level',u'N',0,32767,None, None, None, None, u'New selection Level to set in Feature table if Condition evaluates to TRUE.',),
+(u'AdminUISequence',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Name of action to invoke, either in the engine or the handler DLL.',),
+(u'AdminUISequence',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.',),
+(u'AdminUISequence',u'Sequence',u'Y',-4,32767,None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.',),
+(u'AdvtExecuteSequence',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Name of action to invoke, either in the engine or the handler DLL.',),
+(u'AdvtExecuteSequence',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.',),
+(u'AdvtExecuteSequence',u'Sequence',u'Y',-4,32767,None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.',),
+(u'AdvtUISequence',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Name of action to invoke, either in the engine or the handler DLL.',),
+(u'AdvtUISequence',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.',),
+(u'AdvtUISequence',u'Sequence',u'Y',-4,32767,None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.',),
+(u'AppId',u'AppId',u'N',None, None, None, None, u'Guid',None, None, ),
+(u'AppId',u'ActivateAtStorage',u'Y',0,1,None, None, None, None, None, ),
+(u'AppId',u'DllSurrogate',u'Y',None, None, None, None, u'Text',None, None, ),
+(u'AppId',u'LocalService',u'Y',None, None, None, None, u'Text',None, None, ),
+(u'AppId',u'RemoteServerName',u'Y',None, None, None, None, u'Formatted',None, None, ),
+(u'AppId',u'RunAsInteractiveUser',u'Y',0,1,None, None, None, None, None, ),
+(u'AppId',u'ServiceParameters',u'Y',None, None, None, None, u'Text',None, None, ),
+(u'AppSearch',u'Property',u'N',None, None, None, None, u'Identifier',None, u'The property associated with a Signature',),
+(u'AppSearch',u'Signature_',u'N',None, None, u'Signature;RegLocator;IniLocator;DrLocator;CompLocator',1,u'Identifier',None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature, RegLocator, IniLocator, CompLocator and the DrLocator tables.',),
+(u'Property',u'Property',u'N',None, None, None, None, u'Identifier',None, u'Name of property, uppercase if settable by launcher or loader.',),
+(u'Property',u'Value',u'N',None, None, None, None, u'Text',None, u'String value for property. Never null or empty.',),
+(u'BBControl',u'Type',u'N',None, None, None, None, u'Identifier',None, u'The type of the control.',),
+(u'BBControl',u'Y',u'N',0,32767,None, None, None, None, u'Vertical coordinate of the upper left corner of the bounding rectangle of the control.',),
+(u'BBControl',u'Text',u'Y',None, None, None, None, u'Text',None, u'A string used to set the initial text contained within a control (if appropriate).',),
+(u'BBControl',u'BBControl',u'N',None, None, None, None, u'Identifier',None, u'Name of the control. This name must be unique within a billboard, but can repeat on different billboard.',),
+(u'BBControl',u'Attributes',u'Y',0,2147483647,None, None, None, None, u'A 32-bit word that specifies the attribute flags to be applied to this control.',),
+(u'BBControl',u'Billboard_',u'N',None, None, u'Billboard',1,u'Identifier',None, u'External key to the Billboard table, name of the billboard.',),
+(u'BBControl',u'Height',u'N',0,32767,None, None, None, None, u'Height of the bounding rectangle of the control.',),
+(u'BBControl',u'Width',u'N',0,32767,None, None, None, None, u'Width of the bounding rectangle of the control.',),
+(u'BBControl',u'X',u'N',0,32767,None, None, None, None, u'Horizontal coordinate of the upper left corner of the bounding rectangle of the control.',),
+(u'Billboard',u'Action',u'Y',None, None, None, None, u'Identifier',None, u'The name of an action. The billboard is displayed during the progress messages received from this action.',),
+(u'Billboard',u'Billboard',u'N',None, None, None, None, u'Identifier',None, u'Name of the billboard.',),
+(u'Billboard',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'An external key to the Feature Table. The billboard is shown only if this feature is being installed.',),
+(u'Billboard',u'Ordering',u'Y',0,32767,None, None, None, None, u'A positive integer. If there is more than one billboard corresponding to an action they will be shown in the order defined by this column.',),
+(u'Feature',u'Description',u'Y',None, None, None, None, u'Text',None, u'Longer descriptive text describing a visible feature item.',),
+(u'Feature',u'Attributes',u'N',None, None, None, None, None, u'0;1;2;4;5;6;8;9;10;16;17;18;20;21;22;24;25;26;32;33;34;36;37;38;48;49;50;52;53;54',u'Feature attributes',),
+(u'Feature',u'Feature',u'N',None, None, None, None, u'Identifier',None, u'Primary key used to identify a particular feature record.',),
+(u'Feature',u'Directory_',u'Y',None, None, u'Directory',1,u'UpperCase',None, u'The name of the Directory that can be configured by the UI. A non-null value will enable the browse button.',),
+(u'Feature',u'Level',u'N',0,32767,None, None, None, None, u'The install level at which record will be initially selected. An install level of 0 will disable an item and prevent its display.',),
+(u'Feature',u'Title',u'Y',None, None, None, None, u'Text',None, u'Short text identifying a visible feature item.',),
+(u'Feature',u'Display',u'Y',0,32767,None, None, None, None, u'Numeric sort order, used to force a specific display ordering.',),
+(u'Feature',u'Feature_Parent',u'Y',None, None, u'Feature',1,u'Identifier',None, u'Optional key of a parent record in the same table. If the parent is not selected, then the record will not be installed. Null indicates a root item.',),
+(u'Binary',u'Name',u'N',None, None, None, None, u'Identifier',None, u'Unique key identifying the binary data.',),
+(u'Binary',u'Data',u'N',None, None, None, None, u'Binary',None, u'The unformatted binary data.',),
+(u'BindImage',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'The index into the File table. This must be an executable file.',),
+(u'BindImage',u'Path',u'Y',None, None, None, None, u'Paths',None, u'A list of ; delimited paths that represent the paths to be searched for the import DLLS. The list is usually a list of properties each enclosed within square brackets [] .',),
+(u'File',u'Sequence',u'N',1,32767,None, None, None, None, u'Sequence with respect to the media images; order must track cabinet order.',),
+(u'File',u'Attributes',u'Y',0,32767,None, None, None, None, u'Integer containing bit flags representing file attributes (with the decimal value of each bit position in parentheses)',),
+(u'File',u'File',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token, must match identifier in cabinet. For uncompressed files, this field is ignored.',),
+(u'File',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key referencing Component that controls the file.',),
+(u'File',u'FileName',u'N',None, None, None, None, u'Filename',None, u'File name used for installation, may be localized. This may contain a "short name|long name" pair.',),
+(u'File',u'FileSize',u'N',0,2147483647,None, None, None, None, u'Size of file in bytes (long integer).',),
+(u'File',u'Language',u'Y',None, None, None, None, u'Language',None, u'List of decimal language Ids, comma-separated if more than one.',),
+(u'File',u'Version',u'Y',None, None, u'File',1,u'Version',None, u'Version string for versioned files; Blank for unversioned files.',),
+(u'CCPSearch',u'Signature_',u'N',None, None, u'Signature;RegLocator;IniLocator;DrLocator;CompLocator',1,u'Identifier',None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature, RegLocator, IniLocator, CompLocator and the DrLocator tables.',),
+(u'CheckBox',u'Property',u'N',None, None, None, None, u'Identifier',None, u'A named property to be tied to the item.',),
+(u'CheckBox',u'Value',u'Y',None, None, None, None, u'Formatted',None, u'The value string associated with the item.',),
+(u'Class',u'Description',u'Y',None, None, None, None, u'Text',None, u'Localized description for the Class.',),
+(u'Class',u'Attributes',u'Y',None, 32767,None, None, None, None, u'Class registration attributes.',),
+(u'Class',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'Required foreign key into the Feature Table, specifying the feature to validate or install in order for the CLSID factory to be operational.',),
+(u'Class',u'AppId_',u'Y',None, None, u'AppId',1,u'Guid',None, u'Optional AppID containing DCOM information for associated application (string GUID).',),
+(u'Class',u'Argument',u'Y',None, None, None, None, u'Formatted',None, u'optional argument for LocalServers.',),
+(u'Class',u'CLSID',u'N',None, None, None, None, u'Guid',None, u'The CLSID of an OLE factory.',),
+(u'Class',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.',),
+(u'Class',u'Context',u'N',None, None, None, None, u'Identifier',None, u'The numeric server context for this server. CLSCTX_xxxx',),
+(u'Class',u'DefInprocHandler',u'Y',None, None, None, None, u'Filename',u'1;2;3',u'Optional default inproc handler. Only optionally provided if Context=CLSCTX_LOCAL_SERVER. Typically "ole32.dll" or "mapi32.dll"',),
+(u'Class',u'FileTypeMask',u'Y',None, None, None, None, u'Text',None, u'Optional string containing information for the HKCRthis CLSID) key. If multiple patterns exist, they must be delimited by a semicolon, and numeric subkeys will be generated: 0,1,2...',),
+(u'Class',u'Icon_',u'Y',None, None, u'Icon',1,u'Identifier',None, u'Optional foreign key into the Icon Table, specifying the icon file associated with this CLSID. Will be written under the DefaultIcon key.',),
+(u'Class',u'IconIndex',u'Y',-32767,32767,None, None, None, None, u'Optional icon index.',),
+(u'Class',u'ProgId_Default',u'Y',None, None, u'ProgId',1,u'Text',None, u'Optional ProgId associated with this CLSID.',),
+(u'Component',u'Condition',u'Y',None, None, None, None, u'Condition',None, u"A conditional statement that will disable this component if the specified condition evaluates to the 'True' state. If a component is disabled, it will not be installed, regardless of the 'Action' state associated with the component.",),
+(u'Component',u'Attributes',u'N',None, None, None, None, None, None, u'Remote execution option, one of irsEnum',),
+(u'Component',u'Component',u'N',None, None, None, None, u'Identifier',None, u'Primary key used to identify a particular component record.',),
+(u'Component',u'ComponentId',u'Y',None, None, None, None, u'Guid',None, u'A string GUID unique to this component, version, and language.',),
+(u'Component',u'Directory_',u'N',None, None, u'Directory',1,u'Identifier',None, u'Required key of a Directory table record. This is actually a property name whose value contains the actual path, set either by the AppSearch action or with the default setting obtained from the Directory table.',),
+(u'Component',u'KeyPath',u'Y',None, None, u'File;Registry;ODBCDataSource',1,u'Identifier',None, u'Either the primary key into the File table, Registry table, or ODBCDataSource table. This extract path is stored when the component is installed, and is used to detect the presence of the component and to return the path to it.',),
+(u'Icon',u'Name',u'N',None, None, None, None, u'Identifier',None, u'Primary key. Name of the icon file.',),
+(u'Icon',u'Data',u'N',None, None, None, None, u'Binary',None, u'Binary stream. The binary icon data in PE (.DLL or .EXE) or icon (.ICO) format.',),
+(u'ProgId',u'Description',u'Y',None, None, None, None, u'Text',None, u'Localized description for the Program identifier.',),
+(u'ProgId',u'Icon_',u'Y',None, None, u'Icon',1,u'Identifier',None, u'Optional foreign key into the Icon Table, specifying the icon file associated with this ProgId. Will be written under the DefaultIcon key.',),
+(u'ProgId',u'IconIndex',u'Y',-32767,32767,None, None, None, None, u'Optional icon index.',),
+(u'ProgId',u'ProgId',u'N',None, None, None, None, u'Text',None, u'The Program Identifier. Primary key.',),
+(u'ProgId',u'Class_',u'Y',None, None, u'Class',1,u'Guid',None, u'The CLSID of an OLE factory corresponding to the ProgId.',),
+(u'ProgId',u'ProgId_Parent',u'Y',None, None, u'ProgId',1,u'Text',None, u'The Parent Program Identifier. If specified, the ProgId column becomes a version independent prog id.',),
+(u'ComboBox',u'Text',u'Y',None, None, None, None, u'Formatted',None, u'The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.',),
+(u'ComboBox',u'Property',u'N',None, None, None, None, u'Identifier',None, u'A named property to be tied to this item. All the items tied to the same property become part of the same combobox.',),
+(u'ComboBox',u'Value',u'N',None, None, None, None, u'Formatted',None, u'The value string associated with this item. Selecting the line will set the associated property to this value.',),
+(u'ComboBox',u'Order',u'N',1,32767,None, None, None, None, u'A positive integer used to determine the ordering of the items within one list.\tThe integers do not have to be consecutive.',),
+(u'CompLocator',u'Type',u'Y',0,1,None, None, None, None, u'A boolean value that determines if the registry value is a filename or a directory location.',),
+(u'CompLocator',u'Signature_',u'N',None, None, None, None, u'Identifier',None, u'The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table.',),
+(u'CompLocator',u'ComponentId',u'N',None, None, None, None, u'Guid',None, u'A string GUID unique to this component, version, and language.',),
+(u'Complus',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key referencing Component that controls the ComPlus component.',),
+(u'Complus',u'ExpType',u'Y',0,32767,None, None, None, None, u'ComPlus component attributes.',),
+(u'Directory',u'Directory',u'N',None, None, None, None, u'Identifier',None, u'Unique identifier for directory entry, primary key. If a property by this name is defined, it contains the full path to the directory.',),
+(u'Directory',u'DefaultDir',u'N',None, None, None, None, u'DefaultDir',None, u"The default sub-path under parent's path.",),
+(u'Directory',u'Directory_Parent',u'Y',None, None, u'Directory',1,u'Identifier',None, u'Reference to the entry in this table specifying the default parent directory. A record parented to itself or with a Null parent represents a root of the install tree.',),
+(u'Control',u'Type',u'N',None, None, None, None, u'Identifier',None, u'The type of the control.',),
+(u'Control',u'Y',u'N',0,32767,None, None, None, None, u'Vertical coordinate of the upper left corner of the bounding rectangle of the control.',),
+(u'Control',u'Text',u'Y',None, None, None, None, u'Formatted',None, u'A string used to set the initial text contained within a control (if appropriate).',),
+(u'Control',u'Property',u'Y',None, None, None, None, u'Identifier',None, u'The name of a defined property to be linked to this control. ',),
+(u'Control',u'Attributes',u'Y',0,2147483647,None, None, None, None, u'A 32-bit word that specifies the attribute flags to be applied to this control.',),
+(u'Control',u'Height',u'N',0,32767,None, None, None, None, u'Height of the bounding rectangle of the control.',),
+(u'Control',u'Width',u'N',0,32767,None, None, None, None, u'Width of the bounding rectangle of the control.',),
+(u'Control',u'X',u'N',0,32767,None, None, None, None, u'Horizontal coordinate of the upper left corner of the bounding rectangle of the control.',),
+(u'Control',u'Control',u'N',None, None, None, None, u'Identifier',None, u'Name of the control. This name must be unique within a dialog, but can repeat on different dialogs. ',),
+(u'Control',u'Control_Next',u'Y',None, None, u'Control',2,u'Identifier',None, u'The name of an other control on the same dialog. This link defines the tab order of the controls. The links have to form one or more cycles!',),
+(u'Control',u'Dialog_',u'N',None, None, u'Dialog',1,u'Identifier',None, u'External key to the Dialog table, name of the dialog.',),
+(u'Control',u'Help',u'Y',None, None, None, None, u'Text',None, u'The help strings used with the button. The text is optional. ',),
+(u'Dialog',u'Attributes',u'Y',0,2147483647,None, None, None, None, u'A 32-bit word that specifies the attribute flags to be applied to this dialog.',),
+(u'Dialog',u'Height',u'N',0,32767,None, None, None, None, u'Height of the bounding rectangle of the dialog.',),
+(u'Dialog',u'Width',u'N',0,32767,None, None, None, None, u'Width of the bounding rectangle of the dialog.',),
+(u'Dialog',u'Dialog',u'N',None, None, None, None, u'Identifier',None, u'Name of the dialog.',),
+(u'Dialog',u'Control_Cancel',u'Y',None, None, u'Control',2,u'Identifier',None, u'Defines the cancel control. Hitting escape or clicking on the close icon on the dialog is equivalent to pushing this button.',),
+(u'Dialog',u'Control_Default',u'Y',None, None, u'Control',2,u'Identifier',None, u'Defines the default control. Hitting return is equivalent to pushing this button.',),
+(u'Dialog',u'Control_First',u'N',None, None, u'Control',2,u'Identifier',None, u'Defines the control that has the focus when the dialog is created.',),
+(u'Dialog',u'HCentering',u'N',0,100,None, None, None, None, u'Horizontal position of the dialog on a 0-100 scale. 0 means left end, 100 means right end of the screen, 50 center.',),
+(u'Dialog',u'Title',u'Y',None, None, None, None, u'Formatted',None, u"A text string specifying the title to be displayed in the title bar of the dialog's window.",),
+(u'Dialog',u'VCentering',u'N',0,100,None, None, None, None, u'Vertical position of the dialog on a 0-100 scale. 0 means top end, 100 means bottom end of the screen, 50 center.',),
+(u'ControlCondition',u'Action',u'N',None, None, None, None, None, u'Default;Disable;Enable;Hide;Show',u'The desired action to be taken on the specified control.',),
+(u'ControlCondition',u'Condition',u'N',None, None, None, None, u'Condition',None, u'A standard conditional statement that specifies under which conditions the action should be triggered.',),
+(u'ControlCondition',u'Dialog_',u'N',None, None, u'Dialog',1,u'Identifier',None, u'A foreign key to the Dialog table, name of the dialog.',),
+(u'ControlCondition',u'Control_',u'N',None, None, u'Control',2,u'Identifier',None, u'A foreign key to the Control table, name of the control.',),
+(u'ControlEvent',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'A standard conditional statement that specifies under which conditions an event should be triggered.',),
+(u'ControlEvent',u'Ordering',u'Y',0,2147483647,None, None, None, None, u'An integer used to order several events tied to the same control. Can be left blank.',),
+(u'ControlEvent',u'Argument',u'N',None, None, None, None, u'Formatted',None, u'A value to be used as a modifier when triggering a particular event.',),
+(u'ControlEvent',u'Dialog_',u'N',None, None, u'Dialog',1,u'Identifier',None, u'A foreign key to the Dialog table, name of the dialog.',),
+(u'ControlEvent',u'Control_',u'N',None, None, u'Control',2,u'Identifier',None, u'A foreign key to the Control table, name of the control',),
+(u'ControlEvent',u'Event',u'N',None, None, None, None, u'Formatted',None, u'An identifier that specifies the type of the event that should take place when the user interacts with control specified by the first two entries.',),
+(u'CreateFolder',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table.',),
+(u'CreateFolder',u'Directory_',u'N',None, None, u'Directory',1,u'Identifier',None, u'Primary key, could be foreign key into the Directory table.',),
+(u'CustomAction',u'Type',u'N',1,16383,None, None, None, None, u'The numeric custom action type, consisting of source location, code type, entry, option flags.',),
+(u'CustomAction',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Primary key, name of action, normally appears in sequence table unless private use.',),
+(u'CustomAction',u'Source',u'Y',None, None, None, None, u'CustomSource',None, u'The table reference of the source of the code.',),
+(u'CustomAction',u'Target',u'Y',None, None, None, None, u'Formatted',None, u'Excecution parameter, depends on the type of custom action',),
+(u'DrLocator',u'Signature_',u'N',None, None, None, None, u'Identifier',None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature table.',),
+(u'DrLocator',u'Path',u'Y',None, None, None, None, u'AnyPath',None, u'The path on the user system. This is a either a subpath below the value of the Parent or a full path. The path may contain properties enclosed within [ ] that will be expanded.',),
+(u'DrLocator',u'Depth',u'Y',0,32767,None, None, None, None, u'The depth below the path to which the Signature_ is recursively searched. If absent, the depth is assumed to be 0.',),
+(u'DrLocator',u'Parent',u'Y',None, None, None, None, u'Identifier',None, u'The parent file signature. It is also a foreign key in the Signature table. If null and the Path column does not expand to a full path, then all the fixed drives of the user system are searched using the Path.',),
+(u'DuplicateFile',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'Foreign key referencing the source file to be duplicated.',),
+(u'DuplicateFile',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key referencing Component that controls the duplicate file.',),
+(u'DuplicateFile',u'DestFolder',u'Y',None, None, None, None, u'Identifier',None, u'Name of a property whose value is assumed to resolve to the full pathname to a destination folder.',),
+(u'DuplicateFile',u'DestName',u'Y',None, None, None, None, u'Filename',None, u'Filename to be given to the duplicate file.',),
+(u'DuplicateFile',u'FileKey',u'N',None, None, None, None, u'Identifier',None, u'Primary key used to identify a particular file entry',),
+(u'Environment',u'Name',u'N',None, None, None, None, u'Text',None, u'The name of the environmental value.',),
+(u'Environment',u'Value',u'Y',None, None, None, None, u'Formatted',None, u'The value to set in the environmental settings.',),
+(u'Environment',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table referencing component that controls the installing of the environmental value.',),
+(u'Environment',u'Environment',u'N',None, None, None, None, u'Identifier',None, u'Unique identifier for the environmental variable setting',),
+(u'Error',u'Error',u'N',0,32767,None, None, None, None, u'Integer error number, obtained from header file IError(...) macros.',),
+(u'Error',u'Message',u'Y',None, None, None, None, u'Template',None, u'Error formatting template, obtained from user ed. or localizers.',),
+(u'EventMapping',u'Dialog_',u'N',None, None, u'Dialog',1,u'Identifier',None, u'A foreign key to the Dialog table, name of the Dialog.',),
+(u'EventMapping',u'Control_',u'N',None, None, u'Control',2,u'Identifier',None, u'A foreign key to the Control table, name of the control.',),
+(u'EventMapping',u'Event',u'N',None, None, None, None, u'Identifier',None, u'An identifier that specifies the type of the event that the control subscribes to.',),
+(u'EventMapping',u'Attribute',u'N',None, None, None, None, u'Identifier',None, u'The name of the control attribute, that is set when this event is received.',),
+(u'Extension',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'Required foreign key into the Feature Table, specifying the feature to validate or install in order for the CLSID factory to be operational.',),
+(u'Extension',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.',),
+(u'Extension',u'Extension',u'N',None, None, None, None, u'Text',None, u'The extension associated with the table row.',),
+(u'Extension',u'MIME_',u'Y',None, None, u'MIME',1,u'Text',None, u'Optional Context identifier, typically "type/format" associated with the extension',),
+(u'Extension',u'ProgId_',u'Y',None, None, u'ProgId',1,u'Text',None, u'Optional ProgId associated with this extension.',),
+(u'MIME',u'CLSID',u'Y',None, None, None, None, u'Guid',None, u'Optional associated CLSID.',),
+(u'MIME',u'ContentType',u'N',None, None, None, None, u'Text',None, u'Primary key. Context identifier, typically "type/format".',),
+(u'MIME',u'Extension_',u'N',None, None, u'Extension',1,u'Text',None, u'Optional associated extension (without dot)',),
+(u'FeatureComponents',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'Foreign key into Feature table.',),
+(u'FeatureComponents',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into Component table.',),
+(u'FileSFPCatalog',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'File associated with the catalog',),
+(u'FileSFPCatalog',u'SFPCatalog_',u'N',None, None, u'SFPCatalog',1,u'Filename',None, u'Catalog associated with the file',),
+(u'SFPCatalog',u'SFPCatalog',u'N',None, None, None, None, u'Filename',None, u'File name for the catalog.',),
+(u'SFPCatalog',u'Catalog',u'N',None, None, None, None, u'Binary',None, u'SFP Catalog',),
+(u'SFPCatalog',u'Dependency',u'Y',None, None, None, None, u'Formatted',None, u'Parent catalog - only used by SFP',),
+(u'Font',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'Primary key, foreign key into File table referencing font file.',),
+(u'Font',u'FontTitle',u'Y',None, None, None, None, u'Text',None, u'Font name.',),
+(u'IniFile',u'Action',u'N',None, None, None, None, None, u'0;1;3',u'The type of modification to be made, one of iifEnum',),
+(u'IniFile',u'Value',u'N',None, None, None, None, u'Formatted',None, u'The value to be written.',),
+(u'IniFile',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table referencing component that controls the installing of the .INI value.',),
+(u'IniFile',u'FileName',u'N',None, None, None, None, u'Filename',None, u'The .INI file name in which to write the information',),
+(u'IniFile',u'IniFile',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token.',),
+(u'IniFile',u'DirProperty',u'Y',None, None, None, None, u'Identifier',None, u'Foreign key into the Directory table denoting the directory where the .INI file is.',),
+(u'IniFile',u'Key',u'N',None, None, None, None, u'Formatted',None, u'The .INI file key below Section.',),
+(u'IniFile',u'Section',u'N',None, None, None, None, u'Formatted',None, u'The .INI file Section.',),
+(u'IniLocator',u'Type',u'Y',0,2,None, None, None, None, u'An integer value that determines if the .INI value read is a filename or a directory location or to be used as is w/o interpretation.',),
+(u'IniLocator',u'Signature_',u'N',None, None, None, None, u'Identifier',None, u'The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table.',),
+(u'IniLocator',u'FileName',u'N',None, None, None, None, u'Filename',None, u'The .INI file name.',),
+(u'IniLocator',u'Key',u'N',None, None, None, None, u'Text',None, u'Key value (followed by an equals sign in INI file).',),
+(u'IniLocator',u'Section',u'N',None, None, None, None, u'Text',None, u'Section name within in file (within square brackets in INI file).',),
+(u'IniLocator',u'Field',u'Y',0,32767,None, None, None, None, u'The field in the .INI line. If Field is null or 0 the entire line is read.',),
+(u'InstallExecuteSequence',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Name of action to invoke, either in the engine or the handler DLL.',),
+(u'InstallExecuteSequence',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.',),
+(u'InstallExecuteSequence',u'Sequence',u'Y',-4,32767,None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.',),
+(u'InstallUISequence',u'Action',u'N',None, None, None, None, u'Identifier',None, u'Name of action to invoke, either in the engine or the handler DLL.',),
+(u'InstallUISequence',u'Condition',u'Y',None, None, None, None, u'Condition',None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.',),
+(u'InstallUISequence',u'Sequence',u'Y',-4,32767,None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.',),
+(u'IsolatedComponent',u'Component_Application',u'N',None, None, u'Component',1,u'Identifier',None, u'Key to Component table item for application',),
+(u'IsolatedComponent',u'Component_Shared',u'N',None, None, u'Component',1,u'Identifier',None, u'Key to Component table item to be isolated',),
+(u'LaunchCondition',u'Description',u'N',None, None, None, None, u'Formatted',None, u'Localizable text to display when condition fails and install must abort.',),
+(u'LaunchCondition',u'Condition',u'N',None, None, None, None, u'Condition',None, u'Expression which must evaluate to TRUE in order for install to commence.',),
+(u'ListBox',u'Text',u'Y',None, None, None, None, u'Text',None, u'The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.',),
+(u'ListBox',u'Property',u'N',None, None, None, None, u'Identifier',None, u'A named property to be tied to this item. All the items tied to the same property become part of the same listbox.',),
+(u'ListBox',u'Value',u'N',None, None, None, None, u'Formatted',None, u'The value string associated with this item. Selecting the line will set the associated property to this value.',),
+(u'ListBox',u'Order',u'N',1,32767,None, None, None, None, u'A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.',),
+(u'ListView',u'Text',u'Y',None, None, None, None, u'Text',None, u'The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.',),
+(u'ListView',u'Property',u'N',None, None, None, None, u'Identifier',None, u'A named property to be tied to this item. All the items tied to the same property become part of the same listview.',),
+(u'ListView',u'Value',u'N',None, None, None, None, u'Identifier',None, u'The value string associated with this item. Selecting the line will set the associated property to this value.',),
+(u'ListView',u'Order',u'N',1,32767,None, None, None, None, u'A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.',),
+(u'ListView',u'Binary_',u'Y',None, None, u'Binary',1,u'Identifier',None, u'The name of the icon to be displayed with the icon. The binary information is looked up from the Binary Table.',),
+(u'LockPermissions',u'Table',u'N',None, None, None, None, u'Identifier',u'Directory;File;Registry',u'Reference to another table name',),
+(u'LockPermissions',u'Domain',u'Y',None, None, None, None, u'Formatted',None, u'Domain name for user whose permissions are being set. (usually a property)',),
+(u'LockPermissions',u'LockObject',u'N',None, None, None, None, u'Identifier',None, u'Foreign key into Registry or File table',),
+(u'LockPermissions',u'Permission',u'Y',-2147483647,2147483647,None, None, None, None, u'Permission Access mask. Full Control = 268435456 (GENERIC_ALL = 0x10000000)',),
+(u'LockPermissions',u'User',u'N',None, None, None, None, u'Formatted',None, u'User for permissions to be set. (usually a property)',),
+(u'Media',u'Source',u'Y',None, None, None, None, u'Property',None, u'The property defining the location of the cabinet file.',),
+(u'Media',u'Cabinet',u'Y',None, None, None, None, u'Cabinet',None, u'If some or all of the files stored on the media are compressed in a cabinet, the name of that cabinet.',),
+(u'Media',u'DiskId',u'N',1,32767,None, None, None, None, u'Primary key, integer to determine sort order for table.',),
+(u'Media',u'DiskPrompt',u'Y',None, None, None, None, u'Text',None, u'Disk name: the visible text actually printed on the disk. This will be used to prompt the user when this disk needs to be inserted.',),
+(u'Media',u'LastSequence',u'N',0,32767,None, None, None, None, u'File sequence number for the last file for this media.',),
+(u'Media',u'VolumeLabel',u'Y',None, None, None, None, u'Text',None, u'The label attributed to the volume.',),
+(u'ModuleComponents',u'Component',u'N',None, None, u'Component',1,u'Identifier',None, u'Component contained in the module.',),
+(u'ModuleComponents',u'Language',u'N',None, None, u'ModuleSignature',2,None, None, u'Default language ID for module (may be changed by transform).',),
+(u'ModuleComponents',u'ModuleID',u'N',None, None, u'ModuleSignature',1,u'Identifier',None, u'Module containing the component.',),
+(u'ModuleSignature',u'Language',u'N',None, None, None, None, None, None, u'Default decimal language of module.',),
+(u'ModuleSignature',u'Version',u'N',None, None, None, None, u'Version',None, u'Version of the module.',),
+(u'ModuleSignature',u'ModuleID',u'N',None, None, None, None, u'Identifier',None, u'Module identifier (String.GUID).',),
+(u'ModuleDependency',u'ModuleID',u'N',None, None, u'ModuleSignature',1,u'Identifier',None, u'Module requiring the dependency.',),
+(u'ModuleDependency',u'ModuleLanguage',u'N',None, None, u'ModuleSignature',2,None, None, u'Language of module requiring the dependency.',),
+(u'ModuleDependency',u'RequiredID',u'N',None, None, None, None, None, None, u'String.GUID of required module.',),
+(u'ModuleDependency',u'RequiredLanguage',u'N',None, None, None, None, None, None, u'LanguageID of the required module.',),
+(u'ModuleDependency',u'RequiredVersion',u'Y',None, None, None, None, u'Version',None, u'Version of the required version.',),
+(u'ModuleExclusion',u'ModuleID',u'N',None, None, u'ModuleSignature',1,u'Identifier',None, u'String.GUID of module with exclusion requirement.',),
+(u'ModuleExclusion',u'ModuleLanguage',u'N',None, None, u'ModuleSignature',2,None, None, u'LanguageID of module with exclusion requirement.',),
+(u'ModuleExclusion',u'ExcludedID',u'N',None, None, None, None, None, None, u'String.GUID of excluded module.',),
+(u'ModuleExclusion',u'ExcludedLanguage',u'N',None, None, None, None, None, None, u'Language of excluded module.',),
+(u'ModuleExclusion',u'ExcludedMaxVersion',u'Y',None, None, None, None, u'Version',None, u'Maximum version of excluded module.',),
+(u'ModuleExclusion',u'ExcludedMinVersion',u'Y',None, None, None, None, u'Version',None, u'Minimum version of excluded module.',),
+(u'MoveFile',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'If this component is not "selected" for installation or removal, no action will be taken on the associated MoveFile entry',),
+(u'MoveFile',u'DestFolder',u'N',None, None, None, None, u'Identifier',None, u'Name of a property whose value is assumed to resolve to the full path to the destination directory',),
+(u'MoveFile',u'DestName',u'Y',None, None, None, None, u'Filename',None, u'Name to be given to the original file after it is moved or copied. If blank, the destination file will be given the same name as the source file',),
+(u'MoveFile',u'FileKey',u'N',None, None, None, None, u'Identifier',None, u'Primary key that uniquely identifies a particular MoveFile record',),
+(u'MoveFile',u'Options',u'N',0,1,None, None, None, None, u'Integer value specifying the MoveFile operating mode, one of imfoEnum',),
+(u'MoveFile',u'SourceFolder',u'Y',None, None, None, None, u'Identifier',None, u'Name of a property whose value is assumed to resolve to the full path to the source directory',),
+(u'MoveFile',u'SourceName',u'Y',None, None, None, None, u'Text',None, u"Name of the source file(s) to be moved or copied. Can contain the '*' or '?' wildcards.",),
+(u'MsiAssembly',u'Attributes',u'Y',None, None, None, None, None, None, u'Assembly attributes',),
+(u'MsiAssembly',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'Foreign key into Feature table.',),
+(u'MsiAssembly',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into Component table.',),
+(u'MsiAssembly',u'File_Application',u'Y',None, None, u'File',1,u'Identifier',None, u'Foreign key into File table, denoting the application context for private assemblies. Null for global assemblies.',),
+(u'MsiAssembly',u'File_Manifest',u'Y',None, None, u'File',1,u'Identifier',None, u'Foreign key into the File table denoting the manifest file for the assembly.',),
+(u'MsiAssemblyName',u'Name',u'N',None, None, None, None, u'Text',None, u'The name part of the name-value pairs for the assembly name.',),
+(u'MsiAssemblyName',u'Value',u'N',None, None, None, None, u'Text',None, u'The value part of the name-value pairs for the assembly name.',),
+(u'MsiAssemblyName',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into Component table.',),
+(u'MsiDigitalCertificate',u'CertData',u'N',None, None, None, None, u'Binary',None, u'A certificate context blob for a signer certificate',),
+(u'MsiDigitalCertificate',u'DigitalCertificate',u'N',None, None, None, None, u'Identifier',None, u'A unique identifier for the row',),
+(u'MsiDigitalSignature',u'Table',u'N',None, None, None, None, None, u'Media',u'Reference to another table name (only Media table is supported)',),
+(u'MsiDigitalSignature',u'DigitalCertificate_',u'N',None, None, u'MsiDigitalCertificate',1,u'Identifier',None, u'Foreign key to MsiDigitalCertificate table identifying the signer certificate',),
+(u'MsiDigitalSignature',u'Hash',u'Y',None, None, None, None, u'Binary',None, u'The encoded hash blob from the digital signature',),
+(u'MsiDigitalSignature',u'SignObject',u'N',None, None, None, None, u'Text',None, u'Foreign key to Media table',),
+(u'MsiFileHash',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'Primary key, foreign key into File table referencing file with this hash',),
+(u'MsiFileHash',u'Options',u'N',0,32767,None, None, None, None, u'Various options and attributes for this hash.',),
+(u'MsiFileHash',u'HashPart1',u'N',None, None, None, None, None, None, u'Size of file in bytes (long integer).',),
+(u'MsiFileHash',u'HashPart2',u'N',None, None, None, None, None, None, u'Size of file in bytes (long integer).',),
+(u'MsiFileHash',u'HashPart3',u'N',None, None, None, None, None, None, u'Size of file in bytes (long integer).',),
+(u'MsiFileHash',u'HashPart4',u'N',None, None, None, None, None, None, u'Size of file in bytes (long integer).',),
+(u'MsiPatchHeaders',u'StreamRef',u'N',None, None, None, None, u'Identifier',None, u'Primary key. A unique identifier for the row.',),
+(u'MsiPatchHeaders',u'Header',u'N',None, None, None, None, u'Binary',None, u'Binary stream. The patch header, used for patch validation.',),
+(u'ODBCAttribute',u'Value',u'Y',None, None, None, None, u'Text',None, u'Value for ODBC driver attribute',),
+(u'ODBCAttribute',u'Attribute',u'N',None, None, None, None, u'Text',None, u'Name of ODBC driver attribute',),
+(u'ODBCAttribute',u'Driver_',u'N',None, None, u'ODBCDriver',1,u'Identifier',None, u'Reference to ODBC driver in ODBCDriver table',),
+(u'ODBCDriver',u'Description',u'N',None, None, None, None, u'Text',None, u'Text used as registered name for driver, non-localized',),
+(u'ODBCDriver',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'Reference to key driver file',),
+(u'ODBCDriver',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Reference to associated component',),
+(u'ODBCDriver',u'Driver',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized.internal token for driver',),
+(u'ODBCDriver',u'File_Setup',u'Y',None, None, u'File',1,u'Identifier',None, u'Optional reference to key driver setup DLL',),
+(u'ODBCDataSource',u'Description',u'N',None, None, None, None, u'Text',None, u'Text used as registered name for data source',),
+(u'ODBCDataSource',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Reference to associated component',),
+(u'ODBCDataSource',u'DataSource',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized.internal token for data source',),
+(u'ODBCDataSource',u'DriverDescription',u'N',None, None, None, None, u'Text',None, u'Reference to driver description, may be existing driver',),
+(u'ODBCDataSource',u'Registration',u'N',0,1,None, None, None, None, u'Registration option: 0=machine, 1=user, others t.b.d.',),
+(u'ODBCSourceAttribute',u'Value',u'Y',None, None, None, None, u'Text',None, u'Value for ODBC data source attribute',),
+(u'ODBCSourceAttribute',u'Attribute',u'N',None, None, None, None, u'Text',None, u'Name of ODBC data source attribute',),
+(u'ODBCSourceAttribute',u'DataSource_',u'N',None, None, u'ODBCDataSource',1,u'Identifier',None, u'Reference to ODBC data source in ODBCDataSource table',),
+(u'ODBCTranslator',u'Description',u'N',None, None, None, None, u'Text',None, u'Text used as registered name for translator',),
+(u'ODBCTranslator',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'Reference to key translator file',),
+(u'ODBCTranslator',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Reference to associated component',),
+(u'ODBCTranslator',u'File_Setup',u'Y',None, None, u'File',1,u'Identifier',None, u'Optional reference to key translator setup DLL',),
+(u'ODBCTranslator',u'Translator',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized.internal token for translator',),
+(u'Patch',u'Sequence',u'N',0,32767,None, None, None, None, u'Primary key, sequence with respect to the media images; order must track cabinet order.',),
+(u'Patch',u'Attributes',u'N',0,32767,None, None, None, None, u'Integer containing bit flags representing patch attributes',),
+(u'Patch',u'File_',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token, foreign key to File table, must match identifier in cabinet.',),
+(u'Patch',u'Header',u'Y',None, None, None, None, u'Binary',None, u'Binary stream. The patch header, used for patch validation.',),
+(u'Patch',u'PatchSize',u'N',0,2147483647,None, None, None, None, u'Size of patch in bytes (long integer).',),
+(u'Patch',u'StreamRef_',u'Y',None, None, None, None, u'Identifier',None, u'Identifier. Foreign key to the StreamRef column of the MsiPatchHeaders table.',),
+(u'PatchPackage',u'Media_',u'N',0,32767,None, None, None, None, u'Foreign key to DiskId column of Media table. Indicates the disk containing the patch package.',),
+(u'PatchPackage',u'PatchId',u'N',None, None, None, None, u'Guid',None, u'A unique string GUID representing this patch.',),
+(u'PublishComponent',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'Foreign key into the Feature table.',),
+(u'PublishComponent',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table.',),
+(u'PublishComponent',u'ComponentId',u'N',None, None, None, None, u'Guid',None, u'A string GUID that represents the component id that will be requested by the alien product.',),
+(u'PublishComponent',u'AppData',u'Y',None, None, None, None, u'Text',None, u'This is localisable Application specific data that can be associated with a Qualified Component.',),
+(u'PublishComponent',u'Qualifier',u'N',None, None, None, None, u'Text',None, u'This is defined only when the ComponentId column is an Qualified Component Id. This is the Qualifier for ProvideComponentIndirect.',),
+(u'RadioButton',u'Y',u'N',0,32767,None, None, None, None, u'The vertical coordinate of the upper left corner of the bounding rectangle of the radio button.',),
+(u'RadioButton',u'Text',u'Y',None, None, None, None, u'Text',None, u'The visible title to be assigned to the radio button.',),
+(u'RadioButton',u'Property',u'N',None, None, None, None, u'Identifier',None, u'A named property to be tied to this radio button. All the buttons tied to the same property become part of the same group.',),
+(u'RadioButton',u'Height',u'N',0,32767,None, None, None, None, u'The height of the button.',),
+(u'RadioButton',u'Width',u'N',0,32767,None, None, None, None, u'The width of the button.',),
+(u'RadioButton',u'X',u'N',0,32767,None, None, None, None, u'The horizontal coordinate of the upper left corner of the bounding rectangle of the radio button.',),
+(u'RadioButton',u'Value',u'N',None, None, None, None, u'Formatted',None, u'The value string associated with this button. Selecting the button will set the associated property to this value.',),
+(u'RadioButton',u'Order',u'N',1,32767,None, None, None, None, u'A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.',),
+(u'RadioButton',u'Help',u'Y',None, None, None, None, u'Text',None, u'The help strings used with the button. The text is optional.',),
+(u'Registry',u'Name',u'Y',None, None, None, None, u'Formatted',None, u'The registry value name.',),
+(u'Registry',u'Value',u'Y',None, None, None, None, u'Formatted',None, u'The registry value.',),
+(u'Registry',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table referencing component that controls the installing of the registry value.',),
+(u'Registry',u'Key',u'N',None, None, None, None, u'RegPath',None, u'The key for the registry value.',),
+(u'Registry',u'Registry',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token.',),
+(u'Registry',u'Root',u'N',-1,3,None, None, None, None, u'The predefined root key for the registry value, one of rrkEnum.',),
+(u'RegLocator',u'Name',u'Y',None, None, None, None, u'Formatted',None, u'The registry value name.',),
+(u'RegLocator',u'Type',u'Y',0,18,None, None, None, None, u'An integer value that determines if the registry value is a filename or a directory location or to be used as is w/o interpretation.',),
+(u'RegLocator',u'Signature_',u'N',None, None, None, None, u'Identifier',None, u'The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table. If the type is 0, the registry values refers a directory, and _Signature is not a foreign key.',),
+(u'RegLocator',u'Key',u'N',None, None, None, None, u'RegPath',None, u'The key for the registry value.',),
+(u'RegLocator',u'Root',u'N',0,3,None, None, None, None, u'The predefined root key for the registry value, one of rrkEnum.',),
+(u'RemoveFile',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key referencing Component that controls the file to be removed.',),
+(u'RemoveFile',u'FileKey',u'N',None, None, None, None, u'Identifier',None, u'Primary key used to identify a particular file entry',),
+(u'RemoveFile',u'FileName',u'Y',None, None, None, None, u'WildCardFilename',None, u'Name of the file to be removed.',),
+(u'RemoveFile',u'DirProperty',u'N',None, None, None, None, u'Identifier',None, u'Name of a property whose value is assumed to resolve to the full pathname to the folder of the file to be removed.',),
+(u'RemoveFile',u'InstallMode',u'N',None, None, None, None, None, u'1;2;3',u'Installation option, one of iimEnum.',),
+(u'RemoveIniFile',u'Action',u'N',None, None, None, None, None, u'2;4',u'The type of modification to be made, one of iifEnum.',),
+(u'RemoveIniFile',u'Value',u'Y',None, None, None, None, u'Formatted',None, u'The value to be deleted. The value is required when Action is iifIniRemoveTag',),
+(u'RemoveIniFile',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table referencing component that controls the deletion of the .INI value.',),
+(u'RemoveIniFile',u'FileName',u'N',None, None, None, None, u'Filename',None, u'The .INI file name in which to delete the information',),
+(u'RemoveIniFile',u'DirProperty',u'Y',None, None, None, None, u'Identifier',None, u'Foreign key into the Directory table denoting the directory where the .INI file is.',),
+(u'RemoveIniFile',u'Key',u'N',None, None, None, None, u'Formatted',None, u'The .INI file key below Section.',),
+(u'RemoveIniFile',u'Section',u'N',None, None, None, None, u'Formatted',None, u'The .INI file Section.',),
+(u'RemoveIniFile',u'RemoveIniFile',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token.',),
+(u'RemoveRegistry',u'Name',u'Y',None, None, None, None, u'Formatted',None, u'The registry value name.',),
+(u'RemoveRegistry',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table referencing component that controls the deletion of the registry value.',),
+(u'RemoveRegistry',u'Key',u'N',None, None, None, None, u'RegPath',None, u'The key for the registry value.',),
+(u'RemoveRegistry',u'Root',u'N',-1,3,None, None, None, None, u'The predefined root key for the registry value, one of rrkEnum',),
+(u'RemoveRegistry',u'RemoveRegistry',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token.',),
+(u'ReserveCost',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Reserve a specified amount of space if this component is to be installed.',),
+(u'ReserveCost',u'ReserveFolder',u'Y',None, None, None, None, u'Identifier',None, u'Name of a property whose value is assumed to resolve to the full path to the destination directory',),
+(u'ReserveCost',u'ReserveKey',u'N',None, None, None, None, u'Identifier',None, u'Primary key that uniquely identifies a particular ReserveCost record',),
+(u'ReserveCost',u'ReserveLocal',u'N',0,2147483647,None, None, None, None, u'Disk space to reserve if linked component is installed locally.',),
+(u'ReserveCost',u'ReserveSource',u'N',0,2147483647,None, None, None, None, u'Disk space to reserve if linked component is installed to run from the source location.',),
+(u'SelfReg',u'File_',u'N',None, None, u'File',1,u'Identifier',None, u'Foreign key into the File table denoting the module that needs to be registered.',),
+(u'SelfReg',u'Cost',u'Y',0,32767,None, None, None, None, u'The cost of registering the module.',),
+(u'ServiceControl',u'Name',u'N',None, None, None, None, u'Formatted',None, u'Name of a service. /, \\, comma and space are invalid',),
+(u'ServiceControl',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Required foreign key into the Component Table that controls the startup of the service',),
+(u'ServiceControl',u'Event',u'N',0,187,None, None, None, None, u'Bit field: Install: 0x1 = Start, 0x2 = Stop, 0x8 = Delete, Uninstall: 0x10 = Start, 0x20 = Stop, 0x80 = Delete',),
+(u'ServiceControl',u'ServiceControl',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token.',),
+(u'ServiceControl',u'Arguments',u'Y',None, None, None, None, u'Formatted',None, u'Arguments for the service. Separate by [~].',),
+(u'ServiceControl',u'Wait',u'Y',0,1,None, None, None, None, u'Boolean for whether to wait for the service to fully start',),
+(u'ServiceInstall',u'Name',u'N',None, None, None, None, u'Formatted',None, u'Internal Name of the Service',),
+(u'ServiceInstall',u'Description',u'Y',None, None, None, None, u'Text',None, u'Description of service.',),
+(u'ServiceInstall',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Required foreign key into the Component Table that controls the startup of the service',),
+(u'ServiceInstall',u'Arguments',u'Y',None, None, None, None, u'Formatted',None, u'Arguments to include in every start of the service, passed to WinMain',),
+(u'ServiceInstall',u'ServiceInstall',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token.',),
+(u'ServiceInstall',u'Dependencies',u'Y',None, None, None, None, u'Formatted',None, u'Other services this depends on to start. Separate by [~], and end with [~][~]',),
+(u'ServiceInstall',u'DisplayName',u'Y',None, None, None, None, u'Formatted',None, u'External Name of the Service',),
+(u'ServiceInstall',u'ErrorControl',u'N',-2147483647,2147483647,None, None, None, None, u'Severity of error if service fails to start',),
+(u'ServiceInstall',u'LoadOrderGroup',u'Y',None, None, None, None, u'Formatted',None, u'LoadOrderGroup',),
+(u'ServiceInstall',u'Password',u'Y',None, None, None, None, u'Formatted',None, u'password to run service with. (with StartName)',),
+(u'ServiceInstall',u'ServiceType',u'N',-2147483647,2147483647,None, None, None, None, u'Type of the service',),
+(u'ServiceInstall',u'StartName',u'Y',None, None, None, None, u'Formatted',None, u'User or object name to run service as',),
+(u'ServiceInstall',u'StartType',u'N',0,4,None, None, None, None, u'Type of the service',),
+(u'Shortcut',u'Name',u'N',None, None, None, None, u'Filename',None, u'The name of the shortcut to be created.',),
+(u'Shortcut',u'Description',u'Y',None, None, None, None, u'Text',None, u'The description for the shortcut.',),
+(u'Shortcut',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.',),
+(u'Shortcut',u'Icon_',u'Y',None, None, u'Icon',1,u'Identifier',None, u'Foreign key into the File table denoting the external icon file for the shortcut.',),
+(u'Shortcut',u'IconIndex',u'Y',-32767,32767,None, None, None, None, u'The icon index for the shortcut.',),
+(u'Shortcut',u'Directory_',u'N',None, None, u'Directory',1,u'Identifier',None, u'Foreign key into the Directory table denoting the directory where the shortcut file is created.',),
+(u'Shortcut',u'Target',u'N',None, None, None, None, u'Shortcut',None, u'The shortcut target. This is usually a property that is expanded to a file or a folder that the shortcut points to.',),
+(u'Shortcut',u'Arguments',u'Y',None, None, None, None, u'Formatted',None, u'The command-line arguments for the shortcut.',),
+(u'Shortcut',u'Shortcut',u'N',None, None, None, None, u'Identifier',None, u'Primary key, non-localized token.',),
+(u'Shortcut',u'Hotkey',u'Y',0,32767,None, None, None, None, u'The hotkey for the shortcut. It has the virtual-key code for the key in the low-order byte, and the modifier flags in the high-order byte. ',),
+(u'Shortcut',u'ShowCmd',u'Y',None, None, None, None, None, u'1;3;7',u'The show command for the application window.The following values may be used.',),
+(u'Shortcut',u'WkDir',u'Y',None, None, None, None, u'Identifier',None, u'Name of property defining location of working directory.',),
+(u'Signature',u'FileName',u'N',None, None, None, None, u'Filename',None, u'The name of the file. This may contain a "short name|long name" pair.',),
+(u'Signature',u'Signature',u'N',None, None, None, None, u'Identifier',None, u'The table key. The Signature represents a unique file signature.',),
+(u'Signature',u'Languages',u'Y',None, None, None, None, u'Language',None, u'The languages supported by the file.',),
+(u'Signature',u'MaxDate',u'Y',0,2147483647,None, None, None, None, u'The maximum creation date of the file.',),
+(u'Signature',u'MaxSize',u'Y',0,2147483647,None, None, None, None, u'The maximum size of the file. ',),
+(u'Signature',u'MaxVersion',u'Y',None, None, None, None, u'Text',None, u'The maximum version of the file.',),
+(u'Signature',u'MinDate',u'Y',0,2147483647,None, None, None, None, u'The minimum creation date of the file.',),
+(u'Signature',u'MinSize',u'Y',0,2147483647,None, None, None, None, u'The minimum size of the file.',),
+(u'Signature',u'MinVersion',u'Y',None, None, None, None, u'Text',None, u'The minimum version of the file.',),
+(u'TextStyle',u'TextStyle',u'N',None, None, None, None, u'Identifier',None, u'Name of the style. The primary key of this table. This name is embedded in the texts to indicate a style change.',),
+(u'TextStyle',u'Color',u'Y',0,16777215,None, None, None, None, u'A long integer indicating the color of the string in the RGB format (Red, Green, Blue each 0-255, RGB = R + 256*G + 256^2*B).',),
+(u'TextStyle',u'FaceName',u'N',None, None, None, None, u'Text',None, u'A string indicating the name of the font used. Required. The string must be at most 31 characters long.',),
+(u'TextStyle',u'Size',u'N',0,32767,None, None, None, None, u'The size of the font used. This size is given in our units (1/12 of the system font height). Assuming that the system font is set to 12 point size, this is equivalent to the point size.',),
+(u'TextStyle',u'StyleBits',u'Y',0,15,None, None, None, None, u'A combination of style bits.',),
+(u'TypeLib',u'Description',u'Y',None, None, None, None, u'Text',None, None, ),
+(u'TypeLib',u'Feature_',u'N',None, None, u'Feature',1,u'Identifier',None, u'Required foreign key into the Feature Table, specifying the feature to validate or install in order for the type library to be operational.',),
+(u'TypeLib',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.',),
+(u'TypeLib',u'Directory_',u'Y',None, None, u'Directory',1,u'Identifier',None, u'Optional. The foreign key into the Directory table denoting the path to the help file for the type library.',),
+(u'TypeLib',u'Language',u'N',0,32767,None, None, None, None, u'The language of the library.',),
+(u'TypeLib',u'Version',u'Y',0,16777215,None, None, None, None, u'The version of the library. The minor version is in the lower 8 bits of the integer. The major version is in the next 16 bits. ',),
+(u'TypeLib',u'Cost',u'Y',0,2147483647,None, None, None, None, u'The cost associated with the registration of the typelib. This column is currently optional.',),
+(u'TypeLib',u'LibID',u'N',None, None, None, None, u'Guid',None, u'The GUID that represents the library.',),
+(u'UIText',u'Text',u'Y',None, None, None, None, u'Text',None, u'The localized version of the string.',),
+(u'UIText',u'Key',u'N',None, None, None, None, u'Identifier',None, u'A unique key that identifies the particular string.',),
+(u'Upgrade',u'Attributes',u'N',0,2147483647,None, None, None, None, u'The attributes of this product set.',),
+(u'Upgrade',u'Language',u'Y',None, None, None, None, u'Language',None, u'A comma-separated list of languages for either products in this set or products not in this set.',),
+(u'Upgrade',u'ActionProperty',u'N',None, None, None, None, u'UpperCase',None, u'The property to set when a product in this set is found.',),
+(u'Upgrade',u'Remove',u'Y',None, None, None, None, u'Formatted',None, u'The list of features to remove when uninstalling a product from this set. The default is "ALL".',),
+(u'Upgrade',u'UpgradeCode',u'N',None, None, None, None, u'Guid',None, u'The UpgradeCode GUID belonging to the products in this set.',),
+(u'Upgrade',u'VersionMax',u'Y',None, None, None, None, u'Text',None, u'The maximum ProductVersion of the products in this set. The set may or may not include products with this particular version.',),
+(u'Upgrade',u'VersionMin',u'Y',None, None, None, None, u'Text',None, u'The minimum ProductVersion of the products in this set. The set may or may not include products with this particular version.',),
+(u'Verb',u'Sequence',u'Y',0,32767,None, None, None, None, u'Order within the verbs for a particular extension. Also used simply to specify the default verb.',),
+(u'Verb',u'Argument',u'Y',None, None, None, None, u'Formatted',None, u'Optional value for the command arguments.',),
+(u'Verb',u'Extension_',u'N',None, None, u'Extension',1,u'Text',None, u'The extension associated with the table row.',),
+(u'Verb',u'Verb',u'N',None, None, None, None, u'Text',None, u'The verb for the command.',),
+(u'Verb',u'Command',u'Y',None, None, None, None, u'Formatted',None, u'The command text.',),
+]
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/sequence.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/sequence.py
new file mode 100644
index 0000000000..49d6c5d8c9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/sequence.py
@@ -0,0 +1,126 @@
+AdminExecuteSequence = [
+(u'InstallInitialize', None, 1500),
+(u'InstallFinalize', None, 6600),
+(u'InstallFiles', None, 4000),
+(u'InstallAdminPackage', None, 3900),
+(u'FileCost', None, 900),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'InstallValidate', None, 1400),
+]
+
+AdminUISequence = [
+(u'FileCost', None, 900),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'ExecuteAction', None, 1300),
+(u'ExitDialog', None, -1),
+(u'FatalError', None, -3),
+(u'UserExit', None, -2),
+]
+
+AdvtExecuteSequence = [
+(u'InstallInitialize', None, 1500),
+(u'InstallFinalize', None, 6600),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'InstallValidate', None, 1400),
+(u'CreateShortcuts', None, 4500),
+(u'MsiPublishAssemblies', None, 6250),
+(u'PublishComponents', None, 6200),
+(u'PublishFeatures', None, 6300),
+(u'PublishProduct', None, 6400),
+(u'RegisterClassInfo', None, 4600),
+(u'RegisterExtensionInfo', None, 4700),
+(u'RegisterMIMEInfo', None, 4900),
+(u'RegisterProgIdInfo', None, 4800),
+]
+
+InstallExecuteSequence = [
+(u'InstallInitialize', None, 1500),
+(u'InstallFinalize', None, 6600),
+(u'InstallFiles', None, 4000),
+(u'FileCost', None, 900),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'InstallValidate', None, 1400),
+(u'CreateShortcuts', None, 4500),
+(u'MsiPublishAssemblies', None, 6250),
+(u'PublishComponents', None, 6200),
+(u'PublishFeatures', None, 6300),
+(u'PublishProduct', None, 6400),
+(u'RegisterClassInfo', None, 4600),
+(u'RegisterExtensionInfo', None, 4700),
+(u'RegisterMIMEInfo', None, 4900),
+(u'RegisterProgIdInfo', None, 4800),
+(u'AllocateRegistrySpace', u'NOT Installed', 1550),
+(u'AppSearch', None, 400),
+(u'BindImage', None, 4300),
+(u'CCPSearch', u'NOT Installed', 500),
+(u'CreateFolders', None, 3700),
+(u'DeleteServices', u'VersionNT', 2000),
+(u'DuplicateFiles', None, 4210),
+(u'FindRelatedProducts', None, 200),
+(u'InstallODBC', None, 5400),
+(u'InstallServices', u'VersionNT', 5800),
+(u'IsolateComponents', None, 950),
+(u'LaunchConditions', None, 100),
+(u'MigrateFeatureStates', None, 1200),
+(u'MoveFiles', None, 3800),
+(u'PatchFiles', None, 4090),
+(u'ProcessComponents', None, 1600),
+(u'RegisterComPlus', None, 5700),
+(u'RegisterFonts', None, 5300),
+(u'RegisterProduct', None, 6100),
+(u'RegisterTypeLibraries', None, 5500),
+(u'RegisterUser', None, 6000),
+(u'RemoveDuplicateFiles', None, 3400),
+(u'RemoveEnvironmentStrings', None, 3300),
+(u'RemoveExistingProducts', None, 6700),
+(u'RemoveFiles', None, 3500),
+(u'RemoveFolders', None, 3600),
+(u'RemoveIniValues', None, 3100),
+(u'RemoveODBC', None, 2400),
+(u'RemoveRegistryValues', None, 2600),
+(u'RemoveShortcuts', None, 3200),
+(u'RMCCPSearch', u'NOT Installed', 600),
+(u'SelfRegModules', None, 5600),
+(u'SelfUnregModules', None, 2200),
+(u'SetODBCFolders', None, 1100),
+(u'StartServices', u'VersionNT', 5900),
+(u'StopServices', u'VersionNT', 1900),
+(u'MsiUnpublishAssemblies', None, 1750),
+(u'UnpublishComponents', None, 1700),
+(u'UnpublishFeatures', None, 1800),
+(u'UnregisterClassInfo', None, 2700),
+(u'UnregisterComPlus', None, 2100),
+(u'UnregisterExtensionInfo', None, 2800),
+(u'UnregisterFonts', None, 2500),
+(u'UnregisterMIMEInfo', None, 3000),
+(u'UnregisterProgIdInfo', None, 2900),
+(u'UnregisterTypeLibraries', None, 2300),
+(u'ValidateProductID', None, 700),
+(u'WriteEnvironmentStrings', None, 5200),
+(u'WriteIniValues', None, 5100),
+(u'WriteRegistryValues', None, 5000),
+]
+
+InstallUISequence = [
+(u'FileCost', None, 900),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'ExecuteAction', None, 1300),
+(u'ExitDialog', None, -1),
+(u'FatalError', None, -3),
+(u'UserExit', None, -2),
+(u'AppSearch', None, 400),
+(u'CCPSearch', u'NOT Installed', 500),
+(u'FindRelatedProducts', None, 200),
+(u'IsolateComponents', None, 950),
+(u'LaunchConditions', None, 100),
+(u'MigrateFeatureStates', None, 1200),
+(u'RMCCPSearch', u'NOT Installed', 600),
+(u'ValidateProductID', None, 700),
+]
+
+tables=['AdminExecuteSequence', 'AdminUISequence', 'AdvtExecuteSequence', 'InstallExecuteSequence', 'InstallUISequence']
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uisample.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uisample.py
new file mode 100644
index 0000000000..1e68e92f61
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uisample.py
@@ -0,0 +1,1400 @@
+
+import msilib,os;dirname=os.path.dirname(__file__)
+AdminExecuteSequence = [
+(u'InstallValidate', None, 1400),
+(u'InstallInitialize', None, 1500),
+(u'InstallFinalize', None, 6600),
+(u'InstallFiles', None, 4000),
+(u'InstallAdminPackage', None, 3900),
+(u'FileCost', None, 900),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+]
+
+AdminUISequence = [
+(u'AdminWelcomeDlg', None, 1230),
+(u'FileCost', None, 900),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'ExecuteAction', None, 1300),
+(u'ExitDialog', None, -1),
+(u'FatalError', None, -3),
+(u'PrepareDlg', None, 140),
+(u'ProgressDlg', None, 1280),
+(u'UserExit', None, -2),
+]
+
+AdvtExecuteSequence = [
+(u'InstallValidate', None, 1400),
+(u'InstallInitialize', None, 1500),
+(u'InstallFinalize', None, 6600),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'CreateShortcuts', None, 4500),
+(u'PublishComponents', None, 6200),
+(u'PublishFeatures', None, 6300),
+(u'PublishProduct', None, 6400),
+(u'RegisterClassInfo', None, 4600),
+(u'RegisterExtensionInfo', None, 4700),
+(u'RegisterMIMEInfo', None, 4900),
+(u'RegisterProgIdInfo', None, 4800),
+]
+
+BBControl = [
+]
+
+Billboard = [
+]
+
+Binary = [
+(u'bannrbmp', msilib.Binary(os.path.join(dirname,"bannrbmp.bin"))),
+(u'completi', msilib.Binary(os.path.join(dirname,"completi.bin"))),
+(u'custicon', msilib.Binary(os.path.join(dirname,"custicon.bin"))),
+(u'dlgbmp', msilib.Binary(os.path.join(dirname,"dlgbmp.bin"))),
+(u'exclamic', msilib.Binary(os.path.join(dirname,"exclamic.bin"))),
+(u'info', msilib.Binary(os.path.join(dirname,"info.bin"))),
+(u'insticon', msilib.Binary(os.path.join(dirname,"insticon.bin"))),
+(u'New', msilib.Binary(os.path.join(dirname,"New.bin"))),
+(u'removico', msilib.Binary(os.path.join(dirname,"removico.bin"))),
+(u'repairic', msilib.Binary(os.path.join(dirname,"repairic.bin"))),
+(u'Up', msilib.Binary(os.path.join(dirname,"Up.bin"))),
+]
+
+CheckBox = [
+]
+
+Property = [
+(u'BannerBitmap', u'bannrbmp'),
+(u'IAgree', u'No'),
+(u'ProductID', u'none'),
+(u'ARPHELPLINK', u'http://www.microsoft.com/management'),
+(u'ButtonText_Back', u'< &Back'),
+(u'ButtonText_Browse', u'Br&owse'),
+(u'ButtonText_Cancel', u'Cancel'),
+(u'ButtonText_Exit', u'&Exit'),
+(u'ButtonText_Finish', u'&Finish'),
+(u'ButtonText_Ignore', u'&Ignore'),
+(u'ButtonText_Install', u'&Install'),
+(u'ButtonText_Next', u'&Next >'),
+(u'ButtonText_No', u'&No'),
+(u'ButtonText_OK', u'OK'),
+(u'ButtonText_Remove', u'&Remove'),
+(u'ButtonText_Repair', u'&Repair'),
+(u'ButtonText_Reset', u'&Reset'),
+(u'ButtonText_Resume', u'&Resume'),
+(u'ButtonText_Retry', u'&Retry'),
+(u'ButtonText_Return', u'&Return'),
+(u'ButtonText_Yes', u'&Yes'),
+(u'CompleteSetupIcon', u'completi'),
+(u'ComponentDownload', u'ftp://anonymous@microsoft.com/components/'),
+(u'CustomSetupIcon', u'custicon'),
+(u'DefaultUIFont', u'DlgFont8'),
+(u'DialogBitmap', u'dlgbmp'),
+(u'DlgTitleFont', u'{&DlgFontBold8}'),
+(u'ErrorDialog', u'ErrorDlg'),
+(u'ExclamationIcon', u'exclamic'),
+(u'InfoIcon', u'info'),
+(u'InstallerIcon', u'insticon'),
+(u'INSTALLLEVEL', u'3'),
+(u'InstallMode', u'Typical'),
+(u'PIDTemplate', u'12345<###-%%%%%%%>@@@@@'),
+#(u'ProductLanguage', u'1033'),
+(u'Progress1', u'Installing'),
+(u'Progress2', u'installs'),
+(u'PROMPTROLLBACKCOST', u'P'),
+(u'RemoveIcon', u'removico'),
+(u'RepairIcon', u'repairic'),
+(u'Setup', u'Setup'),
+(u'ShowUserRegistrationDlg', u'1'),
+(u'Wizard', u'Setup Wizard'),
+]
+
+ComboBox = [
+]
+
+Control = [
+(u'AdminWelcomeDlg', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Back', None),
+(u'AdminWelcomeDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'AdminWelcomeDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'AdminWelcomeDlg', u'Description', u'Text', 135, 70, 220, 30, 196611, None, u'The [Wizard] will create a server image of [ProductName], at a specified network location. Click Next to continue or Cancel to exit the [Wizard].', None, None),
+(u'AdminWelcomeDlg', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}Welcome to the [ProductName] [Wizard]', None, None),
+(u'AdminWelcomeDlg', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Next', None),
+(u'AdminWelcomeDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'ExitDialog', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Back', None),
+(u'ExitDialog', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'ExitDialog', u'Cancel', u'PushButton', 304, 243, 56, 17, 1, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'ExitDialog', u'Description', u'Text', 135, 70, 220, 20, 196611, None, u'Click the Finish button to exit the [Wizard].', None, None),
+(u'ExitDialog', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}Completing the [ProductName] [Wizard]', None, None),
+(u'ExitDialog', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Finish', None),
+(u'ExitDialog', u'Finish', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Finish]', u'Cancel', None),
+(u'FatalError', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Back', None),
+(u'FatalError', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'FatalError', u'Cancel', u'PushButton', 304, 243, 56, 17, 1, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'FatalError', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}[ProductName] [Wizard] ended prematurely', None, None),
+(u'FatalError', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Finish', None),
+(u'FatalError', u'Finish', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Finish]', u'Cancel', None),
+(u'FatalError', u'Description1', u'Text', 135, 70, 220, 40, 196611, None, u'[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.', None, None),
+(u'FatalError', u'Description2', u'Text', 135, 115, 220, 20, 196611, None, u'Click the Finish button to exit the [Wizard].', None, None),
+(u'PrepareDlg', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Cancel', None),
+(u'PrepareDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'PrepareDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'PrepareDlg', u'Description', u'Text', 135, 70, 220, 20, 196611, None, u'Please wait while the [Wizard] prepares to guide you through the installation.', None, None),
+(u'PrepareDlg', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}Welcome to the [ProductName] [Wizard]', None, None),
+(u'PrepareDlg', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', None, None),
+(u'PrepareDlg', u'Next', u'PushButton', 236, 243, 56, 17, 1, None, u'[ButtonText_Next]', None, None),
+(u'PrepareDlg', u'ActionData', u'Text', 135, 125, 220, 30, 196611, None, None, None, None),
+(u'PrepareDlg', u'ActionText', u'Text', 135, 100, 220, 20, 196611, None, None, None, None),
+(u'ProgressDlg', u'Text', u'Text', 35, 65, 300, 20, 3, None, u'Please wait while the [Wizard] [Progress2] [ProductName]. This may take several minutes.', None, None),
+(u'ProgressDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'Back', None),
+(u'ProgressDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'ProgressDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'ProgressDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'ProgressDlg', u'Title', u'Text', 20, 15, 200, 15, 196611, None, u'[DlgTitleFont][Progress1] [ProductName]', None, None),
+(u'ProgressDlg', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Next', None),
+(u'ProgressDlg', u'Next', u'PushButton', 236, 243, 56, 17, 1, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'ProgressDlg', u'ActionText', u'Text', 70, 100, 265, 10, 3, None, None, None, None),
+(u'ProgressDlg', u'ProgressBar', u'ProgressBar', 35, 115, 300, 10, 65537, None, u'Progress done', None, None),
+(u'ProgressDlg', u'StatusLabel', u'Text', 35, 100, 35, 10, 3, None, u'Status:', None, None),
+(u'UserExit', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Back', None),
+(u'UserExit', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'UserExit', u'Cancel', u'PushButton', 304, 243, 56, 17, 1, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'UserExit', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}[ProductName] [Wizard] was interrupted', None, None),
+(u'UserExit', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Finish', None),
+(u'UserExit', u'Finish', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Finish]', u'Cancel', None),
+(u'UserExit', u'Description1', u'Text', 135, 70, 220, 40, 196611, None, u'[ProductName] setup was interrupted. Your system has not been modified. To install this program at a later time, please run the installation again.', None, None),
+(u'UserExit', u'Description2', u'Text', 135, 115, 220, 20, 196611, None, u'Click the Finish button to exit the [Wizard].', None, None),
+(u'AdminBrowseDlg', u'Up', u'PushButton', 298, 55, 19, 19, 3670019, None, u'Up', u'NewFolder', u'Up One Level|'),
+(u'AdminBrowseDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'PathEdit', None),
+(u'AdminBrowseDlg', u'PathEdit', u'PathEdit', 84, 202, 261, 17, 3, u'TARGETDIR', None, u'OK', None),
+(u'AdminBrowseDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'AdminBrowseDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'AdminBrowseDlg', u'Cancel', u'PushButton', 240, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'ComboLabel', None),
+(u'AdminBrowseDlg', u'ComboLabel', u'Text', 25, 58, 44, 10, 3, None, u'&Look in:', u'DirectoryCombo', None),
+(u'AdminBrowseDlg', u'DirectoryCombo', u'DirectoryCombo', 70, 55, 220, 80, 458755, u'TARGETDIR', None, u'Up', None),
+(u'AdminBrowseDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'Browse to the destination folder', None, None),
+(u'AdminBrowseDlg', u'DirectoryList', u'DirectoryList', 25, 83, 320, 110, 7, u'TARGETDIR', None, u'PathLabel', None),
+(u'AdminBrowseDlg', u'PathLabel', u'Text', 25, 205, 59, 10, 3, None, u'&Folder name:', u'BannerBitmap', None),
+(u'AdminBrowseDlg', u'NewFolder', u'PushButton', 325, 55, 19, 19, 3670019, None, u'New', u'DirectoryList', u'Create A New Folder|'),
+(u'AdminBrowseDlg', u'OK', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_OK]', u'Cancel', None),
+(u'AdminBrowseDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Change current destination folder', None, None),
+(u'AdminInstallPointDlg', u'Text', u'Text', 25, 80, 320, 10, 3, None, u'&Enter a new network location or click Browse to browse to one.', u'PathEdit', None),
+(u'AdminInstallPointDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'Text', None),
+(u'AdminInstallPointDlg', u'PathEdit', u'PathEdit', 25, 93, 320, 18, 3, u'TARGETDIR', None, u'Browse', None),
+(u'AdminInstallPointDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'AdminInstallPointDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'AdminInstallPointDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'AdminInstallPointDlg', u'Description', u'Text', 25, 20, 280, 20, 196611, None, u'Please specify a network location for the server image of [ProductName] product', None, None),
+(u'AdminInstallPointDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Network Location', None, None),
+(u'AdminInstallPointDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Next', None),
+(u'AdminInstallPointDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'AdminInstallPointDlg', u'Browse', u'PushButton', 289, 119, 56, 17, 3, None, u'[ButtonText_Browse]', u'Back', None),
+(u'AdminRegistrationDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'OrganizationLabel', None),
+(u'AdminRegistrationDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'AdminRegistrationDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'AdminRegistrationDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'AdminRegistrationDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'Please enter your company information', None, None),
+(u'AdminRegistrationDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Company Information', None, None),
+(u'AdminRegistrationDlg', u'Back', u'PushButton', 180, 243, 56, 17, 65539, None, u'[ButtonText_Back]', u'Next', None),
+(u'AdminRegistrationDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'AdminRegistrationDlg', u'OrganizationLabel', u'Text', 45, 71, 285, 30, 3, None, u'&Please enter the name of your organization in the box below. This will be used as default company name for subsequent installations of [ProductName]:', u'OrganizationEdit', None),
+(u'AdminRegistrationDlg', u'CDKeyEdit', u'MaskedEdit', 45, 143, 250, 16, 3, u'PIDKEY', u'[PIDTemplate]', u'Back', None),
+(u'AdminRegistrationDlg', u'CDKeyLabel', u'Text', 45, 130, 50, 10, 3, None, u'CD &Key:', u'CDKeyEdit', None),
+(u'AdminRegistrationDlg', u'OrganizationEdit', u'Edit', 45, 105, 220, 18, 3, u'COMPANYNAME', u'{80}', u'CDKeyLabel', None),
+(u'BrowseDlg', u'Up', u'PushButton', 298, 55, 19, 19, 3670019, None, u'Up', u'NewFolder', u'Up One Level|'),
+(u'BrowseDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'PathEdit', None),
+(u'BrowseDlg', u'PathEdit', u'PathEdit', 84, 202, 261, 18, 11, u'_BrowseProperty', None, u'OK', None),
+(u'BrowseDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'BrowseDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'BrowseDlg', u'Cancel', u'PushButton', 240, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'ComboLabel', None),
+(u'BrowseDlg', u'ComboLabel', u'Text', 25, 58, 44, 10, 3, None, u'&Look in:', u'DirectoryCombo', None),
+(u'BrowseDlg', u'DirectoryCombo', u'DirectoryCombo', 70, 55, 220, 80, 393227, u'_BrowseProperty', None, u'Up', None),
+(u'BrowseDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'Browse to the destination folder', None, None),
+(u'BrowseDlg', u'DirectoryList', u'DirectoryList', 25, 83, 320, 110, 15, u'_BrowseProperty', None, u'PathLabel', None),
+(u'BrowseDlg', u'PathLabel', u'Text', 25, 205, 59, 10, 3, None, u'&Folder name:', u'BannerBitmap', None),
+(u'BrowseDlg', u'NewFolder', u'PushButton', 325, 55, 19, 19, 3670019, None, u'New', u'DirectoryList', u'Create A New Folder|'),
+(u'BrowseDlg', u'OK', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_OK]', u'Cancel', None),
+(u'BrowseDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Change current destination folder', None, None),
+(u'CancelDlg', u'Text', u'Text', 48, 15, 194, 30, 3, None, u'Are you sure you want to cancel [ProductName] installation?', None, None),
+(u'CancelDlg', u'Icon', u'Icon', 15, 15, 24, 24, 5242881, None, u'[InfoIcon]', None, u'Information icon|'),
+(u'CancelDlg', u'No', u'PushButton', 132, 57, 56, 17, 3, None, u'[ButtonText_No]', u'Yes', None),
+(u'CancelDlg', u'Yes', u'PushButton', 72, 57, 56, 17, 3, None, u'[ButtonText_Yes]', u'No', None),
+(u'CustomizeDlg', u'Text', u'Text', 25, 55, 320, 20, 3, None, u'Click on the icons in the tree below to change the way features will be installed.', None, None),
+(u'CustomizeDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'Tree', None),
+(u'CustomizeDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'CustomizeDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'CustomizeDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'CustomizeDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'Select the way you want features to be installed.', None, None),
+(u'CustomizeDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Custom Setup', None, None),
+(u'CustomizeDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Next', None),
+(u'CustomizeDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'CustomizeDlg', u'Browse', u'PushButton', 304, 200, 56, 17, 3, None, u'[ButtonText_Browse]', u'Reset', None),
+(u'CustomizeDlg', u'Tree', u'SelectionTree', 25, 85, 175, 95, 7, u'_BrowseProperty', u'Tree of selections', u'Browse', None),
+(u'CustomizeDlg', u'Box', u'GroupBox', 210, 81, 140, 98, 1, None, None, None, None),
+(u'CustomizeDlg', u'Reset', u'PushButton', 42, 243, 56, 17, 3, None, u'[ButtonText_Reset]', u'DiskCost', None),
+(u'CustomizeDlg', u'DiskCost', u'PushButton', 111, 243, 56, 17, 3, None, u'Disk &Usage', u'Back', None),
+(u'CustomizeDlg', u'ItemDescription', u'Text', 215, 90, 131, 30, 3, None, u'Multiline description of the currently selected item.', None, None),
+(u'CustomizeDlg', u'ItemSize', u'Text', 215, 130, 131, 45, 3, None, u'The size of the currently selected item.', None, None),
+(u'CustomizeDlg', u'Location', u'Text', 75, 200, 215, 20, 3, None, u"<The selection's path>", None, None),
+(u'CustomizeDlg', u'LocationLabel', u'Text', 25, 200, 50, 10, 3, None, u'Location:', None, None),
+(u'DiskCostDlg', u'Text', u'Text', 20, 53, 330, 40, 3, None, u'The highlighted volumes (if any) do not have enough disk space available for the currently selected features. You can either remove some files from the highlighted volumes, or choose to install less features onto local drive(s), or select different destination drive(s).', None, None),
+(u'DiskCostDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'OK', None),
+(u'DiskCostDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'DiskCostDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'DiskCostDlg', u'Description', u'Text', 20, 20, 280, 20, 196611, None, u'The disk space required for the installation of the selected features.', None, None),
+(u'DiskCostDlg', u'OK', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_OK]', u'BannerBitmap', None),
+(u'DiskCostDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Disk Space Requirements', None, None),
+(u'DiskCostDlg', u'VolumeList', u'VolumeCostList', 20, 100, 330, 120, 393223, None, u'{120}{70}{70}{70}{70}', None, None),
+(u'ErrorDlg', u'Y', u'PushButton', 100, 80, 56, 17, 3, None, u'[ButtonText_Yes]', None, None),
+(u'ErrorDlg', u'A', u'PushButton', 100, 80, 56, 17, 3, None, u'[ButtonText_Cancel]', None, None),
+(u'ErrorDlg', u'C', u'PushButton', 100, 80, 56, 17, 3, None, u'[ButtonText_Cancel]', None, None),
+(u'ErrorDlg', u'ErrorIcon', u'Icon', 15, 15, 24, 24, 5242881, None, u'[InfoIcon]', None, u'Information icon|'),
+(u'ErrorDlg', u'ErrorText', u'Text', 48, 15, 205, 60, 3, None, u'Information text', None, None),
+(u'ErrorDlg', u'I', u'PushButton', 100, 80, 56, 17, 3, None, u'[ButtonText_Ignore]', None, None),
+(u'ErrorDlg', u'N', u'PushButton', 100, 80, 56, 17, 3, None, u'[ButtonText_No]', None, None),
+(u'ErrorDlg', u'O', u'PushButton', 100, 80, 56, 17, 3, None, u'[ButtonText_OK]', None, None),
+(u'ErrorDlg', u'R', u'PushButton', 100, 80, 56, 17, 3, None, u'[ButtonText_Retry]', None, None),
+(u'FilesInUse', u'Text', u'Text', 20, 55, 330, 30, 3, None, u'The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.', None, None),
+(u'FilesInUse', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'Retry', None),
+(u'FilesInUse', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'FilesInUse', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'FilesInUse', u'Description', u'Text', 20, 23, 280, 20, 196611, None, u'Some files that need to be updated are currently in use.', None, None),
+(u'FilesInUse', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Files in Use', None, None),
+(u'FilesInUse', u'Retry', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Retry]', u'Ignore', None),
+(u'FilesInUse', u'Exit', u'PushButton', 166, 243, 56, 17, 3, None, u'[ButtonText_Exit]', u'BannerBitmap', None),
+(u'FilesInUse', u'Ignore', u'PushButton', 235, 243, 56, 17, 3, None, u'[ButtonText_Ignore]', u'Exit', None),
+(u'FilesInUse', u'List', u'ListBox', 20, 87, 330, 130, 7, u'FileInUseProcess', None, None, None),
+(u'LicenseAgreementDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'AgreementText', None),
+(u'LicenseAgreementDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'LicenseAgreementDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'LicenseAgreementDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'LicenseAgreementDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'Please read the following license agreement carefully', None, None),
+(u'LicenseAgreementDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]End-User License Agreement', None, None),
+(u'LicenseAgreementDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Next', None),
+(u'LicenseAgreementDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'LicenseAgreementDlg', u'AgreementText', u'ScrollableText', 20, 60, 330, 120, 7, None, u'{\\rtf1\\ansi\\ansicpg1252\\deff0\\deftab720{\\fonttbl{\\f0\\froman\\fprq2 Times New Roman;}}{\\colortbl\\red0\\green0\\blue0;} \\deflang1033\\horzdoc{\\*\\fchars }{\\*\\lchars }\\pard\\plain\\f0\\fs20 <Your license agreement should go here.>\\par }', u'Buttons', None),
+(u'LicenseAgreementDlg', u'Buttons', u'RadioButtonGroup', 20, 187, 330, 40, 3, u'IAgree', None, u'Back', None),
+(u'MaintenanceTypeDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'ChangeLabel', None),
+(u'MaintenanceTypeDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'MaintenanceTypeDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'MaintenanceTypeDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'MaintenanceTypeDlg', u'Description', u'Text', 25, 23, 280, 20, 196611, None, u'Select the operation you wish to perform.', None, None),
+(u'MaintenanceTypeDlg', u'Title', u'Text', 15, 6, 240, 15, 196611, None, u'[DlgTitleFont]Modify, Repair or Remove installation', None, None),
+(u'MaintenanceTypeDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Next', None),
+(u'MaintenanceTypeDlg', u'Next', u'PushButton', 236, 243, 56, 17, 1, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'MaintenanceTypeDlg', u'ChangeLabel', u'Text', 105, 65, 100, 10, 3, None, u'[DlgTitleFont]&Modify', u'ChangeButton', None),
+(u'MaintenanceTypeDlg', u'ChangeButton', u'PushButton', 50, 65, 38, 38, 5767171, None, u'[CustomSetupIcon]', u'RepairLabel', u'Modify Installation|'),
+(u'MaintenanceTypeDlg', u'RepairLabel', u'Text', 105, 114, 100, 10, 3, None, u'[DlgTitleFont]Re&pair', u'RepairButton', None),
+(u'MaintenanceTypeDlg', u'ChangeText', u'Text', 105, 78, 230, 20, 3, None, u'Allows users to change the way features are installed.', None, None),
+(u'MaintenanceTypeDlg', u'RemoveButton', u'PushButton', 50, 163, 38, 38, 5767171, None, u'[RemoveIcon]', u'Back', u'Remove Installation|'),
+(u'MaintenanceTypeDlg', u'RemoveLabel', u'Text', 105, 163, 100, 10, 3, None, u'[DlgTitleFont]&Remove', u'RemoveButton', None),
+(u'MaintenanceTypeDlg', u'RemoveText', u'Text', 105, 176, 230, 20, 3, None, u'Removes [ProductName] from your computer.', None, None),
+(u'MaintenanceTypeDlg', u'RepairButton', u'PushButton', 50, 114, 38, 38, 5767171, None, u'[RepairIcon]', u'RemoveLabel', u'Repair Installation|'),
+(u'MaintenanceTypeDlg', u'RepairText', u'Text', 105, 127, 230, 30, 3, None, u'Repairs errors in the most recent installation state - fixes missing or corrupt files, shortcuts and registry entries.', None, None),
+(u'MaintenanceWelcomeDlg', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Back', None),
+(u'MaintenanceWelcomeDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'MaintenanceWelcomeDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'MaintenanceWelcomeDlg', u'Description', u'Text', 135, 70, 220, 60, 196611, None, u'The [Wizard] will allow you to change the way [ProductName] features are installed on your computer or even to remove [ProductName] from your computer. Click Next to continue or Cancel to exit the [Wizard].', None, None),
+(u'MaintenanceWelcomeDlg', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}Welcome to the [ProductName] [Wizard]', None, None),
+(u'MaintenanceWelcomeDlg', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Next', None),
+(u'MaintenanceWelcomeDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'OutOfDiskDlg', u'Text', u'Text', 20, 53, 330, 40, 3, None, u'The highlighted volumes do not have enough disk space available for the currently selected features. You can either remove some files from the highlighted volumes, or choose to install less features onto local drive(s), or select different destination drive(s).', None, None),
+(u'OutOfDiskDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'OK', None),
+(u'OutOfDiskDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'OutOfDiskDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'OutOfDiskDlg', u'Description', u'Text', 20, 20, 280, 20, 196611, None, u'Disk space required for the installation exceeds available disk space.', None, None),
+(u'OutOfDiskDlg', u'OK', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_OK]', u'BannerBitmap', None),
+(u'OutOfDiskDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Out of Disk Space', None, None),
+(u'OutOfDiskDlg', u'VolumeList', u'VolumeCostList', 20, 100, 330, 120, 393223, None, u'{120}{70}{70}{70}{70}', None, None),
+(u'OutOfRbDiskDlg', u'Text', u'Text', 20, 53, 330, 40, 3, None, u'The highlighted volumes do not have enough disk space available for the currently selected features. You can either remove some files from the highlighted volumes, or choose to install less features onto local drive(s), or select different destination drive(s).', None, None),
+(u'OutOfRbDiskDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'No', None),
+(u'OutOfRbDiskDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'OutOfRbDiskDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'OutOfRbDiskDlg', u'Description', u'Text', 20, 20, 280, 20, 196611, None, u'Disk space required for the installation exceeds available disk space.', None, None),
+(u'OutOfRbDiskDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Out of Disk Space', None, None),
+(u'OutOfRbDiskDlg', u'No', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_No]', u'Yes', None),
+(u'OutOfRbDiskDlg', u'Yes', u'PushButton', 240, 243, 56, 17, 3, None, u'[ButtonText_Yes]', u'BannerBitmap', None),
+(u'OutOfRbDiskDlg', u'VolumeList', u'VolumeCostList', 20, 140, 330, 80, 4587527, None, u'{120}{70}{70}{70}{70}', None, None),
+(u'OutOfRbDiskDlg', u'Text2', u'Text', 20, 94, 330, 40, 3, None, u"Alternatively, you may choose to disable the installer's rollback functionality. This allows the installer to restore your computer's original state should the installation be interrupted in any way. Click Yes if you wish to take the risk to disable rollback.", None, None),
+(u'ResumeDlg', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Back', None),
+(u'ResumeDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'ResumeDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'ResumeDlg', u'Description', u'Text', 135, 70, 220, 30, 196611, None, u'The [Wizard] will complete the installation of [ProductName] on your computer. Click Install to continue or Cancel to exit the [Wizard].', None, None),
+(u'ResumeDlg', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}Resuming the [ProductName] [Wizard]', None, None),
+(u'ResumeDlg', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Install', None),
+(u'ResumeDlg', u'Install', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Install]', u'Cancel', None),
+(u'SetupTypeDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'TypicalLabel', None),
+(u'SetupTypeDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'SetupTypeDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'SetupTypeDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'SetupTypeDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'Choose the setup type that best suits your needs', None, None),
+(u'SetupTypeDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Choose Setup Type', None, None),
+(u'SetupTypeDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Next', None),
+(u'SetupTypeDlg', u'Next', u'PushButton', 236, 243, 56, 17, 1, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'SetupTypeDlg', u'TypicalLabel', u'Text', 105, 65, 100, 10, 3, None, u'[DlgTitleFont]&Typical', u'TypicalButton', None),
+(u'SetupTypeDlg', u'CompleteButton', u'PushButton', 50, 171, 38, 38, 5767171, None, u'[CompleteSetupIcon]', u'Back', u'Complete Installation|'),
+(u'SetupTypeDlg', u'CompleteLabel', u'Text', 105, 171, 100, 10, 3, None, u'[DlgTitleFont]C&omplete', u'CompleteButton', None),
+(u'SetupTypeDlg', u'CompleteText', u'Text', 105, 184, 230, 20, 3, None, u'All program features will be installed. (Requires most disk space)', None, None),
+(u'SetupTypeDlg', u'CustomButton', u'PushButton', 50, 118, 38, 38, 5767171, None, u'[CustomSetupIcon]', u'CompleteLabel', u'Custom Installation|'),
+(u'SetupTypeDlg', u'CustomLabel', u'Text', 105, 118, 100, 10, 3, None, u'[DlgTitleFont]C&ustom', u'CustomButton', None),
+(u'SetupTypeDlg', u'CustomText', u'Text', 105, 131, 230, 30, 3, None, u'Allows users to choose which program features will be installed and where they will be installed. Recommended for advanced users.', None, None),
+(u'SetupTypeDlg', u'TypicalButton', u'PushButton', 50, 65, 38, 38, 5767171, None, u'[InstallerIcon]', u'CustomLabel', u'Typical Installation|'),
+(u'SetupTypeDlg', u'TypicalText', u'Text', 105, 78, 230, 20, 3, None, u'Installs the most common program features. Recommended for most users.', None, None),
+(u'UserRegistrationDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'NameLabel', None),
+(u'UserRegistrationDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'UserRegistrationDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'UserRegistrationDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'UserRegistrationDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'Please enter your customer information', None, None),
+(u'UserRegistrationDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Customer Information', None, None),
+(u'UserRegistrationDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Next', None),
+(u'UserRegistrationDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+(u'UserRegistrationDlg', u'OrganizationLabel', u'Text', 45, 110, 100, 15, 3, None, u'&Organization:', u'OrganizationEdit', None),
+(u'UserRegistrationDlg', u'CDKeyEdit', u'MaskedEdit', 45, 159, 250, 16, 3, u'PIDKEY', u'[PIDTemplate]', u'Back', None),
+(u'UserRegistrationDlg', u'CDKeyLabel', u'Text', 45, 147, 50, 10, 3, None, u'CD &Key:', u'CDKeyEdit', None),
+(u'UserRegistrationDlg', u'OrganizationEdit', u'Edit', 45, 122, 220, 18, 3, u'COMPANYNAME', u'{80}', u'CDKeyLabel', None),
+(u'UserRegistrationDlg', u'NameLabel', u'Text', 45, 73, 100, 15, 3, None, u'&User Name:', u'NameEdit', None),
+(u'UserRegistrationDlg', u'NameEdit', u'Edit', 45, 85, 220, 18, 3, u'USERNAME', u'{80}', u'OrganizationLabel', None),
+(u'VerifyReadyDlg', u'Text', u'Text', 25, 70, 320, 20, 3, None, u'Click Install to begin the installation. If you want to review or change any of your installation settings, click Back. Click Cancel to exit the wizard.', None, None),
+(u'VerifyReadyDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'Back', None),
+(u'VerifyReadyDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'VerifyReadyDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'VerifyReadyDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'VerifyReadyDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'The [Wizard] is ready to begin the [InstallMode] installation', None, None),
+(u'VerifyReadyDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Ready to Install', None, None),
+(u'VerifyReadyDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Install', None),
+(u'VerifyReadyDlg', u'Install', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Install]', u'Cancel', None),
+(u'VerifyRemoveDlg', u'Text', u'Text', 25, 70, 320, 30, 3, None, u'Click Remove to remove [ProductName] from your computer. If you want to review or change any of your installation settings, click Back. Click Cancel to exit the wizard.', None, None),
+(u'VerifyRemoveDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'Back', None),
+(u'VerifyRemoveDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'VerifyRemoveDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'VerifyRemoveDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'VerifyRemoveDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'You have chosen to remove the program from your computer.', None, None),
+(u'VerifyRemoveDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Remove [ProductName]', None, None),
+(u'VerifyRemoveDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Remove', None),
+(u'VerifyRemoveDlg', u'Remove', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Remove]', u'Cancel', None),
+(u'VerifyRepairDlg', u'Text', u'Text', 25, 70, 320, 30, 3, None, u'Click Repair to repair the installation of [ProductName]. If you want to review or change any of your installation settings, click Back. Click Cancel to exit the wizard.', None, None),
+(u'VerifyRepairDlg', u'BannerBitmap', u'Bitmap', 0, 0, 374, 44, 1, None, u'[BannerBitmap]', u'Back', None),
+(u'VerifyRepairDlg', u'BannerLine', u'Line', 0, 44, 374, 0, 1, None, None, None, None),
+(u'VerifyRepairDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'VerifyRepairDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'BannerBitmap', None),
+(u'VerifyRepairDlg', u'Description', u'Text', 25, 23, 280, 15, 196611, None, u'The [Wizard] is ready to begin the repair of [ProductName].', None, None),
+(u'VerifyRepairDlg', u'Title', u'Text', 15, 6, 200, 15, 196611, None, u'[DlgTitleFont]Repair [ProductName]', None, None),
+(u'VerifyRepairDlg', u'Back', u'PushButton', 180, 243, 56, 17, 3, None, u'[ButtonText_Back]', u'Repair', None),
+(u'VerifyRepairDlg', u'Repair', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Repair]', u'Cancel', None),
+(u'WaitForCostingDlg', u'Text', u'Text', 48, 15, 194, 30, 3, None, u'Please wait while the installer finishes determining your disk space requirements.', None, None),
+(u'WaitForCostingDlg', u'Icon', u'Icon', 15, 15, 24, 24, 5242881, None, u'[ExclamationIcon]', None, u'Exclamation icon|'),
+(u'WaitForCostingDlg', u'Return', u'PushButton', 102, 57, 56, 17, 3, None, u'[ButtonText_Return]', None, None),
+(u'WelcomeDlg', u'Bitmap', u'Bitmap', 0, 0, 370, 234, 1, None, u'[DialogBitmap]', u'Back', None),
+(u'WelcomeDlg', u'BottomLine', u'Line', 0, 234, 374, 0, 1, None, None, None, None),
+(u'WelcomeDlg', u'Cancel', u'PushButton', 304, 243, 56, 17, 3, None, u'[ButtonText_Cancel]', u'Bitmap', None),
+(u'WelcomeDlg', u'Description', u'Text', 135, 70, 220, 30, 196611, None, u'The [Wizard] will install [ProductName] on your computer. Click Next to continue or Cancel to exit the [Wizard].', None, None),
+(u'WelcomeDlg', u'Title', u'Text', 135, 20, 220, 60, 196611, None, u'{\\VerdanaBold13}Welcome to the [ProductName] [Wizard]', None, None),
+(u'WelcomeDlg', u'Back', u'PushButton', 180, 243, 56, 17, 1, None, u'[ButtonText_Back]', u'Next', None),
+(u'WelcomeDlg', u'Next', u'PushButton', 236, 243, 56, 17, 3, None, u'[ButtonText_Next]', u'Cancel', None),
+]
+
+ListBox = [
+]
+
+ActionText = [
+(u'InstallValidate', u'Validating install', None),
+(u'InstallFiles', u'Copying new files', u'File: [1], Directory: [9], Size: [6]'),
+(u'InstallAdminPackage', u'Copying network install files', u'File: [1], Directory: [9], Size: [6]'),
+(u'FileCost', u'Computing space requirements', None),
+(u'CostInitialize', u'Computing space requirements', None),
+(u'CostFinalize', u'Computing space requirements', None),
+(u'CreateShortcuts', u'Creating shortcuts', u'Shortcut: [1]'),
+(u'PublishComponents', u'Publishing Qualified Components', u'Component ID: [1], Qualifier: [2]'),
+(u'PublishFeatures', u'Publishing Product Features', u'Feature: [1]'),
+(u'PublishProduct', u'Publishing product information', None),
+(u'RegisterClassInfo', u'Registering Class servers', u'Class Id: [1]'),
+(u'RegisterExtensionInfo', u'Registering extension servers', u'Extension: [1]'),
+(u'RegisterMIMEInfo', u'Registering MIME info', u'MIME Content Type: [1], Extension: [2]'),
+(u'RegisterProgIdInfo', u'Registering program identifiers', u'ProgId: [1]'),
+(u'AllocateRegistrySpace', u'Allocating registry space', u'Free space: [1]'),
+(u'AppSearch', u'Searching for installed applications', u'Property: [1], Signature: [2]'),
+(u'BindImage', u'Binding executables', u'File: [1]'),
+(u'CCPSearch', u'Searching for qualifying products', None),
+(u'CreateFolders', u'Creating folders', u'Folder: [1]'),
+(u'DeleteServices', u'Deleting services', u'Service: [1]'),
+(u'DuplicateFiles', u'Creating duplicate files', u'File: [1], Directory: [9], Size: [6]'),
+(u'FindRelatedProducts', u'Searching for related applications', u'Found application: [1]'),
+(u'InstallODBC', u'Installing ODBC components', None),
+(u'InstallServices', u'Installing new services', u'Service: [2]'),
+(u'LaunchConditions', u'Evaluating launch conditions', None),
+(u'MigrateFeatureStates', u'Migrating feature states from related applications', u'Application: [1]'),
+(u'MoveFiles', u'Moving files', u'File: [1], Directory: [9], Size: [6]'),
+(u'PatchFiles', u'Patching files', u'File: [1], Directory: [2], Size: [3]'),
+(u'ProcessComponents', u'Updating component registration', None),
+(u'RegisterComPlus', u'Registering COM+ Applications and Components', u'AppId: [1]{{, AppType: [2], Users: [3], RSN: [4]}}'),
+(u'RegisterFonts', u'Registering fonts', u'Font: [1]'),
+(u'RegisterProduct', u'Registering product', u'[1]'),
+(u'RegisterTypeLibraries', u'Registering type libraries', u'LibID: [1]'),
+(u'RegisterUser', u'Registering user', u'[1]'),
+(u'RemoveDuplicateFiles', u'Removing duplicated files', u'File: [1], Directory: [9]'),
+(u'RemoveEnvironmentStrings', u'Updating environment strings', u'Name: [1], Value: [2], Action [3]'),
+(u'RemoveExistingProducts', u'Removing applications', u'Application: [1], Command line: [2]'),
+(u'RemoveFiles', u'Removing files', u'File: [1], Directory: [9]'),
+(u'RemoveFolders', u'Removing folders', u'Folder: [1]'),
+(u'RemoveIniValues', u'Removing INI files entries', u'File: [1], Section: [2], Key: [3], Value: [4]'),
+(u'RemoveODBC', u'Removing ODBC components', None),
+(u'RemoveRegistryValues', u'Removing system registry values', u'Key: [1], Name: [2]'),
+(u'RemoveShortcuts', u'Removing shortcuts', u'Shortcut: [1]'),
+(u'RMCCPSearch', u'Searching for qualifying products', None),
+(u'SelfRegModules', u'Registering modules', u'File: [1], Folder: [2]'),
+(u'SelfUnregModules', u'Unregistering modules', u'File: [1], Folder: [2]'),
+(u'SetODBCFolders', u'Initializing ODBC directories', None),
+(u'StartServices', u'Starting services', u'Service: [1]'),
+(u'StopServices', u'Stopping services', u'Service: [1]'),
+(u'UnpublishComponents', u'Unpublishing Qualified Components', u'Component ID: [1], Qualifier: [2]'),
+(u'UnpublishFeatures', u'Unpublishing Product Features', u'Feature: [1]'),
+(u'UnregisterClassInfo', u'Unregister Class servers', u'Class Id: [1]'),
+(u'UnregisterComPlus', u'Unregistering COM+ Applications and Components', u'AppId: [1]{{, AppType: [2]}}'),
+(u'UnregisterExtensionInfo', u'Unregistering extension servers', u'Extension: [1]'),
+(u'UnregisterFonts', u'Unregistering fonts', u'Font: [1]'),
+(u'UnregisterMIMEInfo', u'Unregistering MIME info', u'MIME Content Type: [1], Extension: [2]'),
+(u'UnregisterProgIdInfo', u'Unregistering program identifiers', u'ProgId: [1]'),
+(u'UnregisterTypeLibraries', u'Unregistering type libraries', u'LibID: [1]'),
+(u'WriteEnvironmentStrings', u'Updating environment strings', u'Name: [1], Value: [2], Action [3]'),
+(u'WriteIniValues', u'Writing INI files values', u'File: [1], Section: [2], Key: [3], Value: [4]'),
+(u'WriteRegistryValues', u'Writing system registry values', u'Key: [1], Name: [2], Value: [3]'),
+(u'Advertise', u'Advertising application', None),
+(u'GenerateScript', u'Generating script operations for action:', u'[1]'),
+(u'InstallSFPCatalogFile', u'Installing system catalog', u'File: [1], Dependencies: [2]'),
+(u'MsiPublishAssemblies', u'Publishing assembly information', u'Application Context:[1], Assembly Name:[2]'),
+(u'MsiUnpublishAssemblies', u'Unpublishing assembly information', u'Application Context:[1], Assembly Name:[2]'),
+(u'Rollback', u'Rolling back action:', u'[1]'),
+(u'RollbackCleanup', u'Removing backup files', u'File: [1]'),
+(u'UnmoveFiles', u'Removing moved files', u'File: [1], Directory: [9]'),
+(u'UnpublishProduct', u'Unpublishing product information', None),
+]
+
+ControlCondition = [
+(u'CustomizeDlg', u'Browse', u'Hide', u'Installed'),
+(u'CustomizeDlg', u'Location', u'Hide', u'Installed'),
+(u'CustomizeDlg', u'LocationLabel', u'Hide', u'Installed'),
+(u'LicenseAgreementDlg', u'Next', u'Disable', u'IAgree <> "Yes"'),
+(u'LicenseAgreementDlg', u'Next', u'Enable', u'IAgree = "Yes"'),
+]
+
+ControlEvent = [
+(u'AdminWelcomeDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'AdminWelcomeDlg', u'Next', u'NewDialog', u'AdminRegistrationDlg', u'1', 2),
+(u'AdminWelcomeDlg', u'Next', u'[InstallMode]', u'Server Image', u'1', 1),
+(u'ExitDialog', u'Finish', u'EndDialog', u'Return', u'1', None),
+(u'FatalError', u'Finish', u'EndDialog', u'Exit', u'1', None),
+(u'PrepareDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'ProgressDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'UserExit', u'Finish', u'EndDialog', u'Exit', u'1', None),
+(u'AdminBrowseDlg', u'Up', u'DirectoryListUp', u'0', u'1', None),
+(u'AdminBrowseDlg', u'Cancel', u'Reset', u'0', u'1', 1),
+(u'AdminBrowseDlg', u'Cancel', u'EndDialog', u'Return', u'1', 2),
+(u'AdminBrowseDlg', u'NewFolder', u'DirectoryListNew', u'0', u'1', None),
+(u'AdminBrowseDlg', u'OK', u'EndDialog', u'Return', u'1', 2),
+(u'AdminBrowseDlg', u'OK', u'SetTargetPath', u'TARGETDIR', u'1', 1),
+(u'AdminInstallPointDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'AdminInstallPointDlg', u'Back', u'NewDialog', u'AdminRegistrationDlg', u'1', None),
+(u'AdminInstallPointDlg', u'Next', u'SetTargetPath', u'TARGETDIR', u'1', 1),
+(u'AdminInstallPointDlg', u'Next', u'NewDialog', u'VerifyReadyDlg', u'1', 2),
+(u'AdminInstallPointDlg', u'Browse', u'SpawnDialog', u'AdminBrowseDlg', u'1', None),
+(u'AdminRegistrationDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'AdminRegistrationDlg', u'Back', u'NewDialog', u'AdminWelcomeDlg', u'1', None),
+(u'AdminRegistrationDlg', u'Next', u'NewDialog', u'AdminInstallPointDlg', u'ProductID', 2),
+(u'AdminRegistrationDlg', u'Next', u'ValidateProductID', u'0', u'0', 1),
+(u'BrowseDlg', u'Up', u'DirectoryListUp', u'0', u'1', None),
+(u'BrowseDlg', u'Cancel', u'Reset', u'0', u'1', 1),
+(u'BrowseDlg', u'Cancel', u'EndDialog', u'Return', u'1', 2),
+(u'BrowseDlg', u'NewFolder', u'DirectoryListNew', u'0', u'1', None),
+(u'BrowseDlg', u'OK', u'EndDialog', u'Return', u'1', 2),
+(u'BrowseDlg', u'OK', u'SetTargetPath', u'[_BrowseProperty]', u'1', 1),
+(u'CancelDlg', u'No', u'EndDialog', u'Return', u'1', None),
+(u'CancelDlg', u'Yes', u'EndDialog', u'Exit', u'1', None),
+(u'CustomizeDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'CustomizeDlg', u'Back', u'NewDialog', u'MaintenanceTypeDlg', u'InstallMode = "Change"', None),
+(u'CustomizeDlg', u'Back', u'NewDialog', u'SetupTypeDlg', u'InstallMode = "Custom"', None),
+(u'CustomizeDlg', u'Next', u'NewDialog', u'VerifyReadyDlg', u'1', None),
+(u'CustomizeDlg', u'Browse', u'SelectionBrowse', u'BrowseDlg', u'1', None),
+(u'CustomizeDlg', u'Reset', u'Reset', u'0', u'1', None),
+(u'CustomizeDlg', u'DiskCost', u'SpawnDialog', u'DiskCostDlg', u'1', 2),
+(u'DiskCostDlg', u'OK', u'EndDialog', u'Return', u'1', None),
+(u'ErrorDlg', u'Y', u'EndDialog', u'ErrorYes', u'1', None),
+(u'ErrorDlg', u'A', u'EndDialog', u'ErrorAbort', u'1', None),
+(u'ErrorDlg', u'C', u'EndDialog', u'ErrorCancel', u'1', None),
+(u'ErrorDlg', u'I', u'EndDialog', u'ErrorIgnore', u'1', None),
+(u'ErrorDlg', u'N', u'EndDialog', u'ErrorNo', u'1', None),
+(u'ErrorDlg', u'O', u'EndDialog', u'ErrorOk', u'1', None),
+(u'ErrorDlg', u'R', u'EndDialog', u'ErrorRetry', u'1', None),
+(u'FilesInUse', u'Retry', u'EndDialog', u'Retry', u'1', None),
+(u'FilesInUse', u'Exit', u'EndDialog', u'Exit', u'1', None),
+(u'FilesInUse', u'Ignore', u'EndDialog', u'Ignore', u'1', None),
+(u'LicenseAgreementDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'LicenseAgreementDlg', u'Back', u'NewDialog', u'WelcomeDlg', u'1', None),
+(u'LicenseAgreementDlg', u'Next', u'NewDialog', u'SetupTypeDlg', u'IAgree = "Yes" AND ShowUserRegistrationDlg <> 1', 3),
+(u'LicenseAgreementDlg', u'Next', u'NewDialog', u'UserRegistrationDlg', u'IAgree = "Yes" AND ShowUserRegistrationDlg = 1', 1),
+(u'LicenseAgreementDlg', u'Next', u'SpawnWaitDialog', u'WaitForCostingDlg', u'CostingComplete = 1', 2),
+(u'MaintenanceTypeDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'MaintenanceTypeDlg', u'Back', u'NewDialog', u'MaintenanceWelcomeDlg', u'1', None),
+(u'MaintenanceTypeDlg', u'ChangeButton', u'NewDialog', u'CustomizeDlg', u'1', 4),
+(u'MaintenanceTypeDlg', u'ChangeButton', u'[InstallMode]', u'Change', u'1', 1),
+(u'MaintenanceTypeDlg', u'ChangeButton', u'[Progress1]', u'Changing', u'1', 2),
+(u'MaintenanceTypeDlg', u'ChangeButton', u'[Progress2]', u'changes', u'1', 3),
+(u'MaintenanceTypeDlg', u'RemoveButton', u'NewDialog', u'VerifyRemoveDlg', u'1', 4),
+(u'MaintenanceTypeDlg', u'RemoveButton', u'[InstallMode]', u'Remove', u'1', 1),
+(u'MaintenanceTypeDlg', u'RemoveButton', u'[Progress1]', u'Removing', u'1', 2),
+(u'MaintenanceTypeDlg', u'RemoveButton', u'[Progress2]', u'removes', u'1', 3),
+(u'MaintenanceTypeDlg', u'RepairButton', u'NewDialog', u'VerifyRepairDlg', u'1', 4),
+(u'MaintenanceTypeDlg', u'RepairButton', u'[InstallMode]', u'Repair', u'1', 1),
+(u'MaintenanceTypeDlg', u'RepairButton', u'[Progress1]', u'Repairing', u'1', 2),
+(u'MaintenanceTypeDlg', u'RepairButton', u'[Progress2]', u'repairs', u'1', 3),
+(u'MaintenanceWelcomeDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'MaintenanceWelcomeDlg', u'Next', u'NewDialog', u'MaintenanceTypeDlg', u'1', 2),
+(u'MaintenanceWelcomeDlg', u'Next', u'SpawnWaitDialog', u'WaitForCostingDlg', u'CostingComplete = 1', 1),
+(u'OutOfDiskDlg', u'OK', u'EndDialog', u'Return', u'1', None),
+(u'OutOfRbDiskDlg', u'No', u'EndDialog', u'Return', u'1', None),
+(u'OutOfRbDiskDlg', u'Yes', u'EndDialog', u'Return', u'1', 2),
+(u'OutOfRbDiskDlg', u'Yes', u'EnableRollback', u'False', u'1', 1),
+(u'ResumeDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'ResumeDlg', u'Install', u'EndDialog', u'Return', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 4),
+(u'ResumeDlg', u'Install', u'EndDialog', u'Return', u'OutOfDiskSpace <> 1', 2),
+(u'ResumeDlg', u'Install', u'SpawnDialog', u'OutOfDiskDlg', u'(OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 1) OR (OutOfDiskSpace = 1 AND PROMPTROLLBACKCOST="F")', 6),
+(u'ResumeDlg', u'Install', u'SpawnDialog', u'OutOfRbDiskDlg', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND (PROMPTROLLBACKCOST="P" OR NOT PROMPTROLLBACKCOST)', 3),
+(u'ResumeDlg', u'Install', u'SpawnWaitDialog', u'WaitForCostingDlg', u'CostingComplete = 1', 1),
+(u'ResumeDlg', u'Install', u'EnableRollback', u'False', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 5),
+(u'SetupTypeDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'SetupTypeDlg', u'Back', u'NewDialog', u'LicenseAgreementDlg', u'ShowUserRegistrationDlg <> 1', None),
+(u'SetupTypeDlg', u'Back', u'NewDialog', u'UserRegistrationDlg', u'ShowUserRegistrationDlg = 1', None),
+(u'SetupTypeDlg', u'CompleteButton', u'NewDialog', u'VerifyReadyDlg', u'1', 3),
+(u'SetupTypeDlg', u'CompleteButton', u'[InstallMode]', u'Complete', u'1', 1),
+(u'SetupTypeDlg', u'CompleteButton', u'SetInstallLevel', u'1000', u'1', 2),
+(u'SetupTypeDlg', u'CustomButton', u'NewDialog', u'CustomizeDlg', u'1', 2),
+(u'SetupTypeDlg', u'CustomButton', u'[InstallMode]', u'Custom', u'1', 1),
+(u'SetupTypeDlg', u'TypicalButton', u'NewDialog', u'VerifyReadyDlg', u'1', 3),
+(u'SetupTypeDlg', u'TypicalButton', u'[InstallMode]', u'Typical', u'1', 1),
+(u'SetupTypeDlg', u'TypicalButton', u'SetInstallLevel', u'3', u'1', 2),
+(u'UserRegistrationDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'UserRegistrationDlg', u'Back', u'NewDialog', u'LicenseAgreementDlg', u'1', None),
+(u'UserRegistrationDlg', u'Next', u'NewDialog', u'SetupTypeDlg', u'ProductID', 3),
+(u'UserRegistrationDlg', u'Next', u'ValidateProductID', u'0', u'0', 1),
+(u'UserRegistrationDlg', u'Next', u'SpawnWaitDialog', u'WaitForCostingDlg', u'CostingComplete = 1', 2),
+(u'VerifyReadyDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'VerifyReadyDlg', u'Back', u'NewDialog', u'AdminInstallPointDlg', u'InstallMode = "Server Image"', None),
+(u'VerifyReadyDlg', u'Back', u'NewDialog', u'CustomizeDlg', u'InstallMode = "Custom" OR InstallMode = "Change"', None),
+(u'VerifyReadyDlg', u'Back', u'NewDialog', u'MaintenanceTypeDlg', u'InstallMode = "Repair"', None),
+(u'VerifyReadyDlg', u'Back', u'NewDialog', u'SetupTypeDlg', u'InstallMode = "Typical" OR InstallMode = "Complete"', None),
+(u'VerifyReadyDlg', u'Install', u'EndDialog', u'Return', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 3),
+(u'VerifyReadyDlg', u'Install', u'EndDialog', u'Return', u'OutOfDiskSpace <> 1', 1),
+(u'VerifyReadyDlg', u'Install', u'SpawnDialog', u'OutOfDiskDlg', u'(OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 1) OR (OutOfDiskSpace = 1 AND PROMPTROLLBACKCOST="F")', 5),
+(u'VerifyReadyDlg', u'Install', u'SpawnDialog', u'OutOfRbDiskDlg', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND (PROMPTROLLBACKCOST="P" OR NOT PROMPTROLLBACKCOST)', 2),
+(u'VerifyReadyDlg', u'Install', u'EnableRollback', u'False', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 4),
+(u'VerifyRemoveDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'VerifyRemoveDlg', u'Back', u'NewDialog', u'MaintenanceTypeDlg', u'1', None),
+(u'VerifyRemoveDlg', u'Remove', u'Remove', u'All', u'OutOfDiskSpace <> 1', 1),
+(u'VerifyRemoveDlg', u'Remove', u'EndDialog', u'Return', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 4),
+(u'VerifyRemoveDlg', u'Remove', u'EndDialog', u'Return', u'OutOfDiskSpace <> 1', 2),
+(u'VerifyRemoveDlg', u'Remove', u'SpawnDialog', u'OutOfDiskDlg', u'(OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 1) OR (OutOfDiskSpace = 1 AND PROMPTROLLBACKCOST="F")', 6),
+(u'VerifyRemoveDlg', u'Remove', u'SpawnDialog', u'OutOfRbDiskDlg', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND (PROMPTROLLBACKCOST="P" OR NOT PROMPTROLLBACKCOST)', 3),
+(u'VerifyRemoveDlg', u'Remove', u'EnableRollback', u'False', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 5),
+(u'VerifyRepairDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'VerifyRepairDlg', u'Back', u'NewDialog', u'MaintenanceTypeDlg', u'1', None),
+(u'VerifyRepairDlg', u'Repair', u'EndDialog', u'Return', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 5),
+(u'VerifyRepairDlg', u'Repair', u'EndDialog', u'Return', u'OutOfDiskSpace <> 1', 3),
+(u'VerifyRepairDlg', u'Repair', u'SpawnDialog', u'OutOfDiskDlg', u'(OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 1) OR (OutOfDiskSpace = 1 AND PROMPTROLLBACKCOST="F")', 7),
+(u'VerifyRepairDlg', u'Repair', u'SpawnDialog', u'OutOfRbDiskDlg', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND (PROMPTROLLBACKCOST="P" OR NOT PROMPTROLLBACKCOST)', 4),
+(u'VerifyRepairDlg', u'Repair', u'EnableRollback', u'False', u'OutOfDiskSpace = 1 AND OutOfNoRbDiskSpace = 0 AND PROMPTROLLBACKCOST="D"', 6),
+(u'VerifyRepairDlg', u'Repair', u'Reinstall', u'All', u'OutOfDiskSpace <> 1', 2),
+(u'VerifyRepairDlg', u'Repair', u'ReinstallMode', u'ecmus', u'OutOfDiskSpace <> 1', 1),
+(u'WaitForCostingDlg', u'Return', u'EndDialog', u'Exit', u'1', None),
+(u'WelcomeDlg', u'Cancel', u'SpawnDialog', u'CancelDlg', u'1', None),
+(u'WelcomeDlg', u'Next', u'NewDialog', u'LicenseAgreementDlg', u'1', None),
+]
+
+Dialog = [
+(u'AdminWelcomeDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Next', u'Next', u'Cancel'),
+(u'ExitDialog', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Finish', u'Finish', u'Finish'),
+(u'FatalError', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Finish', u'Finish', u'Finish'),
+(u'PrepareDlg', 50, 50, 370, 270, 1, u'[ProductName] [Setup]', u'Cancel', u'Cancel', u'Cancel'),
+(u'ProgressDlg', 50, 50, 370, 270, 1, u'[ProductName] [Setup]', u'Cancel', u'Cancel', u'Cancel'),
+(u'UserExit', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Finish', u'Finish', u'Finish'),
+(u'AdminBrowseDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'PathEdit', u'OK', u'Cancel'),
+(u'AdminInstallPointDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Text', u'Next', u'Cancel'),
+(u'AdminRegistrationDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'OrganizationLabel', u'Next', u'Cancel'),
+(u'BrowseDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'PathEdit', u'OK', u'Cancel'),
+(u'CancelDlg', 50, 10, 260, 85, 3, u'[ProductName] [Setup]', u'No', u'No', u'No'),
+(u'CustomizeDlg', 50, 50, 370, 270, 35, u'[ProductName] [Setup]', u'Tree', u'Next', u'Cancel'),
+(u'DiskCostDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'OK', u'OK', u'OK'),
+(u'ErrorDlg', 50, 10, 270, 105, 65539, u'Installer Information', u'ErrorText', None, None),
+(u'FilesInUse', 50, 50, 370, 270, 19, u'[ProductName] [Setup]', u'Retry', u'Retry', u'Retry'),
+(u'LicenseAgreementDlg', 50, 50, 370, 270, 3, u'[ProductName] License Agreement', u'Buttons', u'Next', u'Cancel'),
+(u'MaintenanceTypeDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'ChangeLabel', u'ChangeButton', u'Cancel'),
+(u'MaintenanceWelcomeDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Next', u'Next', u'Cancel'),
+(u'OutOfDiskDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'OK', u'OK', u'OK'),
+(u'OutOfRbDiskDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'No', u'No', u'No'),
+(u'ResumeDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Install', u'Install', u'Cancel'),
+(u'SetupTypeDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'TypicalLabel', u'TypicalButton', u'Cancel'),
+(u'UserRegistrationDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'NameLabel', u'Next', u'Cancel'),
+(u'VerifyReadyDlg', 50, 50, 370, 270, 35, u'[ProductName] [Setup]', u'Install', u'Install', u'Cancel'),
+(u'VerifyRemoveDlg', 50, 50, 370, 270, 35, u'[ProductName] [Setup]', u'Back', u'Back', u'Cancel'),
+(u'VerifyRepairDlg', 50, 50, 370, 270, 35, u'[ProductName] [Setup]', u'Repair', u'Repair', u'Cancel'),
+(u'WaitForCostingDlg', 50, 10, 260, 85, 3, u'[ProductName] [Setup]', u'Return', u'Return', u'Return'),
+(u'WelcomeDlg', 50, 50, 370, 270, 3, u'[ProductName] [Setup]', u'Next', u'Next', u'Cancel'),
+]
+
+EventMapping = [
+(u'PrepareDlg', u'ActionData', u'ActionData', u'Text'),
+(u'PrepareDlg', u'ActionText', u'ActionText', u'Text'),
+(u'ProgressDlg', u'ActionText', u'ActionText', u'Text'),
+(u'ProgressDlg', u'ProgressBar', u'SetProgress', u'Progress'),
+(u'AdminBrowseDlg', u'DirectoryCombo', u'IgnoreChange', u'IgnoreChange'),
+(u'BrowseDlg', u'DirectoryCombo', u'IgnoreChange', u'IgnoreChange'),
+(u'CustomizeDlg', u'Next', u'SelectionNoItems', u'Enabled'),
+(u'CustomizeDlg', u'Reset', u'SelectionNoItems', u'Enabled'),
+(u'CustomizeDlg', u'DiskCost', u'SelectionNoItems', u'Enabled'),
+(u'CustomizeDlg', u'ItemDescription', u'SelectionDescription', u'Text'),
+(u'CustomizeDlg', u'ItemSize', u'SelectionSize', u'Text'),
+(u'CustomizeDlg', u'Location', u'SelectionPath', u'Text'),
+(u'CustomizeDlg', u'Location', u'SelectionPathOn', u'Visible'),
+(u'CustomizeDlg', u'LocationLabel', u'SelectionPathOn', u'Visible'),
+]
+
+InstallExecuteSequence = [
+(u'InstallValidate', None, 1400),
+(u'InstallInitialize', None, 1500),
+(u'InstallFinalize', None, 6600),
+(u'InstallFiles', None, 4000),
+(u'FileCost', None, 900),
+(u'CostInitialize', None, 800),
+(u'CostFinalize', None, 1000),
+(u'CreateShortcuts', None, 4500),
+(u'PublishComponents', None, 6200),
+(u'PublishFeatures', None, 6300),
+(u'PublishProduct', None, 6400),
+(u'RegisterClassInfo', None, 4600),
+(u'RegisterExtensionInfo', None, 4700),
+(u'RegisterMIMEInfo', None, 4900),
+(u'RegisterProgIdInfo', None, 4800),
+(u'ValidateProductID', None, 700),
+(u'AllocateRegistrySpace', u'NOT Installed', 1550),
+(u'AppSearch', None, 400),
+(u'BindImage', None, 4300),
+(u'CCPSearch', u'NOT Installed', 500),
+(u'CreateFolders', None, 3700),
+(u'DeleteServices', u'VersionNT', 2000),
+(u'DuplicateFiles', None, 4210),
+(u'FindRelatedProducts', None, 200),
+(u'InstallODBC', None, 5400),
+(u'InstallServices', u'VersionNT', 5800),
+(u'LaunchConditions', None, 100),
+(u'MigrateFeatureStates', None, 1200),
+(u'MoveFiles', None, 3800),
+(u'PatchFiles', None, 4090),
+(u'ProcessComponents', None, 1600),
+(u'RegisterComPlus', None, 5700),
+(u'RegisterFonts', None, 5300),
+(u'RegisterProduct', None, 6100),
+(u'RegisterTypeLibraries', None, 5500),
+(u'RegisterUser', None, 6000),
+(u'RemoveDuplicateFiles', None, 3400),
+(u'RemoveEnvironmentStrings', None, 3300),
+(u'RemoveExistingProducts', None, 6700),
+(u'RemoveFiles', None, 3500),
+(u'RemoveFolders', None, 3600),
+(u'RemoveIniValues', None, 3100),
+(u'RemoveODBC', None, 2400),
+(u'RemoveRegistryValues', None, 2600),
+(u'RemoveShortcuts', None, 3200),
+(u'RMCCPSearch', u'NOT Installed', 600),
+(u'SelfRegModules', None, 5600),
+(u'SelfUnregModules', None, 2200),
+(u'SetODBCFolders', None, 1100),
+(u'StartServices', u'VersionNT', 5900),
+(u'StopServices', u'VersionNT', 1900),
+(u'UnpublishComponents', None, 1700),
+(u'UnpublishFeatures', None, 1800),
+(u'UnregisterClassInfo', None, 2700),
+(u'UnregisterComPlus', None, 2100),
+(u'UnregisterExtensionInfo', None, 2800),
+(u'UnregisterFonts', None, 2500),
+(u'UnregisterMIMEInfo', None, 3000),
+(u'UnregisterProgIdInfo', None, 2900),
+(u'UnregisterTypeLibraries', None, 2300),
+(u'WriteEnvironmentStrings', None, 5200),
+(u'WriteIniValues', None, 5100),
+(u'WriteRegistryValues', None, 5000),
+]
+
+InstallUISequence = [
+#(u'FileCost', None, 900),
+#(u'CostInitialize', None, 800),
+#(u'CostFinalize', None, 1000),
+#(u'ExecuteAction', None, 1300),
+#(u'ExitDialog', None, -1),
+#(u'FatalError', None, -3),
+(u'PrepareDlg', None, 140),
+(u'ProgressDlg', None, 1280),
+#(u'UserExit', None, -2),
+(u'MaintenanceWelcomeDlg', u'Installed AND NOT RESUME AND NOT Preselected', 1250),
+(u'ResumeDlg', u'Installed AND (RESUME OR Preselected)', 1240),
+(u'WelcomeDlg', u'NOT Installed', 1230),
+#(u'AppSearch', None, 400),
+#(u'CCPSearch', u'NOT Installed', 500),
+#(u'FindRelatedProducts', None, 200),
+#(u'LaunchConditions', None, 100),
+#(u'MigrateFeatureStates', None, 1200),
+#(u'RMCCPSearch', u'NOT Installed', 600),
+]
+
+ListView = [
+]
+
+RadioButton = [
+(u'IAgree', 1, u'Yes', 5, 0, 250, 15, u'{\\DlgFont8}I &accept the terms in the License Agreement', None),
+(u'IAgree', 2, u'No', 5, 20, 250, 15, u'{\\DlgFont8}I &do not accept the terms in the License Agreement', None),
+]
+
+TextStyle = [
+(u'DlgFont8', u'Tahoma', 8, None, 0),
+(u'DlgFontBold8', u'Tahoma', 8, None, 1),
+(u'VerdanaBold13', u'Verdana', 13, None, 1),
+]
+
+UIText = [
+(u'AbsentPath', None),
+(u'bytes', u'bytes'),
+(u'GB', u'GB'),
+(u'KB', u'KB'),
+(u'MB', u'MB'),
+(u'MenuAbsent', u'Entire feature will be unavailable'),
+(u'MenuAdvertise', u'Feature will be installed when required'),
+(u'MenuAllCD', u'Entire feature will be installed to run from CD'),
+(u'MenuAllLocal', u'Entire feature will be installed on local hard drive'),
+(u'MenuAllNetwork', u'Entire feature will be installed to run from network'),
+(u'MenuCD', u'Will be installed to run from CD'),
+(u'MenuLocal', u'Will be installed on local hard drive'),
+(u'MenuNetwork', u'Will be installed to run from network'),
+(u'ScriptInProgress', u'Gathering required information...'),
+(u'SelAbsentAbsent', u'This feature will remain uninstalled'),
+(u'SelAbsentAdvertise', u'This feature will be set to be installed when required'),
+(u'SelAbsentCD', u'This feature will be installed to run from CD'),
+(u'SelAbsentLocal', u'This feature will be installed on the local hard drive'),
+(u'SelAbsentNetwork', u'This feature will be installed to run from the network'),
+(u'SelAdvertiseAbsent', u'This feature will become unavailable'),
+(u'SelAdvertiseAdvertise', u'Will be installed when required'),
+(u'SelAdvertiseCD', u'This feature will be available to run from CD'),
+(u'SelAdvertiseLocal', u'This feature will be installed on your local hard drive'),
+(u'SelAdvertiseNetwork', u'This feature will be available to run from the network'),
+(u'SelCDAbsent', u"This feature will be uninstalled completely, you won't be able to run it from CD"),
+(u'SelCDAdvertise', u'This feature will change from run from CD state to set to be installed when required'),
+(u'SelCDCD', u'This feature will remain to be run from CD'),
+(u'SelCDLocal', u'This feature will change from run from CD state to be installed on the local hard drive'),
+(u'SelChildCostNeg', u'This feature frees up [1] on your hard drive.'),
+(u'SelChildCostPos', u'This feature requires [1] on your hard drive.'),
+(u'SelCostPending', u'Compiling cost for this feature...'),
+(u'SelLocalAbsent', u'This feature will be completely removed'),
+(u'SelLocalAdvertise', u'This feature will be removed from your local hard drive, but will be set to be installed when required'),
+(u'SelLocalCD', u'This feature will be removed from your local hard drive, but will be still available to run from CD'),
+(u'SelLocalLocal', u'This feature will remain on you local hard drive'),
+(u'SelLocalNetwork', u'This feature will be removed from your local hard drive, but will be still available to run from the network'),
+(u'SelNetworkAbsent', u"This feature will be uninstalled completely, you won't be able to run it from the network"),
+(u'SelNetworkAdvertise', u'This feature will change from run from network state to set to be installed when required'),
+(u'SelNetworkLocal', u'This feature will change from run from network state to be installed on the local hard drive'),
+(u'SelNetworkNetwork', u'This feature will remain to be run from the network'),
+(u'SelParentCostNegNeg', u'This feature frees up [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures free up [4] on your hard drive.'),
+(u'SelParentCostNegPos', u'This feature frees up [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures require [4] on your hard drive.'),
+(u'SelParentCostPosNeg', u'This feature requires [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures free up [4] on your hard drive.'),
+(u'SelParentCostPosPos', u'This feature requires [1] on your hard drive. It has [2] of [3] subfeatures selected. The subfeatures require [4] on your hard drive.'),
+(u'TimeRemaining', u'Time remaining: {[1] minutes }{[2] seconds}'),
+(u'VolumeCostAvailable', u'Available'),
+(u'VolumeCostDifference', u'Difference'),
+(u'VolumeCostRequired', u'Required'),
+(u'VolumeCostSize', u'Disk Size'),
+(u'VolumeCostVolume', u'Volume'),
+]
+
+_Validation = [
+(u'AdminExecuteSequence', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Name of action to invoke, either in the engine or the handler DLL.'),
+(u'AdminExecuteSequence', u'Sequence', u'Y', -4, 32767, None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.'),
+(u'AdminExecuteSequence', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.'),
+(u'AdminUISequence', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Name of action to invoke, either in the engine or the handler DLL.'),
+(u'AdminUISequence', u'Sequence', u'Y', -4, 32767, None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.'),
+(u'AdminUISequence', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.'),
+(u'Condition', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'Expression evaluated to determine if Level in the Feature table is to change.'),
+(u'Condition', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'Reference to a Feature entry in Feature table.'),
+(u'Condition', u'Level', u'N', 0, 32767, None, None, None, None, u'New selection Level to set in Feature table if Condition evaluates to TRUE.'),
+(u'AdvtExecuteSequence', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Name of action to invoke, either in the engine or the handler DLL.'),
+(u'AdvtExecuteSequence', u'Sequence', u'Y', -4, 32767, None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.'),
+(u'AdvtExecuteSequence', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.'),
+(u'BBControl', u'Type', u'N', None, None, None, None, u'Identifier', None, u'The type of the control.'),
+(u'BBControl', u'BBControl', u'N', None, None, None, None, u'Identifier', None, u'Name of the control. This name must be unique within a billboard, but can repeat on different billboard.'),
+(u'BBControl', u'Billboard_', u'N', None, None, u'Billboard', 1, u'Identifier', None, u'External key to the Billboard table, name of the billboard.'),
+(u'BBControl', u'X', u'N', 0, 32767, None, None, None, None, u'Horizontal coordinate of the upper left corner of the bounding rectangle of the control.'),
+(u'BBControl', u'Y', u'N', 0, 32767, None, None, None, None, u'Vertical coordinate of the upper left corner of the bounding rectangle of the control.'),
+(u'BBControl', u'Width', u'N', 0, 32767, None, None, None, None, u'Width of the bounding rectangle of the control.'),
+(u'BBControl', u'Height', u'N', 0, 32767, None, None, None, None, u'Height of the bounding rectangle of the control.'),
+(u'BBControl', u'Attributes', u'Y', 0, 2147483647, None, None, None, None, u'A 32-bit word that specifies the attribute flags to be applied to this control.'),
+(u'BBControl', u'Text', u'Y', None, None, None, None, u'Text', None, u'A string used to set the initial text contained within a control (if appropriate).'),
+(u'Billboard', u'Action', u'Y', None, None, None, None, u'Identifier', None, u'The name of an action. The billboard is displayed during the progress messages received from this action.'),
+(u'Billboard', u'Billboard', u'N', None, None, None, None, u'Identifier', None, u'Name of the billboard.'),
+(u'Billboard', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'An external key to the Feature Table. The billboard is shown only if this feature is being installed.'),
+(u'Billboard', u'Ordering', u'Y', 0, 32767, None, None, None, None, u'A positive integer. If there is more than one billboard corresponding to an action they will be shown in the order defined by this column.'),
+(u'Binary', u'Name', u'N', None, None, None, None, u'Identifier', None, u'Unique key identifying the binary data.'),
+(u'Binary', u'Data', u'N', None, None, None, None, u'Binary', None, u'The unformatted binary data.'),
+(u'CheckBox', u'Property', u'N', None, None, None, None, u'Identifier', None, u'A named property to be tied to the item.'),
+(u'CheckBox', u'Value', u'Y', None, None, None, None, u'Formatted', None, u'The value string associated with the item.'),
+(u'Property', u'Property', u'N', None, None, None, None, u'Identifier', None, u'Name of property, uppercase if settable by launcher or loader.'),
+(u'Property', u'Value', u'N', None, None, None, None, u'Text', None, u'String value for property. Never null or empty.'),
+(u'ComboBox', u'Text', u'Y', None, None, None, None, u'Formatted', None, u'The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.'),
+(u'ComboBox', u'Property', u'N', None, None, None, None, u'Identifier', None, u'A named property to be tied to this item. All the items tied to the same property become part of the same combobox.'),
+(u'ComboBox', u'Value', u'N', None, None, None, None, u'Formatted', None, u'The value string associated with this item. Selecting the line will set the associated property to this value.'),
+(u'ComboBox', u'Order', u'N', 1, 32767, None, None, None, None, u'A positive integer used to determine the ordering of the items within one list.\tThe integers do not have to be consecutive.'),
+(u'Control', u'Type', u'N', None, None, None, None, u'Identifier', None, u'The type of the control.'),
+(u'Control', u'X', u'N', 0, 32767, None, None, None, None, u'Horizontal coordinate of the upper left corner of the bounding rectangle of the control.'),
+(u'Control', u'Y', u'N', 0, 32767, None, None, None, None, u'Vertical coordinate of the upper left corner of the bounding rectangle of the control.'),
+(u'Control', u'Width', u'N', 0, 32767, None, None, None, None, u'Width of the bounding rectangle of the control.'),
+(u'Control', u'Height', u'N', 0, 32767, None, None, None, None, u'Height of the bounding rectangle of the control.'),
+(u'Control', u'Attributes', u'Y', 0, 2147483647, None, None, None, None, u'A 32-bit word that specifies the attribute flags to be applied to this control.'),
+(u'Control', u'Text', u'Y', None, None, None, None, u'Formatted', None, u'A string used to set the initial text contained within a control (if appropriate).'),
+(u'Control', u'Property', u'Y', None, None, None, None, u'Identifier', None, u'The name of a defined property to be linked to this control. '),
+(u'Control', u'Control', u'N', None, None, None, None, u'Identifier', None, u'Name of the control. This name must be unique within a dialog, but can repeat on different dialogs. '),
+(u'Control', u'Dialog_', u'N', None, None, u'Dialog', 1, u'Identifier', None, u'External key to the Dialog table, name of the dialog.'),
+(u'Control', u'Control_Next', u'Y', None, None, u'Control', 2, u'Identifier', None, u'The name of an other control on the same dialog. This link defines the tab order of the controls. The links have to form one or more cycles!'),
+(u'Control', u'Help', u'Y', None, None, None, None, u'Text', None, u'The help strings used with the button. The text is optional. '),
+(u'Icon', u'Name', u'N', None, None, None, None, u'Identifier', None, u'Primary key. Name of the icon file.'),
+(u'Icon', u'Data', u'N', None, None, None, None, u'Binary', None, u'Binary stream. The binary icon data in PE (.DLL or .EXE) or icon (.ICO) format.'),
+(u'ListBox', u'Text', u'Y', None, None, None, None, u'Text', None, u'The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.'),
+(u'ListBox', u'Property', u'N', None, None, None, None, u'Identifier', None, u'A named property to be tied to this item. All the items tied to the same property become part of the same listbox.'),
+(u'ListBox', u'Value', u'N', None, None, None, None, u'Formatted', None, u'The value string associated with this item. Selecting the line will set the associated property to this value.'),
+(u'ListBox', u'Order', u'N', 1, 32767, None, None, None, None, u'A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.'),
+(u'ActionText', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Name of action to be described.'),
+(u'ActionText', u'Description', u'Y', None, None, None, None, u'Text', None, u'Localized description displayed in progress dialog and log when action is executing.'),
+(u'ActionText', u'Template', u'Y', None, None, None, None, u'Template', None, u'Optional localized format template used to format action data records for display during action execution.'),
+(u'ControlCondition', u'Action', u'N', None, None, None, None, None, u'Default;Disable;Enable;Hide;Show', u'The desired action to be taken on the specified control.'),
+(u'ControlCondition', u'Condition', u'N', None, None, None, None, u'Condition', None, u'A standard conditional statement that specifies under which conditions the action should be triggered.'),
+(u'ControlCondition', u'Dialog_', u'N', None, None, u'Dialog', 1, u'Identifier', None, u'A foreign key to the Dialog table, name of the dialog.'),
+(u'ControlCondition', u'Control_', u'N', None, None, u'Control', 2, u'Identifier', None, u'A foreign key to the Control table, name of the control.'),
+(u'ControlEvent', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'A standard conditional statement that specifies under which conditions an event should be triggered.'),
+(u'ControlEvent', u'Ordering', u'Y', 0, 2147483647, None, None, None, None, u'An integer used to order several events tied to the same control. Can be left blank.'),
+(u'ControlEvent', u'Dialog_', u'N', None, None, u'Dialog', 1, u'Identifier', None, u'A foreign key to the Dialog table, name of the dialog.'),
+(u'ControlEvent', u'Control_', u'N', None, None, u'Control', 2, u'Identifier', None, u'A foreign key to the Control table, name of the control'),
+(u'ControlEvent', u'Event', u'N', None, None, None, None, u'Formatted', None, u'An identifier that specifies the type of the event that should take place when the user interacts with control specified by the first two entries.'),
+(u'ControlEvent', u'Argument', u'N', None, None, None, None, u'Formatted', None, u'A value to be used as a modifier when triggering a particular event.'),
+(u'Dialog', u'Width', u'N', 0, 32767, None, None, None, None, u'Width of the bounding rectangle of the dialog.'),
+(u'Dialog', u'Height', u'N', 0, 32767, None, None, None, None, u'Height of the bounding rectangle of the dialog.'),
+(u'Dialog', u'Attributes', u'Y', 0, 2147483647, None, None, None, None, u'A 32-bit word that specifies the attribute flags to be applied to this dialog.'),
+(u'Dialog', u'Title', u'Y', None, None, None, None, u'Formatted', None, u"A text string specifying the title to be displayed in the title bar of the dialog's window."),
+(u'Dialog', u'Dialog', u'N', None, None, None, None, u'Identifier', None, u'Name of the dialog.'),
+(u'Dialog', u'HCentering', u'N', 0, 100, None, None, None, None, u'Horizontal position of the dialog on a 0-100 scale. 0 means left end, 100 means right end of the screen, 50 center.'),
+(u'Dialog', u'VCentering', u'N', 0, 100, None, None, None, None, u'Vertical position of the dialog on a 0-100 scale. 0 means top end, 100 means bottom end of the screen, 50 center.'),
+(u'Dialog', u'Control_First', u'N', None, None, u'Control', 2, u'Identifier', None, u'Defines the control that has the focus when the dialog is created.'),
+(u'Dialog', u'Control_Default', u'Y', None, None, u'Control', 2, u'Identifier', None, u'Defines the default control. Hitting return is equivalent to pushing this button.'),
+(u'Dialog', u'Control_Cancel', u'Y', None, None, u'Control', 2, u'Identifier', None, u'Defines the cancel control. Hitting escape or clicking on the close icon on the dialog is equivalent to pushing this button.'),
+(u'EventMapping', u'Dialog_', u'N', None, None, u'Dialog', 1, u'Identifier', None, u'A foreign key to the Dialog table, name of the Dialog.'),
+(u'EventMapping', u'Control_', u'N', None, None, u'Control', 2, u'Identifier', None, u'A foreign key to the Control table, name of the control.'),
+(u'EventMapping', u'Event', u'N', None, None, None, None, u'Identifier', None, u'An identifier that specifies the type of the event that the control subscribes to.'),
+(u'EventMapping', u'Attribute', u'N', None, None, None, None, u'Identifier', None, u'The name of the control attribute, that is set when this event is received.'),
+(u'InstallExecuteSequence', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Name of action to invoke, either in the engine or the handler DLL.'),
+(u'InstallExecuteSequence', u'Sequence', u'Y', -4, 32767, None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.'),
+(u'InstallExecuteSequence', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.'),
+(u'AppSearch', u'Property', u'N', None, None, None, None, u'Identifier', None, u'The property associated with a Signature'),
+(u'AppSearch', u'Signature_', u'N', None, None, u'Signature;RegLocator;IniLocator;DrLocator;CompLocator', 1, u'Identifier', None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature, RegLocator, IniLocator, CompLocator and the DrLocator tables.'),
+(u'BindImage', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'The index into the File table. This must be an executable file.'),
+(u'BindImage', u'Path', u'Y', None, None, None, None, u'Paths', None, u'A list of ; delimited paths that represent the paths to be searched for the import DLLS. The list is usually a list of properties each enclosed within square brackets [] .'),
+(u'CCPSearch', u'Signature_', u'N', None, None, u'Signature;RegLocator;IniLocator;DrLocator;CompLocator', 1, u'Identifier', None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature, RegLocator, IniLocator, CompLocator and the DrLocator tables.'),
+(u'InstallUISequence', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Name of action to invoke, either in the engine or the handler DLL.'),
+(u'InstallUISequence', u'Sequence', u'Y', -4, 32767, None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.'),
+(u'InstallUISequence', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.'),
+(u'ListView', u'Text', u'Y', None, None, None, None, u'Text', None, u'The visible text to be assigned to the item. Optional. If this entry or the entire column is missing, the text is the same as the value.'),
+(u'ListView', u'Property', u'N', None, None, None, None, u'Identifier', None, u'A named property to be tied to this item. All the items tied to the same property become part of the same listview.'),
+(u'ListView', u'Value', u'N', None, None, None, None, u'Identifier', None, u'The value string associated with this item. Selecting the line will set the associated property to this value.'),
+(u'ListView', u'Order', u'N', 1, 32767, None, None, None, None, u'A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.'),
+(u'ListView', u'Binary_', u'Y', None, None, u'Binary', 1, u'Identifier', None, u'The name of the icon to be displayed with the icon. The binary information is looked up from the Binary Table.'),
+(u'RadioButton', u'X', u'N', 0, 32767, None, None, None, None, u'The horizontal coordinate of the upper left corner of the bounding rectangle of the radio button.'),
+(u'RadioButton', u'Y', u'N', 0, 32767, None, None, None, None, u'The vertical coordinate of the upper left corner of the bounding rectangle of the radio button.'),
+(u'RadioButton', u'Width', u'N', 0, 32767, None, None, None, None, u'The width of the button.'),
+(u'RadioButton', u'Height', u'N', 0, 32767, None, None, None, None, u'The height of the button.'),
+(u'RadioButton', u'Text', u'Y', None, None, None, None, u'Text', None, u'The visible title to be assigned to the radio button.'),
+(u'RadioButton', u'Property', u'N', None, None, None, None, u'Identifier', None, u'A named property to be tied to this radio button. All the buttons tied to the same property become part of the same group.'),
+(u'RadioButton', u'Value', u'N', None, None, None, None, u'Formatted', None, u'The value string associated with this button. Selecting the button will set the associated property to this value.'),
+(u'RadioButton', u'Order', u'N', 1, 32767, None, None, None, None, u'A positive integer used to determine the ordering of the items within one list..The integers do not have to be consecutive.'),
+(u'RadioButton', u'Help', u'Y', None, None, None, None, u'Text', None, u'The help strings used with the button. The text is optional.'),
+(u'TextStyle', u'TextStyle', u'N', None, None, None, None, u'Identifier', None, u'Name of the style. The primary key of this table. This name is embedded in the texts to indicate a style change.'),
+(u'TextStyle', u'FaceName', u'N', None, None, None, None, u'Text', None, u'A string indicating the name of the font used. Required. The string must be at most 31 characters long.'),
+(u'TextStyle', u'Size', u'N', 0, 32767, None, None, None, None, u'The size of the font used. This size is given in our units (1/12 of the system font height). Assuming that the system font is set to 12 point size, this is equivalent to the point size.'),
+(u'TextStyle', u'Color', u'Y', 0, 16777215, None, None, None, None, u'A long integer indicating the color of the string in the RGB format (Red, Green, Blue each 0-255, RGB = R + 256*G + 256^2*B).'),
+(u'TextStyle', u'StyleBits', u'Y', 0, 15, None, None, None, None, u'A combination of style bits.'),
+(u'UIText', u'Text', u'Y', None, None, None, None, u'Text', None, u'The localized version of the string.'),
+(u'UIText', u'Key', u'N', None, None, None, None, u'Identifier', None, u'A unique key that identifies the particular string.'),
+(u'_Validation', u'Table', u'N', None, None, None, None, u'Identifier', None, u'Name of table'),
+(u'_Validation', u'Description', u'Y', None, None, None, None, u'Text', None, u'Description of column'),
+(u'_Validation', u'Column', u'N', None, None, None, None, u'Identifier', None, u'Name of column'),
+(u'_Validation', u'Nullable', u'N', None, None, None, None, None, u'Y;N;@', u'Whether the column is nullable'),
+(u'_Validation', u'MinValue', u'Y', -2147483647, 2147483647, None, None, None, None, u'Minimum value allowed'),
+(u'_Validation', u'MaxValue', u'Y', -2147483647, 2147483647, None, None, None, None, u'Maximum value allowed'),
+(u'_Validation', u'KeyTable', u'Y', None, None, None, None, u'Identifier', None, u'For foreign key, Name of table to which data must link'),
+(u'_Validation', u'KeyColumn', u'Y', 1, 32, None, None, None, None, u'Column to which foreign key connects'),
+(u'_Validation', u'Category', u'Y', None, None, None, None, None, u'Text;Formatted;Template;Condition;Guid;Path;Version;Language;Identifier;Binary;UpperCase;LowerCase;Filename;Paths;AnyPath;WildCardFilename;RegPath;KeyFormatted;CustomSource;Property;Cabinet;Shortcut;URL', u'String category'),
+(u'_Validation', u'Set', u'Y', None, None, None, None, u'Text', None, u'Set of values that are permitted'),
+(u'AdvtUISequence', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Name of action to invoke, either in the engine or the handler DLL.'),
+(u'AdvtUISequence', u'Sequence', u'Y', -4, 32767, None, None, None, None, u'Number that determines the sort order in which the actions are to be executed. Leave blank to suppress action.'),
+(u'AdvtUISequence', u'Condition', u'Y', None, None, None, None, u'Condition', None, u'Optional expression which skips the action if evaluates to expFalse.If the expression syntax is invalid, the engine will terminate, returning iesBadActionData.'),
+(u'AppId', u'AppId', u'N', None, None, None, None, u'Guid', None, None),
+(u'AppId', u'ActivateAtStorage', u'Y', 0, 1, None, None, None, None, None),
+(u'AppId', u'DllSurrogate', u'Y', None, None, None, None, u'Text', None, None),
+(u'AppId', u'LocalService', u'Y', None, None, None, None, u'Text', None, None),
+(u'AppId', u'RemoteServerName', u'Y', None, None, None, None, u'Formatted', None, None),
+(u'AppId', u'RunAsInteractiveUser', u'Y', 0, 1, None, None, None, None, None),
+(u'AppId', u'ServiceParameters', u'Y', None, None, None, None, u'Text', None, None),
+(u'Feature', u'Attributes', u'N', None, None, None, None, None, u'0;1;2;4;5;6;8;9;10;16;17;18;20;21;22;24;25;26;32;33;34;36;37;38;48;49;50;52;53;54', u'Feature attributes'),
+(u'Feature', u'Description', u'Y', None, None, None, None, u'Text', None, u'Longer descriptive text describing a visible feature item.'),
+(u'Feature', u'Title', u'Y', None, None, None, None, u'Text', None, u'Short text identifying a visible feature item.'),
+(u'Feature', u'Feature', u'N', None, None, None, None, u'Identifier', None, u'Primary key used to identify a particular feature record.'),
+(u'Feature', u'Directory_', u'Y', None, None, u'Directory', 1, u'UpperCase', None, u'The name of the Directory that can be configured by the UI. A non-null value will enable the browse button.'),
+(u'Feature', u'Level', u'N', 0, 32767, None, None, None, None, u'The install level at which record will be initially selected. An install level of 0 will disable an item and prevent its display.'),
+(u'Feature', u'Display', u'Y', 0, 32767, None, None, None, None, u'Numeric sort order, used to force a specific display ordering.'),
+(u'Feature', u'Feature_Parent', u'Y', None, None, u'Feature', 1, u'Identifier', None, u'Optional key of a parent record in the same table. If the parent is not selected, then the record will not be installed. Null indicates a root item.'),
+(u'File', u'Sequence', u'N', 1, 32767, None, None, None, None, u'Sequence with respect to the media images; order must track cabinet order.'),
+(u'File', u'Attributes', u'Y', 0, 32767, None, None, None, None, u'Integer containing bit flags representing file attributes (with the decimal value of each bit position in parentheses)'),
+(u'File', u'File', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token, must match identifier in cabinet. For uncompressed files, this field is ignored.'),
+(u'File', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key referencing Component that controls the file.'),
+(u'File', u'FileName', u'N', None, None, None, None, u'Filename', None, u'File name used for installation, may be localized. This may contain a "short name|long name" pair.'),
+(u'File', u'FileSize', u'N', 0, 2147483647, None, None, None, None, u'Size of file in bytes (long integer).'),
+(u'File', u'Language', u'Y', None, None, None, None, u'Language', None, u'List of decimal language Ids, comma-separated if more than one.'),
+(u'File', u'Version', u'Y', None, None, u'File', 1, u'Version', None, u'Version string for versioned files; Blank for unversioned files.'),
+(u'Class', u'Attributes', u'Y', None, 32767, None, None, None, None, u'Class registration attributes.'),
+(u'Class', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'Required foreign key into the Feature Table, specifying the feature to validate or install in order for the CLSID factory to be operational.'),
+(u'Class', u'Description', u'Y', None, None, None, None, u'Text', None, u'Localized description for the Class.'),
+(u'Class', u'Argument', u'Y', None, None, None, None, u'Formatted', None, u'optional argument for LocalServers.'),
+(u'Class', u'AppId_', u'Y', None, None, u'AppId', 1, u'Guid', None, u'Optional AppID containing DCOM information for associated application (string GUID).'),
+(u'Class', u'CLSID', u'N', None, None, None, None, u'Guid', None, u'The CLSID of an OLE factory.'),
+(u'Class', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.'),
+(u'Class', u'Context', u'N', None, None, None, None, u'Identifier', None, u'The numeric server context for this server. CLSCTX_xxxx'),
+(u'Class', u'DefInprocHandler', u'Y', None, None, None, None, u'Filename', u'1;2;3', u'Optional default inproc handler. Only optionally provided if Context=CLSCTX_LOCAL_SERVER. Typically "ole32.dll" or "mapi32.dll"'),
+(u'Class', u'FileTypeMask', u'Y', None, None, None, None, u'Text', None, u'Optional string containing information for the HKCRthis CLSID) key. If multiple patterns exist, they must be delimited by a semicolon, and numeric subkeys will be generated: 0,1,2...'),
+(u'Class', u'Icon_', u'Y', None, None, u'Icon', 1, u'Identifier', None, u'Optional foreign key into the Icon Table, specifying the icon file associated with this CLSID. Will be written under the DefaultIcon key.'),
+(u'Class', u'IconIndex', u'Y', -32767, 32767, None, None, None, None, u'Optional icon index.'),
+(u'Class', u'ProgId_Default', u'Y', None, None, u'ProgId', 1, u'Text', None, u'Optional ProgId associated with this CLSID.'),
+(u'Component', u'Condition', u'Y', None, None, None, None, u'Condition', None, u"A conditional statement that will disable this component if the specified condition evaluates to the 'True' state. If a component is disabled, it will not be installed, regardless of the 'Action' state associated with the component."),
+(u'Component', u'Attributes', u'N', None, None, None, None, None, None, u'Remote execution option, one of irsEnum'),
+(u'Component', u'Component', u'N', None, None, None, None, u'Identifier', None, u'Primary key used to identify a particular component record.'),
+(u'Component', u'ComponentId', u'Y', None, None, None, None, u'Guid', None, u'A string GUID unique to this component, version, and language.'),
+(u'Component', u'Directory_', u'N', None, None, u'Directory', 1, u'Identifier', None, u'Required key of a Directory table record. This is actually a property name whose value contains the actual path, set either by the AppSearch action or with the default setting obtained from the Directory table.'),
+(u'Component', u'KeyPath', u'Y', None, None, u'File;Registry;ODBCDataSource', 1, u'Identifier', None, u'Either the primary key into the File table, Registry table, or ODBCDataSource table. This extract path is stored when the component is installed, and is used to detect the presence of the component and to return the path to it.'),
+(u'ProgId', u'Description', u'Y', None, None, None, None, u'Text', None, u'Localized description for the Program identifier.'),
+(u'ProgId', u'Icon_', u'Y', None, None, u'Icon', 1, u'Identifier', None, u'Optional foreign key into the Icon Table, specifying the icon file associated with this ProgId. Will be written under the DefaultIcon key.'),
+(u'ProgId', u'IconIndex', u'Y', -32767, 32767, None, None, None, None, u'Optional icon index.'),
+(u'ProgId', u'ProgId', u'N', None, None, None, None, u'Text', None, u'The Program Identifier. Primary key.'),
+(u'ProgId', u'Class_', u'Y', None, None, u'Class', 1, u'Guid', None, u'The CLSID of an OLE factory corresponding to the ProgId.'),
+(u'ProgId', u'ProgId_Parent', u'Y', None, None, u'ProgId', 1, u'Text', None, u'The Parent Program Identifier. If specified, the ProgId column becomes a version independent prog id.'),
+(u'CompLocator', u'Type', u'Y', 0, 1, None, None, None, None, u'A boolean value that determines if the registry value is a filename or a directory location.'),
+(u'CompLocator', u'Signature_', u'N', None, None, None, None, u'Identifier', None, u'The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table.'),
+(u'CompLocator', u'ComponentId', u'N', None, None, None, None, u'Guid', None, u'A string GUID unique to this component, version, and language.'),
+(u'Complus', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key referencing Component that controls the ComPlus component.'),
+(u'Complus', u'ExpType', u'Y', 0, 32767, None, None, None, None, u'ComPlus component attributes.'),
+(u'Directory', u'Directory', u'N', None, None, None, None, u'Identifier', None, u'Unique identifier for directory entry, primary key. If a property by this name is defined, it contains the full path to the directory.'),
+(u'Directory', u'DefaultDir', u'N', None, None, None, None, u'DefaultDir', None, u"The default sub-path under parent's path."),
+(u'Directory', u'Directory_Parent', u'Y', None, None, u'Directory', 1, u'Identifier', None, u'Reference to the entry in this table specifying the default parent directory. A record parented to itself or with a Null parent represents a root of the install tree.'),
+(u'CreateFolder', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table.'),
+(u'CreateFolder', u'Directory_', u'N', None, None, u'Directory', 1, u'Identifier', None, u'Primary key, could be foreign key into the Directory table.'),
+(u'CustomAction', u'Type', u'N', 1, 16383, None, None, None, None, u'The numeric custom action type, consisting of source location, code type, entry, option flags.'),
+(u'CustomAction', u'Action', u'N', None, None, None, None, u'Identifier', None, u'Primary key, name of action, normally appears in sequence table unless private use.'),
+(u'CustomAction', u'Source', u'Y', None, None, None, None, u'CustomSource', None, u'The table reference of the source of the code.'),
+(u'CustomAction', u'Target', u'Y', None, None, None, None, u'Formatted', None, u'Excecution parameter, depends on the type of custom action'),
+(u'DrLocator', u'Signature_', u'N', None, None, None, None, u'Identifier', None, u'The Signature_ represents a unique file signature and is also the foreign key in the Signature table.'),
+(u'DrLocator', u'Path', u'Y', None, None, None, None, u'AnyPath', None, u'The path on the user system. This is a either a subpath below the value of the Parent or a full path. The path may contain properties enclosed within [ ] that will be expanded.'),
+(u'DrLocator', u'Depth', u'Y', 0, 32767, None, None, None, None, u'The depth below the path to which the Signature_ is recursively searched. If absent, the depth is assumed to be 0.'),
+(u'DrLocator', u'Parent', u'Y', None, None, None, None, u'Identifier', None, u'The parent file signature. It is also a foreign key in the Signature table. If null and the Path column does not expand to a full path, then all the fixed drives of the user system are searched using the Path.'),
+(u'DuplicateFile', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'Foreign key referencing the source file to be duplicated.'),
+(u'DuplicateFile', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key referencing Component that controls the duplicate file.'),
+(u'DuplicateFile', u'DestFolder', u'Y', None, None, None, None, u'Identifier', None, u'Name of a property whose value is assumed to resolve to the full pathname to a destination folder.'),
+(u'DuplicateFile', u'DestName', u'Y', None, None, None, None, u'Filename', None, u'Filename to be given to the duplicate file.'),
+(u'DuplicateFile', u'FileKey', u'N', None, None, None, None, u'Identifier', None, u'Primary key used to identify a particular file entry'),
+(u'Environment', u'Name', u'N', None, None, None, None, u'Text', None, u'The name of the environmental value.'),
+(u'Environment', u'Value', u'Y', None, None, None, None, u'Formatted', None, u'The value to set in the environmental settings.'),
+(u'Environment', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table referencing component that controls the installing of the environmental value.'),
+(u'Environment', u'Environment', u'N', None, None, None, None, u'Identifier', None, u'Unique identifier for the environmental variable setting'),
+(u'Error', u'Error', u'N', 0, 32767, None, None, None, None, u'Integer error number, obtained from header file IError(...) macros.'),
+(u'Error', u'Message', u'Y', None, None, None, None, u'Template', None, u'Error formatting template, obtained from user ed. or localizers.'),
+(u'Extension', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'Required foreign key into the Feature Table, specifying the feature to validate or install in order for the CLSID factory to be operational.'),
+(u'Extension', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.'),
+(u'Extension', u'Extension', u'N', None, None, None, None, u'Text', None, u'The extension associated with the table row.'),
+(u'Extension', u'MIME_', u'Y', None, None, u'MIME', 1, u'Text', None, u'Optional Context identifier, typically "type/format" associated with the extension'),
+(u'Extension', u'ProgId_', u'Y', None, None, u'ProgId', 1, u'Text', None, u'Optional ProgId associated with this extension.'),
+(u'MIME', u'CLSID', u'Y', None, None, None, None, u'Guid', None, u'Optional associated CLSID.'),
+(u'MIME', u'ContentType', u'N', None, None, None, None, u'Text', None, u'Primary key. Context identifier, typically "type/format".'),
+(u'MIME', u'Extension_', u'N', None, None, u'Extension', 1, u'Text', None, u'Optional associated extension (without dot)'),
+(u'FeatureComponents', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'Foreign key into Feature table.'),
+(u'FeatureComponents', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into Component table.'),
+(u'FileSFPCatalog', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'File associated with the catalog'),
+(u'FileSFPCatalog', u'SFPCatalog_', u'N', None, None, u'SFPCatalog', 1, u'Filename', None, u'Catalog associated with the file'),
+(u'SFPCatalog', u'SFPCatalog', u'N', None, None, None, None, u'Filename', None, u'File name for the catalog.'),
+(u'SFPCatalog', u'Catalog', u'N', None, None, None, None, u'Binary', None, u'SFP Catalog'),
+(u'SFPCatalog', u'Dependency', u'Y', None, None, None, None, u'Formatted', None, u'Parent catalog - only used by SFP'),
+(u'Font', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'Primary key, foreign key into File table referencing font file.'),
+(u'Font', u'FontTitle', u'Y', None, None, None, None, u'Text', None, u'Font name.'),
+(u'IniFile', u'Action', u'N', None, None, None, None, None, u'0;1;3', u'The type of modification to be made, one of iifEnum'),
+(u'IniFile', u'Value', u'N', None, None, None, None, u'Formatted', None, u'The value to be written.'),
+(u'IniFile', u'Key', u'N', None, None, None, None, u'Formatted', None, u'The .INI file key below Section.'),
+(u'IniFile', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table referencing component that controls the installing of the .INI value.'),
+(u'IniFile', u'FileName', u'N', None, None, None, None, u'Filename', None, u'The .INI file name in which to write the information'),
+(u'IniFile', u'IniFile', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token.'),
+(u'IniFile', u'DirProperty', u'Y', None, None, None, None, u'Identifier', None, u'Foreign key into the Directory table denoting the directory where the .INI file is.'),
+(u'IniFile', u'Section', u'N', None, None, None, None, u'Formatted', None, u'The .INI file Section.'),
+(u'IniLocator', u'Type', u'Y', 0, 2, None, None, None, None, u'An integer value that determines if the .INI value read is a filename or a directory location or to be used as is w/o interpretation.'),
+(u'IniLocator', u'Key', u'N', None, None, None, None, u'Text', None, u'Key value (followed by an equals sign in INI file).'),
+(u'IniLocator', u'Signature_', u'N', None, None, None, None, u'Identifier', None, u'The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table.'),
+(u'IniLocator', u'FileName', u'N', None, None, None, None, u'Filename', None, u'The .INI file name.'),
+(u'IniLocator', u'Section', u'N', None, None, None, None, u'Text', None, u'Section name within in file (within square brackets in INI file).'),
+(u'IniLocator', u'Field', u'Y', 0, 32767, None, None, None, None, u'The field in the .INI line. If Field is null or 0 the entire line is read.'),
+(u'IsolatedComponent', u'Component_Application', u'N', None, None, u'Component', 1, u'Identifier', None, u'Key to Component table item for application'),
+(u'IsolatedComponent', u'Component_Shared', u'N', None, None, u'Component', 1, u'Identifier', None, u'Key to Component table item to be isolated'),
+(u'LaunchCondition', u'Condition', u'N', None, None, None, None, u'Condition', None, u'Expression which must evaluate to TRUE in order for install to commence.'),
+(u'LaunchCondition', u'Description', u'N', None, None, None, None, u'Formatted', None, u'Localizable text to display when condition fails and install must abort.'),
+(u'LockPermissions', u'Table', u'N', None, None, None, None, u'Identifier', u'Directory;File;Registry', u'Reference to another table name'),
+(u'LockPermissions', u'Domain', u'Y', None, None, None, None, u'Formatted', None, u'Domain name for user whose permissions are being set. (usually a property)'),
+(u'LockPermissions', u'LockObject', u'N', None, None, None, None, u'Identifier', None, u'Foreign key into Registry or File table'),
+(u'LockPermissions', u'Permission', u'Y', -2147483647, 2147483647, None, None, None, None, u'Permission Access mask. Full Control = 268435456 (GENERIC_ALL = 0x10000000)'),
+(u'LockPermissions', u'User', u'N', None, None, None, None, u'Formatted', None, u'User for permissions to be set. (usually a property)'),
+(u'Media', u'Source', u'Y', None, None, None, None, u'Property', None, u'The property defining the location of the cabinet file.'),
+(u'Media', u'Cabinet', u'Y', None, None, None, None, u'Cabinet', None, u'If some or all of the files stored on the media are compressed in a cabinet, the name of that cabinet.'),
+(u'Media', u'DiskId', u'N', 1, 32767, None, None, None, None, u'Primary key, integer to determine sort order for table.'),
+(u'Media', u'DiskPrompt', u'Y', None, None, None, None, u'Text', None, u'Disk name: the visible text actually printed on the disk. This will be used to prompt the user when this disk needs to be inserted.'),
+(u'Media', u'LastSequence', u'N', 0, 32767, None, None, None, None, u'File sequence number for the last file for this media.'),
+(u'Media', u'VolumeLabel', u'Y', None, None, None, None, u'Text', None, u'The label attributed to the volume.'),
+(u'ModuleComponents', u'Component', u'N', None, None, u'Component', 1, u'Identifier', None, u'Component contained in the module.'),
+(u'ModuleComponents', u'Language', u'N', None, None, u'ModuleSignature', 2, None, None, u'Default language ID for module (may be changed by transform).'),
+(u'ModuleComponents', u'ModuleID', u'N', None, None, u'ModuleSignature', 1, u'Identifier', None, u'Module containing the component.'),
+(u'ModuleSignature', u'Language', u'N', None, None, None, None, None, None, u'Default decimal language of module.'),
+(u'ModuleSignature', u'Version', u'N', None, None, None, None, u'Version', None, u'Version of the module.'),
+(u'ModuleSignature', u'ModuleID', u'N', None, None, None, None, u'Identifier', None, u'Module identifier (String.GUID).'),
+(u'ModuleDependency', u'ModuleID', u'N', None, None, u'ModuleSignature', 1, u'Identifier', None, u'Module requiring the dependency.'),
+(u'ModuleDependency', u'ModuleLanguage', u'N', None, None, u'ModuleSignature', 2, None, None, u'Language of module requiring the dependency.'),
+(u'ModuleDependency', u'RequiredID', u'N', None, None, None, None, None, None, u'String.GUID of required module.'),
+(u'ModuleDependency', u'RequiredLanguage', u'N', None, None, None, None, None, None, u'LanguageID of the required module.'),
+(u'ModuleDependency', u'RequiredVersion', u'Y', None, None, None, None, u'Version', None, u'Version of the required version.'),
+(u'ModuleExclusion', u'ModuleID', u'N', None, None, u'ModuleSignature', 1, u'Identifier', None, u'String.GUID of module with exclusion requirement.'),
+(u'ModuleExclusion', u'ModuleLanguage', u'N', None, None, u'ModuleSignature', 2, None, None, u'LanguageID of module with exclusion requirement.'),
+(u'ModuleExclusion', u'ExcludedID', u'N', None, None, None, None, None, None, u'String.GUID of excluded module.'),
+(u'ModuleExclusion', u'ExcludedLanguage', u'N', None, None, None, None, None, None, u'Language of excluded module.'),
+(u'ModuleExclusion', u'ExcludedMaxVersion', u'Y', None, None, None, None, u'Version', None, u'Maximum version of excluded module.'),
+(u'ModuleExclusion', u'ExcludedMinVersion', u'Y', None, None, None, None, u'Version', None, u'Minimum version of excluded module.'),
+(u'MoveFile', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'If this component is not "selected" for installation or removal, no action will be taken on the associated MoveFile entry'),
+(u'MoveFile', u'DestFolder', u'N', None, None, None, None, u'Identifier', None, u'Name of a property whose value is assumed to resolve to the full path to the destination directory'),
+(u'MoveFile', u'DestName', u'Y', None, None, None, None, u'Filename', None, u'Name to be given to the original file after it is moved or copied. If blank, the destination file will be given the same name as the source file'),
+(u'MoveFile', u'FileKey', u'N', None, None, None, None, u'Identifier', None, u'Primary key that uniquely identifies a particular MoveFile record'),
+(u'MoveFile', u'Options', u'N', 0, 1, None, None, None, None, u'Integer value specifying the MoveFile operating mode, one of imfoEnum'),
+(u'MoveFile', u'SourceFolder', u'Y', None, None, None, None, u'Identifier', None, u'Name of a property whose value is assumed to resolve to the full path to the source directory'),
+(u'MoveFile', u'SourceName', u'Y', None, None, None, None, u'Text', None, u"Name of the source file(s) to be moved or copied. Can contain the '*' or '?' wildcards."),
+(u'MsiAssembly', u'Attributes', u'Y', None, None, None, None, None, None, u'Assembly attributes'),
+(u'MsiAssembly', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'Foreign key into Feature table.'),
+(u'MsiAssembly', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into Component table.'),
+(u'MsiAssembly', u'File_Application', u'Y', None, None, u'File', 1, u'Identifier', None, u'Foreign key into File table, denoting the application context for private assemblies. Null for global assemblies.'),
+(u'MsiAssembly', u'File_Manifest', u'Y', None, None, u'File', 1, u'Identifier', None, u'Foreign key into the File table denoting the manifest file for the assembly.'),
+(u'MsiAssemblyName', u'Name', u'N', None, None, None, None, u'Text', None, u'The name part of the name-value pairs for the assembly name.'),
+(u'MsiAssemblyName', u'Value', u'N', None, None, None, None, u'Text', None, u'The value part of the name-value pairs for the assembly name.'),
+(u'MsiAssemblyName', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into Component table.'),
+(u'MsiDigitalCertificate', u'CertData', u'N', None, None, None, None, u'Binary', None, u'A certificate context blob for a signer certificate'),
+(u'MsiDigitalCertificate', u'DigitalCertificate', u'N', None, None, None, None, u'Identifier', None, u'A unique identifier for the row'),
+(u'MsiDigitalSignature', u'Table', u'N', None, None, None, None, None, u'Media', u'Reference to another table name (only Media table is supported)'),
+(u'MsiDigitalSignature', u'DigitalCertificate_', u'N', None, None, u'MsiDigitalCertificate', 1, u'Identifier', None, u'Foreign key to MsiDigitalCertificate table identifying the signer certificate'),
+(u'MsiDigitalSignature', u'Hash', u'Y', None, None, None, None, u'Binary', None, u'The encoded hash blob from the digital signature'),
+(u'MsiDigitalSignature', u'SignObject', u'N', None, None, None, None, u'Text', None, u'Foreign key to Media table'),
+(u'MsiFileHash', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'Primary key, foreign key into File table referencing file with this hash'),
+(u'MsiFileHash', u'Options', u'N', 0, 32767, None, None, None, None, u'Various options and attributes for this hash.'),
+(u'MsiFileHash', u'HashPart1', u'N', None, None, None, None, None, None, u'Size of file in bytes (long integer).'),
+(u'MsiFileHash', u'HashPart2', u'N', None, None, None, None, None, None, u'Size of file in bytes (long integer).'),
+(u'MsiFileHash', u'HashPart3', u'N', None, None, None, None, None, None, u'Size of file in bytes (long integer).'),
+(u'MsiFileHash', u'HashPart4', u'N', None, None, None, None, None, None, u'Size of file in bytes (long integer).'),
+(u'MsiPatchHeaders', u'StreamRef', u'N', None, None, None, None, u'Identifier', None, u'Primary key. A unique identifier for the row.'),
+(u'MsiPatchHeaders', u'Header', u'N', None, None, None, None, u'Binary', None, u'Binary stream. The patch header, used for patch validation.'),
+(u'ODBCAttribute', u'Value', u'Y', None, None, None, None, u'Text', None, u'Value for ODBC driver attribute'),
+(u'ODBCAttribute', u'Attribute', u'N', None, None, None, None, u'Text', None, u'Name of ODBC driver attribute'),
+(u'ODBCAttribute', u'Driver_', u'N', None, None, u'ODBCDriver', 1, u'Identifier', None, u'Reference to ODBC driver in ODBCDriver table'),
+(u'ODBCDriver', u'Description', u'N', None, None, None, None, u'Text', None, u'Text used as registered name for driver, non-localized'),
+(u'ODBCDriver', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'Reference to key driver file'),
+(u'ODBCDriver', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Reference to associated component'),
+(u'ODBCDriver', u'Driver', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized.internal token for driver'),
+(u'ODBCDriver', u'File_Setup', u'Y', None, None, u'File', 1, u'Identifier', None, u'Optional reference to key driver setup DLL'),
+(u'ODBCDataSource', u'Description', u'N', None, None, None, None, u'Text', None, u'Text used as registered name for data source'),
+(u'ODBCDataSource', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Reference to associated component'),
+(u'ODBCDataSource', u'DataSource', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized.internal token for data source'),
+(u'ODBCDataSource', u'DriverDescription', u'N', None, None, None, None, u'Text', None, u'Reference to driver description, may be existing driver'),
+(u'ODBCDataSource', u'Registration', u'N', 0, 1, None, None, None, None, u'Registration option: 0=machine, 1=user, others t.b.d.'),
+(u'ODBCSourceAttribute', u'Value', u'Y', None, None, None, None, u'Text', None, u'Value for ODBC data source attribute'),
+(u'ODBCSourceAttribute', u'Attribute', u'N', None, None, None, None, u'Text', None, u'Name of ODBC data source attribute'),
+(u'ODBCSourceAttribute', u'DataSource_', u'N', None, None, u'ODBCDataSource', 1, u'Identifier', None, u'Reference to ODBC data source in ODBCDataSource table'),
+(u'ODBCTranslator', u'Description', u'N', None, None, None, None, u'Text', None, u'Text used as registered name for translator'),
+(u'ODBCTranslator', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'Reference to key translator file'),
+(u'ODBCTranslator', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Reference to associated component'),
+(u'ODBCTranslator', u'File_Setup', u'Y', None, None, u'File', 1, u'Identifier', None, u'Optional reference to key translator setup DLL'),
+(u'ODBCTranslator', u'Translator', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized.internal token for translator'),
+(u'Patch', u'Sequence', u'N', 0, 32767, None, None, None, None, u'Primary key, sequence with respect to the media images; order must track cabinet order.'),
+(u'Patch', u'Attributes', u'N', 0, 32767, None, None, None, None, u'Integer containing bit flags representing patch attributes'),
+(u'Patch', u'File_', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token, foreign key to File table, must match identifier in cabinet.'),
+(u'Patch', u'Header', u'Y', None, None, None, None, u'Binary', None, u'Binary stream. The patch header, used for patch validation.'),
+(u'Patch', u'PatchSize', u'N', 0, 2147483647, None, None, None, None, u'Size of patch in bytes (long integer).'),
+(u'Patch', u'StreamRef_', u'Y', None, None, None, None, u'Identifier', None, u'Identifier. Foreign key to the StreamRef column of the MsiPatchHeaders table.'),
+(u'PatchPackage', u'Media_', u'N', 0, 32767, None, None, None, None, u'Foreign key to DiskId column of Media table. Indicates the disk containing the patch package.'),
+(u'PatchPackage', u'PatchId', u'N', None, None, None, None, u'Guid', None, u'A unique string GUID representing this patch.'),
+(u'PublishComponent', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'Foreign key into the Feature table.'),
+(u'PublishComponent', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table.'),
+(u'PublishComponent', u'ComponentId', u'N', None, None, None, None, u'Guid', None, u'A string GUID that represents the component id that will be requested by the alien product.'),
+(u'PublishComponent', u'AppData', u'Y', None, None, None, None, u'Text', None, u'This is localisable Application specific data that can be associated with a Qualified Component.'),
+(u'PublishComponent', u'Qualifier', u'N', None, None, None, None, u'Text', None, u'This is defined only when the ComponentId column is an Qualified Component Id. This is the Qualifier for ProvideComponentIndirect.'),
+(u'Registry', u'Name', u'Y', None, None, None, None, u'Formatted', None, u'The registry value name.'),
+(u'Registry', u'Value', u'Y', None, None, None, None, u'Formatted', None, u'The registry value.'),
+(u'Registry', u'Key', u'N', None, None, None, None, u'RegPath', None, u'The key for the registry value.'),
+(u'Registry', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table referencing component that controls the installing of the registry value.'),
+(u'Registry', u'Registry', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token.'),
+(u'Registry', u'Root', u'N', -1, 3, None, None, None, None, u'The predefined root key for the registry value, one of rrkEnum.'),
+(u'RegLocator', u'Name', u'Y', None, None, None, None, u'Formatted', None, u'The registry value name.'),
+(u'RegLocator', u'Type', u'Y', 0, 18, None, None, None, None, u'An integer value that determines if the registry value is a filename or a directory location or to be used as is w/o interpretation.'),
+(u'RegLocator', u'Key', u'N', None, None, None, None, u'RegPath', None, u'The key for the registry value.'),
+(u'RegLocator', u'Signature_', u'N', None, None, None, None, u'Identifier', None, u'The table key. The Signature_ represents a unique file signature and is also the foreign key in the Signature table. If the type is 0, the registry values refers a directory, and _Signature is not a foreign key.'),
+(u'RegLocator', u'Root', u'N', 0, 3, None, None, None, None, u'The predefined root key for the registry value, one of rrkEnum.'),
+(u'RemoveFile', u'InstallMode', u'N', None, None, None, None, None, u'1;2;3', u'Installation option, one of iimEnum.'),
+(u'RemoveFile', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key referencing Component that controls the file to be removed.'),
+(u'RemoveFile', u'FileKey', u'N', None, None, None, None, u'Identifier', None, u'Primary key used to identify a particular file entry'),
+(u'RemoveFile', u'FileName', u'Y', None, None, None, None, u'WildCardFilename', None, u'Name of the file to be removed.'),
+(u'RemoveFile', u'DirProperty', u'N', None, None, None, None, u'Identifier', None, u'Name of a property whose value is assumed to resolve to the full pathname to the folder of the file to be removed.'),
+(u'RemoveIniFile', u'Action', u'N', None, None, None, None, None, u'2;4', u'The type of modification to be made, one of iifEnum.'),
+(u'RemoveIniFile', u'Value', u'Y', None, None, None, None, u'Formatted', None, u'The value to be deleted. The value is required when Action is iifIniRemoveTag'),
+(u'RemoveIniFile', u'Key', u'N', None, None, None, None, u'Formatted', None, u'The .INI file key below Section.'),
+(u'RemoveIniFile', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table referencing component that controls the deletion of the .INI value.'),
+(u'RemoveIniFile', u'FileName', u'N', None, None, None, None, u'Filename', None, u'The .INI file name in which to delete the information'),
+(u'RemoveIniFile', u'DirProperty', u'Y', None, None, None, None, u'Identifier', None, u'Foreign key into the Directory table denoting the directory where the .INI file is.'),
+(u'RemoveIniFile', u'Section', u'N', None, None, None, None, u'Formatted', None, u'The .INI file Section.'),
+(u'RemoveIniFile', u'RemoveIniFile', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token.'),
+(u'RemoveRegistry', u'Name', u'Y', None, None, None, None, u'Formatted', None, u'The registry value name.'),
+(u'RemoveRegistry', u'Key', u'N', None, None, None, None, u'RegPath', None, u'The key for the registry value.'),
+(u'RemoveRegistry', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table referencing component that controls the deletion of the registry value.'),
+(u'RemoveRegistry', u'Root', u'N', -1, 3, None, None, None, None, u'The predefined root key for the registry value, one of rrkEnum'),
+(u'RemoveRegistry', u'RemoveRegistry', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token.'),
+(u'ReserveCost', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Reserve a specified amount of space if this component is to be installed.'),
+(u'ReserveCost', u'ReserveFolder', u'Y', None, None, None, None, u'Identifier', None, u'Name of a property whose value is assumed to resolve to the full path to the destination directory'),
+(u'ReserveCost', u'ReserveKey', u'N', None, None, None, None, u'Identifier', None, u'Primary key that uniquely identifies a particular ReserveCost record'),
+(u'ReserveCost', u'ReserveLocal', u'N', 0, 2147483647, None, None, None, None, u'Disk space to reserve if linked component is installed locally.'),
+(u'ReserveCost', u'ReserveSource', u'N', 0, 2147483647, None, None, None, None, u'Disk space to reserve if linked component is installed to run from the source location.'),
+(u'SelfReg', u'File_', u'N', None, None, u'File', 1, u'Identifier', None, u'Foreign key into the File table denoting the module that needs to be registered.'),
+(u'SelfReg', u'Cost', u'Y', 0, 32767, None, None, None, None, u'The cost of registering the module.'),
+(u'ServiceControl', u'Name', u'N', None, None, None, None, u'Formatted', None, u'Name of a service. /, \\, comma and space are invalid'),
+(u'ServiceControl', u'Event', u'N', 0, 187, None, None, None, None, u'Bit field: Install: 0x1 = Start, 0x2 = Stop, 0x8 = Delete, Uninstall: 0x10 = Start, 0x20 = Stop, 0x80 = Delete'),
+(u'ServiceControl', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Required foreign key into the Component Table that controls the startup of the service'),
+(u'ServiceControl', u'ServiceControl', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token.'),
+(u'ServiceControl', u'Arguments', u'Y', None, None, None, None, u'Formatted', None, u'Arguments for the service. Separate by [~].'),
+(u'ServiceControl', u'Wait', u'Y', 0, 1, None, None, None, None, u'Boolean for whether to wait for the service to fully start'),
+(u'ServiceInstall', u'Name', u'N', None, None, None, None, u'Formatted', None, u'Internal Name of the Service'),
+(u'ServiceInstall', u'Description', u'Y', None, None, None, None, u'Text', None, u'Description of service.'),
+(u'ServiceInstall', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Required foreign key into the Component Table that controls the startup of the service'),
+(u'ServiceInstall', u'Arguments', u'Y', None, None, None, None, u'Formatted', None, u'Arguments to include in every start of the service, passed to WinMain'),
+(u'ServiceInstall', u'ServiceInstall', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token.'),
+(u'ServiceInstall', u'Dependencies', u'Y', None, None, None, None, u'Formatted', None, u'Other services this depends on to start. Separate by [~], and end with [~][~]'),
+(u'ServiceInstall', u'DisplayName', u'Y', None, None, None, None, u'Formatted', None, u'External Name of the Service'),
+(u'ServiceInstall', u'ErrorControl', u'N', -2147483647, 2147483647, None, None, None, None, u'Severity of error if service fails to start'),
+(u'ServiceInstall', u'LoadOrderGroup', u'Y', None, None, None, None, u'Formatted', None, u'LoadOrderGroup'),
+(u'ServiceInstall', u'Password', u'Y', None, None, None, None, u'Formatted', None, u'password to run service with. (with StartName)'),
+(u'ServiceInstall', u'ServiceType', u'N', -2147483647, 2147483647, None, None, None, None, u'Type of the service'),
+(u'ServiceInstall', u'StartName', u'Y', None, None, None, None, u'Formatted', None, u'User or object name to run service as'),
+(u'ServiceInstall', u'StartType', u'N', 0, 4, None, None, None, None, u'Type of the service'),
+(u'Shortcut', u'Name', u'N', None, None, None, None, u'Filename', None, u'The name of the shortcut to be created.'),
+(u'Shortcut', u'Description', u'Y', None, None, None, None, u'Text', None, u'The description for the shortcut.'),
+(u'Shortcut', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.'),
+(u'Shortcut', u'Icon_', u'Y', None, None, u'Icon', 1, u'Identifier', None, u'Foreign key into the File table denoting the external icon file for the shortcut.'),
+(u'Shortcut', u'IconIndex', u'Y', -32767, 32767, None, None, None, None, u'The icon index for the shortcut.'),
+(u'Shortcut', u'Directory_', u'N', None, None, u'Directory', 1, u'Identifier', None, u'Foreign key into the Directory table denoting the directory where the shortcut file is created.'),
+(u'Shortcut', u'Target', u'N', None, None, None, None, u'Shortcut', None, u'The shortcut target. This is usually a property that is expanded to a file or a folder that the shortcut points to.'),
+(u'Shortcut', u'Arguments', u'Y', None, None, None, None, u'Formatted', None, u'The command-line arguments for the shortcut.'),
+(u'Shortcut', u'Shortcut', u'N', None, None, None, None, u'Identifier', None, u'Primary key, non-localized token.'),
+(u'Shortcut', u'Hotkey', u'Y', 0, 32767, None, None, None, None, u'The hotkey for the shortcut. It has the virtual-key code for the key in the low-order byte, and the modifier flags in the high-order byte. '),
+(u'Shortcut', u'ShowCmd', u'Y', None, None, None, None, None, u'1;3;7', u'The show command for the application window.The following values may be used.'),
+(u'Shortcut', u'WkDir', u'Y', None, None, None, None, u'Identifier', None, u'Name of property defining location of working directory.'),
+(u'Signature', u'FileName', u'N', None, None, None, None, u'Filename', None, u'The name of the file. This may contain a "short name|long name" pair.'),
+(u'Signature', u'Signature', u'N', None, None, None, None, u'Identifier', None, u'The table key. The Signature represents a unique file signature.'),
+(u'Signature', u'Languages', u'Y', None, None, None, None, u'Language', None, u'The languages supported by the file.'),
+(u'Signature', u'MaxDate', u'Y', 0, 2147483647, None, None, None, None, u'The maximum creation date of the file.'),
+(u'Signature', u'MaxSize', u'Y', 0, 2147483647, None, None, None, None, u'The maximum size of the file. '),
+(u'Signature', u'MaxVersion', u'Y', None, None, None, None, u'Text', None, u'The maximum version of the file.'),
+(u'Signature', u'MinDate', u'Y', 0, 2147483647, None, None, None, None, u'The minimum creation date of the file.'),
+(u'Signature', u'MinSize', u'Y', 0, 2147483647, None, None, None, None, u'The minimum size of the file.'),
+(u'Signature', u'MinVersion', u'Y', None, None, None, None, u'Text', None, u'The minimum version of the file.'),
+(u'TypeLib', u'Feature_', u'N', None, None, u'Feature', 1, u'Identifier', None, u'Required foreign key into the Feature Table, specifying the feature to validate or install in order for the type library to be operational.'),
+(u'TypeLib', u'Description', u'Y', None, None, None, None, u'Text', None, None),
+(u'TypeLib', u'Component_', u'N', None, None, u'Component', 1, u'Identifier', None, u'Required foreign key into the Component Table, specifying the component for which to return a path when called through LocateComponent.'),
+(u'TypeLib', u'Directory_', u'Y', None, None, u'Directory', 1, u'Identifier', None, u'Optional. The foreign key into the Directory table denoting the path to the help file for the type library.'),
+(u'TypeLib', u'Language', u'N', 0, 32767, None, None, None, None, u'The language of the library.'),
+(u'TypeLib', u'Version', u'Y', 0, 16777215, None, None, None, None, u'The version of the library. The minor version is in the lower 8 bits of the integer. The major version is in the next 16 bits. '),
+(u'TypeLib', u'Cost', u'Y', 0, 2147483647, None, None, None, None, u'The cost associated with the registration of the typelib. This column is currently optional.'),
+(u'TypeLib', u'LibID', u'N', None, None, None, None, u'Guid', None, u'The GUID that represents the library.'),
+(u'Upgrade', u'Attributes', u'N', 0, 2147483647, None, None, None, None, u'The attributes of this product set.'),
+(u'Upgrade', u'Remove', u'Y', None, None, None, None, u'Formatted', None, u'The list of features to remove when uninstalling a product from this set. The default is "ALL".'),
+(u'Upgrade', u'Language', u'Y', None, None, None, None, u'Language', None, u'A comma-separated list of languages for either products in this set or products not in this set.'),
+(u'Upgrade', u'ActionProperty', u'N', None, None, None, None, u'UpperCase', None, u'The property to set when a product in this set is found.'),
+(u'Upgrade', u'UpgradeCode', u'N', None, None, None, None, u'Guid', None, u'The UpgradeCode GUID belonging to the products in this set.'),
+(u'Upgrade', u'VersionMax', u'Y', None, None, None, None, u'Text', None, u'The maximum ProductVersion of the products in this set. The set may or may not include products with this particular version.'),
+(u'Upgrade', u'VersionMin', u'Y', None, None, None, None, u'Text', None, u'The minimum ProductVersion of the products in this set. The set may or may not include products with this particular version.'),
+(u'Verb', u'Sequence', u'Y', 0, 32767, None, None, None, None, u'Order within the verbs for a particular extension. Also used simply to specify the default verb.'),
+(u'Verb', u'Argument', u'Y', None, None, None, None, u'Formatted', None, u'Optional value for the command arguments.'),
+(u'Verb', u'Extension_', u'N', None, None, u'Extension', 1, u'Text', None, u'The extension associated with the table row.'),
+(u'Verb', u'Verb', u'N', None, None, None, None, u'Text', None, u'The verb for the command.'),
+(u'Verb', u'Command', u'Y', None, None, None, None, u'Formatted', None, u'The command text.'),
+]
+
+Error = [
+(0, u'{{Fatal error: }}'),
+(1, u'{{Error [1]. }}'),
+(2, u'Warning [1]. '),
+(3, None),
+(4, u'Info [1]. '),
+(5, u'The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is [1]. {{The arguments are: [2], [3], [4]}}'),
+(6, None),
+(7, u'{{Disk full: }}'),
+(8, u'Action [Time]: [1]. [2]'),
+(9, u'[ProductName]'),
+(10, u'{[2]}{, [3]}{, [4]}'),
+(11, u'Message type: [1], Argument: [2]'),
+(12, u'=== Logging started: [Date] [Time] ==='),
+(13, u'=== Logging stopped: [Date] [Time] ==='),
+(14, u'Action start [Time]: [1].'),
+(15, u'Action ended [Time]: [1]. Return value [2].'),
+(16, u'Time remaining: {[1] minutes }{[2] seconds}'),
+(17, u'Out of memory. Shut down other applications before retrying.'),
+(18, u'Installer is no longer responding.'),
+(19, u'Installer stopped prematurely.'),
+(20, u'Please wait while Windows configures [ProductName]'),
+(21, u'Gathering required information...'),
+(22, u'Removing older versions of this application...'),
+(23, u'Preparing to remove older versions of this application...'),
+(32, u'{[ProductName] }Setup completed successfully.'),
+(33, u'{[ProductName] }Setup failed.'),
+(1101, u'Error reading from file: [2]. {{ System error [3].}} Verify that the file exists and that you can access it.'),
+(1301, u"Cannot create the file '[2]'. A directory with this name already exists. Cancel the install and try installing to a different location."),
+(1302, u'Please insert the disk: [2]'),
+(1303, u'The installer has insufficient privileges to access this directory: [2]. The installation cannot continue. Log on as administrator or contact your system administrator.'),
+(1304, u'Error writing to file: [2]. Verify that you have access to that directory.'),
+(1305, u'Error reading from file [2]. {{ System error [3].}} Verify that the file exists and that you can access it.'),
+(1306, u"Another application has exclusive access to the file '[2]'. Please shut down all other applications, then click Retry."),
+(1307, u'There is not enough disk space to install this file: [2]. Free some disk space and click Retry, or click Cancel to exit.'),
+(1308, u'Source file not found: [2]. Verify that the file exists and that you can access it.'),
+(1309, u'Error reading from file: [3]. {{ System error [2].}} Verify that the file exists and that you can access it.'),
+(1310, u'Error writing to file: [3]. {{ System error [2].}} Verify that you have access to that directory.'),
+(1311, u'Source file not found{{(cabinet)}}: [2]. Verify that the file exists and that you can access it.'),
+(1312, u"Cannot create the directory '[2]'. A file with this name already exists. Please rename or remove the file and click retry, or click Cancel to exit."),
+(1313, u'The volume [2] is currently unavailable. Please select another.'),
+(1314, u"The specified path '[2]' is unavailable."),
+(1315, u'Unable to write to the specified folder: [2].'),
+(1316, u'A network error occurred while attempting to read from the file: [2]'),
+(1317, u'An error occurred while attempting to create the directory: [2]'),
+(1318, u'A network error occurred while attempting to create the directory: [2]'),
+(1319, u'A network error occurred while attempting to open the source file cabinet: [2]'),
+(1320, u'The specified path is too long: [2]'),
+(1321, u'The Installer has insufficient privileges to modify this file: [2].'),
+(1322, u"A portion of the folder path '[2]' is invalid. It is either empty or exceeds the length allowed by the system."),
+(1323, u"The folder path '[2]' contains words that are not valid in folder paths."),
+(1324, u"The folder path '[2]' contains an invalid character."),
+(1325, u"'[2]' is not a valid short file name."),
+(1326, u'Error getting file security: [3] GetLastError: [2]'),
+(1327, u'Invalid Drive: [2]'),
+(1328, u'Error applying patch to file [2]. It has probably been updated by other means, and can no longer be modified by this patch. For more information contact your patch vendor. {{System Error: [3]}}'),
+(1329, u'A file that is required cannot be installed because the cabinet file [2] is not digitally signed. This may indicate that the cabinet file is corrupt.'),
+(1330, u'A file that is required cannot be installed because the cabinet file [2] has an invalid digital signature. This may indicate that the cabinet file is corrupt.{{ Error [3] was returned by WinVerifyTrust.}}'),
+(1331, u'Failed to correctly copy [2] file: CRC error.'),
+(1332, u'Failed to correctly move [2] file: CRC error.'),
+(1333, u'Failed to correctly patch [2] file: CRC error.'),
+(1334, u"The file '[2]' cannot be installed because the file cannot be found in cabinet file '[3]'. This could indicate a network error, an error reading from the CD-ROM, or a problem with this package."),
+(1335, u"The cabinet file '[2]' required for this installation is corrupt and cannot be used. This could indicate a network error, an error reading from the CD-ROM, or a problem with this package."),
+(1336, u'There was an error creating a temporary file that is needed to complete this installation.{{ Folder: [3]. System error code: [2]}}'),
+(1401, u'Could not create key: [2]. {{ System error [3].}} Verify that you have sufficient access to that key, or contact your support personnel. '),
+(1402, u'Could not open key: [2]. {{ System error [3].}} Verify that you have sufficient access to that key, or contact your support personnel. '),
+(1403, u'Could not delete value [2] from key [3]. {{ System error [4].}} Verify that you have sufficient access to that key, or contact your support personnel. '),
+(1404, u'Could not delete key [2]. {{ System error [3].}} Verify that you have sufficient access to that key, or contact your support personnel. '),
+(1405, u'Could not read value [2] from key [3]. {{ System error [4].}} Verify that you have sufficient access to that key, or contact your support personnel. '),
+(1406, u'Could not write value [2] to key [3]. {{ System error [4].}} Verify that you have sufficient access to that key, or contact your support personnel.'),
+(1407, u'Could not get value names for key [2]. {{ System error [3].}} Verify that you have sufficient access to that key, or contact your support personnel.'),
+(1408, u'Could not get sub key names for key [2]. {{ System error [3].}} Verify that you have sufficient access to that key, or contact your support personnel.'),
+(1409, u'Could not read security information for key [2]. {{ System error [3].}} Verify that you have sufficient access to that key, or contact your support personnel.'),
+(1410, u'Could not increase the available registry space. [2] KB of free registry space is required for the installation of this application.'),
+(1500, u'Another installation is in progress. You must complete that installation before continuing this one.'),
+(1501, u'Error accessing secured data. Please make sure the Windows Installer is configured properly and try the install again.'),
+(1502, u"User '[2]' has previously initiated an install for product '[3]'. That user will need to run that install again before they can use that product. Your current install will now continue."),
+(1503, u"User '[2]' has previously initiated an install for product '[3]'. That user will need to run that install again before they can use that product."),
+(1601, u"Out of disk space -- Volume: '[2]'; required space: [3] KB; available space: [4] KB. Free some disk space and retry."),
+(1602, u'Are you sure you want to cancel?'),
+(1603, u"The file [2][3] is being held in use{ by the following process: Name: [4], Id: [5], Window Title: '[6]'}. Close that application and retry."),
+(1604, u"The product '[2]' is already installed, preventing the installation of this product. The two products are incompatible."),
+(1605, u"There is not enough disk space on the volume '[2]' to continue the install with recovery enabled. [3] KB are required, but only [4] KB are available. Click Ignore to continue the install without saving recovery information, click Retry to check for available space again, or click Cancel to quit the installation."),
+(1606, u'Could not access network location [2].'),
+(1607, u'The following applications should be closed before continuing the install:'),
+(1608, u'Could not find any previously installed compliant products on the machine for installing this product.'),
+(1609, u"An error occurred while applying security settings. [2] is not a valid user or group. This could be a problem with the package, or a problem connecting to a domain controller on the network. Check your network connection and click Retry, or Cancel to end the install. {{Unable to locate the user's SID, system error [3]}}"),
+(1701, u'The key [2] is not valid. Verify that you entered the correct key.'),
+(1702, u'The installer must restart your system before configuration of [2] can continue. Click Yes to restart now or No if you plan to manually restart later.'),
+(1703, u'You must restart your system for the configuration changes made to [2] to take effect. Click Yes to restart now or No if you plan to manually restart later.'),
+(1704, u'An installation for [2] is currently suspended. You must undo the changes made by that installation to continue. Do you want to undo those changes?'),
+(1705, u'A previous installation for this product is in progress. You must undo the changes made by that installation to continue. Do you want to undo those changes?'),
+(1706, u"An installation package for the product [2] cannot be found. Try the installation again using a valid copy of the installation package '[3]'."),
+(1707, u'Installation completed successfully.'),
+(1708, u'Installation failed.'),
+(1709, u'Product: [2] -- [3]'),
+(1710, u'You may either restore your computer to its previous state or continue the install later. Would you like to restore?'),
+(1711, u'An error occurred while writing installation information to disk. Check to make sure enough disk space is available, and click Retry, or Cancel to end the install.'),
+(1712, u'One or more of the files required to restore your computer to its previous state could not be found. Restoration will not be possible.'),
+(1713, u'[2] cannot install one of its required products. Contact your technical support group. {{System Error: [3].}}'),
+(1714, u'The older version of [2] cannot be removed. Contact your technical support group. {{System Error [3].}}'),
+(1715, u'Installed [2]'),
+(1716, u'Configured [2]'),
+(1717, u'Removed [2]'),
+(1718, u'File [2] was rejected by digital signature policy.'),
+(1719, u'The Windows Installer Service could not be accessed. This can occur if you are running Windows in safe mode, or if the Windows Installer is not correctly installed. Contact your support personnel for assistance.'),
+(1720, u'There is a problem with this Windows Installer package. A script required for this install to complete could not be run. Contact your support personnel or package vendor. {{Custom action [2] script error [3], [4]: [5] Line [6], Column [7], [8] }}'),
+(1721, u'There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor. {{Action: [2], location: [3], command: [4] }}'),
+(1722, u'There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor. {{Action [2], location: [3], command: [4] }}'),
+(1723, u'There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendor. {{Action [2], entry: [3], library: [4] }}'),
+(1724, u'Removal completed successfully.'),
+(1725, u'Removal failed.'),
+(1726, u'Advertisement completed successfully.'),
+(1727, u'Advertisement failed.'),
+(1728, u'Configuration completed successfully.'),
+(1729, u'Configuration failed.'),
+(1730, u'You must be an Administrator to remove this application. To remove this application, you can log on as an Administrator, or contact your technical support group for assistance.'),
+(1801, u'The path [2] is not valid. Please specify a valid path.'),
+(1802, u'Out of memory. Shut down other applications before retrying.'),
+(1803, u'There is no disk in drive [2]. Please insert one and click Retry, or click Cancel to go back to the previously selected volume.'),
+(1804, u'There is no disk in drive [2]. Please insert one and click Retry, or click Cancel to return to the browse dialog and select a different volume.'),
+(1805, u'The folder [2] does not exist. Please enter a path to an existing folder.'),
+(1806, u'You have insufficient privileges to read this folder.'),
+(1807, u'A valid destination folder for the install could not be determined.'),
+(1901, u'Error attempting to read from the source install database: [2].'),
+(1902, u'Scheduling reboot operation: Renaming file [2] to [3]. Must reboot to complete operation.'),
+(1903, u'Scheduling reboot operation: Deleting file [2]. Must reboot to complete operation.'),
+(1904, u'Module [2] failed to register. HRESULT [3]. Contact your support personnel.'),
+(1905, u'Module [2] failed to unregister. HRESULT [3]. Contact your support personnel.'),
+(1906, u'Failed to cache package [2]. Error: [3]. Contact your support personnel.'),
+(1907, u'Could not register font [2]. Verify that you have sufficient permissions to install fonts, and that the system supports this font.'),
+(1908, u'Could not unregister font [2]. Verify that you that you have sufficient permissions to remove fonts.'),
+(1909, u'Could not create Shortcut [2]. Verify that the destination folder exists and that you can access it.'),
+(1910, u'Could not remove Shortcut [2]. Verify that the shortcut file exists and that you can access it.'),
+(1911, u'Could not register type library for file [2]. Contact your support personnel.'),
+(1912, u'Could not unregister type library for file [2]. Contact your support personnel.'),
+(1913, u'Could not update the ini file [2][3]. Verify that the file exists and that you can access it.'),
+(1914, u'Could not schedule file [2] to replace file [3] on reboot. Verify that you have write permissions to file [3].'),
+(1915, u'Error removing ODBC driver manager, ODBC error [2]: [3]. Contact your support personnel.'),
+(1916, u'Error installing ODBC driver manager, ODBC error [2]: [3]. Contact your support personnel.'),
+(1917, u'Error removing ODBC driver: [4], ODBC error [2]: [3]. Verify that you have sufficient privileges to remove ODBC drivers.'),
+(1918, u'Error installing ODBC driver: [4], ODBC error [2]: [3]. Verify that the file [4] exists and that you can access it.'),
+(1919, u'Error configuring ODBC data source: [4], ODBC error [2]: [3]. Verify that the file [4] exists and that you can access it.'),
+(1920, u"Service '[2]' ([3]) failed to start. Verify that you have sufficient privileges to start system services."),
+(1921, u"Service '[2]' ([3]) could not be stopped. Verify that you have sufficient privileges to stop system services."),
+(1922, u"Service '[2]' ([3]) could not be deleted. Verify that you have sufficient privileges to remove system services."),
+(1923, u"Service '[2]' ([3]) could not be installed. Verify that you have sufficient privileges to install system services."),
+(1924, u"Could not update environment variable '[2]'. Verify that you have sufficient privileges to modify environment variables."),
+(1925, u'You do not have sufficient privileges to complete this installation for all users of the machine. Log on as administrator and then retry this installation.'),
+(1926, u"Could not set file security for file '[3]'. Error: [2]. Verify that you have sufficient privileges to modify the security permissions for this file."),
+(1927, u'Component Services (COM+ 1.0) are not installed on this computer. This installation requires Component Services in order to complete successfully. Component Services are available on Windows 2000.'),
+(1928, u'Error registering COM+ Application. Contact your support personnel for more information.'),
+(1929, u'Error unregistering COM+ Application. Contact your support personnel for more information.'),
+(1930, u"The description for service '[2]' ([3]) could not be changed."),
+(1931, u'The Windows Installer service cannot update the system file [2] because the file is protected by Windows. You may need to update your operating system for this program to work correctly. {{Package version: [3], OS Protected version: [4]}}'),
+(1932, u'The Windows Installer service cannot update the protected Windows file [2]. {{Package version: [3], OS Protected version: [4], SFP Error: [5]}}'),
+(1933, u'The Windows Installer service cannot update one or more protected Windows files. {{SFP Error: [2]. List of protected files:\\r\\n[3]}}'),
+(1934, u'User installations are disabled via policy on the machine.'),
+(1935, u'An error occurred during the installation of assembly component [2]. HRESULT: [3]. {{assembly interface: [4], function: [5], assembly name: [6]}}'),
+]
+
+tables=['AdminExecuteSequence', 'AdminUISequence', 'AdvtExecuteSequence', 'BBControl', 'Billboard', 'Binary', 'CheckBox', 'Property', 'ComboBox', 'Control', 'ListBox', 'ActionText', 'ControlCondition', 'ControlEvent', 'Dialog', 'EventMapping', 'InstallExecuteSequence', 'InstallUISequence', 'ListView', 'RadioButton', 'TextStyle', 'UIText', '_Validation', 'Error']
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uuids.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uuids.py
new file mode 100644
index 0000000000..1160584925
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/msi/uuids.py
@@ -0,0 +1,58 @@
+# This should be extended for each Python release.
+# The product code must change whenever the name of the MSI file
+# changes, and when new component codes are issued for existing
+# components. See "Changing the Product Code". As we change the
+# component codes with every build, we need a new product code
+# each time. For intermediate (snapshot) releases, they are automatically
+# generated. For official releases, we record the product codes,
+# so people can refer to them.
+product_codes = {
+ '2.5.101': '{bc14ce3e-5e72-4a64-ac1f-bf59a571898c}', # 2.5a1
+ '2.5.102': '{5eed51c1-8e9d-4071-94c5-b40de5d49ba5}', # 2.5a2
+ '2.5.103': '{73dcd966-ffec-415f-bb39-8342c1f47017}', # 2.5a3
+ '2.5.111': '{c797ecf8-a8e6-4fec-bb99-526b65f28626}', # 2.5b1
+ '2.5.112': '{32beb774-f625-439d-b587-7187487baf15}', # 2.5b2
+ '2.5.113': '{89f23918-11cf-4f08-be13-b9b2e6463fd9}', # 2.5b3
+ '2.5.121': '{8e9321bc-6b24-48a3-8fd4-c95f8e531e5f}', # 2.5c1
+ '2.5.122': '{a6cd508d-9599-45da-a441-cbffa9f7e070}', # 2.5c2
+ '2.5.150': '{0a2c5854-557e-48c8-835a-3b9f074bdcaa}', # 2.5.0
+ '2.5.1121':'{0378b43e-6184-4c2f-be1a-4a367781cd54}', # 2.5.1c1
+ '2.5.1150':'{31800004-6386-4999-a519-518f2d78d8f0}', # 2.5.1
+ '2.5.2150':'{6304a7da-1132-4e91-a343-a296269eab8a}', # 2.5.2c1
+ '2.5.2150':'{6b976adf-8ae8-434e-b282-a06c7f624d2f}', # 2.5.2
+ '2.6.101': '{0ba82e1b-52fd-4e03-8610-a6c76238e8a8}', # 2.6a1
+ '2.6.102': '{3b27e16c-56db-4570-a2d3-e9a26180c60b}', # 2.6a2
+ '2.6.103': '{cd06a9c5-bde5-4bd7-9874-48933997122a}', # 2.6a3
+ '2.6.104': '{dc6ed634-474a-4a50-a547-8de4b7491e53}', # 2.6a4
+ '2.6.111': '{3f82079a-5bee-4c4a-8a41-8292389e24ae}', # 2.6b1
+ '2.6.112': '{8a0e5970-f3e6-4737-9a2b-bc5ff0f15fb5}', # 2.6b2
+ '2.6.113': '{df4f5c21-6fcc-4540-95de-85feba634e76}', # 2.6b3
+ '2.6.121': '{bbd34464-ddeb-4028-99e5-f16c4a8fbdb3}', # 2.6c1
+ '2.6.122': '{8f64787e-a023-4c60-bfee-25d3a3f592c6}', # 2.6c2
+ '2.6.150': '{110eb5c4-e995-4cfb-ab80-a5f315bea9e8}', # 2.6.0
+ '2.6.1150':'{9cc89170-000b-457d-91f1-53691f85b223}', # 2.6.1
+ '2.6.2121':'{adac412b-b209-4c15-b6ab-dca1b6e47144}', # 2.6.2c1
+ '2.6.2150':'{24aab420-4e30-4496-9739-3e216f3de6ae}', # 2.6.2
+ '2.6.3121':'{a73e0254-dcda-4fe4-bf37-c7e1c4f4ebb6}', # 2.6.3c1
+ '2.6.3150':'{3d9ac095-e115-4e94-bdef-7f7edf17697d}', # 2.6.3
+ '2.6.4121':'{727de605-0359-4606-a94b-c2033652379b}', # 2.6.4c1
+ '2.6.4122':'{4f7603c6-6352-4299-a398-150a31b19acc}', # 2.6.4c2
+ '2.6.4150':'{e7394a0f-3f80-45b1-87fc-abcd51893246}', # 2.6.4
+ '2.6.5121':'{e0e273d7-7598-4701-8325-c90c069fd5ff}', # 2.6.5c1
+ '2.6.5122':'{fa227b76-0671-4dc6-b826-c2ff2a70dfd5}', # 2.6.5c2
+ '2.6.5150':'{4723f199-fa64-4233-8e6e-9fccc95a18ee}', # 2.6.5
+ '2.7.101': '{eca1bbef-432c-49ae-a667-c213cc7bbf22}', # 2.7a1
+ '2.7.102': '{21ce16ed-73c4-460d-9b11-522f417b2090}', # 2.7a2
+ '2.7.103': '{6e7dbd55-ba4a-48ac-a688-6c75db4d7500}', # 2.7a3
+ '2.7.104': '{ee774ba3-74a5-48d9-b425-b35a287260c8}', # 2.7a4
+ '2.7.111': '{9cfd9ec7-a9c7-4980-a1c6-054fc6493eb3}', # 2.7b1
+ '2.7.112': '{9a72faf6-c304-4165-8595-9291ff30cac6}', # 2.7b2
+ '2.7.121': '{f530c94a-dd53-4de9-948e-b632b9cb48d2}', # 2.7c1
+ '2.7.122': '{f80905d2-dd8d-4b8e-8a40-c23c93dca07d}', # 2.7c2
+ '2.7.150': '{20c31435-2a0a-4580-be8b-ac06fc243ca4}', # 2.7.0
+ '2.7.1121':'{60a4036a-374c-4fd2-84b9-bfae7db03931}', # 2.7.1rc1
+ '2.7.1122':'{5965e7d1-5584-4de9-b13a-694e0b2ee3a6}', # 2.7.1rc2
+ '2.7.1150':'{32939827-d8e5-470a-b126-870db3c69fdf}', # 2.7.1
+ '2.7.2121':'{B2E1F06E-F719-4786-972A-488A336EB2A0}', # 2.7.2rc1
+ '2.7.2150':'{2E295B5B-1AD4-4d36-97C2-A316084722CF}', # 2.7.2
+}
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Arithmetic.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Arithmetic.py
new file mode 100644
index 0000000000..c88c837bda
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Arithmetic.py
@@ -0,0 +1,777 @@
+from pybench import Test
+
+class SimpleIntegerArithmetic(Test):
+
+ version = 2.0
+ operations = 5 * (3 + 5 + 5 + 3 + 3 + 3)
+ rounds = 120000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ a = 2
+ b = 3
+ c = 3
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+class SimpleFloatArithmetic(Test):
+
+ version = 2.0
+ operations = 5 * (3 + 5 + 5 + 3 + 3 + 3)
+ rounds = 120000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ a = 2.1
+ b = 3.3332
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2.1
+ b = 3.3332
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2.1
+ b = 3.3332
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2.1
+ b = 3.3332
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2.1
+ b = 3.3332
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+class SimpleIntFloatArithmetic(Test):
+
+ version = 2.0
+ operations = 5 * (3 + 5 + 5 + 3 + 3 + 3)
+ rounds = 120000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ a = 2
+ b = 3
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2
+ b = 3
+ c = 3.14159
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class SimpleLongArithmetic(Test):
+
+ version = 2.0
+ operations = 5 * (3 + 5 + 5 + 3 + 3 + 3)
+ rounds = 60000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ a = 2220001L
+ b = 100001L
+ c = 30005L
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2220001L
+ b = 100001L
+ c = 30005L
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2220001L
+ b = 100001L
+ c = 30005L
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2220001L
+ b = 100001L
+ c = 30005L
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2220001L
+ b = 100001L
+ c = 30005L
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+class SimpleComplexArithmetic(Test):
+
+ version = 2.0
+ operations = 5 * (3 + 5 + 5 + 3 + 3 + 3)
+ rounds = 80000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ a = 2 + 3j
+ b = 2.5 + 4.5j
+ c = 1.2 + 6.2j
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2 + 3j
+ b = 2.5 + 4.5j
+ c = 1.2 + 6.2j
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2 + 3j
+ b = 2.5 + 4.5j
+ c = 1.2 + 6.2j
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2 + 3j
+ b = 2.5 + 4.5j
+ c = 1.2 + 6.2j
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ a = 2 + 3j
+ b = 2.5 + 4.5j
+ c = 1.2 + 6.2j
+
+ c = a + b
+ c = b + c
+ c = c + a
+ c = a + b
+ c = b + c
+
+ c = c - a
+ c = a - b
+ c = b - c
+ c = c - a
+ c = b - c
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ c = a * b
+ c = b * a
+ c = c * b
+
+ c = a / b
+ c = b / a
+ c = c / b
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Calls.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Calls.py
new file mode 100644
index 0000000000..631dbf09f6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Calls.py
@@ -0,0 +1,560 @@
+from pybench import Test
+
+class PythonFunctionCalls(Test):
+
+ version = 2.0
+ operations = 5*(1+4+4+2)
+ rounds = 60000
+
+ def test(self):
+
+ global f,f1,g,h
+
+ # define functions
+ def f():
+ pass
+
+ def f1(x):
+ pass
+
+ def g(a,b,c):
+ return a,b,c
+
+ def h(a,b,c,d=1,e=2,f=3):
+ return d,e,f
+
+ # do calls
+ for i in xrange(self.rounds):
+
+ f()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ h(i,i,3,i,i)
+ h(i,i,i,2,i,3)
+
+ f()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ h(i,i,3,i,i)
+ h(i,i,i,2,i,3)
+
+ f()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ h(i,i,3,i,i)
+ h(i,i,i,2,i,3)
+
+ f()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ h(i,i,3,i,i)
+ h(i,i,i,2,i,3)
+
+ f()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ g(i,i,i)
+ h(i,i,3,i,i)
+ h(i,i,i,2,i,3)
+
+ def calibrate(self):
+
+ global f,f1,g,h
+
+ # define functions
+ def f():
+ pass
+
+ def f1(x):
+ pass
+
+ def g(a,b,c):
+ return a,b,c
+
+ def h(a,b,c,d=1,e=2,f=3):
+ return d,e,f
+
+ # do calls
+ for i in xrange(self.rounds):
+ pass
+
+###
+
+class ComplexPythonFunctionCalls(Test):
+
+ version = 2.0
+ operations = 4*5
+ rounds = 100000
+
+ def test(self):
+
+ # define functions
+ def f(a,b,c,d=1,e=2,f=3):
+ return f
+
+ args = 1,2
+ kwargs = dict(c=3,d=4,e=5)
+
+ # do calls
+ for i in xrange(self.rounds):
+ f(a=i,b=i,c=i)
+ f(f=i,e=i,d=i,c=2,b=i,a=3)
+ f(1,b=i,**kwargs)
+ f(*args,**kwargs)
+
+ f(a=i,b=i,c=i)
+ f(f=i,e=i,d=i,c=2,b=i,a=3)
+ f(1,b=i,**kwargs)
+ f(*args,**kwargs)
+
+ f(a=i,b=i,c=i)
+ f(f=i,e=i,d=i,c=2,b=i,a=3)
+ f(1,b=i,**kwargs)
+ f(*args,**kwargs)
+
+ f(a=i,b=i,c=i)
+ f(f=i,e=i,d=i,c=2,b=i,a=3)
+ f(1,b=i,**kwargs)
+ f(*args,**kwargs)
+
+ f(a=i,b=i,c=i)
+ f(f=i,e=i,d=i,c=2,b=i,a=3)
+ f(1,b=i,**kwargs)
+ f(*args,**kwargs)
+
+
+ def calibrate(self):
+
+ # define functions
+ def f(a,b,c,d=1,e=2,f=3):
+ return f
+
+ args = 1,2
+ kwargs = dict(c=3,d=4,e=5)
+
+ # do calls
+ for i in xrange(self.rounds):
+ pass
+
+###
+
+class BuiltinFunctionCalls(Test):
+
+ version = 2.0
+ operations = 5*(2+5+5+5)
+ rounds = 60000
+
+ def test(self):
+
+ # localize functions
+ f0 = globals
+ f1 = hash
+ f2 = cmp
+ f3 = range
+
+ # do calls
+ for i in xrange(self.rounds):
+
+ f0()
+ f0()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+
+ f0()
+ f0()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+
+ f0()
+ f0()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+
+ f0()
+ f0()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+
+ f0()
+ f0()
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f1(i)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f2(1,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+ f3(1,3,2)
+
+ def calibrate(self):
+
+ # localize functions
+ f0 = dir
+ f1 = hash
+ f2 = range
+ f3 = range
+
+ # do calls
+ for i in xrange(self.rounds):
+ pass
+
+###
+
+class PythonMethodCalls(Test):
+
+ version = 2.0
+ operations = 5*(6 + 5 + 4)
+ rounds = 30000
+
+ def test(self):
+
+ class c:
+
+ x = 2
+ s = 'string'
+
+ def f(self):
+
+ return self.x
+
+ def j(self,a,b):
+
+ self.y = a
+ self.t = b
+ return self.y
+
+ def k(self,a,b,c=3):
+
+ self.y = a
+ self.s = b
+ self.t = c
+
+ o = c()
+
+ for i in xrange(self.rounds):
+
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.j(i,i)
+ o.j(i,i)
+ o.j(i,2)
+ o.j(i,2)
+ o.j(2,2)
+ o.k(i,i)
+ o.k(i,2)
+ o.k(i,2,3)
+ o.k(i,i,c=4)
+
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.j(i,i)
+ o.j(i,i)
+ o.j(i,2)
+ o.j(i,2)
+ o.j(2,2)
+ o.k(i,i)
+ o.k(i,2)
+ o.k(i,2,3)
+ o.k(i,i,c=4)
+
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.j(i,i)
+ o.j(i,i)
+ o.j(i,2)
+ o.j(i,2)
+ o.j(2,2)
+ o.k(i,i)
+ o.k(i,2)
+ o.k(i,2,3)
+ o.k(i,i,c=4)
+
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.j(i,i)
+ o.j(i,i)
+ o.j(i,2)
+ o.j(i,2)
+ o.j(2,2)
+ o.k(i,i)
+ o.k(i,2)
+ o.k(i,2,3)
+ o.k(i,i,c=4)
+
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.f()
+ o.j(i,i)
+ o.j(i,i)
+ o.j(i,2)
+ o.j(i,2)
+ o.j(2,2)
+ o.k(i,i)
+ o.k(i,2)
+ o.k(i,2,3)
+ o.k(i,i,c=4)
+
+ def calibrate(self):
+
+ class c:
+
+ x = 2
+ s = 'string'
+
+ def f(self):
+
+ return self.x
+
+ def j(self,a,b):
+
+ self.y = a
+ self.t = b
+
+ def k(self,a,b,c=3):
+
+ self.y = a
+ self.s = b
+ self.t = c
+
+ o = c
+
+ for i in xrange(self.rounds):
+ pass
+
+###
+
+class Recursion(Test):
+
+ version = 2.0
+ operations = 5
+ rounds = 100000
+
+ def test(self):
+
+ global f
+
+ def f(x):
+
+ if x > 1:
+ return f(x-1)
+ return 1
+
+ for i in xrange(self.rounds):
+ f(10)
+ f(10)
+ f(10)
+ f(10)
+ f(10)
+
+ def calibrate(self):
+
+ global f
+
+ def f(x):
+
+ if x > 0:
+ return f(x-1)
+ return 1
+
+ for i in xrange(self.rounds):
+ pass
+
+
+### Test to make Fredrik happy...
+
+if __name__ == '__main__':
+ import timeit
+ if 0:
+ timeit.TestClass = PythonFunctionCalls
+ timeit.main(['-s', 'test = TestClass(); test.rounds = 1000',
+ 'test.test()'])
+ else:
+ setup = """\
+global f,f1,g,h
+
+# define functions
+def f():
+ pass
+
+def f1(x):
+ pass
+
+def g(a,b,c):
+ return a,b,c
+
+def h(a,b,c,d=1,e=2,f=3):
+ return d,e,f
+
+i = 1
+"""
+ test = """\
+f()
+f1(i)
+f1(i)
+f1(i)
+f1(i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+h(i,i,3,i,i)
+h(i,i,i,2,i,3)
+
+f()
+f1(i)
+f1(i)
+f1(i)
+f1(i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+h(i,i,3,i,i)
+h(i,i,i,2,i,3)
+
+f()
+f1(i)
+f1(i)
+f1(i)
+f1(i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+h(i,i,3,i,i)
+h(i,i,i,2,i,3)
+
+f()
+f1(i)
+f1(i)
+f1(i)
+f1(i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+h(i,i,3,i,i)
+h(i,i,i,2,i,3)
+
+f()
+f1(i)
+f1(i)
+f1(i)
+f1(i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+g(i,i,i)
+h(i,i,3,i,i)
+h(i,i,i,2,i,3)
+"""
+
+ timeit.main(['-s', setup,
+ test])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/CommandLine.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/CommandLine.py
new file mode 100644
index 0000000000..2cb0836025
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/CommandLine.py
@@ -0,0 +1,634 @@
+""" CommandLine - Get and parse command line options
+
+ NOTE: This still is very much work in progress !!!
+
+ Different version are likely to be incompatible.
+
+ TODO:
+
+ * Incorporate the changes made by (see Inbox)
+ * Add number range option using srange()
+
+"""
+
+__copyright__ = """\
+Copyright (c), 1997-2006, Marc-Andre Lemburg (mal@lemburg.com)
+Copyright (c), 2000-2006, eGenix.com Software GmbH (info@egenix.com)
+See the documentation for further information on copyrights,
+or contact the author. All Rights Reserved.
+"""
+
+__version__ = '1.2'
+
+import sys, getopt, string, glob, os, re, exceptions, traceback
+
+### Helpers
+
+def _getopt_flags(options):
+
+ """ Convert the option list to a getopt flag string and long opt
+ list
+
+ """
+ s = []
+ l = []
+ for o in options:
+ if o.prefix == '-':
+ # short option
+ s.append(o.name)
+ if o.takes_argument:
+ s.append(':')
+ else:
+ # long option
+ if o.takes_argument:
+ l.append(o.name+'=')
+ else:
+ l.append(o.name)
+ return string.join(s,''),l
+
+def invisible_input(prompt='>>> '):
+
+ """ Get raw input from a terminal without echoing the characters to
+ the terminal, e.g. for password queries.
+
+ """
+ import getpass
+ entry = getpass.getpass(prompt)
+ if entry is None:
+ raise KeyboardInterrupt
+ return entry
+
+def fileopen(name, mode='wb', encoding=None):
+
+ """ Open a file using mode.
+
+ Default mode is 'wb' meaning to open the file for writing in
+ binary mode. If encoding is given, I/O to and from the file is
+ transparently encoded using the given encoding.
+
+ Files opened for writing are chmod()ed to 0600.
+
+ """
+ if name == 'stdout':
+ return sys.stdout
+ elif name == 'stderr':
+ return sys.stderr
+ elif name == 'stdin':
+ return sys.stdin
+ else:
+ if encoding is not None:
+ import codecs
+ f = codecs.open(name, mode, encoding)
+ else:
+ f = open(name, mode)
+ if 'w' in mode:
+ os.chmod(name, 0600)
+ return f
+
+def option_dict(options):
+
+ """ Return a dictionary mapping option names to Option instances.
+ """
+ d = {}
+ for option in options:
+ d[option.name] = option
+ return d
+
+# Alias
+getpasswd = invisible_input
+
+_integerRE = re.compile('\s*(-?\d+)\s*$')
+_integerRangeRE = re.compile('\s*(-?\d+)\s*-\s*(-?\d+)\s*$')
+
+def srange(s,
+
+ split=string.split,integer=_integerRE,
+ integerRange=_integerRangeRE):
+
+ """ Converts a textual representation of integer numbers and ranges
+ to a Python list.
+
+ Supported formats: 2,3,4,2-10,-1 - -3, 5 - -2
+
+ Values are appended to the created list in the order specified
+ in the string.
+
+ """
+ l = []
+ append = l.append
+ for entry in split(s,','):
+ m = integer.match(entry)
+ if m:
+ append(int(m.groups()[0]))
+ continue
+ m = integerRange.match(entry)
+ if m:
+ start,end = map(int,m.groups())
+ l[len(l):] = range(start,end+1)
+ return l
+
+def abspath(path,
+
+ expandvars=os.path.expandvars,expanduser=os.path.expanduser,
+ join=os.path.join,getcwd=os.getcwd):
+
+ """ Return the corresponding absolute path for path.
+
+ path is expanded in the usual shell ways before
+ joining it with the current working directory.
+
+ """
+ try:
+ path = expandvars(path)
+ except AttributeError:
+ pass
+ try:
+ path = expanduser(path)
+ except AttributeError:
+ pass
+ return join(getcwd(), path)
+
+### Option classes
+
+class Option:
+
+ """ Option base class. Takes no argument.
+
+ """
+ default = None
+ helptext = ''
+ prefix = '-'
+ takes_argument = 0
+ has_default = 0
+ tab = 15
+
+ def __init__(self,name,help=None):
+
+ if not name[:1] == '-':
+ raise TypeError,'option names must start with "-"'
+ if name[1:2] == '-':
+ self.prefix = '--'
+ self.name = name[2:]
+ else:
+ self.name = name[1:]
+ if help:
+ self.help = help
+
+ def __str__(self):
+
+ o = self
+ name = o.prefix + o.name
+ if o.takes_argument:
+ name = name + ' arg'
+ if len(name) > self.tab:
+ name = name + '\n' + ' ' * (self.tab + 1 + len(o.prefix))
+ else:
+ name = '%-*s ' % (self.tab, name)
+ description = o.help
+ if o.has_default:
+ description = description + ' (%s)' % o.default
+ return '%s %s' % (name, description)
+
+class ArgumentOption(Option):
+
+ """ Option that takes an argument.
+
+ An optional default argument can be given.
+
+ """
+ def __init__(self,name,help=None,default=None):
+
+ # Basemethod
+ Option.__init__(self,name,help)
+
+ if default is not None:
+ self.default = default
+ self.has_default = 1
+ self.takes_argument = 1
+
+class SwitchOption(Option):
+
+ """ Options that can be on or off. Has an optional default value.
+
+ """
+ def __init__(self,name,help=None,default=None):
+
+ # Basemethod
+ Option.__init__(self,name,help)
+
+ if default is not None:
+ self.default = default
+ self.has_default = 1
+
+### Application baseclass
+
+class Application:
+
+ """ Command line application interface with builtin argument
+ parsing.
+
+ """
+ # Options the program accepts (Option instances)
+ options = []
+
+ # Standard settings; these are appended to options in __init__
+ preset_options = [SwitchOption('-v',
+ 'generate verbose output'),
+ SwitchOption('-h',
+ 'show this help text'),
+ SwitchOption('--help',
+ 'show this help text'),
+ SwitchOption('--debug',
+ 'enable debugging'),
+ SwitchOption('--copyright',
+ 'show copyright'),
+ SwitchOption('--examples',
+ 'show examples of usage')]
+
+ # The help layout looks like this:
+ # [header] - defaults to ''
+ #
+ # [synopsis] - formatted as '<self.name> %s' % self.synopsis
+ #
+ # options:
+ # [options] - formatted from self.options
+ #
+ # [version] - formatted as 'Version:\n %s' % self.version, if given
+ #
+ # [about] - defaults to ''
+ #
+ # Note: all fields that do not behave as template are formatted
+ # using the instances dictionary as substitution namespace,
+ # e.g. %(name)s will be replaced by the applications name.
+ #
+
+ # Header (default to program name)
+ header = ''
+
+ # Name (defaults to program name)
+ name = ''
+
+ # Synopsis (%(name)s is replaced by the program name)
+ synopsis = '%(name)s [option] files...'
+
+ # Version (optional)
+ version = ''
+
+ # General information printed after the possible options (optional)
+ about = ''
+
+ # Examples of usage to show when the --examples option is given (optional)
+ examples = ''
+
+ # Copyright to show
+ copyright = __copyright__
+
+ # Apply file globbing ?
+ globbing = 1
+
+ # Generate debug output ?
+ debug = 0
+
+ # Generate verbose output ?
+ verbose = 0
+
+ # Internal errors to catch
+ InternalError = exceptions.Exception
+
+ # Instance variables:
+ values = None # Dictionary of passed options (or default values)
+ # indexed by the options name, e.g. '-h'
+ files = None # List of passed filenames
+ optionlist = None # List of passed options
+
+ def __init__(self,argv=None):
+
+ # Setup application specs
+ if argv is None:
+ argv = sys.argv
+ self.filename = os.path.split(argv[0])[1]
+ if not self.name:
+ self.name = os.path.split(self.filename)[1]
+ else:
+ self.name = self.name
+ if not self.header:
+ self.header = self.name
+ else:
+ self.header = self.header
+
+ # Init .arguments list
+ self.arguments = argv[1:]
+
+ # Setup Option mapping
+ self.option_map = option_dict(self.options)
+
+ # Append preset options
+ for option in self.preset_options:
+ if not self.option_map.has_key(option.name):
+ self.add_option(option)
+
+ # Init .files list
+ self.files = []
+
+ # Start Application
+ try:
+ # Process startup
+ rc = self.startup()
+ if rc is not None:
+ raise SystemExit,rc
+
+ # Parse command line
+ rc = self.parse()
+ if rc is not None:
+ raise SystemExit,rc
+
+ # Start application
+ rc = self.main()
+ if rc is None:
+ rc = 0
+
+ except SystemExit,rc:
+ pass
+
+ except KeyboardInterrupt:
+ print
+ print '* User Break'
+ print
+ rc = 1
+
+ except self.InternalError:
+ print
+ print '* Internal Error (use --debug to display the traceback)'
+ if self.debug:
+ print
+ traceback.print_exc(20, sys.stdout)
+ elif self.verbose:
+ print ' %s: %s' % sys.exc_info()[:2]
+ print
+ rc = 1
+
+ raise SystemExit,rc
+
+ def add_option(self, option):
+
+ """ Add a new Option instance to the Application dynamically.
+
+ Note that this has to be done *before* .parse() is being
+ executed.
+
+ """
+ self.options.append(option)
+ self.option_map[option.name] = option
+
+ def startup(self):
+
+ """ Set user defined instance variables.
+
+ If this method returns anything other than None, the
+ process is terminated with the return value as exit code.
+
+ """
+ return None
+
+ def exit(self, rc=0):
+
+ """ Exit the program.
+
+ rc is used as exit code and passed back to the calling
+ program. It defaults to 0 which usually means: OK.
+
+ """
+ raise SystemExit, rc
+
+ def parse(self):
+
+ """ Parse the command line and fill in self.values and self.files.
+
+ After having parsed the options, the remaining command line
+ arguments are interpreted as files and passed to .handle_files()
+ for processing.
+
+ As final step the option handlers are called in the order
+ of the options given on the command line.
+
+ """
+ # Parse arguments
+ self.values = values = {}
+ for o in self.options:
+ if o.has_default:
+ values[o.prefix+o.name] = o.default
+ else:
+ values[o.prefix+o.name] = 0
+ flags,lflags = _getopt_flags(self.options)
+ try:
+ optlist,files = getopt.getopt(self.arguments,flags,lflags)
+ if self.globbing:
+ l = []
+ for f in files:
+ gf = glob.glob(f)
+ if not gf:
+ l.append(f)
+ else:
+ l[len(l):] = gf
+ files = l
+ self.optionlist = optlist
+ self.files = files + self.files
+ except getopt.error,why:
+ self.help(why)
+ sys.exit(1)
+
+ # Call file handler
+ rc = self.handle_files(self.files)
+ if rc is not None:
+ sys.exit(rc)
+
+ # Call option handlers
+ for optionname, value in optlist:
+
+ # Try to convert value to integer
+ try:
+ value = string.atoi(value)
+ except ValueError:
+ pass
+
+ # Find handler and call it (or count the number of option
+ # instances on the command line)
+ handlername = 'handle' + string.replace(optionname, '-', '_')
+ try:
+ handler = getattr(self, handlername)
+ except AttributeError:
+ if value == '':
+ # count the number of occurances
+ if values.has_key(optionname):
+ values[optionname] = values[optionname] + 1
+ else:
+ values[optionname] = 1
+ else:
+ values[optionname] = value
+ else:
+ rc = handler(value)
+ if rc is not None:
+ raise SystemExit, rc
+
+ # Apply final file check (for backward compatibility)
+ rc = self.check_files(self.files)
+ if rc is not None:
+ sys.exit(rc)
+
+ def check_files(self,filelist):
+
+ """ Apply some user defined checks on the files given in filelist.
+
+ This may modify filelist in place. A typical application
+ is checking that at least n files are given.
+
+ If this method returns anything other than None, the
+ process is terminated with the return value as exit code.
+
+ """
+ return None
+
+ def help(self,note=''):
+
+ self.print_header()
+ if self.synopsis:
+ print 'Synopsis:'
+ # To remain backward compatible:
+ try:
+ synopsis = self.synopsis % self.name
+ except (NameError, KeyError, TypeError):
+ synopsis = self.synopsis % self.__dict__
+ print ' ' + synopsis
+ print
+ self.print_options()
+ if self.version:
+ print 'Version:'
+ print ' %s' % self.version
+ print
+ if self.about:
+ print string.strip(self.about % self.__dict__)
+ print
+ if note:
+ print '-'*72
+ print 'Note:',note
+ print
+
+ def notice(self,note):
+
+ print '-'*72
+ print 'Note:',note
+ print '-'*72
+ print
+
+ def print_header(self):
+
+ print '-'*72
+ print self.header % self.__dict__
+ print '-'*72
+ print
+
+ def print_options(self):
+
+ options = self.options
+ print 'Options and default settings:'
+ if not options:
+ print ' None'
+ return
+ long = filter(lambda x: x.prefix == '--', options)
+ short = filter(lambda x: x.prefix == '-', options)
+ items = short + long
+ for o in options:
+ print ' ',o
+ print
+
+ #
+ # Example handlers:
+ #
+ # If a handler returns anything other than None, processing stops
+ # and the return value is passed to sys.exit() as argument.
+ #
+
+ # File handler
+ def handle_files(self,files):
+
+ """ This may process the files list in place.
+ """
+ return None
+
+ # Short option handler
+ def handle_h(self,arg):
+
+ self.help()
+ return 0
+
+ def handle_v(self, value):
+
+ """ Turn on verbose output.
+ """
+ self.verbose = 1
+
+ # Handlers for long options have two underscores in their name
+ def handle__help(self,arg):
+
+ self.help()
+ return 0
+
+ def handle__debug(self,arg):
+
+ self.debug = 1
+ # We don't want to catch internal errors:
+ self.InternalError = None
+
+ def handle__copyright(self,arg):
+
+ self.print_header()
+ print string.strip(self.copyright % self.__dict__)
+ print
+ return 0
+
+ def handle__examples(self,arg):
+
+ self.print_header()
+ if self.examples:
+ print 'Examples:'
+ print
+ print string.strip(self.examples % self.__dict__)
+ print
+ else:
+ print 'No examples available.'
+ print
+ return 0
+
+ def main(self):
+
+ """ Override this method as program entry point.
+
+ The return value is passed to sys.exit() as argument. If
+ it is None, 0 is assumed (meaning OK). Unhandled
+ exceptions are reported with exit status code 1 (see
+ __init__ for further details).
+
+ """
+ return None
+
+# Alias
+CommandLine = Application
+
+def _test():
+
+ class MyApplication(Application):
+ header = 'Test Application'
+ version = __version__
+ options = [Option('-v','verbose')]
+
+ def handle_v(self,arg):
+ print 'VERBOSE, Yeah !'
+
+ cmd = MyApplication()
+ if not cmd.values['-h']:
+ cmd.help()
+ print 'files:',cmd.files
+ print 'Bye...'
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Constructs.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Constructs.py
new file mode 100644
index 0000000000..b43e125f54
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Constructs.py
@@ -0,0 +1,564 @@
+from pybench import Test
+
+class IfThenElse(Test):
+
+ version = 2.0
+ operations = 30*3 # hard to say...
+ rounds = 150000
+
+ def test(self):
+
+ a,b,c = 1,2,3
+ for i in xrange(self.rounds):
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ if a == 1:
+ if b == 2:
+ if c != 3:
+ c = 3
+ b = 3
+ else:
+ c = 2
+ elif b == 3:
+ b = 2
+ a = 2
+ elif a == 2:
+ a = 3
+ else:
+ a = 1
+
+ def calibrate(self):
+
+ a,b,c = 1,2,3
+ for i in xrange(self.rounds):
+ pass
+
+class NestedForLoops(Test):
+
+ version = 2.0
+ operations = 1000*10*5
+ rounds = 300
+
+ def test(self):
+
+ l1 = range(1000)
+ l2 = range(10)
+ l3 = range(5)
+ for i in xrange(self.rounds):
+ for i in l1:
+ for j in l2:
+ for k in l3:
+ pass
+
+ def calibrate(self):
+
+ l1 = range(1000)
+ l2 = range(10)
+ l3 = range(5)
+ for i in xrange(self.rounds):
+ pass
+
+class ForLoops(Test):
+
+ version = 2.0
+ operations = 5 * 5
+ rounds = 10000
+
+ def test(self):
+
+ l1 = range(100)
+ for i in xrange(self.rounds):
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+ for i in l1:
+ pass
+
+ def calibrate(self):
+
+ l1 = range(1000)
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Dict.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Dict.py
new file mode 100644
index 0000000000..57ff97905e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Dict.py
@@ -0,0 +1,504 @@
+from pybench import Test
+
+class DictCreation(Test):
+
+ version = 2.0
+ operations = 5*(5 + 5)
+ rounds = 80000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ d1 = {}
+ d2 = {}
+ d3 = {}
+ d4 = {}
+ d5 = {}
+
+ d1 = {1:2,3:4,5:6}
+ d2 = {2:3,4:5,6:7}
+ d3 = {3:4,5:6,7:8}
+ d4 = {4:5,6:7,8:9}
+ d5 = {6:7,8:9,10:11}
+
+ d1 = {}
+ d2 = {}
+ d3 = {}
+ d4 = {}
+ d5 = {}
+
+ d1 = {1:2,3:4,5:6}
+ d2 = {2:3,4:5,6:7}
+ d3 = {3:4,5:6,7:8}
+ d4 = {4:5,6:7,8:9}
+ d5 = {6:7,8:9,10:11}
+
+ d1 = {}
+ d2 = {}
+ d3 = {}
+ d4 = {}
+ d5 = {}
+
+ d1 = {1:2,3:4,5:6}
+ d2 = {2:3,4:5,6:7}
+ d3 = {3:4,5:6,7:8}
+ d4 = {4:5,6:7,8:9}
+ d5 = {6:7,8:9,10:11}
+
+ d1 = {}
+ d2 = {}
+ d3 = {}
+ d4 = {}
+ d5 = {}
+
+ d1 = {1:2,3:4,5:6}
+ d2 = {2:3,4:5,6:7}
+ d3 = {3:4,5:6,7:8}
+ d4 = {4:5,6:7,8:9}
+ d5 = {6:7,8:9,10:11}
+
+ d1 = {}
+ d2 = {}
+ d3 = {}
+ d4 = {}
+ d5 = {}
+
+ d1 = {1:2,3:4,5:6}
+ d2 = {2:3,4:5,6:7}
+ d3 = {3:4,5:6,7:8}
+ d4 = {4:5,6:7,8:9}
+ d5 = {6:7,8:9,10:11}
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+class DictWithStringKeys(Test):
+
+ version = 2.0
+ operations = 5*(6 + 6)
+ rounds = 200000
+
+ def test(self):
+
+ d = {}
+
+ for i in xrange(self.rounds):
+
+ d['abc'] = 1
+ d['def'] = 2
+ d['ghi'] = 3
+ d['jkl'] = 4
+ d['mno'] = 5
+ d['pqr'] = 6
+
+ d['abc']
+ d['def']
+ d['ghi']
+ d['jkl']
+ d['mno']
+ d['pqr']
+
+ d['abc'] = 1
+ d['def'] = 2
+ d['ghi'] = 3
+ d['jkl'] = 4
+ d['mno'] = 5
+ d['pqr'] = 6
+
+ d['abc']
+ d['def']
+ d['ghi']
+ d['jkl']
+ d['mno']
+ d['pqr']
+
+ d['abc'] = 1
+ d['def'] = 2
+ d['ghi'] = 3
+ d['jkl'] = 4
+ d['mno'] = 5
+ d['pqr'] = 6
+
+ d['abc']
+ d['def']
+ d['ghi']
+ d['jkl']
+ d['mno']
+ d['pqr']
+
+ d['abc'] = 1
+ d['def'] = 2
+ d['ghi'] = 3
+ d['jkl'] = 4
+ d['mno'] = 5
+ d['pqr'] = 6
+
+ d['abc']
+ d['def']
+ d['ghi']
+ d['jkl']
+ d['mno']
+ d['pqr']
+
+ d['abc'] = 1
+ d['def'] = 2
+ d['ghi'] = 3
+ d['jkl'] = 4
+ d['mno'] = 5
+ d['pqr'] = 6
+
+ d['abc']
+ d['def']
+ d['ghi']
+ d['jkl']
+ d['mno']
+ d['pqr']
+
+ def calibrate(self):
+
+ d = {}
+
+ for i in xrange(self.rounds):
+ pass
+
+class DictWithFloatKeys(Test):
+
+ version = 2.0
+ operations = 5*(6 + 6)
+ rounds = 150000
+
+ def test(self):
+
+ d = {}
+
+ for i in xrange(self.rounds):
+
+ d[1.234] = 1
+ d[2.345] = 2
+ d[3.456] = 3
+ d[4.567] = 4
+ d[5.678] = 5
+ d[6.789] = 6
+
+ d[1.234]
+ d[2.345]
+ d[3.456]
+ d[4.567]
+ d[5.678]
+ d[6.789]
+
+ d[1.234] = 1
+ d[2.345] = 2
+ d[3.456] = 3
+ d[4.567] = 4
+ d[5.678] = 5
+ d[6.789] = 6
+
+ d[1.234]
+ d[2.345]
+ d[3.456]
+ d[4.567]
+ d[5.678]
+ d[6.789]
+
+ d[1.234] = 1
+ d[2.345] = 2
+ d[3.456] = 3
+ d[4.567] = 4
+ d[5.678] = 5
+ d[6.789] = 6
+
+ d[1.234]
+ d[2.345]
+ d[3.456]
+ d[4.567]
+ d[5.678]
+ d[6.789]
+
+ d[1.234] = 1
+ d[2.345] = 2
+ d[3.456] = 3
+ d[4.567] = 4
+ d[5.678] = 5
+ d[6.789] = 6
+
+ d[1.234]
+ d[2.345]
+ d[3.456]
+ d[4.567]
+ d[5.678]
+ d[6.789]
+
+ d[1.234] = 1
+ d[2.345] = 2
+ d[3.456] = 3
+ d[4.567] = 4
+ d[5.678] = 5
+ d[6.789] = 6
+
+ d[1.234]
+ d[2.345]
+ d[3.456]
+ d[4.567]
+ d[5.678]
+ d[6.789]
+
+ def calibrate(self):
+
+ d = {}
+
+ for i in xrange(self.rounds):
+ pass
+
+class DictWithIntegerKeys(Test):
+
+ version = 2.0
+ operations = 5*(6 + 6)
+ rounds = 200000
+
+ def test(self):
+
+ d = {}
+
+ for i in xrange(self.rounds):
+
+ d[1] = 1
+ d[2] = 2
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+ d[6] = 6
+
+ d[1]
+ d[2]
+ d[3]
+ d[4]
+ d[5]
+ d[6]
+
+ d[1] = 1
+ d[2] = 2
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+ d[6] = 6
+
+ d[1]
+ d[2]
+ d[3]
+ d[4]
+ d[5]
+ d[6]
+
+ d[1] = 1
+ d[2] = 2
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+ d[6] = 6
+
+ d[1]
+ d[2]
+ d[3]
+ d[4]
+ d[5]
+ d[6]
+
+ d[1] = 1
+ d[2] = 2
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+ d[6] = 6
+
+ d[1]
+ d[2]
+ d[3]
+ d[4]
+ d[5]
+ d[6]
+
+ d[1] = 1
+ d[2] = 2
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+ d[6] = 6
+
+ d[1]
+ d[2]
+ d[3]
+ d[4]
+ d[5]
+ d[6]
+
+ def calibrate(self):
+
+ d = {}
+
+ for i in xrange(self.rounds):
+ pass
+
+class SimpleDictManipulation(Test):
+
+ version = 2.0
+ operations = 5*(6 + 6 + 6 + 6)
+ rounds = 100000
+
+ def test(self):
+
+ d = {}
+ has_key = d.has_key
+
+ for i in xrange(self.rounds):
+
+ d[0] = 3
+ d[1] = 4
+ d[2] = 5
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+
+ x = d[0]
+ x = d[1]
+ x = d[2]
+ x = d[3]
+ x = d[4]
+ x = d[5]
+
+ has_key(0)
+ has_key(2)
+ has_key(4)
+ has_key(6)
+ has_key(8)
+ has_key(10)
+
+ del d[0]
+ del d[1]
+ del d[2]
+ del d[3]
+ del d[4]
+ del d[5]
+
+ d[0] = 3
+ d[1] = 4
+ d[2] = 5
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+
+ x = d[0]
+ x = d[1]
+ x = d[2]
+ x = d[3]
+ x = d[4]
+ x = d[5]
+
+ has_key(0)
+ has_key(2)
+ has_key(4)
+ has_key(6)
+ has_key(8)
+ has_key(10)
+
+ del d[0]
+ del d[1]
+ del d[2]
+ del d[3]
+ del d[4]
+ del d[5]
+
+ d[0] = 3
+ d[1] = 4
+ d[2] = 5
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+
+ x = d[0]
+ x = d[1]
+ x = d[2]
+ x = d[3]
+ x = d[4]
+ x = d[5]
+
+ has_key(0)
+ has_key(2)
+ has_key(4)
+ has_key(6)
+ has_key(8)
+ has_key(10)
+
+ del d[0]
+ del d[1]
+ del d[2]
+ del d[3]
+ del d[4]
+ del d[5]
+
+ d[0] = 3
+ d[1] = 4
+ d[2] = 5
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+
+ x = d[0]
+ x = d[1]
+ x = d[2]
+ x = d[3]
+ x = d[4]
+ x = d[5]
+
+ has_key(0)
+ has_key(2)
+ has_key(4)
+ has_key(6)
+ has_key(8)
+ has_key(10)
+
+ del d[0]
+ del d[1]
+ del d[2]
+ del d[3]
+ del d[4]
+ del d[5]
+
+ d[0] = 3
+ d[1] = 4
+ d[2] = 5
+ d[3] = 3
+ d[4] = 4
+ d[5] = 5
+
+ x = d[0]
+ x = d[1]
+ x = d[2]
+ x = d[3]
+ x = d[4]
+ x = d[5]
+
+ has_key(0)
+ has_key(2)
+ has_key(4)
+ has_key(6)
+ has_key(8)
+ has_key(10)
+
+ del d[0]
+ del d[1]
+ del d[2]
+ del d[3]
+ del d[4]
+ del d[5]
+
+ def calibrate(self):
+
+ d = {}
+ has_key = d.has_key
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Exceptions.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Exceptions.py
new file mode 100644
index 0000000000..4b2456f9fd
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Exceptions.py
@@ -0,0 +1,699 @@
+from pybench import Test
+
+class TryRaiseExcept(Test):
+
+ version = 2.0
+ operations = 2 + 3 + 3
+ rounds = 80000
+
+ def test(self):
+
+ error = ValueError
+
+ for i in xrange(self.rounds):
+ try:
+ raise error
+ except:
+ pass
+ try:
+ raise error
+ except:
+ pass
+ try:
+ raise error,"something"
+ except:
+ pass
+ try:
+ raise error,"something"
+ except:
+ pass
+ try:
+ raise error,"something"
+ except:
+ pass
+ try:
+ raise error("something")
+ except:
+ pass
+ try:
+ raise error("something")
+ except:
+ pass
+ try:
+ raise error("something")
+ except:
+ pass
+
+ def calibrate(self):
+
+ error = ValueError
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class TryExcept(Test):
+
+ version = 2.0
+ operations = 15 * 10
+ rounds = 150000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+ try:
+ pass
+ except:
+ pass
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+### Test to make Fredrik happy...
+
+if __name__ == '__main__':
+ import timeit
+ timeit.TestClass = TryRaiseExcept
+ timeit.main(['-s', 'test = TestClass(); test.rounds = 1000',
+ 'test.test()'])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Imports.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Imports.py
new file mode 100644
index 0000000000..b9677d45a9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Imports.py
@@ -0,0 +1,138 @@
+from pybench import Test
+
+# First imports:
+import os
+import package.submodule
+
+class SecondImport(Test):
+
+ version = 2.0
+ operations = 5 * 5
+ rounds = 40000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+ import os
+ import os
+ import os
+ import os
+ import os
+
+ import os
+ import os
+ import os
+ import os
+ import os
+
+ import os
+ import os
+ import os
+ import os
+ import os
+
+ import os
+ import os
+ import os
+ import os
+ import os
+
+ import os
+ import os
+ import os
+ import os
+ import os
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class SecondPackageImport(Test):
+
+ version = 2.0
+ operations = 5 * 5
+ rounds = 40000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+ import package
+ import package
+ import package
+ import package
+ import package
+
+ import package
+ import package
+ import package
+ import package
+ import package
+
+ import package
+ import package
+ import package
+ import package
+ import package
+
+ import package
+ import package
+ import package
+ import package
+ import package
+
+ import package
+ import package
+ import package
+ import package
+ import package
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+class SecondSubmoduleImport(Test):
+
+ version = 2.0
+ operations = 5 * 5
+ rounds = 40000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+ import package.submodule
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Instances.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Instances.py
new file mode 100644
index 0000000000..27cddfa200
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Instances.py
@@ -0,0 +1,66 @@
+from pybench import Test
+
+class CreateInstances(Test):
+
+ version = 2.0
+ operations = 3 + 7 + 4
+ rounds = 80000
+
+ def test(self):
+
+ class c:
+ pass
+
+ class d:
+ def __init__(self,a,b,c):
+ self.a = a
+ self.b = b
+ self.c = c
+
+ class e:
+ def __init__(self,a,b,c=4):
+ self.a = a
+ self.b = b
+ self.c = c
+ self.d = a
+ self.e = b
+ self.f = c
+
+ for i in xrange(self.rounds):
+ o = c()
+ o1 = c()
+ o2 = c()
+ p = d(i,i,3)
+ p1 = d(i,i,3)
+ p2 = d(i,3,3)
+ p3 = d(3,i,3)
+ p4 = d(i,i,i)
+ p5 = d(3,i,3)
+ p6 = d(i,i,i)
+ q = e(i,i,3)
+ q1 = e(i,i,3)
+ q2 = e(i,i,3)
+ q3 = e(i,i)
+
+ def calibrate(self):
+
+ class c:
+ pass
+
+ class d:
+ def __init__(self,a,b,c):
+ self.a = a
+ self.b = b
+ self.c = c
+
+ class e:
+ def __init__(self,a,b,c=4):
+ self.a = a
+ self.b = b
+ self.c = c
+ self.d = a
+ self.e = b
+ self.f = c
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/LICENSE b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/LICENSE
new file mode 100644
index 0000000000..ef44f6f140
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/LICENSE
@@ -0,0 +1,25 @@
+pybench License
+---------------
+
+This copyright notice and license applies to all files in the pybench
+directory of the pybench distribution.
+
+Copyright (c), 1997-2006, Marc-Andre Lemburg (mal@lemburg.com)
+Copyright (c), 2000-2006, eGenix.com Software GmbH (info@egenix.com)
+
+ All Rights Reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee or royalty is hereby
+granted, provided that the above copyright notice appear in all copies
+and that both that copyright notice and this permission notice appear
+in supporting documentation or portions thereof, including
+modifications, that you make.
+
+THE AUTHOR MARC-ANDRE LEMBURG DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
+INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lists.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lists.py
new file mode 100644
index 0000000000..f784a638c6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lists.py
@@ -0,0 +1,350 @@
+from pybench import Test
+
+class SimpleListManipulation(Test):
+
+ version = 2.0
+ operations = 5* (6 + 6 + 6)
+ rounds = 130000
+
+ def test(self):
+
+ l = []
+ append = l.append
+
+ for i in xrange(self.rounds):
+
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ x = l[0]
+ x = l[1]
+ x = l[2]
+ x = l[3]
+ x = l[4]
+ x = l[5]
+
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ x = l[0]
+ x = l[1]
+ x = l[2]
+ x = l[3]
+ x = l[4]
+ x = l[5]
+
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ x = l[0]
+ x = l[1]
+ x = l[2]
+ x = l[3]
+ x = l[4]
+ x = l[5]
+
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ x = l[0]
+ x = l[1]
+ x = l[2]
+ x = l[3]
+ x = l[4]
+ x = l[5]
+
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ x = l[0]
+ x = l[1]
+ x = l[2]
+ x = l[3]
+ x = l[4]
+ x = l[5]
+
+ if len(l) > 10000:
+ # cut down the size
+ del l[:]
+
+ def calibrate(self):
+
+ l = []
+ append = l.append
+
+ for i in xrange(self.rounds):
+ pass
+
+class ListSlicing(Test):
+
+ version = 2.0
+ operations = 25*(3+1+2+1)
+ rounds = 800
+
+ def test(self):
+
+ n = range(100)
+ r = range(25)
+
+ for i in xrange(self.rounds):
+
+ l = n[:]
+
+ for j in r:
+
+ m = l[50:]
+ m = l[:25]
+ m = l[50:55]
+ l[:3] = n
+ m = l[:-1]
+ m = l[1:]
+ l[-1:] = n
+
+ def calibrate(self):
+
+ n = range(100)
+ r = range(25)
+
+ for i in xrange(self.rounds):
+ for j in r:
+ pass
+
+class SmallLists(Test):
+
+ version = 2.0
+ operations = 5*(1+ 6 + 6 + 3 + 1)
+ rounds = 80000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ l = []
+
+ append = l.append
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ l[:3] = [1,2,3]
+ m = l[:-1]
+ m = l[1:]
+
+ l[-1:] = [4,5,6]
+
+ l = []
+
+ append = l.append
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ l[:3] = [1,2,3]
+ m = l[:-1]
+ m = l[1:]
+
+ l[-1:] = [4,5,6]
+
+ l = []
+
+ append = l.append
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ l[:3] = [1,2,3]
+ m = l[:-1]
+ m = l[1:]
+
+ l[-1:] = [4,5,6]
+
+ l = []
+
+ append = l.append
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ l[:3] = [1,2,3]
+ m = l[:-1]
+ m = l[1:]
+
+ l[-1:] = [4,5,6]
+
+ l = []
+
+ append = l.append
+ append(2)
+ append(3)
+ append(4)
+ append(2)
+ append(3)
+ append(4)
+
+ l[0] = 3
+ l[1] = 4
+ l[2] = 5
+ l[3] = 3
+ l[4] = 4
+ l[5] = 5
+
+ l[:3] = [1,2,3]
+ m = l[:-1]
+ m = l[1:]
+
+ l[-1:] = [4,5,6]
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+class SimpleListComprehensions(Test):
+
+ version = 2.0
+ operations = 6
+ rounds = 20000
+
+ def test(self):
+
+ n = range(10) * 10
+
+ for i in xrange(self.rounds):
+ l = [x for x in n]
+ l = [x for x in n if x]
+ l = [x for x in n if not x]
+
+ l = [x for x in n]
+ l = [x for x in n if x]
+ l = [x for x in n if not x]
+
+ def calibrate(self):
+
+ n = range(10) * 10
+
+ for i in xrange(self.rounds):
+ pass
+
+class NestedListComprehensions(Test):
+
+ version = 2.0
+ operations = 6
+ rounds = 20000
+
+ def test(self):
+
+ m = range(10)
+ n = range(10)
+
+ for i in xrange(self.rounds):
+ l = [x for x in n for y in m]
+ l = [y for x in n for y in m]
+
+ l = [x for x in n for y in m if y]
+ l = [y for x in n for y in m if x]
+
+ l = [x for x in n for y in m if not y]
+ l = [y for x in n for y in m if not x]
+
+ def calibrate(self):
+
+ m = range(10)
+ n = range(10)
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lookups.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lookups.py
new file mode 100644
index 0000000000..76ac6aea49
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Lookups.py
@@ -0,0 +1,945 @@
+from pybench import Test
+
+class SpecialClassAttribute(Test):
+
+ version = 2.0
+ operations = 5*(12 + 12)
+ rounds = 100000
+
+ def test(self):
+
+ class c:
+ pass
+
+ for i in xrange(self.rounds):
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ c.__a = 2
+ c.__b = 3
+ c.__c = 4
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ x = c.__a
+ x = c.__b
+ x = c.__c
+
+ def calibrate(self):
+
+ class c:
+ pass
+
+ for i in xrange(self.rounds):
+ pass
+
+class NormalClassAttribute(Test):
+
+ version = 2.0
+ operations = 5*(12 + 12)
+ rounds = 100000
+
+ def test(self):
+
+ class c:
+ pass
+
+ for i in xrange(self.rounds):
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+ c.a = 2
+ c.b = 3
+ c.c = 4
+
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ x = c.a
+ x = c.b
+ x = c.c
+
+ def calibrate(self):
+
+ class c:
+ pass
+
+ for i in xrange(self.rounds):
+ pass
+
+class SpecialInstanceAttribute(Test):
+
+ version = 2.0
+ operations = 5*(12 + 12)
+ rounds = 100000
+
+ def test(self):
+
+ class c:
+ pass
+ o = c()
+
+ for i in xrange(self.rounds):
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+ o.__a__ = 2
+ o.__b__ = 3
+ o.__c__ = 4
+
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ x = o.__a__
+ x = o.__b__
+ x = o.__c__
+
+ def calibrate(self):
+
+ class c:
+ pass
+ o = c()
+
+ for i in xrange(self.rounds):
+ pass
+
+class NormalInstanceAttribute(Test):
+
+ version = 2.0
+ operations = 5*(12 + 12)
+ rounds = 100000
+
+ def test(self):
+
+ class c:
+ pass
+ o = c()
+
+ for i in xrange(self.rounds):
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+ o.a = 2
+ o.b = 3
+ o.c = 4
+
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ x = o.a
+ x = o.b
+ x = o.c
+
+ def calibrate(self):
+
+ class c:
+ pass
+ o = c()
+
+ for i in xrange(self.rounds):
+ pass
+
+class BuiltinMethodLookup(Test):
+
+ version = 2.0
+ operations = 5*(3*5 + 3*5)
+ rounds = 70000
+
+ def test(self):
+
+ l = []
+ d = {}
+
+ for i in xrange(self.rounds):
+
+ l.append
+ l.append
+ l.append
+ l.append
+ l.append
+
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+
+ d.items
+ d.items
+ d.items
+ d.items
+ d.items
+
+ d.get
+ d.get
+ d.get
+ d.get
+ d.get
+
+ l.append
+ l.append
+ l.append
+ l.append
+ l.append
+
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+
+ d.items
+ d.items
+ d.items
+ d.items
+ d.items
+
+ d.get
+ d.get
+ d.get
+ d.get
+ d.get
+
+ l.append
+ l.append
+ l.append
+ l.append
+ l.append
+
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+
+ d.items
+ d.items
+ d.items
+ d.items
+ d.items
+
+ d.get
+ d.get
+ d.get
+ d.get
+ d.get
+
+ l.append
+ l.append
+ l.append
+ l.append
+ l.append
+
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+
+ d.items
+ d.items
+ d.items
+ d.items
+ d.items
+
+ d.get
+ d.get
+ d.get
+ d.get
+ d.get
+
+ l.append
+ l.append
+ l.append
+ l.append
+ l.append
+
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+ l.insert
+
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+ l.sort
+
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+ d.has_key
+
+ d.items
+ d.items
+ d.items
+ d.items
+ d.items
+
+ d.get
+ d.get
+ d.get
+ d.get
+ d.get
+
+ def calibrate(self):
+
+ l = []
+ d = {}
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/NewInstances.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/NewInstances.py
new file mode 100644
index 0000000000..db7ed3b71b
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/NewInstances.py
@@ -0,0 +1,75 @@
+from pybench import Test
+
+# Check for new-style class support:
+try:
+ class c(object):
+ pass
+except NameError:
+ raise ImportError
+
+###
+
+class CreateNewInstances(Test):
+
+ version = 2.0
+ operations = 3 + 7 + 4
+ rounds = 60000
+
+ def test(self):
+
+ class c(object):
+ pass
+
+ class d(object):
+ def __init__(self,a,b,c):
+ self.a = a
+ self.b = b
+ self.c = c
+
+ class e(object):
+ def __init__(self,a,b,c=4):
+ self.a = a
+ self.b = b
+ self.c = c
+ self.d = a
+ self.e = b
+ self.f = c
+
+ for i in xrange(self.rounds):
+ o = c()
+ o1 = c()
+ o2 = c()
+ p = d(i,i,3)
+ p1 = d(i,i,3)
+ p2 = d(i,3,3)
+ p3 = d(3,i,3)
+ p4 = d(i,i,i)
+ p5 = d(3,i,3)
+ p6 = d(i,i,i)
+ q = e(i,i,3)
+ q1 = e(i,i,3)
+ q2 = e(i,i,3)
+ q3 = e(i,i)
+
+ def calibrate(self):
+
+ class c(object):
+ pass
+
+ class d(object):
+ def __init__(self,a,b,c):
+ self.a = a
+ self.b = b
+ self.c = c
+
+ class e(object):
+ def __init__(self,a,b,c=4):
+ self.a = a
+ self.b = b
+ self.c = c
+ self.d = a
+ self.e = b
+ self.f = c
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Numbers.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Numbers.py
new file mode 100644
index 0000000000..cb41742055
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Numbers.py
@@ -0,0 +1,784 @@
+from pybench import Test
+
+class CompareIntegers(Test):
+
+ version = 2.0
+ operations = 30 * 5
+ rounds = 120000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ 2 < 3
+ 2 > 3
+ 2 == 3
+ 2 > 3
+ 2 < 3
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CompareFloats(Test):
+
+ version = 2.0
+ operations = 30 * 5
+ rounds = 80000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ 2.1 < 3.31
+ 2.1 > 3.31
+ 2.1 == 3.31
+ 2.1 > 3.31
+ 2.1 < 3.31
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CompareFloatsIntegers(Test):
+
+ version = 2.0
+ operations = 30 * 5
+ rounds = 60000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ 2.1 < 4
+ 2.1 > 4
+ 2.1 == 4
+ 2.1 > 4
+ 2.1 < 4
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CompareLongs(Test):
+
+ version = 2.0
+ operations = 30 * 5
+ rounds = 70000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ 1234567890L < 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L == 3456789012345L
+ 1234567890L > 3456789012345L
+ 1234567890L < 3456789012345L
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/README
new file mode 100644
index 0000000000..f4f34f641a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/README
@@ -0,0 +1,368 @@
+________________________________________________________________________
+
+PYBENCH - A Python Benchmark Suite
+________________________________________________________________________
+
+ Extendable suite of of low-level benchmarks for measuring
+ the performance of the Python implementation
+ (interpreter, compiler or VM).
+
+pybench is a collection of tests that provides a standardized way to
+measure the performance of Python implementations. It takes a very
+close look at different aspects of Python programs and let's you
+decide which factors are more important to you than others, rather
+than wrapping everything up in one number, like the other performance
+tests do (e.g. pystone which is included in the Python Standard
+Library).
+
+pybench has been used in the past by several Python developers to
+track down performance bottlenecks or to demonstrate the impact of
+optimizations and new features in Python.
+
+The command line interface for pybench is the file pybench.py. Run
+this script with option '--help' to get a listing of the possible
+options. Without options, pybench will simply execute the benchmark
+and then print out a report to stdout.
+
+
+Micro-Manual
+------------
+
+Run 'pybench.py -h' to see the help screen. Run 'pybench.py' to run
+the benchmark suite using default settings and 'pybench.py -f <file>'
+to have it store the results in a file too.
+
+It is usually a good idea to run pybench.py multiple times to see
+whether the environment, timers and benchmark run-times are suitable
+for doing benchmark tests.
+
+You can use the comparison feature of pybench.py ('pybench.py -c
+<file>') to check how well the system behaves in comparison to a
+reference run.
+
+If the differences are well below 10% for each test, then you have a
+system that is good for doing benchmark testings. Of you get random
+differences of more than 10% or significant differences between the
+values for minimum and average time, then you likely have some
+background processes running which cause the readings to become
+inconsistent. Examples include: web-browsers, email clients, RSS
+readers, music players, backup programs, etc.
+
+If you are only interested in a few tests of the whole suite, you can
+use the filtering option, e.g. 'pybench.py -t string' will only
+run/show the tests that have 'string' in their name.
+
+This is the current output of pybench.py --help:
+
+"""
+------------------------------------------------------------------------
+PYBENCH - a benchmark test suite for Python interpreters/compilers.
+------------------------------------------------------------------------
+
+Synopsis:
+ pybench.py [option] files...
+
+Options and default settings:
+ -n arg number of rounds (10)
+ -f arg save benchmark to file arg ()
+ -c arg compare benchmark with the one in file arg ()
+ -s arg show benchmark in file arg, then exit ()
+ -w arg set warp factor to arg (10)
+ -t arg run only tests with names matching arg ()
+ -C arg set the number of calibration runs to arg (20)
+ -d hide noise in comparisons (0)
+ -v verbose output (not recommended) (0)
+ --with-gc enable garbage collection (0)
+ --with-syscheck use default sys check interval (0)
+ --timer arg use given timer (time.time)
+ -h show this help text
+ --help show this help text
+ --debug enable debugging
+ --copyright show copyright
+ --examples show examples of usage
+
+Version:
+ 2.0
+
+The normal operation is to run the suite and display the
+results. Use -f to save them for later reuse or comparisons.
+
+Available timers:
+
+ time.time
+ time.clock
+ systimes.processtime
+
+Examples:
+
+python2.1 pybench.py -f p21.pybench
+python2.5 pybench.py -f p25.pybench
+python pybench.py -s p25.pybench -c p21.pybench
+"""
+
+License
+-------
+
+See LICENSE file.
+
+
+Sample output
+-------------
+
+"""
+-------------------------------------------------------------------------------
+PYBENCH 2.0
+-------------------------------------------------------------------------------
+* using Python 2.4.2
+* disabled garbage collection
+* system check interval set to maximum: 2147483647
+* using timer: time.time
+
+Calibrating tests. Please wait...
+
+Running 10 round(s) of the suite at warp factor 10:
+
+* Round 1 done in 6.388 seconds.
+* Round 2 done in 6.485 seconds.
+* Round 3 done in 6.786 seconds.
+...
+* Round 10 done in 6.546 seconds.
+
+-------------------------------------------------------------------------------
+Benchmark: 2006-06-12 12:09:25
+-------------------------------------------------------------------------------
+
+ Rounds: 10
+ Warp: 10
+ Timer: time.time
+
+ Machine Details:
+ Platform ID: Linux-2.6.8-24.19-default-x86_64-with-SuSE-9.2-x86-64
+ Processor: x86_64
+
+ Python:
+ Executable: /usr/local/bin/python
+ Version: 2.4.2
+ Compiler: GCC 3.3.4 (pre 3.3.5 20040809)
+ Bits: 64bit
+ Build: Oct 1 2005 15:24:35 (#1)
+ Unicode: UCS2
+
+
+Test minimum average operation overhead
+-------------------------------------------------------------------------------
+ BuiltinFunctionCalls: 126ms 145ms 0.28us 0.274ms
+ BuiltinMethodLookup: 124ms 130ms 0.12us 0.316ms
+ CompareFloats: 109ms 110ms 0.09us 0.361ms
+ CompareFloatsIntegers: 100ms 104ms 0.12us 0.271ms
+ CompareIntegers: 137ms 138ms 0.08us 0.542ms
+ CompareInternedStrings: 124ms 127ms 0.08us 1.367ms
+ CompareLongs: 100ms 104ms 0.10us 0.316ms
+ CompareStrings: 111ms 115ms 0.12us 0.929ms
+ CompareUnicode: 108ms 128ms 0.17us 0.693ms
+ ConcatStrings: 142ms 155ms 0.31us 0.562ms
+ ConcatUnicode: 119ms 127ms 0.42us 0.384ms
+ CreateInstances: 123ms 128ms 1.14us 0.367ms
+ CreateNewInstances: 121ms 126ms 1.49us 0.335ms
+ CreateStringsWithConcat: 130ms 135ms 0.14us 0.916ms
+ CreateUnicodeWithConcat: 130ms 135ms 0.34us 0.361ms
+ DictCreation: 108ms 109ms 0.27us 0.361ms
+ DictWithFloatKeys: 149ms 153ms 0.17us 0.678ms
+ DictWithIntegerKeys: 124ms 126ms 0.11us 0.915ms
+ DictWithStringKeys: 114ms 117ms 0.10us 0.905ms
+ ForLoops: 110ms 111ms 4.46us 0.063ms
+ IfThenElse: 118ms 119ms 0.09us 0.685ms
+ ListSlicing: 116ms 120ms 8.59us 0.103ms
+ NestedForLoops: 125ms 137ms 0.09us 0.019ms
+ NormalClassAttribute: 124ms 136ms 0.11us 0.457ms
+ NormalInstanceAttribute: 110ms 117ms 0.10us 0.454ms
+ PythonFunctionCalls: 107ms 113ms 0.34us 0.271ms
+ PythonMethodCalls: 140ms 149ms 0.66us 0.141ms
+ Recursion: 156ms 166ms 3.32us 0.452ms
+ SecondImport: 112ms 118ms 1.18us 0.180ms
+ SecondPackageImport: 118ms 127ms 1.27us 0.180ms
+ SecondSubmoduleImport: 140ms 151ms 1.51us 0.180ms
+ SimpleComplexArithmetic: 128ms 139ms 0.16us 0.361ms
+ SimpleDictManipulation: 134ms 136ms 0.11us 0.452ms
+ SimpleFloatArithmetic: 110ms 113ms 0.09us 0.571ms
+ SimpleIntFloatArithmetic: 106ms 111ms 0.08us 0.548ms
+ SimpleIntegerArithmetic: 106ms 109ms 0.08us 0.544ms
+ SimpleListManipulation: 103ms 113ms 0.10us 0.587ms
+ SimpleLongArithmetic: 112ms 118ms 0.18us 0.271ms
+ SmallLists: 105ms 116ms 0.17us 0.366ms
+ SmallTuples: 108ms 128ms 0.24us 0.406ms
+ SpecialClassAttribute: 119ms 136ms 0.11us 0.453ms
+ SpecialInstanceAttribute: 143ms 155ms 0.13us 0.454ms
+ StringMappings: 115ms 121ms 0.48us 0.405ms
+ StringPredicates: 120ms 129ms 0.18us 2.064ms
+ StringSlicing: 111ms 127ms 0.23us 0.781ms
+ TryExcept: 125ms 126ms 0.06us 0.681ms
+ TryRaiseExcept: 133ms 137ms 2.14us 0.361ms
+ TupleSlicing: 117ms 120ms 0.46us 0.066ms
+ UnicodeMappings: 156ms 160ms 4.44us 0.429ms
+ UnicodePredicates: 117ms 121ms 0.22us 2.487ms
+ UnicodeProperties: 115ms 153ms 0.38us 2.070ms
+ UnicodeSlicing: 126ms 129ms 0.26us 0.689ms
+-------------------------------------------------------------------------------
+Totals: 6283ms 6673ms
+"""
+________________________________________________________________________
+
+Writing New Tests
+________________________________________________________________________
+
+pybench tests are simple modules defining one or more pybench.Test
+subclasses.
+
+Writing a test essentially boils down to providing two methods:
+.test() which runs .rounds number of .operations test operations each
+and .calibrate() which does the same except that it doesn't actually
+execute the operations.
+
+
+Here's an example:
+------------------
+
+from pybench import Test
+
+class IntegerCounting(Test):
+
+ # Version number of the test as float (x.yy); this is important
+ # for comparisons of benchmark runs - tests with unequal version
+ # number will not get compared.
+ version = 1.0
+
+ # The number of abstract operations done in each round of the
+ # test. An operation is the basic unit of what you want to
+ # measure. The benchmark will output the amount of run-time per
+ # operation. Note that in order to raise the measured timings
+ # significantly above noise level, it is often required to repeat
+ # sets of operations more than once per test round. The measured
+ # overhead per test round should be less than 1 second.
+ operations = 20
+
+ # Number of rounds to execute per test run. This should be
+ # adjusted to a figure that results in a test run-time of between
+ # 1-2 seconds (at warp 1).
+ rounds = 100000
+
+ def test(self):
+
+ """ Run the test.
+
+ The test needs to run self.rounds executing
+ self.operations number of operations each.
+
+ """
+ # Init the test
+ a = 1
+
+ # Run test rounds
+ #
+ # NOTE: Use xrange() for all test loops unless you want to face
+ # a 20MB process !
+ #
+ for i in xrange(self.rounds):
+
+ # Repeat the operations per round to raise the run-time
+ # per operation significantly above the noise level of the
+ # for-loop overhead.
+
+ # Execute 20 operations (a += 1):
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+ a += 1
+
+ def calibrate(self):
+
+ """ Calibrate the test.
+
+ This method should execute everything that is needed to
+ setup and run the test - except for the actual operations
+ that you intend to measure. pybench uses this method to
+ measure the test implementation overhead.
+
+ """
+ # Init the test
+ a = 1
+
+ # Run test rounds (without actually doing any operation)
+ for i in xrange(self.rounds):
+
+ # Skip the actual execution of the operations, since we
+ # only want to measure the test's administration overhead.
+ pass
+
+Registering a new test module
+-----------------------------
+
+To register a test module with pybench, the classes need to be
+imported into the pybench.Setup module. pybench will then scan all the
+symbols defined in that module for subclasses of pybench.Test and
+automatically add them to the benchmark suite.
+
+
+Breaking Comparability
+----------------------
+
+If a change is made to any individual test that means it is no
+longer strictly comparable with previous runs, the '.version' class
+variable should be updated. Therefafter, comparisons with previous
+versions of the test will list as "n/a" to reflect the change.
+
+
+Version History
+---------------
+
+ 2.0: rewrote parts of pybench which resulted in more repeatable
+ timings:
+ - made timer a parameter
+ - changed the platform default timer to use high-resolution
+ timers rather than process timers (which have a much lower
+ resolution)
+ - added option to select timer
+ - added process time timer (using systimes.py)
+ - changed to use min() as timing estimator (average
+ is still taken as well to provide an idea of the difference)
+ - garbage collection is turned off per default
+ - sys check interval is set to the highest possible value
+ - calibration is now a separate step and done using
+ a different strategy that allows measuring the test
+ overhead more accurately
+ - modified the tests to each give a run-time of between
+ 100-200ms using warp 10
+ - changed default warp factor to 10 (from 20)
+ - compared results with timeit.py and confirmed measurements
+ - bumped all test versions to 2.0
+ - updated platform.py to the latest version
+ - changed the output format a bit to make it look
+ nicer
+ - refactored the APIs somewhat
+ 1.3+: Steve Holden added the NewInstances test and the filtering
+ option during the NeedForSpeed sprint; this also triggered a long
+ discussion on how to improve benchmark timing and finally
+ resulted in the release of 2.0
+ 1.3: initial checkin into the Python SVN repository
+
+
+Have fun,
+--
+Marc-Andre Lemburg
+mal@lemburg.com
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Setup.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Setup.py
new file mode 100644
index 0000000000..565893b1a7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Setup.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+
+# Setup file for pybench
+#
+# This file has to import all tests to be run; it is executed as
+# Python source file, so you can do all kinds of manipulations here
+# rather than having to edit the tests themselves.
+#
+# Note: Please keep this module compatible to Python 1.5.2.
+#
+# Tests may include features in later Python versions, but these
+# should then be embedded in try-except clauses in this configuration
+# module.
+
+# Defaults
+Number_of_rounds = 10
+Warp_factor = 10
+
+# Import tests
+from Arithmetic import *
+from Calls import *
+from Constructs import *
+from Lookups import *
+from Instances import *
+try:
+ from NewInstances import *
+except ImportError:
+ pass
+from Lists import *
+from Tuples import *
+from Dict import *
+from Exceptions import *
+try:
+ from With import *
+except SyntaxError:
+ pass
+from Imports import *
+from Strings import *
+from Numbers import *
+try:
+ from Unicode import *
+except (ImportError, SyntaxError):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Strings.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Strings.py
new file mode 100644
index 0000000000..b7626b5042
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Strings.py
@@ -0,0 +1,562 @@
+from pybench import Test
+from string import join
+
+class ConcatStrings(Test):
+
+ version = 2.0
+ operations = 10 * 5
+ rounds = 100000
+
+ def test(self):
+
+ # Make sure the strings are *not* interned
+ s = join(map(str,range(100)))
+ t = join(map(str,range(1,101)))
+
+ for i in xrange(self.rounds):
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ def calibrate(self):
+
+ s = join(map(str,range(100)))
+ t = join(map(str,range(1,101)))
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CompareStrings(Test):
+
+ version = 2.0
+ operations = 10 * 5
+ rounds = 200000
+
+ def test(self):
+
+ # Make sure the strings are *not* interned
+ s = join(map(str,range(10)))
+ t = join(map(str,range(10))) + "abc"
+
+ for i in xrange(self.rounds):
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ def calibrate(self):
+
+ s = join(map(str,range(10)))
+ t = join(map(str,range(10))) + "abc"
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CompareInternedStrings(Test):
+
+ version = 2.0
+ operations = 10 * 5
+ rounds = 300000
+
+ def test(self):
+
+ # Make sure the strings *are* interned
+ s = intern(join(map(str,range(10))))
+ t = s
+
+ for i in xrange(self.rounds):
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ t == s
+ t == s
+ t >= s
+ t > s
+ t < s
+
+ def calibrate(self):
+
+ s = intern(join(map(str,range(10))))
+ t = s
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CreateStringsWithConcat(Test):
+
+ version = 2.0
+ operations = 10 * 5
+ rounds = 200000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+ s = 'om'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ s = s + 'xax'
+ s = s + 'xbx'
+ s = s + 'xcx'
+ s = s + 'xdx'
+ s = s + 'xex'
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class StringSlicing(Test):
+
+ version = 2.0
+ operations = 5 * 7
+ rounds = 160000
+
+ def test(self):
+
+ s = join(map(str,range(100)))
+
+ for i in xrange(self.rounds):
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ def calibrate(self):
+
+ s = join(map(str,range(100)))
+
+ for i in xrange(self.rounds):
+ pass
+
+### String methods
+
+if hasattr('', 'lower'):
+
+ class StringMappings(Test):
+
+ version = 2.0
+ operations = 3 * (5 + 4 + 2 + 1)
+ rounds = 70000
+
+ def test(self):
+
+ s = join(map(chr,range(20)),'')
+ t = join(map(chr,range(50)),'')
+ u = join(map(chr,range(100)),'')
+ v = join(map(chr,range(256)),'')
+
+ for i in xrange(self.rounds):
+
+ s.lower()
+ s.lower()
+ s.lower()
+ s.lower()
+ s.lower()
+
+ s.upper()
+ s.upper()
+ s.upper()
+ s.upper()
+ s.upper()
+
+ s.title()
+ s.title()
+ s.title()
+ s.title()
+ s.title()
+
+ t.lower()
+ t.lower()
+ t.lower()
+ t.lower()
+
+ t.upper()
+ t.upper()
+ t.upper()
+ t.upper()
+
+ t.title()
+ t.title()
+ t.title()
+ t.title()
+
+ u.lower()
+ u.lower()
+
+ u.upper()
+ u.upper()
+
+ u.title()
+ u.title()
+
+ v.lower()
+
+ v.upper()
+
+ v.title()
+
+ def calibrate(self):
+
+ s = join(map(chr,range(20)),'')
+ t = join(map(chr,range(50)),'')
+ u = join(map(chr,range(100)),'')
+ v = join(map(chr,range(256)),'')
+
+ for i in xrange(self.rounds):
+ pass
+
+ class StringPredicates(Test):
+
+ version = 2.0
+ operations = 10 * 7
+ rounds = 100000
+
+ def test(self):
+
+ data = ('abc', '123', ' ', '\xe4\xf6\xfc', '\xdf'*10)
+ len_data = len(data)
+
+ for i in xrange(self.rounds):
+ s = data[i % len_data]
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdigit()
+ s.islower()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ def calibrate(self):
+
+ data = ('abc', '123', ' ', '\u1234\u2345\u3456', '\uFFFF'*10)
+ data = ('abc', '123', ' ', '\xe4\xf6\xfc', '\xdf'*10)
+ len_data = len(data)
+
+ for i in xrange(self.rounds):
+ s = data[i % len_data]
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Tuples.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Tuples.py
new file mode 100644
index 0000000000..f17d52c64d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Tuples.py
@@ -0,0 +1,360 @@
+from pybench import Test
+
+class TupleSlicing(Test):
+
+ version = 2.0
+ operations = 3 * 25 * 10 * 7
+ rounds = 500
+
+ def test(self):
+
+ r = range(25)
+ t = tuple(range(100))
+
+ for i in xrange(self.rounds):
+
+ for j in r:
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ m = t[50:]
+ m = t[:25]
+ m = t[50:55]
+ m = t[:-1]
+ m = t[1:]
+ m = t[-10:]
+ m = t[:10]
+
+ def calibrate(self):
+
+ r = range(25)
+ t = tuple(range(100))
+
+ for i in xrange(self.rounds):
+ for j in r:
+ pass
+
+class SmallTuples(Test):
+
+ version = 2.0
+ operations = 5*(1 + 3 + 6 + 2)
+ rounds = 90000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+
+ t = (1,2,3,4,5,6)
+
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+
+ l = list(t)
+ t = tuple(l)
+
+ t = (1,2,3,4,5,6)
+
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+
+ l = list(t)
+ t = tuple(l)
+
+ t = (1,2,3,4,5,6)
+
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+
+ l = list(t)
+ t = tuple(l)
+
+ t = (1,2,3,4,5,6)
+
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+
+ l = list(t)
+ t = tuple(l)
+
+ t = (1,2,3,4,5,6)
+
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+ a,b,c,d,e,f = t
+
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+ a,b,c = t[:3]
+
+ l = list(t)
+ t = tuple(l)
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Unicode.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Unicode.py
new file mode 100644
index 0000000000..3e6b2d8cdd
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/Unicode.py
@@ -0,0 +1,542 @@
+try:
+ unicode
+except NameError:
+ raise ImportError
+
+from pybench import Test
+from string import join
+
+class ConcatUnicode(Test):
+
+ version = 2.0
+ operations = 10 * 5
+ rounds = 60000
+
+ def test(self):
+
+ # Make sure the strings are *not* interned
+ s = unicode(join(map(str,range(100))))
+ t = unicode(join(map(str,range(1,101))))
+
+ for i in xrange(self.rounds):
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ t + s
+ t + s
+ t + s
+ t + s
+ t + s
+
+ def calibrate(self):
+
+ s = unicode(join(map(str,range(100))))
+ t = unicode(join(map(str,range(1,101))))
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CompareUnicode(Test):
+
+ version = 2.0
+ operations = 10 * 5
+ rounds = 150000
+
+ def test(self):
+
+ # Make sure the strings are *not* interned
+ s = unicode(join(map(str,range(10))))
+ t = unicode(join(map(str,range(10))) + "abc")
+
+ for i in xrange(self.rounds):
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ t < s
+ t > s
+ t == s
+ t > s
+ t < s
+
+ def calibrate(self):
+
+ s = unicode(join(map(str,range(10))))
+ t = unicode(join(map(str,range(10))) + "abc")
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class CreateUnicodeWithConcat(Test):
+
+ version = 2.0
+ operations = 10 * 5
+ rounds = 80000
+
+ def test(self):
+
+ for i in xrange(self.rounds):
+ s = u'om'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ s = s + u'xax'
+ s = s + u'xbx'
+ s = s + u'xcx'
+ s = s + u'xdx'
+ s = s + u'xex'
+
+ def calibrate(self):
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class UnicodeSlicing(Test):
+
+ version = 2.0
+ operations = 5 * 7
+ rounds = 140000
+
+ def test(self):
+
+ s = unicode(join(map(str,range(100))))
+
+ for i in xrange(self.rounds):
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ s[50:]
+ s[:25]
+ s[50:55]
+ s[-1:]
+ s[:1]
+ s[2:]
+ s[11:-11]
+
+ def calibrate(self):
+
+ s = unicode(join(map(str,range(100))))
+
+ for i in xrange(self.rounds):
+ pass
+
+### String methods
+
+class UnicodeMappings(Test):
+
+ version = 2.0
+ operations = 3 * (5 + 4 + 2 + 1)
+ rounds = 10000
+
+ def test(self):
+
+ s = join(map(unichr,range(20)),'')
+ t = join(map(unichr,range(100)),'')
+ u = join(map(unichr,range(500)),'')
+ v = join(map(unichr,range(1000)),'')
+
+ for i in xrange(self.rounds):
+
+ s.lower()
+ s.lower()
+ s.lower()
+ s.lower()
+ s.lower()
+
+ s.upper()
+ s.upper()
+ s.upper()
+ s.upper()
+ s.upper()
+
+ s.title()
+ s.title()
+ s.title()
+ s.title()
+ s.title()
+
+ t.lower()
+ t.lower()
+ t.lower()
+ t.lower()
+
+ t.upper()
+ t.upper()
+ t.upper()
+ t.upper()
+
+ t.title()
+ t.title()
+ t.title()
+ t.title()
+
+ u.lower()
+ u.lower()
+
+ u.upper()
+ u.upper()
+
+ u.title()
+ u.title()
+
+ v.lower()
+
+ v.upper()
+
+ v.title()
+
+ def calibrate(self):
+
+ s = join(map(unichr,range(20)),'')
+ t = join(map(unichr,range(100)),'')
+ u = join(map(unichr,range(500)),'')
+ v = join(map(unichr,range(1000)),'')
+
+ for i in xrange(self.rounds):
+ pass
+
+class UnicodePredicates(Test):
+
+ version = 2.0
+ operations = 5 * 9
+ rounds = 120000
+
+ def test(self):
+
+ data = (u'abc', u'123', u' ', u'\u1234\u2345\u3456', u'\uFFFF'*10)
+ len_data = len(data)
+
+ for i in xrange(self.rounds):
+ s = data[i % len_data]
+
+ s.isalnum()
+ s.isalpha()
+ s.isdecimal()
+ s.isdigit()
+ s.islower()
+ s.isnumeric()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdecimal()
+ s.isdigit()
+ s.islower()
+ s.isnumeric()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdecimal()
+ s.isdigit()
+ s.islower()
+ s.isnumeric()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdecimal()
+ s.isdigit()
+ s.islower()
+ s.isnumeric()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ s.isalnum()
+ s.isalpha()
+ s.isdecimal()
+ s.isdigit()
+ s.islower()
+ s.isnumeric()
+ s.isspace()
+ s.istitle()
+ s.isupper()
+
+ def calibrate(self):
+
+ data = (u'abc', u'123', u' ', u'\u1234\u2345\u3456', u'\uFFFF'*10)
+ len_data = len(data)
+
+ for i in xrange(self.rounds):
+ s = data[i % len_data]
+
+try:
+ import unicodedata
+except ImportError:
+ pass
+else:
+ class UnicodeProperties(Test):
+
+ version = 2.0
+ operations = 5 * 8
+ rounds = 100000
+
+ def test(self):
+
+ data = (u'a', u'1', u' ', u'\u1234', u'\uFFFF')
+ len_data = len(data)
+ digit = unicodedata.digit
+ numeric = unicodedata.numeric
+ decimal = unicodedata.decimal
+ category = unicodedata.category
+ bidirectional = unicodedata.bidirectional
+ decomposition = unicodedata.decomposition
+ mirrored = unicodedata.mirrored
+ combining = unicodedata.combining
+
+ for i in xrange(self.rounds):
+
+ c = data[i % len_data]
+
+ digit(c, None)
+ numeric(c, None)
+ decimal(c, None)
+ category(c)
+ bidirectional(c)
+ decomposition(c)
+ mirrored(c)
+ combining(c)
+
+ digit(c, None)
+ numeric(c, None)
+ decimal(c, None)
+ category(c)
+ bidirectional(c)
+ decomposition(c)
+ mirrored(c)
+ combining(c)
+
+ digit(c, None)
+ numeric(c, None)
+ decimal(c, None)
+ category(c)
+ bidirectional(c)
+ decomposition(c)
+ mirrored(c)
+ combining(c)
+
+ digit(c, None)
+ numeric(c, None)
+ decimal(c, None)
+ category(c)
+ bidirectional(c)
+ decomposition(c)
+ mirrored(c)
+ combining(c)
+
+ digit(c, None)
+ numeric(c, None)
+ decimal(c, None)
+ category(c)
+ bidirectional(c)
+ decomposition(c)
+ mirrored(c)
+ combining(c)
+
+ def calibrate(self):
+
+ data = (u'a', u'1', u' ', u'\u1234', u'\uFFFF')
+ len_data = len(data)
+ digit = unicodedata.digit
+ numeric = unicodedata.numeric
+ decimal = unicodedata.decimal
+ category = unicodedata.category
+ bidirectional = unicodedata.bidirectional
+ decomposition = unicodedata.decomposition
+ mirrored = unicodedata.mirrored
+ combining = unicodedata.combining
+
+ for i in xrange(self.rounds):
+
+ c = data[i % len_data]
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/With.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/With.py
new file mode 100644
index 0000000000..01e075fdd1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/With.py
@@ -0,0 +1,190 @@
+from __future__ import with_statement
+from pybench import Test
+
+class WithFinally(Test):
+
+ version = 2.0
+ operations = 20
+ rounds = 80000
+
+ class ContextManager(object):
+ def __enter__(self):
+ pass
+ def __exit__(self, exc, val, tb):
+ pass
+
+ def test(self):
+
+ cm = self.ContextManager()
+
+ for i in xrange(self.rounds):
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+ with cm: pass
+
+ def calibrate(self):
+
+ cm = self.ContextManager()
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class TryFinally(Test):
+
+ version = 2.0
+ operations = 20
+ rounds = 80000
+
+ class ContextManager(object):
+ def __enter__(self):
+ pass
+ def __exit__(self):
+ # "Context manager" objects used just for their cleanup
+ # actions in finally blocks usually don't have parameters.
+ pass
+
+ def test(self):
+
+ cm = self.ContextManager()
+
+ for i in xrange(self.rounds):
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ cm.__enter__()
+ try: pass
+ finally: cm.__exit__()
+
+ def calibrate(self):
+
+ cm = self.ContextManager()
+
+ for i in xrange(self.rounds):
+ pass
+
+
+class WithRaiseExcept(Test):
+
+ version = 2.0
+ operations = 2 + 3 + 3
+ rounds = 100000
+
+ class BlockExceptions(object):
+ def __enter__(self):
+ pass
+ def __exit__(self, exc, val, tb):
+ return True
+
+ def test(self):
+
+ error = ValueError
+ be = self.BlockExceptions()
+
+ for i in xrange(self.rounds):
+ with be: raise error
+ with be: raise error
+ with be: raise error,"something"
+ with be: raise error,"something"
+ with be: raise error,"something"
+ with be: raise error("something")
+ with be: raise error("something")
+ with be: raise error("something")
+
+ def calibrate(self):
+
+ error = ValueError
+ be = self.BlockExceptions()
+
+ for i in xrange(self.rounds):
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/clockres.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/clockres.py
new file mode 100644
index 0000000000..7636be62ef
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/clockres.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+
+""" clockres - calculates the resolution in seconds of a given timer.
+
+ Copyright (c) 2006, Marc-Andre Lemburg (mal@egenix.com). See the
+ documentation for further information on copyrights, or contact
+ the author. All Rights Reserved.
+
+"""
+import time
+
+TEST_TIME = 1.0
+
+def clockres(timer):
+ d = {}
+ wallclock = time.time
+ start = wallclock()
+ stop = wallclock() + TEST_TIME
+ spin_loops = range(1000)
+ while 1:
+ now = wallclock()
+ if now >= stop:
+ break
+ for i in spin_loops:
+ d[timer()] = 1
+ values = d.keys()
+ values.sort()
+ min_diff = TEST_TIME
+ for i in range(len(values) - 1):
+ diff = values[i+1] - values[i]
+ if diff < min_diff:
+ min_diff = diff
+ return min_diff
+
+if __name__ == '__main__':
+ print 'Clock resolution of various timer implementations:'
+ print 'time.clock: %10.3fus' % (clockres(time.clock) * 1e6)
+ print 'time.time: %10.3fus' % (clockres(time.time) * 1e6)
+ try:
+ import systimes
+ print 'systimes.processtime: %10.3fus' % (clockres(systimes.processtime) * 1e6)
+ except ImportError:
+ pass
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/__init__.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/__init__.py
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/submodule.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/submodule.py
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/package/submodule.py
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/pybench.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/pybench.py
new file mode 100644
index 0000000000..4bfc7f28df
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/pybench.py
@@ -0,0 +1,961 @@
+#!/usr/local/bin/python -O
+
+""" A Python Benchmark Suite
+
+"""
+#
+# Note: Please keep this module compatible to Python 1.5.2.
+#
+# Tests may include features in later Python versions, but these
+# should then be embedded in try-except clauses in the configuration
+# module Setup.py.
+#
+
+# pybench Copyright
+__copyright__ = """\
+Copyright (c), 1997-2006, Marc-Andre Lemburg (mal@lemburg.com)
+Copyright (c), 2000-2006, eGenix.com Software GmbH (info@egenix.com)
+
+ All Rights Reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee or royalty is hereby
+granted, provided that the above copyright notice appear in all copies
+and that both that copyright notice and this permission notice appear
+in supporting documentation or portions thereof, including
+modifications, that you make.
+
+THE AUTHOR MARC-ANDRE LEMBURG DISCLAIMS ALL WARRANTIES WITH REGARD TO
+THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
+INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
+"""
+
+import sys, time, operator, string, platform
+from CommandLine import *
+
+try:
+ import cPickle
+ pickle = cPickle
+except ImportError:
+ import pickle
+
+# Version number; version history: see README file !
+__version__ = '2.0'
+
+### Constants
+
+# Second fractions
+MILLI_SECONDS = 1e3
+MICRO_SECONDS = 1e6
+
+# Percent unit
+PERCENT = 100
+
+# Horizontal line length
+LINE = 79
+
+# Minimum test run-time
+MIN_TEST_RUNTIME = 1e-3
+
+# Number of calibration runs to use for calibrating the tests
+CALIBRATION_RUNS = 20
+
+# Number of calibration loops to run for each calibration run
+CALIBRATION_LOOPS = 20
+
+# Allow skipping calibration ?
+ALLOW_SKIPPING_CALIBRATION = 1
+
+# Timer types
+TIMER_TIME_TIME = 'time.time'
+TIMER_TIME_CLOCK = 'time.clock'
+TIMER_SYSTIMES_PROCESSTIME = 'systimes.processtime'
+
+# Choose platform default timer
+if sys.platform[:3] == 'win':
+ # On WinXP this has 2.5ms resolution
+ TIMER_PLATFORM_DEFAULT = TIMER_TIME_CLOCK
+else:
+ # On Linux this has 1ms resolution
+ TIMER_PLATFORM_DEFAULT = TIMER_TIME_TIME
+
+# Print debug information ?
+_debug = 0
+
+### Helpers
+
+def get_timer(timertype):
+
+ if timertype == TIMER_TIME_TIME:
+ return time.time
+ elif timertype == TIMER_TIME_CLOCK:
+ return time.clock
+ elif timertype == TIMER_SYSTIMES_PROCESSTIME:
+ import systimes
+ return systimes.processtime
+ else:
+ raise TypeError('unknown timer type: %s' % timertype)
+
+def get_machine_details():
+
+ if _debug:
+ print 'Getting machine details...'
+ buildno, builddate = platform.python_build()
+ python = platform.python_version()
+ try:
+ unichr(100000)
+ except ValueError:
+ # UCS2 build (standard)
+ unicode = 'UCS2'
+ except NameError:
+ unicode = None
+ else:
+ # UCS4 build (most recent Linux distros)
+ unicode = 'UCS4'
+ bits, linkage = platform.architecture()
+ return {
+ 'platform': platform.platform(),
+ 'processor': platform.processor(),
+ 'executable': sys.executable,
+ 'implementation': getattr(platform, 'python_implementation',
+ lambda:'n/a')(),
+ 'python': platform.python_version(),
+ 'compiler': platform.python_compiler(),
+ 'buildno': buildno,
+ 'builddate': builddate,
+ 'unicode': unicode,
+ 'bits': bits,
+ }
+
+def print_machine_details(d, indent=''):
+
+ l = ['Machine Details:',
+ ' Platform ID: %s' % d.get('platform', 'n/a'),
+ ' Processor: %s' % d.get('processor', 'n/a'),
+ '',
+ 'Python:',
+ ' Implementation: %s' % d.get('implementation', 'n/a'),
+ ' Executable: %s' % d.get('executable', 'n/a'),
+ ' Version: %s' % d.get('python', 'n/a'),
+ ' Compiler: %s' % d.get('compiler', 'n/a'),
+ ' Bits: %s' % d.get('bits', 'n/a'),
+ ' Build: %s (#%s)' % (d.get('builddate', 'n/a'),
+ d.get('buildno', 'n/a')),
+ ' Unicode: %s' % d.get('unicode', 'n/a'),
+ ]
+ print indent + string.join(l, '\n' + indent) + '\n'
+
+### Test baseclass
+
+class Test:
+
+ """ All test must have this class as baseclass. It provides
+ the necessary interface to the benchmark machinery.
+
+ The tests must set .rounds to a value high enough to let the
+ test run between 20-50 seconds. This is needed because
+ clock()-timing only gives rather inaccurate values (on Linux,
+ for example, it is accurate to a few hundreths of a
+ second). If you don't want to wait that long, use a warp
+ factor larger than 1.
+
+ It is also important to set the .operations variable to a
+ value representing the number of "virtual operations" done per
+ call of .run().
+
+ If you change a test in some way, don't forget to increase
+ its version number.
+
+ """
+
+ ### Instance variables that each test should override
+
+ # Version number of the test as float (x.yy); this is important
+ # for comparisons of benchmark runs - tests with unequal version
+ # number will not get compared.
+ version = 2.0
+
+ # The number of abstract operations done in each round of the
+ # test. An operation is the basic unit of what you want to
+ # measure. The benchmark will output the amount of run-time per
+ # operation. Note that in order to raise the measured timings
+ # significantly above noise level, it is often required to repeat
+ # sets of operations more than once per test round. The measured
+ # overhead per test round should be less than 1 second.
+ operations = 1
+
+ # Number of rounds to execute per test run. This should be
+ # adjusted to a figure that results in a test run-time of between
+ # 1-2 seconds.
+ rounds = 100000
+
+ ### Internal variables
+
+ # Mark this class as implementing a test
+ is_a_test = 1
+
+ # Last timing: (real, run, overhead)
+ last_timing = (0.0, 0.0, 0.0)
+
+ # Warp factor to use for this test
+ warp = 1
+
+ # Number of calibration runs to use
+ calibration_runs = CALIBRATION_RUNS
+
+ # List of calibration timings
+ overhead_times = None
+
+ # List of test run timings
+ times = []
+
+ # Timer used for the benchmark
+ timer = TIMER_PLATFORM_DEFAULT
+
+ def __init__(self, warp=None, calibration_runs=None, timer=None):
+
+ # Set parameters
+ if warp is not None:
+ self.rounds = int(self.rounds / warp)
+ if self.rounds == 0:
+ raise ValueError('warp factor set too high')
+ self.warp = warp
+ if calibration_runs is not None:
+ if (not ALLOW_SKIPPING_CALIBRATION and
+ calibration_runs < 1):
+ raise ValueError('at least one calibration run is required')
+ self.calibration_runs = calibration_runs
+ if timer is not None:
+ self.timer = timer
+
+ # Init variables
+ self.times = []
+ self.overhead_times = []
+
+ # We want these to be in the instance dict, so that pickle
+ # saves them
+ self.version = self.version
+ self.operations = self.operations
+ self.rounds = self.rounds
+
+ def get_timer(self):
+
+ """ Return the timer function to use for the test.
+
+ """
+ return get_timer(self.timer)
+
+ def compatible(self, other):
+
+ """ Return 1/0 depending on whether the test is compatible
+ with the other Test instance or not.
+
+ """
+ if self.version != other.version:
+ return 0
+ if self.rounds != other.rounds:
+ return 0
+ return 1
+
+ def calibrate_test(self):
+
+ if self.calibration_runs == 0:
+ self.overhead_times = [0.0]
+ return
+
+ calibrate = self.calibrate
+ timer = self.get_timer()
+ calibration_loops = range(CALIBRATION_LOOPS)
+
+ # Time the calibration loop overhead
+ prep_times = []
+ for i in range(self.calibration_runs):
+ t = timer()
+ for i in calibration_loops:
+ pass
+ t = timer() - t
+ prep_times.append(t / CALIBRATION_LOOPS)
+ min_prep_time = min(prep_times)
+ if _debug:
+ print
+ print 'Calib. prep time = %.6fms' % (
+ min_prep_time * MILLI_SECONDS)
+
+ # Time the calibration runs (doing CALIBRATION_LOOPS loops of
+ # .calibrate() method calls each)
+ for i in range(self.calibration_runs):
+ t = timer()
+ for i in calibration_loops:
+ calibrate()
+ t = timer() - t
+ self.overhead_times.append(t / CALIBRATION_LOOPS
+ - min_prep_time)
+
+ # Check the measured times
+ min_overhead = min(self.overhead_times)
+ max_overhead = max(self.overhead_times)
+ if _debug:
+ print 'Calib. overhead time = %.6fms' % (
+ min_overhead * MILLI_SECONDS)
+ if min_overhead < 0.0:
+ raise ValueError('calibration setup did not work')
+ if max_overhead - min_overhead > 0.1:
+ raise ValueError(
+ 'overhead calibration timing range too inaccurate: '
+ '%r - %r' % (min_overhead, max_overhead))
+
+ def run(self):
+
+ """ Run the test in two phases: first calibrate, then
+ do the actual test. Be careful to keep the calibration
+ timing low w/r to the test timing.
+
+ """
+ test = self.test
+ timer = self.get_timer()
+
+ # Get calibration
+ min_overhead = min(self.overhead_times)
+
+ # Test run
+ t = timer()
+ test()
+ t = timer() - t
+ if t < MIN_TEST_RUNTIME:
+ raise ValueError('warp factor too high: '
+ 'test times are < 10ms')
+ eff_time = t - min_overhead
+ if eff_time < 0:
+ raise ValueError('wrong calibration')
+ self.last_timing = (eff_time, t, min_overhead)
+ self.times.append(eff_time)
+
+ def calibrate(self):
+
+ """ Calibrate the test.
+
+ This method should execute everything that is needed to
+ setup and run the test - except for the actual operations
+ that you intend to measure. pybench uses this method to
+ measure the test implementation overhead.
+
+ """
+ return
+
+ def test(self):
+
+ """ Run the test.
+
+ The test needs to run self.rounds executing
+ self.operations number of operations each.
+
+ """
+ return
+
+ def stat(self):
+
+ """ Return test run statistics as tuple:
+
+ (minimum run time,
+ average run time,
+ total run time,
+ average time per operation,
+ minimum overhead time)
+
+ """
+ runs = len(self.times)
+ if runs == 0:
+ return 0.0, 0.0, 0.0, 0.0
+ min_time = min(self.times)
+ total_time = reduce(operator.add, self.times, 0.0)
+ avg_time = total_time / float(runs)
+ operation_avg = total_time / float(runs
+ * self.rounds
+ * self.operations)
+ if self.overhead_times:
+ min_overhead = min(self.overhead_times)
+ else:
+ min_overhead = self.last_timing[2]
+ return min_time, avg_time, total_time, operation_avg, min_overhead
+
+### Load Setup
+
+# This has to be done after the definition of the Test class, since
+# the Setup module will import subclasses using this class.
+
+import Setup
+
+### Benchmark base class
+
+class Benchmark:
+
+ # Name of the benchmark
+ name = ''
+
+ # Number of benchmark rounds to run
+ rounds = 1
+
+ # Warp factor use to run the tests
+ warp = 1 # Warp factor
+
+ # Average benchmark round time
+ roundtime = 0
+
+ # Benchmark version number as float x.yy
+ version = 2.0
+
+ # Produce verbose output ?
+ verbose = 0
+
+ # Dictionary with the machine details
+ machine_details = None
+
+ # Timer used for the benchmark
+ timer = TIMER_PLATFORM_DEFAULT
+
+ def __init__(self, name, verbose=None, timer=None, warp=None,
+ calibration_runs=None):
+
+ if name:
+ self.name = name
+ else:
+ self.name = '%04i-%02i-%02i %02i:%02i:%02i' % \
+ (time.localtime(time.time())[:6])
+ if verbose is not None:
+ self.verbose = verbose
+ if timer is not None:
+ self.timer = timer
+ if warp is not None:
+ self.warp = warp
+ if calibration_runs is not None:
+ self.calibration_runs = calibration_runs
+
+ # Init vars
+ self.tests = {}
+ if _debug:
+ print 'Getting machine details...'
+ self.machine_details = get_machine_details()
+
+ # Make .version an instance attribute to have it saved in the
+ # Benchmark pickle
+ self.version = self.version
+
+ def get_timer(self):
+
+ """ Return the timer function to use for the test.
+
+ """
+ return get_timer(self.timer)
+
+ def compatible(self, other):
+
+ """ Return 1/0 depending on whether the benchmark is
+ compatible with the other Benchmark instance or not.
+
+ """
+ if self.version != other.version:
+ return 0
+ if (self.machine_details == other.machine_details and
+ self.timer != other.timer):
+ return 0
+ if (self.calibration_runs == 0 and
+ other.calibration_runs != 0):
+ return 0
+ if (self.calibration_runs != 0 and
+ other.calibration_runs == 0):
+ return 0
+ return 1
+
+ def load_tests(self, setupmod, limitnames=None):
+
+ # Add tests
+ if self.verbose:
+ print 'Searching for tests ...'
+ print '--------------------------------------'
+ for testclass in setupmod.__dict__.values():
+ if not hasattr(testclass, 'is_a_test'):
+ continue
+ name = testclass.__name__
+ if name == 'Test':
+ continue
+ if (limitnames is not None and
+ limitnames.search(name) is None):
+ continue
+ self.tests[name] = testclass(
+ warp=self.warp,
+ calibration_runs=self.calibration_runs,
+ timer=self.timer)
+ l = self.tests.keys()
+ l.sort()
+ if self.verbose:
+ for name in l:
+ print ' %s' % name
+ print '--------------------------------------'
+ print ' %i tests found' % len(l)
+ print
+
+ def calibrate(self):
+
+ print 'Calibrating tests. Please wait...',
+ sys.stdout.flush()
+ if self.verbose:
+ print
+ print
+ print 'Test min max'
+ print '-' * LINE
+ tests = self.tests.items()
+ tests.sort()
+ for i in range(len(tests)):
+ name, test = tests[i]
+ test.calibrate_test()
+ if self.verbose:
+ print '%30s: %6.3fms %6.3fms' % \
+ (name,
+ min(test.overhead_times) * MILLI_SECONDS,
+ max(test.overhead_times) * MILLI_SECONDS)
+ if self.verbose:
+ print
+ print 'Done with the calibration.'
+ else:
+ print 'done.'
+ print
+
+ def run(self):
+
+ tests = self.tests.items()
+ tests.sort()
+ timer = self.get_timer()
+ print 'Running %i round(s) of the suite at warp factor %i:' % \
+ (self.rounds, self.warp)
+ print
+ self.roundtimes = []
+ for i in range(self.rounds):
+ if self.verbose:
+ print ' Round %-25i effective absolute overhead' % (i+1)
+ total_eff_time = 0.0
+ for j in range(len(tests)):
+ name, test = tests[j]
+ if self.verbose:
+ print '%30s:' % name,
+ test.run()
+ (eff_time, abs_time, min_overhead) = test.last_timing
+ total_eff_time = total_eff_time + eff_time
+ if self.verbose:
+ print ' %5.0fms %5.0fms %7.3fms' % \
+ (eff_time * MILLI_SECONDS,
+ abs_time * MILLI_SECONDS,
+ min_overhead * MILLI_SECONDS)
+ self.roundtimes.append(total_eff_time)
+ if self.verbose:
+ print (' '
+ ' ------------------------------')
+ print (' '
+ ' Totals: %6.0fms' %
+ (total_eff_time * MILLI_SECONDS))
+ print
+ else:
+ print '* Round %i done in %.3f seconds.' % (i+1,
+ total_eff_time)
+ print
+
+ def stat(self):
+
+ """ Return benchmark run statistics as tuple:
+
+ (minimum round time,
+ average round time,
+ maximum round time)
+
+ XXX Currently not used, since the benchmark does test
+ statistics across all rounds.
+
+ """
+ runs = len(self.roundtimes)
+ if runs == 0:
+ return 0.0, 0.0
+ min_time = min(self.roundtimes)
+ total_time = reduce(operator.add, self.roundtimes, 0.0)
+ avg_time = total_time / float(runs)
+ max_time = max(self.roundtimes)
+ return (min_time, avg_time, max_time)
+
+ def print_header(self, title='Benchmark'):
+
+ print '-' * LINE
+ print '%s: %s' % (title, self.name)
+ print '-' * LINE
+ print
+ print ' Rounds: %s' % self.rounds
+ print ' Warp: %s' % self.warp
+ print ' Timer: %s' % self.timer
+ print
+ if self.machine_details:
+ print_machine_details(self.machine_details, indent=' ')
+ print
+
+ def print_benchmark(self, hidenoise=0, limitnames=None):
+
+ print ('Test '
+ ' minimum average operation overhead')
+ print '-' * LINE
+ tests = self.tests.items()
+ tests.sort()
+ total_min_time = 0.0
+ total_avg_time = 0.0
+ for name, test in tests:
+ if (limitnames is not None and
+ limitnames.search(name) is None):
+ continue
+ (min_time,
+ avg_time,
+ total_time,
+ op_avg,
+ min_overhead) = test.stat()
+ total_min_time = total_min_time + min_time
+ total_avg_time = total_avg_time + avg_time
+ print '%30s: %5.0fms %5.0fms %6.2fus %7.3fms' % \
+ (name,
+ min_time * MILLI_SECONDS,
+ avg_time * MILLI_SECONDS,
+ op_avg * MICRO_SECONDS,
+ min_overhead *MILLI_SECONDS)
+ print '-' * LINE
+ print ('Totals: '
+ ' %6.0fms %6.0fms' %
+ (total_min_time * MILLI_SECONDS,
+ total_avg_time * MILLI_SECONDS,
+ ))
+ print
+
+ def print_comparison(self, compare_to, hidenoise=0, limitnames=None):
+
+ # Check benchmark versions
+ if compare_to.version != self.version:
+ print ('* Benchmark versions differ: '
+ 'cannot compare this benchmark to "%s" !' %
+ compare_to.name)
+ print
+ self.print_benchmark(hidenoise=hidenoise,
+ limitnames=limitnames)
+ return
+
+ # Print header
+ compare_to.print_header('Comparing with')
+ print ('Test '
+ ' minimum run-time average run-time')
+ print (' '
+ ' this other diff this other diff')
+ print '-' * LINE
+
+ # Print test comparisons
+ tests = self.tests.items()
+ tests.sort()
+ total_min_time = other_total_min_time = 0.0
+ total_avg_time = other_total_avg_time = 0.0
+ benchmarks_compatible = self.compatible(compare_to)
+ tests_compatible = 1
+ for name, test in tests:
+ if (limitnames is not None and
+ limitnames.search(name) is None):
+ continue
+ (min_time,
+ avg_time,
+ total_time,
+ op_avg,
+ min_overhead) = test.stat()
+ total_min_time = total_min_time + min_time
+ total_avg_time = total_avg_time + avg_time
+ try:
+ other = compare_to.tests[name]
+ except KeyError:
+ other = None
+ if other is None:
+ # Other benchmark doesn't include the given test
+ min_diff, avg_diff = 'n/a', 'n/a'
+ other_min_time = 0.0
+ other_avg_time = 0.0
+ tests_compatible = 0
+ else:
+ (other_min_time,
+ other_avg_time,
+ other_total_time,
+ other_op_avg,
+ other_min_overhead) = other.stat()
+ other_total_min_time = other_total_min_time + other_min_time
+ other_total_avg_time = other_total_avg_time + other_avg_time
+ if (benchmarks_compatible and
+ test.compatible(other)):
+ # Both benchmark and tests are comparable
+ min_diff = ((min_time * self.warp) /
+ (other_min_time * other.warp) - 1.0)
+ avg_diff = ((avg_time * self.warp) /
+ (other_avg_time * other.warp) - 1.0)
+ if hidenoise and abs(min_diff) < 10.0:
+ min_diff = ''
+ else:
+ min_diff = '%+5.1f%%' % (min_diff * PERCENT)
+ if hidenoise and abs(avg_diff) < 10.0:
+ avg_diff = ''
+ else:
+ avg_diff = '%+5.1f%%' % (avg_diff * PERCENT)
+ else:
+ # Benchmark or tests are not comparable
+ min_diff, avg_diff = 'n/a', 'n/a'
+ tests_compatible = 0
+ print '%30s: %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' % \
+ (name,
+ min_time * MILLI_SECONDS,
+ other_min_time * MILLI_SECONDS * compare_to.warp / self.warp,
+ min_diff,
+ avg_time * MILLI_SECONDS,
+ other_avg_time * MILLI_SECONDS * compare_to.warp / self.warp,
+ avg_diff)
+ print '-' * LINE
+
+ # Summarise test results
+ if not benchmarks_compatible or not tests_compatible:
+ min_diff, avg_diff = 'n/a', 'n/a'
+ else:
+ if other_total_min_time != 0.0:
+ min_diff = '%+5.1f%%' % (
+ ((total_min_time * self.warp) /
+ (other_total_min_time * compare_to.warp) - 1.0) * PERCENT)
+ else:
+ min_diff = 'n/a'
+ if other_total_avg_time != 0.0:
+ avg_diff = '%+5.1f%%' % (
+ ((total_avg_time * self.warp) /
+ (other_total_avg_time * compare_to.warp) - 1.0) * PERCENT)
+ else:
+ avg_diff = 'n/a'
+ print ('Totals: '
+ ' %5.0fms %5.0fms %7s %5.0fms %5.0fms %7s' %
+ (total_min_time * MILLI_SECONDS,
+ (other_total_min_time * compare_to.warp/self.warp
+ * MILLI_SECONDS),
+ min_diff,
+ total_avg_time * MILLI_SECONDS,
+ (other_total_avg_time * compare_to.warp/self.warp
+ * MILLI_SECONDS),
+ avg_diff
+ ))
+ print
+ print '(this=%s, other=%s)' % (self.name,
+ compare_to.name)
+ print
+
+class PyBenchCmdline(Application):
+
+ header = ("PYBENCH - a benchmark test suite for Python "
+ "interpreters/compilers.")
+
+ version = __version__
+
+ debug = _debug
+
+ options = [ArgumentOption('-n',
+ 'number of rounds',
+ Setup.Number_of_rounds),
+ ArgumentOption('-f',
+ 'save benchmark to file arg',
+ ''),
+ ArgumentOption('-c',
+ 'compare benchmark with the one in file arg',
+ ''),
+ ArgumentOption('-s',
+ 'show benchmark in file arg, then exit',
+ ''),
+ ArgumentOption('-w',
+ 'set warp factor to arg',
+ Setup.Warp_factor),
+ ArgumentOption('-t',
+ 'run only tests with names matching arg',
+ ''),
+ ArgumentOption('-C',
+ 'set the number of calibration runs to arg',
+ CALIBRATION_RUNS),
+ SwitchOption('-d',
+ 'hide noise in comparisons',
+ 0),
+ SwitchOption('-v',
+ 'verbose output (not recommended)',
+ 0),
+ SwitchOption('--with-gc',
+ 'enable garbage collection',
+ 0),
+ SwitchOption('--with-syscheck',
+ 'use default sys check interval',
+ 0),
+ ArgumentOption('--timer',
+ 'use given timer',
+ TIMER_PLATFORM_DEFAULT),
+ ]
+
+ about = """\
+The normal operation is to run the suite and display the
+results. Use -f to save them for later reuse or comparisons.
+
+Available timers:
+
+ time.time
+ time.clock
+ systimes.processtime
+
+Examples:
+
+python2.1 pybench.py -f p21.pybench
+python2.5 pybench.py -f p25.pybench
+python pybench.py -s p25.pybench -c p21.pybench
+"""
+ copyright = __copyright__
+
+ def main(self):
+
+ rounds = self.values['-n']
+ reportfile = self.values['-f']
+ show_bench = self.values['-s']
+ compare_to = self.values['-c']
+ hidenoise = self.values['-d']
+ warp = int(self.values['-w'])
+ withgc = self.values['--with-gc']
+ limitnames = self.values['-t']
+ if limitnames:
+ if _debug:
+ print '* limiting test names to one with substring "%s"' % \
+ limitnames
+ limitnames = re.compile(limitnames, re.I)
+ else:
+ limitnames = None
+ verbose = self.verbose
+ withsyscheck = self.values['--with-syscheck']
+ calibration_runs = self.values['-C']
+ timer = self.values['--timer']
+
+ print '-' * LINE
+ print 'PYBENCH %s' % __version__
+ print '-' * LINE
+ print '* using %s %s' % (
+ getattr(platform, 'python_implementation', lambda:'Python')(),
+ string.join(string.split(sys.version), ' '))
+
+ # Switch off garbage collection
+ if not withgc:
+ try:
+ import gc
+ except ImportError:
+ print '* Python version doesn\'t support garbage collection'
+ else:
+ try:
+ gc.disable()
+ except NotImplementedError:
+ print '* Python version doesn\'t support gc.disable'
+ else:
+ print '* disabled garbage collection'
+
+ # "Disable" sys check interval
+ if not withsyscheck:
+ # Too bad the check interval uses an int instead of a long...
+ value = 2147483647
+ try:
+ sys.setcheckinterval(value)
+ except (AttributeError, NotImplementedError):
+ print '* Python version doesn\'t support sys.setcheckinterval'
+ else:
+ print '* system check interval set to maximum: %s' % value
+
+ if timer == TIMER_SYSTIMES_PROCESSTIME:
+ import systimes
+ print '* using timer: systimes.processtime (%s)' % \
+ systimes.SYSTIMES_IMPLEMENTATION
+ else:
+ print '* using timer: %s' % timer
+
+ print
+
+ if compare_to:
+ try:
+ f = open(compare_to,'rb')
+ bench = pickle.load(f)
+ bench.name = compare_to
+ f.close()
+ compare_to = bench
+ except IOError, reason:
+ print '* Error opening/reading file %s: %s' % (
+ repr(compare_to),
+ reason)
+ compare_to = None
+
+ if show_bench:
+ try:
+ f = open(show_bench,'rb')
+ bench = pickle.load(f)
+ bench.name = show_bench
+ f.close()
+ bench.print_header()
+ if compare_to:
+ bench.print_comparison(compare_to,
+ hidenoise=hidenoise,
+ limitnames=limitnames)
+ else:
+ bench.print_benchmark(hidenoise=hidenoise,
+ limitnames=limitnames)
+ except IOError, reason:
+ print '* Error opening/reading file %s: %s' % (
+ repr(show_bench),
+ reason)
+ print
+ return
+
+ if reportfile:
+ print 'Creating benchmark: %s (rounds=%i, warp=%i)' % \
+ (reportfile, rounds, warp)
+ print
+
+ # Create benchmark object
+ bench = Benchmark(reportfile,
+ verbose=verbose,
+ timer=timer,
+ warp=warp,
+ calibration_runs=calibration_runs)
+ bench.rounds = rounds
+ bench.load_tests(Setup, limitnames=limitnames)
+ try:
+ bench.calibrate()
+ bench.run()
+ except KeyboardInterrupt:
+ print
+ print '*** KeyboardInterrupt -- Aborting'
+ print
+ return
+ bench.print_header()
+ if compare_to:
+ bench.print_comparison(compare_to,
+ hidenoise=hidenoise,
+ limitnames=limitnames)
+ else:
+ bench.print_benchmark(hidenoise=hidenoise,
+ limitnames=limitnames)
+
+ # Ring bell
+ sys.stderr.write('\007')
+
+ if reportfile:
+ try:
+ f = open(reportfile,'wb')
+ bench.name = reportfile
+ pickle.dump(bench,f)
+ f.close()
+ except IOError, reason:
+ print '* Error opening/writing reportfile'
+ except IOError, reason:
+ print '* Error opening/writing reportfile %s: %s' % (
+ reportfile,
+ reason)
+ print
+
+if __name__ == '__main__':
+ PyBenchCmdline()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/systimes.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/systimes.py
new file mode 100644
index 0000000000..2c0b440417
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/pybench/systimes.py
@@ -0,0 +1,211 @@
+#!/usr/bin/env python
+
+""" systimes() user and system timer implementations for use by
+ pybench.
+
+ This module implements various different strategies for measuring
+ performance timings. It tries to choose the best available method
+ based on the platforma and available tools.
+
+ On Windows, it is recommended to have the Mark Hammond win32
+ package installed. Alternatively, the Thomas Heller ctypes
+ packages can also be used.
+
+ On Unix systems, the standard resource module provides the highest
+ resolution timings. Unfortunately, it is not available on all Unix
+ platforms.
+
+ If no supported timing methods based on process time can be found,
+ the module reverts to the highest resolution wall-clock timer
+ instead. The system time part will then always be 0.0.
+
+ The module exports one public API:
+
+ def systimes():
+
+ Return the current timer values for measuring user and system
+ time as tuple of seconds (user_time, system_time).
+
+ Copyright (c) 2006, Marc-Andre Lemburg (mal@egenix.com). See the
+ documentation for further information on copyrights, or contact
+ the author. All Rights Reserved.
+
+"""
+import time, sys
+
+#
+# Note: Please keep this module compatible to Python 1.5.2.
+#
+# TODOs:
+#
+# * Add ctypes wrapper for new clock_gettime() real-time POSIX APIs;
+# these will then provide nano-second resolution where available.
+#
+# * Add a function that returns the resolution of systimes()
+# values, ie. systimesres().
+#
+
+### Choose an implementation
+
+SYSTIMES_IMPLEMENTATION = None
+USE_CTYPES_GETPROCESSTIMES = 'ctypes GetProcessTimes() wrapper'
+USE_WIN32PROCESS_GETPROCESSTIMES = 'win32process.GetProcessTimes()'
+USE_RESOURCE_GETRUSAGE = 'resource.getrusage()'
+USE_PROCESS_TIME_CLOCK = 'time.clock() (process time)'
+USE_WALL_TIME_CLOCK = 'time.clock() (wall-clock)'
+USE_WALL_TIME_TIME = 'time.time() (wall-clock)'
+
+if sys.platform[:3] == 'win':
+ # Windows platform
+ try:
+ import win32process
+ except ImportError:
+ try:
+ import ctypes
+ except ImportError:
+ # Use the wall-clock implementation time.clock(), since this
+ # is the highest resolution clock available on Windows
+ SYSTIMES_IMPLEMENTATION = USE_WALL_TIME_CLOCK
+ else:
+ SYSTIMES_IMPLEMENTATION = USE_CTYPES_GETPROCESSTIMES
+ else:
+ SYSTIMES_IMPLEMENTATION = USE_WIN32PROCESS_GETPROCESSTIMES
+else:
+ # All other platforms
+ try:
+ import resource
+ except ImportError:
+ pass
+ else:
+ SYSTIMES_IMPLEMENTATION = USE_RESOURCE_GETRUSAGE
+
+# Fall-back solution
+if SYSTIMES_IMPLEMENTATION is None:
+ # Check whether we can use time.clock() as approximation
+ # for systimes()
+ start = time.clock()
+ time.sleep(0.1)
+ stop = time.clock()
+ if stop - start < 0.001:
+ # Looks like time.clock() is usable (and measures process
+ # time)
+ SYSTIMES_IMPLEMENTATION = USE_PROCESS_TIME_CLOCK
+ else:
+ # Use wall-clock implementation time.time() since this provides
+ # the highest resolution clock on most systems
+ SYSTIMES_IMPLEMENTATION = USE_WALL_TIME_TIME
+
+### Implementations
+
+def getrusage_systimes():
+ return resource.getrusage(resource.RUSAGE_SELF)[:2]
+
+def process_time_clock_systimes():
+ return (time.clock(), 0.0)
+
+def wall_clock_clock_systimes():
+ return (time.clock(), 0.0)
+
+def wall_clock_time_systimes():
+ return (time.time(), 0.0)
+
+# Number of clock ticks per second for the values returned
+# by GetProcessTimes() on Windows.
+#
+# Note: Ticks returned by GetProcessTimes() are 100ns intervals on
+# Windows XP. However, the process times are only updated with every
+# clock tick and the frequency of these is somewhat lower: depending
+# on the OS version between 10ms and 15ms. Even worse, the process
+# time seems to be allocated to process currently running when the
+# clock interrupt arrives, ie. it is possible that the current time
+# slice gets accounted to a different process.
+
+WIN32_PROCESS_TIMES_TICKS_PER_SECOND = 1e7
+
+def win32process_getprocesstimes_systimes():
+ d = win32process.GetProcessTimes(win32process.GetCurrentProcess())
+ return (d['UserTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND,
+ d['KernelTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND)
+
+def ctypes_getprocesstimes_systimes():
+ creationtime = ctypes.c_ulonglong()
+ exittime = ctypes.c_ulonglong()
+ kerneltime = ctypes.c_ulonglong()
+ usertime = ctypes.c_ulonglong()
+ rc = ctypes.windll.kernel32.GetProcessTimes(
+ ctypes.windll.kernel32.GetCurrentProcess(),
+ ctypes.byref(creationtime),
+ ctypes.byref(exittime),
+ ctypes.byref(kerneltime),
+ ctypes.byref(usertime))
+ if not rc:
+ raise TypeError('GetProcessTimes() returned an error')
+ return (usertime.value / WIN32_PROCESS_TIMES_TICKS_PER_SECOND,
+ kerneltime.value / WIN32_PROCESS_TIMES_TICKS_PER_SECOND)
+
+# Select the default for the systimes() function
+
+if SYSTIMES_IMPLEMENTATION is USE_RESOURCE_GETRUSAGE:
+ systimes = getrusage_systimes
+
+elif SYSTIMES_IMPLEMENTATION is USE_PROCESS_TIME_CLOCK:
+ systimes = process_time_clock_systimes
+
+elif SYSTIMES_IMPLEMENTATION is USE_WALL_TIME_CLOCK:
+ systimes = wall_clock_clock_systimes
+
+elif SYSTIMES_IMPLEMENTATION is USE_WALL_TIME_TIME:
+ systimes = wall_clock_time_systimes
+
+elif SYSTIMES_IMPLEMENTATION is USE_WIN32PROCESS_GETPROCESSTIMES:
+ systimes = win32process_getprocesstimes_systimes
+
+elif SYSTIMES_IMPLEMENTATION is USE_CTYPES_GETPROCESSTIMES:
+ systimes = ctypes_getprocesstimes_systimes
+
+else:
+ raise TypeError('no suitable systimes() implementation found')
+
+def processtime():
+
+ """ Return the total time spent on the process.
+
+ This is the sum of user and system time as returned by
+ systimes().
+
+ """
+ user, system = systimes()
+ return user + system
+
+### Testing
+
+def some_workload():
+ x = 0L
+ for i in xrange(10000000L):
+ x = x + 1L
+
+def test_workload():
+ print 'Testing systimes() under load conditions'
+ t0 = systimes()
+ some_workload()
+ t1 = systimes()
+ print 'before:', t0
+ print 'after:', t1
+ print 'differences:', (t1[0] - t0[0], t1[1] - t0[1])
+ print
+
+def test_idle():
+ print 'Testing systimes() under idle conditions'
+ t0 = systimes()
+ time.sleep(1)
+ t1 = systimes()
+ print 'before:', t0
+ print 'after:', t1
+ print 'differences:', (t1[0] - t0[0], t1[1] - t0[1])
+ print
+
+if __name__ == '__main__':
+ print 'Using %s as timer' % SYSTIMES_IMPLEMENTATION
+ print
+ test_workload()
+ test_idle()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/2to3 b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/2to3
new file mode 100644
index 0000000000..4e21946897
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/2to3
@@ -0,0 +1,5 @@
+#!/usr/bin/env python
+import sys
+from lib2to3.main import main
+
+sys.exit(main("lib2to3.fixes"))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/README
new file mode 100644
index 0000000000..762cce44c6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/README
@@ -0,0 +1,69 @@
+This directory contains a collection of executable Python scripts that
+are useful while building, extending or managing Python. Some (e.g.,
+dutree or lll) are also generally useful UNIX tools.
+
+See also the Demo/scripts directory!
+
+analyze_dxp.py Analyzes the result of sys.getdxp()
+byext.py Print lines/words/chars stats of files by extension
+byteyears.py Print product of a file's size and age
+checkappend.py Search for multi-argument .append() calls
+checkpyc.py Check presence and validity of ".pyc" files
+classfix.py Convert old class syntax to new
+cleanfuture.py Fix reduntant Python __future__ statements
+combinerefs.py A helper for analyzing PYTHONDUMPREFS output.
+copytime.py Copy one file's atime and mtime to another
+crlf.py Change CRLF line endings to LF (Windows to Unix)
+cvsfiles.py Print a list of files that are under CVS
+db2pickle.py Dump a database file to a pickle
+diff.py Print file diffs in context, unified, or ndiff formats
+dutree.py Format du(1) output as a tree sorted by size
+eptags.py Create Emacs TAGS file for Python modules
+find_recursionlimit.py Find the maximum recursion limit on this machine
+finddiv.py A grep-like tool that looks for division operators
+findlinksto.py Recursively find symbolic links to a given path prefix
+findnocoding.py Find source files which need an encoding declaration
+fixcid.py Massive identifier substitution on C source files
+fixdiv.py Tool to fix division operators.
+fixheader.py Add some cpp magic to a C include file
+fixnotice.py Fix the copyright notice in source files
+fixps.py Fix Python scripts' first line (if #!)
+ftpmirror.py FTP mirror script
+google.py Open a webbrowser with Google
+gprof2html.py Transform gprof(1) output into useful HTML
+h2py.py Translate #define's into Python assignments
+hotshotmain.py Main program to run script under control of hotshot
+idle Main program to start IDLE
+ifdef.py Remove #if(n)def groups from C sources
+lfcr.py Change LF line endings to CRLF (Unix to Windows)
+linktree.py Make a copy of a tree with links to original files
+lll.py Find and list symbolic links in current directory
+logmerge.py Consolidate CVS/RCS logs read from stdin
+mailerdaemon.py parse error messages from mailer daemons (Sjoerd&Jack)
+md5sum.py Print MD5 checksums of argument files.
+methfix.py Fix old method syntax def f(self, (a1, ..., aN)):
+mkreal.py Turn a symbolic link into a real file or directory
+ndiff.py Intelligent diff between text files (Tim Peters)
+nm2def.py Create a template for PC/python_nt.def (Marc Lemburg)
+objgraph.py Print object graph from nm output on a library
+parseentities.py Utility for parsing HTML entity definitions
+pathfix.py Change #!/usr/local/bin/python into something else
+pdeps.py Print dependencies between Python modules
+pickle2db.py Load a pickle generated by db2pickle.py to a database
+pindent.py Indent Python code, giving block-closing comments
+ptags.py Create vi tags file for Python modules
+pydoc Python documentation browser.
+pysource.py Find Python source files
+redemo.py Basic regular expression demonstration facility
+reindent.py Change .py files to use 4-space indents.
+rgrep.py Reverse grep through a file (useful for big logfiles)
+serve.py Small wsgiref-based web server, used in make serve in Doc
+setup.py Install all scripts listed here
+suff.py Sort a list of files by suffix
+svneol.py Sets svn:eol-style on all files in directory
+texcheck.py Validate Python LaTeX formatting (Raymond Hettinger)
+texi2html.py Convert GNU texinfo files into HTML
+treesync.py Synchronize source trees (very ideosyncratic)
+untabify.py Replace tabs with spaces in argument files
+which.py Find a program in $PATH
+xxci.py Wrapper for rcsdiff and ci
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/analyze_dxp.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/analyze_dxp.py
new file mode 100644
index 0000000000..780001120d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/analyze_dxp.py
@@ -0,0 +1,129 @@
+"""
+Some helper functions to analyze the output of sys.getdxp() (which is
+only available if Python was built with -DDYNAMIC_EXECUTION_PROFILE).
+These will tell you which opcodes have been executed most frequently
+in the current process, and, if Python was also built with -DDXPAIRS,
+will tell you which instruction _pairs_ were executed most frequently,
+which may help in choosing new instructions.
+
+If Python was built without -DDYNAMIC_EXECUTION_PROFILE, importing
+this module will raise a RuntimeError.
+
+If you're running a script you want to profile, a simple way to get
+the common pairs is:
+
+$ PYTHONPATH=$PYTHONPATH:<python_srcdir>/Tools/scripts \
+./python -i -O the_script.py --args
+...
+> from analyze_dxp import *
+> s = render_common_pairs()
+> open('/tmp/some_file', 'w').write(s)
+"""
+
+import copy
+import opcode
+import operator
+import sys
+import threading
+
+if not hasattr(sys, "getdxp"):
+ raise RuntimeError("Can't import analyze_dxp: Python built without"
+ " -DDYNAMIC_EXECUTION_PROFILE.")
+
+
+_profile_lock = threading.RLock()
+_cumulative_profile = sys.getdxp()
+
+# If Python was built with -DDXPAIRS, sys.getdxp() returns a list of
+# lists of ints. Otherwise it returns just a list of ints.
+def has_pairs(profile):
+ """Returns True if the Python that produced the argument profile
+ was built with -DDXPAIRS."""
+
+ return len(profile) > 0 and isinstance(profile[0], list)
+
+
+def reset_profile():
+ """Forgets any execution profile that has been gathered so far."""
+ with _profile_lock:
+ sys.getdxp() # Resets the internal profile
+ global _cumulative_profile
+ _cumulative_profile = sys.getdxp() # 0s out our copy.
+
+
+def merge_profile():
+ """Reads sys.getdxp() and merges it into this module's cached copy.
+
+ We need this because sys.getdxp() 0s itself every time it's called."""
+
+ with _profile_lock:
+ new_profile = sys.getdxp()
+ if has_pairs(new_profile):
+ for first_inst in range(len(_cumulative_profile)):
+ for second_inst in range(len(_cumulative_profile[first_inst])):
+ _cumulative_profile[first_inst][second_inst] += (
+ new_profile[first_inst][second_inst])
+ else:
+ for inst in range(len(_cumulative_profile)):
+ _cumulative_profile[inst] += new_profile[inst]
+
+
+def snapshot_profile():
+ """Returns the cumulative execution profile until this call."""
+ with _profile_lock:
+ merge_profile()
+ return copy.deepcopy(_cumulative_profile)
+
+
+def common_instructions(profile):
+ """Returns the most common opcodes in order of descending frequency.
+
+ The result is a list of tuples of the form
+ (opcode, opname, # of occurrences)
+
+ """
+ if has_pairs(profile) and profile:
+ inst_list = profile[-1]
+ else:
+ inst_list = profile
+ result = [(op, opcode.opname[op], count)
+ for op, count in enumerate(inst_list)
+ if count > 0]
+ result.sort(key=operator.itemgetter(2), reverse=True)
+ return result
+
+
+def common_pairs(profile):
+ """Returns the most common opcode pairs in order of descending frequency.
+
+ The result is a list of tuples of the form
+ ((1st opcode, 2nd opcode),
+ (1st opname, 2nd opname),
+ # of occurrences of the pair)
+
+ """
+ if not has_pairs(profile):
+ return []
+ result = [((op1, op2), (opcode.opname[op1], opcode.opname[op2]), count)
+ # Drop the row of single-op profiles with [:-1]
+ for op1, op1profile in enumerate(profile[:-1])
+ for op2, count in enumerate(op1profile)
+ if count > 0]
+ result.sort(key=operator.itemgetter(2), reverse=True)
+ return result
+
+
+def render_common_pairs(profile=None):
+ """Renders the most common opcode pairs to a string in order of
+ descending frequency.
+
+ The result is a series of lines of the form:
+ # of occurrences: ('1st opname', '2nd opname')
+
+ """
+ if profile is None:
+ profile = snapshot_profile()
+ def seq():
+ for _, ops, count in common_pairs(profile):
+ yield "%s: %s\n" % (count, ops)
+ return ''.join(seq())
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byext.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byext.py
new file mode 100644
index 0000000000..7e3e7f7f23
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byext.py
@@ -0,0 +1,131 @@
+#! /usr/bin/env python
+
+"""Show file statistics by extension."""
+
+import os
+import sys
+
+class Stats:
+
+ def __init__(self):
+ self.stats = {}
+
+ def statargs(self, args):
+ for arg in args:
+ if os.path.isdir(arg):
+ self.statdir(arg)
+ elif os.path.isfile(arg):
+ self.statfile(arg)
+ else:
+ sys.stderr.write("Can't find %s\n" % arg)
+ self.addstats("<???>", "unknown", 1)
+
+ def statdir(self, dir):
+ self.addstats("<dir>", "dirs", 1)
+ try:
+ names = os.listdir(dir)
+ except os.error, err:
+ sys.stderr.write("Can't list %s: %s\n" % (dir, err))
+ self.addstats("<dir>", "unlistable", 1)
+ return
+ names.sort()
+ for name in names:
+ if name.startswith(".#"):
+ continue # Skip CVS temp files
+ if name.endswith("~"):
+ continue# Skip Emacs backup files
+ full = os.path.join(dir, name)
+ if os.path.islink(full):
+ self.addstats("<lnk>", "links", 1)
+ elif os.path.isdir(full):
+ self.statdir(full)
+ else:
+ self.statfile(full)
+
+ def statfile(self, filename):
+ head, ext = os.path.splitext(filename)
+ head, base = os.path.split(filename)
+ if ext == base:
+ ext = "" # E.g. .cvsignore is deemed not to have an extension
+ ext = os.path.normcase(ext)
+ if not ext:
+ ext = "<none>"
+ self.addstats(ext, "files", 1)
+ try:
+ f = open(filename, "rb")
+ except IOError, err:
+ sys.stderr.write("Can't open %s: %s\n" % (filename, err))
+ self.addstats(ext, "unopenable", 1)
+ return
+ data = f.read()
+ f.close()
+ self.addstats(ext, "bytes", len(data))
+ if '\0' in data:
+ self.addstats(ext, "binary", 1)
+ return
+ if not data:
+ self.addstats(ext, "empty", 1)
+ #self.addstats(ext, "chars", len(data))
+ lines = data.splitlines()
+ self.addstats(ext, "lines", len(lines))
+ del lines
+ words = data.split()
+ self.addstats(ext, "words", len(words))
+
+ def addstats(self, ext, key, n):
+ d = self.stats.setdefault(ext, {})
+ d[key] = d.get(key, 0) + n
+
+ def report(self):
+ exts = self.stats.keys()
+ exts.sort()
+ # Get the column keys
+ columns = {}
+ for ext in exts:
+ columns.update(self.stats[ext])
+ cols = columns.keys()
+ cols.sort()
+ colwidth = {}
+ colwidth["ext"] = max([len(ext) for ext in exts])
+ minwidth = 6
+ self.stats["TOTAL"] = {}
+ for col in cols:
+ total = 0
+ cw = max(minwidth, len(col))
+ for ext in exts:
+ value = self.stats[ext].get(col)
+ if value is None:
+ w = 0
+ else:
+ w = len("%d" % value)
+ total += value
+ cw = max(cw, w)
+ cw = max(cw, len(str(total)))
+ colwidth[col] = cw
+ self.stats["TOTAL"][col] = total
+ exts.append("TOTAL")
+ for ext in exts:
+ self.stats[ext]["ext"] = ext
+ cols.insert(0, "ext")
+ def printheader():
+ for col in cols:
+ print "%*s" % (colwidth[col], col),
+ print
+ printheader()
+ for ext in exts:
+ for col in cols:
+ value = self.stats[ext].get(col, "")
+ print "%*s" % (colwidth[col], value),
+ print
+ printheader() # Another header at the bottom
+
+def main():
+ args = sys.argv[1:]
+ if not args:
+ args = [os.curdir]
+ s = Stats()
+ s.statargs(args)
+ s.report()
+
+if __name__ == "__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byteyears.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byteyears.py
new file mode 100644
index 0000000000..e87454d0a8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/byteyears.py
@@ -0,0 +1,61 @@
+#! /usr/bin/env python
+
+# Print the product of age and size of each file, in suitable units.
+#
+# Usage: byteyears [ -a | -m | -c ] file ...
+#
+# Options -[amc] select atime, mtime (default) or ctime as age.
+
+import sys, os, time
+from stat import *
+
+def main():
+
+ # Use lstat() to stat files if it exists, else stat()
+ try:
+ statfunc = os.lstat
+ except AttributeError:
+ statfunc = os.stat
+
+ # Parse options
+ if sys.argv[1] == '-m':
+ itime = ST_MTIME
+ del sys.argv[1]
+ elif sys.argv[1] == '-c':
+ itime = ST_CTIME
+ del sys.argv[1]
+ elif sys.argv[1] == '-a':
+ itime = ST_CTIME
+ del sys.argv[1]
+ else:
+ itime = ST_MTIME
+
+ secs_per_year = 365.0 * 24.0 * 3600.0 # Scale factor
+ now = time.time() # Current time, for age computations
+ status = 0 # Exit status, set to 1 on errors
+
+ # Compute max file name length
+ maxlen = 1
+ for filename in sys.argv[1:]:
+ maxlen = max(maxlen, len(filename))
+
+ # Process each argument in turn
+ for filename in sys.argv[1:]:
+ try:
+ st = statfunc(filename)
+ except os.error, msg:
+ sys.stderr.write("can't stat %r: %r\n" % (filename, msg))
+ status = 1
+ st = ()
+ if st:
+ anytime = st[itime]
+ size = st[ST_SIZE]
+ age = now - anytime
+ byteyears = float(size) * float(age) / secs_per_year
+ print filename.ljust(maxlen),
+ print repr(int(byteyears)).rjust(8)
+
+ sys.exit(status)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkappend.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkappend.py
new file mode 100644
index 0000000000..6671ab422f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkappend.py
@@ -0,0 +1,167 @@
+#! /usr/bin/env python
+
+# Released to the public domain, by Tim Peters, 28 February 2000.
+
+"""checkappend.py -- search for multi-argument .append() calls.
+
+Usage: specify one or more file or directory paths:
+ checkappend [-v] file_or_dir [file_or_dir] ...
+
+Each file_or_dir is checked for multi-argument .append() calls. When
+a directory, all .py files in the directory, and recursively in its
+subdirectories, are checked.
+
+Use -v for status msgs. Use -vv for more status msgs.
+
+In the absence of -v, the only output is pairs of the form
+
+ filename(linenumber):
+ line containing the suspicious append
+
+Note that this finds multi-argument append calls regardless of whether
+they're attached to list objects. If a module defines a class with an
+append method that takes more than one argument, calls to that method
+will be listed.
+
+Note that this will not find multi-argument list.append calls made via a
+bound method object. For example, this is not caught:
+
+ somelist = []
+ push = somelist.append
+ push(1, 2, 3)
+"""
+
+__version__ = 1, 0, 0
+
+import os
+import sys
+import getopt
+import tokenize
+
+verbose = 0
+
+def errprint(*args):
+ msg = ' '.join(args)
+ sys.stderr.write(msg)
+ sys.stderr.write("\n")
+
+def main():
+ args = sys.argv[1:]
+ global verbose
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "v")
+ except getopt.error, msg:
+ errprint(str(msg) + "\n\n" + __doc__)
+ return
+ for opt, optarg in opts:
+ if opt == '-v':
+ verbose = verbose + 1
+ if not args:
+ errprint(__doc__)
+ return
+ for arg in args:
+ check(arg)
+
+def check(file):
+ if os.path.isdir(file) and not os.path.islink(file):
+ if verbose:
+ print "%r: listing directory" % (file,)
+ names = os.listdir(file)
+ for name in names:
+ fullname = os.path.join(file, name)
+ if ((os.path.isdir(fullname) and
+ not os.path.islink(fullname))
+ or os.path.normcase(name[-3:]) == ".py"):
+ check(fullname)
+ return
+
+ try:
+ f = open(file)
+ except IOError, msg:
+ errprint("%r: I/O Error: %s" % (file, msg))
+ return
+
+ if verbose > 1:
+ print "checking %r ..." % (file,)
+
+ ok = AppendChecker(file, f).run()
+ if verbose and ok:
+ print "%r: Clean bill of health." % (file,)
+
+[FIND_DOT,
+ FIND_APPEND,
+ FIND_LPAREN,
+ FIND_COMMA,
+ FIND_STMT] = range(5)
+
+class AppendChecker:
+ def __init__(self, fname, file):
+ self.fname = fname
+ self.file = file
+ self.state = FIND_DOT
+ self.nerrors = 0
+
+ def run(self):
+ try:
+ tokenize.tokenize(self.file.readline, self.tokeneater)
+ except tokenize.TokenError, msg:
+ errprint("%r: Token Error: %s" % (self.fname, msg))
+ self.nerrors = self.nerrors + 1
+ return self.nerrors == 0
+
+ def tokeneater(self, type, token, start, end, line,
+ NEWLINE=tokenize.NEWLINE,
+ JUNK=(tokenize.COMMENT, tokenize.NL),
+ OP=tokenize.OP,
+ NAME=tokenize.NAME):
+
+ state = self.state
+
+ if type in JUNK:
+ pass
+
+ elif state is FIND_DOT:
+ if type is OP and token == ".":
+ state = FIND_APPEND
+
+ elif state is FIND_APPEND:
+ if type is NAME and token == "append":
+ self.line = line
+ self.lineno = start[0]
+ state = FIND_LPAREN
+ else:
+ state = FIND_DOT
+
+ elif state is FIND_LPAREN:
+ if type is OP and token == "(":
+ self.level = 1
+ state = FIND_COMMA
+ else:
+ state = FIND_DOT
+
+ elif state is FIND_COMMA:
+ if type is OP:
+ if token in ("(", "{", "["):
+ self.level = self.level + 1
+ elif token in (")", "}", "]"):
+ self.level = self.level - 1
+ if self.level == 0:
+ state = FIND_DOT
+ elif token == "," and self.level == 1:
+ self.nerrors = self.nerrors + 1
+ print "%s(%d):\n%s" % (self.fname, self.lineno,
+ self.line)
+ # don't gripe about this stmt again
+ state = FIND_STMT
+
+ elif state is FIND_STMT:
+ if type is NEWLINE:
+ state = FIND_DOT
+
+ else:
+ raise SystemError("unknown internal state '%r'" % (state,))
+
+ self.state = state
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkpyc.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkpyc.py
new file mode 100644
index 0000000000..8f10643ace
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/checkpyc.py
@@ -0,0 +1,66 @@
+#! /usr/bin/env python
+# Check that all ".pyc" files exist and are up-to-date
+# Uses module 'os'
+
+import sys
+import os
+from stat import ST_MTIME
+import imp
+
+def main():
+ silent = 0
+ verbose = 0
+ if sys.argv[1:]:
+ if sys.argv[1] == '-v':
+ verbose = 1
+ elif sys.argv[1] == '-s':
+ silent = 1
+ MAGIC = imp.get_magic()
+ if not silent:
+ print 'Using MAGIC word', repr(MAGIC)
+ for dirname in sys.path:
+ try:
+ names = os.listdir(dirname)
+ except os.error:
+ print 'Cannot list directory', repr(dirname)
+ continue
+ if not silent:
+ print 'Checking ', repr(dirname), '...'
+ names.sort()
+ for name in names:
+ if name[-3:] == '.py':
+ name = os.path.join(dirname, name)
+ try:
+ st = os.stat(name)
+ except os.error:
+ print 'Cannot stat', repr(name)
+ continue
+ if verbose:
+ print 'Check', repr(name), '...'
+ name_c = name + 'c'
+ try:
+ f = open(name_c, 'r')
+ except IOError:
+ print 'Cannot open', repr(name_c)
+ continue
+ magic_str = f.read(4)
+ mtime_str = f.read(4)
+ f.close()
+ if magic_str <> MAGIC:
+ print 'Bad MAGIC word in ".pyc" file',
+ print repr(name_c)
+ continue
+ mtime = get_long(mtime_str)
+ if mtime == 0 or mtime == -1:
+ print 'Bad ".pyc" file', repr(name_c)
+ elif mtime <> st[ST_MTIME]:
+ print 'Out-of-date ".pyc" file',
+ print repr(name_c)
+
+def get_long(s):
+ if len(s) <> 4:
+ return -1
+ return ord(s[0]) + (ord(s[1])<<8) + (ord(s[2])<<16) + (ord(s[3])<<24)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/classfix.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/classfix.py
new file mode 100644
index 0000000000..cf0ccdff13
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/classfix.py
@@ -0,0 +1,190 @@
+#! /usr/bin/env python
+
+# This script is obsolete -- it is kept for historical purposes only.
+#
+# Fix Python source files to use the new class definition syntax, i.e.,
+# the syntax used in Python versions before 0.9.8:
+# class C() = base(), base(), ...: ...
+# is changed to the current syntax:
+# class C(base, base, ...): ...
+#
+# The script uses heuristics to find class definitions that usually
+# work but occasionally can fail; carefully check the output!
+#
+# Command line arguments are files or directories to be processed.
+# Directories are searched recursively for files whose name looks
+# like a python module.
+# Symbolic links are always ignored (except as explicit directory
+# arguments). Of course, the original file is kept as a back-up
+# (with a "~" attached to its name).
+#
+# Changes made are reported to stdout in a diff-like format.
+#
+# Undoubtedly you can do this using find and sed or perl, but this is
+# a nice example of Python code that recurses down a directory tree
+# and uses regular expressions. Also note several subtleties like
+# preserving the file's mode and avoiding to even write a temp file
+# when no changes are needed for a file.
+#
+# NB: by changing only the function fixline() you can turn this
+# into a program for a different change to Python programs...
+
+import sys
+import re
+import os
+from stat import *
+
+err = sys.stderr.write
+dbg = err
+rep = sys.stdout.write
+
+def main():
+ bad = 0
+ if not sys.argv[1:]: # No arguments
+ err('usage: ' + sys.argv[0] + ' file-or-directory ...\n')
+ sys.exit(2)
+ for arg in sys.argv[1:]:
+ if os.path.isdir(arg):
+ if recursedown(arg): bad = 1
+ elif os.path.islink(arg):
+ err(arg + ': will not process symbolic links\n')
+ bad = 1
+ else:
+ if fix(arg): bad = 1
+ sys.exit(bad)
+
+ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
+def ispython(name):
+ return ispythonprog.match(name) >= 0
+
+def recursedown(dirname):
+ dbg('recursedown(%r)\n' % (dirname,))
+ bad = 0
+ try:
+ names = os.listdir(dirname)
+ except os.error, msg:
+ err('%s: cannot list directory: %r\n' % (dirname, msg))
+ return 1
+ names.sort()
+ subdirs = []
+ for name in names:
+ if name in (os.curdir, os.pardir): continue
+ fullname = os.path.join(dirname, name)
+ if os.path.islink(fullname): pass
+ elif os.path.isdir(fullname):
+ subdirs.append(fullname)
+ elif ispython(name):
+ if fix(fullname): bad = 1
+ for fullname in subdirs:
+ if recursedown(fullname): bad = 1
+ return bad
+
+def fix(filename):
+## dbg('fix(%r)\n' % (filename,))
+ try:
+ f = open(filename, 'r')
+ except IOError, msg:
+ err('%s: cannot open: %r\n' % (filename, msg))
+ return 1
+ head, tail = os.path.split(filename)
+ tempname = os.path.join(head, '@' + tail)
+ g = None
+ # If we find a match, we rewind the file and start over but
+ # now copy everything to a temp file.
+ lineno = 0
+ while 1:
+ line = f.readline()
+ if not line: break
+ lineno = lineno + 1
+ while line[-2:] == '\\\n':
+ nextline = f.readline()
+ if not nextline: break
+ line = line + nextline
+ lineno = lineno + 1
+ newline = fixline(line)
+ if newline != line:
+ if g is None:
+ try:
+ g = open(tempname, 'w')
+ except IOError, msg:
+ f.close()
+ err('%s: cannot create: %r\n' % (tempname, msg))
+ return 1
+ f.seek(0)
+ lineno = 0
+ rep(filename + ':\n')
+ continue # restart from the beginning
+ rep(repr(lineno) + '\n')
+ rep('< ' + line)
+ rep('> ' + newline)
+ if g is not None:
+ g.write(newline)
+
+ # End of file
+ f.close()
+ if not g: return 0 # No changes
+
+ # Finishing touch -- move files
+
+ # First copy the file's mode to the temp file
+ try:
+ statbuf = os.stat(filename)
+ os.chmod(tempname, statbuf[ST_MODE] & 07777)
+ except os.error, msg:
+ err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
+ # Then make a backup of the original file as filename~
+ try:
+ os.rename(filename, filename + '~')
+ except os.error, msg:
+ err('%s: warning: backup failed (%r)\n' % (filename, msg))
+ # Now move the temp file to the original file
+ try:
+ os.rename(tempname, filename)
+ except os.error, msg:
+ err('%s: rename failed (%r)\n' % (filename, msg))
+ return 1
+ # Return succes
+ return 0
+
+# This expression doesn't catch *all* class definition headers,
+# but it's pretty darn close.
+classexpr = '^([ \t]*class +[a-zA-Z0-9_]+) *( *) *((=.*)?):'
+classprog = re.compile(classexpr)
+
+# Expressions for finding base class expressions.
+baseexpr = '^ *(.*) *( *) *$'
+baseprog = re.compile(baseexpr)
+
+def fixline(line):
+ if classprog.match(line) < 0: # No 'class' keyword -- no change
+ return line
+
+ (a0, b0), (a1, b1), (a2, b2) = classprog.regs[:3]
+ # a0, b0 = Whole match (up to ':')
+ # a1, b1 = First subexpression (up to classname)
+ # a2, b2 = Second subexpression (=.*)
+ head = line[:b1]
+ tail = line[b0:] # Unmatched rest of line
+
+ if a2 == b2: # No base classes -- easy case
+ return head + ':' + tail
+
+ # Get rid of leading '='
+ basepart = line[a2+1:b2]
+
+ # Extract list of base expressions
+ bases = basepart.split(',')
+
+ # Strip trailing '()' from each base expression
+ for i in range(len(bases)):
+ if baseprog.match(bases[i]) >= 0:
+ x1, y1 = baseprog.regs[1]
+ bases[i] = bases[i][x1:y1]
+
+ # Join the bases back again and build the new line
+ basepart = ', '.join(bases)
+
+ return head + '(' + basepart + '):' + tail
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cleanfuture.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cleanfuture.py
new file mode 100644
index 0000000000..4984b078e2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cleanfuture.py
@@ -0,0 +1,276 @@
+#! /usr/bin/env python
+
+"""cleanfuture [-d][-r][-v] path ...
+
+-d Dry run. Analyze, but don't make any changes to, files.
+-r Recurse. Search for all .py files in subdirectories too.
+-v Verbose. Print informative msgs.
+
+Search Python (.py) files for future statements, and remove the features
+from such statements that are already mandatory in the version of Python
+you're using.
+
+Pass one or more file and/or directory paths. When a directory path, all
+.py files within the directory will be examined, and, if the -r option is
+given, likewise recursively for subdirectories.
+
+Overwrites files in place, renaming the originals with a .bak extension. If
+cleanfuture finds nothing to change, the file is left alone. If cleanfuture
+does change a file, the changed file is a fixed-point (i.e., running
+cleanfuture on the resulting .py file won't change it again, at least not
+until you try it again with a later Python release).
+
+Limitations: You can do these things, but this tool won't help you then:
+
++ A future statement cannot be mixed with any other statement on the same
+ physical line (separated by semicolon).
+
++ A future statement cannot contain an "as" clause.
+
+Example: Assuming you're using Python 2.2, if a file containing
+
+from __future__ import nested_scopes, generators
+
+is analyzed by cleanfuture, the line is rewritten to
+
+from __future__ import generators
+
+because nested_scopes is no longer optional in 2.2 but generators is.
+"""
+
+import __future__
+import tokenize
+import os
+import sys
+
+dryrun = 0
+recurse = 0
+verbose = 0
+
+def errprint(*args):
+ strings = map(str, args)
+ msg = ' '.join(strings)
+ if msg[-1:] != '\n':
+ msg += '\n'
+ sys.stderr.write(msg)
+
+def main():
+ import getopt
+ global verbose, recurse, dryrun
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "drv")
+ except getopt.error, msg:
+ errprint(msg)
+ return
+ for o, a in opts:
+ if o == '-d':
+ dryrun += 1
+ elif o == '-r':
+ recurse += 1
+ elif o == '-v':
+ verbose += 1
+ if not args:
+ errprint("Usage:", __doc__)
+ return
+ for arg in args:
+ check(arg)
+
+def check(file):
+ if os.path.isdir(file) and not os.path.islink(file):
+ if verbose:
+ print "listing directory", file
+ names = os.listdir(file)
+ for name in names:
+ fullname = os.path.join(file, name)
+ if ((recurse and os.path.isdir(fullname) and
+ not os.path.islink(fullname))
+ or name.lower().endswith(".py")):
+ check(fullname)
+ return
+
+ if verbose:
+ print "checking", file, "...",
+ try:
+ f = open(file)
+ except IOError, msg:
+ errprint("%r: I/O Error: %s" % (file, str(msg)))
+ return
+
+ ff = FutureFinder(f, file)
+ changed = ff.run()
+ if changed:
+ ff.gettherest()
+ f.close()
+ if changed:
+ if verbose:
+ print "changed."
+ if dryrun:
+ print "But this is a dry run, so leaving it alone."
+ for s, e, line in changed:
+ print "%r lines %d-%d" % (file, s+1, e+1)
+ for i in range(s, e+1):
+ print ff.lines[i],
+ if line is None:
+ print "-- deleted"
+ else:
+ print "-- change to:"
+ print line,
+ if not dryrun:
+ bak = file + ".bak"
+ if os.path.exists(bak):
+ os.remove(bak)
+ os.rename(file, bak)
+ if verbose:
+ print "renamed", file, "to", bak
+ g = open(file, "w")
+ ff.write(g)
+ g.close()
+ if verbose:
+ print "wrote new", file
+ else:
+ if verbose:
+ print "unchanged."
+
+class FutureFinder:
+
+ def __init__(self, f, fname):
+ self.f = f
+ self.fname = fname
+ self.ateof = 0
+ self.lines = [] # raw file lines
+
+ # List of (start_index, end_index, new_line) triples.
+ self.changed = []
+
+ # Line-getter for tokenize.
+ def getline(self):
+ if self.ateof:
+ return ""
+ line = self.f.readline()
+ if line == "":
+ self.ateof = 1
+ else:
+ self.lines.append(line)
+ return line
+
+ def run(self):
+ STRING = tokenize.STRING
+ NL = tokenize.NL
+ NEWLINE = tokenize.NEWLINE
+ COMMENT = tokenize.COMMENT
+ NAME = tokenize.NAME
+ OP = tokenize.OP
+
+ changed = self.changed
+ get = tokenize.generate_tokens(self.getline).next
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ # Chew up initial comments and blank lines (if any).
+ while type in (COMMENT, NL, NEWLINE):
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ # Chew up docstring (if any -- and it may be implicitly catenated!).
+ while type is STRING:
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ # Analyze the future stmts.
+ while 1:
+ # Chew up comments and blank lines (if any).
+ while type in (COMMENT, NL, NEWLINE):
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ if not (type is NAME and token == "from"):
+ break
+ startline = srow - 1 # tokenize is one-based
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ if not (type is NAME and token == "__future__"):
+ break
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ if not (type is NAME and token == "import"):
+ break
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ # Get the list of features.
+ features = []
+ while type is NAME:
+ features.append(token)
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ if not (type is OP and token == ','):
+ break
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ # A trailing comment?
+ comment = None
+ if type is COMMENT:
+ comment = token
+ type, token, (srow, scol), (erow, ecol), line = get()
+
+ if type is not NEWLINE:
+ errprint("Skipping file %r; can't parse line %d:\n%s" %
+ (self.fname, srow, line))
+ return []
+
+ endline = srow - 1
+
+ # Check for obsolete features.
+ okfeatures = []
+ for f in features:
+ object = getattr(__future__, f, None)
+ if object is None:
+ # A feature we don't know about yet -- leave it in.
+ # They'll get a compile-time error when they compile
+ # this program, but that's not our job to sort out.
+ okfeatures.append(f)
+ else:
+ released = object.getMandatoryRelease()
+ if released is None or released <= sys.version_info:
+ # Withdrawn or obsolete.
+ pass
+ else:
+ okfeatures.append(f)
+
+ # Rewrite the line if at least one future-feature is obsolete.
+ if len(okfeatures) < len(features):
+ if len(okfeatures) == 0:
+ line = None
+ else:
+ line = "from __future__ import "
+ line += ', '.join(okfeatures)
+ if comment is not None:
+ line += ' ' + comment
+ line += '\n'
+ changed.append((startline, endline, line))
+
+ # Loop back for more future statements.
+
+ return changed
+
+ def gettherest(self):
+ if self.ateof:
+ self.therest = ''
+ else:
+ self.therest = self.f.read()
+
+ def write(self, f):
+ changed = self.changed
+ assert changed
+ # Prevent calling this again.
+ self.changed = []
+ # Apply changes in reverse order.
+ changed.reverse()
+ for s, e, line in changed:
+ if line is None:
+ # pure deletion
+ del self.lines[s:e+1]
+ else:
+ self.lines[s:e+1] = [line]
+ f.writelines(self.lines)
+ # Copy over the remainder of the file.
+ if self.therest:
+ f.write(self.therest)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/combinerefs.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/combinerefs.py
new file mode 100644
index 0000000000..b7369daa80
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/combinerefs.py
@@ -0,0 +1,127 @@
+#! /usr/bin/env python
+
+"""
+combinerefs path
+
+A helper for analyzing PYTHONDUMPREFS output.
+
+When the PYTHONDUMPREFS envar is set in a debug build, at Python shutdown
+time Py_Finalize() prints the list of all live objects twice: first it
+prints the repr() of each object while the interpreter is still fully intact.
+After cleaning up everything it can, it prints all remaining live objects
+again, but the second time just prints their addresses, refcounts, and type
+names (because the interpreter has been torn down, calling repr methods at
+this point can get into infinite loops or blow up).
+
+Save all this output into a file, then run this script passing the path to
+that file. The script finds both output chunks, combines them, then prints
+a line of output for each object still alive at the end:
+
+ address refcnt typename repr
+
+address is the address of the object, in whatever format the platform C
+produces for a %p format code.
+
+refcnt is of the form
+
+ "[" ref "]"
+
+when the object's refcount is the same in both PYTHONDUMPREFS output blocks,
+or
+
+ "[" ref_before "->" ref_after "]"
+
+if the refcount changed.
+
+typename is object->ob_type->tp_name, extracted from the second PYTHONDUMPREFS
+output block.
+
+repr is repr(object), extracted from the first PYTHONDUMPREFS output block.
+CAUTION: If object is a container type, it may not actually contain all the
+objects shown in the repr: the repr was captured from the first output block,
+and some of the containees may have been released since then. For example,
+it's common for the line showing the dict of interned strings to display
+strings that no longer exist at the end of Py_Finalize; this can be recognized
+(albeit painfully) because such containees don't have a line of their own.
+
+The objects are listed in allocation order, with most-recently allocated
+printed first, and the first object allocated printed last.
+
+
+Simple examples:
+
+ 00857060 [14] str '__len__'
+
+The str object '__len__' is alive at shutdown time, and both PYTHONDUMPREFS
+output blocks said there were 14 references to it. This is probably due to
+C modules that intern the string "__len__" and keep a reference to it in a
+file static.
+
+ 00857038 [46->5] tuple ()
+
+46-5 = 41 references to the empty tuple were removed by the cleanup actions
+between the times PYTHONDUMPREFS produced output.
+
+ 00858028 [1025->1456] str '<dummy key>'
+
+The string '<dummy key>', which is used in dictobject.c to overwrite a real
+key that gets deleted, grew several hundred references during cleanup. It
+suggests that stuff did get removed from dicts by cleanup, but that the dicts
+themselves are staying alive for some reason. """
+
+import re
+import sys
+
+# Generate lines from fileiter. If whilematch is true, continue reading
+# while the regexp object pat matches line. If whilematch is false, lines
+# are read so long as pat doesn't match them. In any case, the first line
+# that doesn't match pat (when whilematch is true), or that does match pat
+# (when whilematch is false), is lost, and fileiter will resume at the line
+# following it.
+def read(fileiter, pat, whilematch):
+ for line in fileiter:
+ if bool(pat.match(line)) == whilematch:
+ yield line
+ else:
+ break
+
+def combine(fname):
+ f = file(fname)
+ fi = iter(f)
+
+ for line in read(fi, re.compile(r'^Remaining objects:$'), False):
+ pass
+
+ crack = re.compile(r'([a-zA-Z\d]+) \[(\d+)\] (.*)')
+ addr2rc = {}
+ addr2guts = {}
+ before = 0
+ for line in read(fi, re.compile(r'^Remaining object addresses:$'), False):
+ m = crack.match(line)
+ if m:
+ addr, addr2rc[addr], addr2guts[addr] = m.groups()
+ before += 1
+ else:
+ print '??? skipped:', line
+
+ after = 0
+ for line in read(fi, crack, True):
+ after += 1
+ m = crack.match(line)
+ assert m
+ addr, rc, guts = m.groups() # guts is type name here
+ if addr not in addr2rc:
+ print '??? new object created while tearing down:', line.rstrip()
+ continue
+ print addr,
+ if rc == addr2rc[addr]:
+ print '[%s]' % rc,
+ else:
+ print '[%s->%s]' % (addr2rc[addr], rc),
+ print guts, addr2guts[addr]
+
+ f.close()
+ print "%d objects before, %d after" % (before, after)
+
+if __name__ == '__main__':
+ combine(sys.argv[1])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/copytime.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/copytime.py
new file mode 100644
index 0000000000..0bef525b40
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/copytime.py
@@ -0,0 +1,26 @@
+#! /usr/bin/env python
+
+# Copy one file's atime and mtime to another
+
+import sys
+import os
+from stat import ST_ATIME, ST_MTIME # Really constants 7 and 8
+
+def main():
+ if len(sys.argv) <> 3:
+ sys.stderr.write('usage: copytime source destination\n')
+ sys.exit(2)
+ file1, file2 = sys.argv[1], sys.argv[2]
+ try:
+ stat1 = os.stat(file1)
+ except os.error:
+ sys.stderr.write(file1 + ': cannot stat\n')
+ sys.exit(1)
+ try:
+ os.utime(file2, (stat1[ST_ATIME], stat1[ST_MTIME]))
+ except os.error:
+ sys.stderr.write(file2 + ': cannot change time\n')
+ sys.exit(2)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/crlf.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/crlf.py
new file mode 100644
index 0000000000..d6525aac88
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/crlf.py
@@ -0,0 +1,23 @@
+#! /usr/bin/env python
+"Replace CRLF with LF in argument files. Print names of changed files."
+
+import sys, os
+
+def main():
+ for filename in sys.argv[1:]:
+ if os.path.isdir(filename):
+ print filename, "Directory!"
+ continue
+ data = open(filename, "rb").read()
+ if '\0' in data:
+ print filename, "Binary!"
+ continue
+ newdata = data.replace("\r\n", "\n")
+ if newdata != data:
+ print filename
+ f = open(filename, "wb")
+ f.write(newdata)
+ f.close()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cvsfiles.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cvsfiles.py
new file mode 100644
index 0000000000..a9795ac6cb
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/cvsfiles.py
@@ -0,0 +1,72 @@
+#! /usr/bin/env python
+
+"""Print a list of files that are mentioned in CVS directories.
+
+Usage: cvsfiles.py [-n file] [directory] ...
+
+If the '-n file' option is given, only files under CVS that are newer
+than the given file are printed; by default, all files under CVS are
+printed. As a special case, if a file does not exist, it is always
+printed.
+"""
+
+import os
+import sys
+import stat
+import getopt
+
+cutofftime = 0
+
+def main():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "n:")
+ except getopt.error, msg:
+ print msg
+ print __doc__,
+ return 1
+ global cutofftime
+ newerfile = None
+ for o, a in opts:
+ if o == '-n':
+ cutofftime = getmtime(a)
+ if args:
+ for arg in args:
+ process(arg)
+ else:
+ process(".")
+
+def process(dir):
+ cvsdir = 0
+ subdirs = []
+ names = os.listdir(dir)
+ for name in names:
+ fullname = os.path.join(dir, name)
+ if name == "CVS":
+ cvsdir = fullname
+ else:
+ if os.path.isdir(fullname):
+ if not os.path.islink(fullname):
+ subdirs.append(fullname)
+ if cvsdir:
+ entries = os.path.join(cvsdir, "Entries")
+ for e in open(entries).readlines():
+ words = e.split('/')
+ if words[0] == '' and words[1:]:
+ name = words[1]
+ fullname = os.path.join(dir, name)
+ if cutofftime and getmtime(fullname) <= cutofftime:
+ pass
+ else:
+ print fullname
+ for sub in subdirs:
+ process(sub)
+
+def getmtime(filename):
+ try:
+ st = os.stat(filename)
+ except os.error:
+ return 0
+ return st[stat.ST_MTIME]
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/db2pickle.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/db2pickle.py
new file mode 100644
index 0000000000..df6db980bf
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/db2pickle.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python
+
+"""
+Synopsis: %(prog)s [-h|-g|-b|-r|-a] dbfile [ picklefile ]
+
+Convert the database file given on the command line to a pickle
+representation. The optional flags indicate the type of the database:
+
+ -a - open using anydbm
+ -b - open as bsddb btree file
+ -d - open as dbm file
+ -g - open as gdbm file
+ -h - open as bsddb hash file
+ -r - open as bsddb recno file
+
+The default is hash. If a pickle file is named it is opened for write
+access (deleting any existing data). If no pickle file is named, the pickle
+output is written to standard output.
+
+"""
+
+import getopt
+try:
+ import bsddb
+except ImportError:
+ bsddb = None
+try:
+ import dbm
+except ImportError:
+ dbm = None
+try:
+ import gdbm
+except ImportError:
+ gdbm = None
+try:
+ import anydbm
+except ImportError:
+ anydbm = None
+import sys
+try:
+ import cPickle as pickle
+except ImportError:
+ import pickle
+
+prog = sys.argv[0]
+
+def usage():
+ sys.stderr.write(__doc__ % globals())
+
+def main(args):
+ try:
+ opts, args = getopt.getopt(args, "hbrdag",
+ ["hash", "btree", "recno", "dbm",
+ "gdbm", "anydbm"])
+ except getopt.error:
+ usage()
+ return 1
+
+ if len(args) == 0 or len(args) > 2:
+ usage()
+ return 1
+ elif len(args) == 1:
+ dbfile = args[0]
+ pfile = sys.stdout
+ else:
+ dbfile = args[0]
+ try:
+ pfile = open(args[1], 'wb')
+ except IOError:
+ sys.stderr.write("Unable to open %s\n" % args[1])
+ return 1
+
+ dbopen = None
+ for opt, arg in opts:
+ if opt in ("-h", "--hash"):
+ try:
+ dbopen = bsddb.hashopen
+ except AttributeError:
+ sys.stderr.write("bsddb module unavailable.\n")
+ return 1
+ elif opt in ("-b", "--btree"):
+ try:
+ dbopen = bsddb.btopen
+ except AttributeError:
+ sys.stderr.write("bsddb module unavailable.\n")
+ return 1
+ elif opt in ("-r", "--recno"):
+ try:
+ dbopen = bsddb.rnopen
+ except AttributeError:
+ sys.stderr.write("bsddb module unavailable.\n")
+ return 1
+ elif opt in ("-a", "--anydbm"):
+ try:
+ dbopen = anydbm.open
+ except AttributeError:
+ sys.stderr.write("anydbm module unavailable.\n")
+ return 1
+ elif opt in ("-g", "--gdbm"):
+ try:
+ dbopen = gdbm.open
+ except AttributeError:
+ sys.stderr.write("gdbm module unavailable.\n")
+ return 1
+ elif opt in ("-d", "--dbm"):
+ try:
+ dbopen = dbm.open
+ except AttributeError:
+ sys.stderr.write("dbm module unavailable.\n")
+ return 1
+ if dbopen is None:
+ if bsddb is None:
+ sys.stderr.write("bsddb module unavailable - ")
+ sys.stderr.write("must specify dbtype.\n")
+ return 1
+ else:
+ dbopen = bsddb.hashopen
+
+ try:
+ db = dbopen(dbfile, 'r')
+ except bsddb.error:
+ sys.stderr.write("Unable to open %s. " % dbfile)
+ sys.stderr.write("Check for format or version mismatch.\n")
+ return 1
+
+ for k in db.keys():
+ pickle.dump((k, db[k]), pfile, 1==1)
+
+ db.close()
+ pfile.close()
+
+ return 0
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/diff.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/diff.py
new file mode 100644
index 0000000000..976519362d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/diff.py
@@ -0,0 +1,49 @@
+""" Command line interface to difflib.py providing diffs in four formats:
+
+* ndiff: lists every line and highlights interline changes.
+* context: highlights clusters of changes in a before/after format.
+* unified: highlights clusters of changes in an inline format.
+* html: generates side by side comparison with change highlights.
+
+"""
+
+import sys, os, time, difflib, optparse
+
+def main():
+
+ usage = "usage: %prog [options] fromfile tofile"
+ parser = optparse.OptionParser(usage)
+ parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)')
+ parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff')
+ parser.add_option("-m", action="store_true", default=False, help='Produce HTML side by side diff (can use -c and -l in conjunction)')
+ parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff')
+ parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)')
+ (options, args) = parser.parse_args()
+
+ if len(args) == 0:
+ parser.print_help()
+ sys.exit(1)
+ if len(args) != 2:
+ parser.error("need to specify both a fromfile and tofile")
+
+ n = options.lines
+ fromfile, tofile = args
+
+ fromdate = time.ctime(os.stat(fromfile).st_mtime)
+ todate = time.ctime(os.stat(tofile).st_mtime)
+ fromlines = open(fromfile, 'U').readlines()
+ tolines = open(tofile, 'U').readlines()
+
+ if options.u:
+ diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
+ elif options.n:
+ diff = difflib.ndiff(fromlines, tolines)
+ elif options.m:
+ diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
+ else:
+ diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
+
+ sys.stdout.writelines(diff)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.doc b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.doc
new file mode 100644
index 0000000000..36c765905d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.doc
@@ -0,0 +1,54 @@
+Path: cwi.nl!sun4nl!mcsun!uunet!cs.utexas.edu!convex!usenet
+From: tchrist@convex.COM (Tom Christiansen)
+Newsgroups: comp.lang.perl
+Subject: Re: The problems of Perl (Re: Question (silly?))
+Message-ID: <1992Jan17.053115.4220@convex.com>
+Date: 17 Jan 92 05:31:15 GMT
+References: <17458@ector.cs.purdue.edu> <1992Jan16.165347.25583@cherokee.uswest.com> <=#Hues+4@cs.psu.edu>
+Sender: usenet@convex.com (news access account)
+Reply-To: tchrist@convex.COM (Tom Christiansen)
+Organization: CONVEX Realtime Development, Colorado Springs, CO
+Lines: 83
+Nntp-Posting-Host: pixel.convex.com
+
+From the keyboard of flee@cs.psu.edu (Felix Lee):
+:And Perl is definitely awkward with data types. I haven't yet found a
+:pleasant way of shoving non-trivial data types into Perl's grammar.
+
+Yes, it's pretty aweful at that, alright. Sometimes I write perl programs
+that need them, and sometimes it just takes a little creativity. But
+sometimes it's not worth it. I actually wrote a C program the other day
+(gasp) because I didn't want to deal with a game matrix with six links per node.
+
+:Here's a very simple problem that's tricky to express in Perl: process
+:the output of "du" to produce output that's indented to reflect the
+:tree structure, and with each subtree sorted by size. Something like:
+: 434 /etc
+: | 344 .
+: | 50 install
+: | 35 uucp
+: | 3 nserve
+: | | 2 .
+: | | 1 auth.info
+: | 1 sm
+: | 1 sm.bak
+
+At first I thought I could just keep one local list around
+at once, but this seems inherently recursive. Which means
+I need an real recursive data structure. Maybe you could
+do it with one of the %assoc arrays Larry uses in the begat
+programs, but I broke down and got dirty. I think the hardest
+part was matching Felix's desired output exactly. It's not
+blazingly fast: I should probably inline the &childof routine,
+but it *was* faster to write than I could have written the
+equivalent C program.
+
+
+--tom
+
+--
+"GUIs normally make it simple to accomplish simple actions and impossible
+to accomplish complex actions." --Doug Gwyn (22/Jun/91 in comp.unix.wizards)
+
+ Tom Christiansen tchrist@convex.com convex!tchrist
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.py
new file mode 100644
index 0000000000..422f3bd65f
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/dutree.py
@@ -0,0 +1,60 @@
+#! /usr/bin/env python
+# Format du output in a tree shape
+
+import os, sys, errno
+
+def main():
+ p = os.popen('du ' + ' '.join(sys.argv[1:]), 'r')
+ total, d = None, {}
+ for line in p.readlines():
+ i = 0
+ while line[i] in '0123456789': i = i+1
+ size = eval(line[:i])
+ while line[i] in ' \t': i = i+1
+ filename = line[i:-1]
+ comps = filename.split('/')
+ if comps[0] == '': comps[0] = '/'
+ if comps[len(comps)-1] == '': del comps[len(comps)-1]
+ total, d = store(size, comps, total, d)
+ try:
+ display(total, d)
+ except IOError, e:
+ if e.errno != errno.EPIPE:
+ raise
+
+def store(size, comps, total, d):
+ if comps == []:
+ return size, d
+ if not d.has_key(comps[0]):
+ d[comps[0]] = None, {}
+ t1, d1 = d[comps[0]]
+ d[comps[0]] = store(size, comps[1:], t1, d1)
+ return total, d
+
+def display(total, d):
+ show(total, d, '')
+
+def show(total, d, prefix):
+ if not d: return
+ list = []
+ sum = 0
+ for key in d.keys():
+ tsub, dsub = d[key]
+ list.append((tsub, key))
+ if tsub is not None: sum = sum + tsub
+## if sum < total:
+## list.append((total - sum, os.curdir))
+ list.sort()
+ list.reverse()
+ width = len(repr(list[0][0]))
+ for tsub, key in list:
+ if tsub is None:
+ psub = prefix
+ else:
+ print prefix + repr(tsub).rjust(width) + ' ' + key
+ psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1)
+ if d.has_key(key):
+ show(tsub, d[key][1], psub)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/eptags.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/eptags.py
new file mode 100644
index 0000000000..55afd1311c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/eptags.py
@@ -0,0 +1,56 @@
+#! /usr/bin/env python
+"""Create a TAGS file for Python programs, usable with GNU Emacs.
+
+usage: eptags pyfiles...
+
+The output TAGS file is usable with Emacs version 18, 19, 20.
+Tagged are:
+ - functions (even inside other defs or classes)
+ - classes
+
+eptags warns about files it cannot open.
+eptags will not give warnings about duplicate tags.
+
+BUGS:
+ Because of tag duplication (methods with the same name in different
+ classes), TAGS files are not very useful for most object-oriented
+ python projects.
+"""
+import sys,re
+
+expr = r'^[ \t]*(def|class)[ \t]+([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*[:\(]'
+matcher = re.compile(expr)
+
+def treat_file(filename, outfp):
+ """Append tags found in file named 'filename' to the open file 'outfp'"""
+ try:
+ fp = open(filename, 'r')
+ except:
+ sys.stderr.write('Cannot open %s\n'%filename)
+ return
+ charno = 0
+ lineno = 0
+ tags = []
+ size = 0
+ while 1:
+ line = fp.readline()
+ if not line:
+ break
+ lineno = lineno + 1
+ m = matcher.search(line)
+ if m:
+ tag = m.group(0) + '\177%d,%d\n' % (lineno, charno)
+ tags.append(tag)
+ size = size + len(tag)
+ charno = charno + len(line)
+ outfp.write('\f\n%s,%d\n' % (filename,size))
+ for tag in tags:
+ outfp.write(tag)
+
+def main():
+ outfp = open('TAGS', 'w')
+ for filename in sys.argv[1:]:
+ treat_file(filename, outfp)
+
+if __name__=="__main__":
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/find_recursionlimit.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/find_recursionlimit.py
new file mode 100644
index 0000000000..8b578e9294
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/find_recursionlimit.py
@@ -0,0 +1,117 @@
+#! /usr/bin/env python
+"""Find the maximum recursion limit that prevents interpreter termination.
+
+This script finds the maximum safe recursion limit on a particular
+platform. If you need to change the recursion limit on your system,
+this script will tell you a safe upper bound. To use the new limit,
+call sys.setrecursionlimit().
+
+This module implements several ways to create infinite recursion in
+Python. Different implementations end up pushing different numbers of
+C stack frames, depending on how many calls through Python's abstract
+C API occur.
+
+After each round of tests, it prints a message:
+"Limit of NNNN is fine".
+
+The highest printed value of "NNNN" is therefore the highest potentially
+safe limit for your system (which depends on the OS, architecture, but also
+the compilation flags). Please note that it is practically impossible to
+test all possible recursion paths in the interpreter, so the results of
+this test should not be trusted blindly -- although they give a good hint
+of which values are reasonable.
+
+NOTE: When the C stack space allocated by your system is exceeded due
+to excessive recursion, exact behaviour depends on the platform, although
+the interpreter will always fail in a likely brutal way: either a
+segmentation fault, a MemoryError, or just a silent abort.
+
+NB: A program that does not use __methods__ can set a higher limit.
+"""
+
+import sys
+import itertools
+
+class RecursiveBlowup1:
+ def __init__(self):
+ self.__init__()
+
+def test_init():
+ return RecursiveBlowup1()
+
+class RecursiveBlowup2:
+ def __repr__(self):
+ return repr(self)
+
+def test_repr():
+ return repr(RecursiveBlowup2())
+
+class RecursiveBlowup4:
+ def __add__(self, x):
+ return x + self
+
+def test_add():
+ return RecursiveBlowup4() + RecursiveBlowup4()
+
+class RecursiveBlowup5:
+ def __getattr__(self, attr):
+ return getattr(self, attr)
+
+def test_getattr():
+ return RecursiveBlowup5().attr
+
+class RecursiveBlowup6:
+ def __getitem__(self, item):
+ return self[item - 2] + self[item - 1]
+
+def test_getitem():
+ return RecursiveBlowup6()[5]
+
+def test_recurse():
+ return test_recurse()
+
+def test_cpickle(_cache={}):
+ try:
+ import cPickle
+ except ImportError:
+ print "cannot import cPickle, skipped!"
+ return
+ l = None
+ for n in itertools.count():
+ try:
+ l = _cache[n]
+ continue # Already tried and it works, let's save some time
+ except KeyError:
+ for i in range(100):
+ l = [l]
+ cPickle.dumps(l, protocol=-1)
+ _cache[n] = l
+
+def check_limit(n, test_func_name):
+ sys.setrecursionlimit(n)
+ if test_func_name.startswith("test_"):
+ print test_func_name[5:]
+ else:
+ print test_func_name
+ test_func = globals()[test_func_name]
+ try:
+ test_func()
+ # AttributeError can be raised because of the way e.g. PyDict_GetItem()
+ # silences all exceptions and returns NULL, which is usually interpreted
+ # as "missing attribute".
+ except (RuntimeError, AttributeError):
+ pass
+ else:
+ print "Yikes!"
+
+limit = 1000
+while 1:
+ check_limit(limit, "test_recurse")
+ check_limit(limit, "test_add")
+ check_limit(limit, "test_repr")
+ check_limit(limit, "test_init")
+ check_limit(limit, "test_getattr")
+ check_limit(limit, "test_getitem")
+ check_limit(limit, "test_cpickle")
+ print "Limit of %d is fine" % limit
+ limit = limit + 100
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/finddiv.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/finddiv.py
new file mode 100644
index 0000000000..b7b57c04cf
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/finddiv.py
@@ -0,0 +1,89 @@
+#! /usr/bin/env python
+
+"""finddiv - a grep-like tool that looks for division operators.
+
+Usage: finddiv [-l] file_or_directory ...
+
+For directory arguments, all files in the directory whose name ends in
+.py are processed, and subdirectories are processed recursively.
+
+This actually tokenizes the files to avoid false hits in comments or
+strings literals.
+
+By default, this prints all lines containing a / or /= operator, in
+grep -n style. With the -l option specified, it prints the filename
+of files that contain at least one / or /= operator.
+"""
+
+import os
+import sys
+import getopt
+import tokenize
+
+def main():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "lh")
+ except getopt.error, msg:
+ usage(msg)
+ return 2
+ if not args:
+ usage("at least one file argument is required")
+ return 2
+ listnames = 0
+ for o, a in opts:
+ if o == "-h":
+ print __doc__
+ return
+ if o == "-l":
+ listnames = 1
+ exit = None
+ for filename in args:
+ x = process(filename, listnames)
+ exit = exit or x
+ return exit
+
+def usage(msg):
+ sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
+ sys.stderr.write("Usage: %s [-l] file ...\n" % sys.argv[0])
+ sys.stderr.write("Try `%s -h' for more information.\n" % sys.argv[0])
+
+def process(filename, listnames):
+ if os.path.isdir(filename):
+ return processdir(filename, listnames)
+ try:
+ fp = open(filename)
+ except IOError, msg:
+ sys.stderr.write("Can't open: %s\n" % msg)
+ return 1
+ g = tokenize.generate_tokens(fp.readline)
+ lastrow = None
+ for type, token, (row, col), end, line in g:
+ if token in ("/", "/="):
+ if listnames:
+ print filename
+ break
+ if row != lastrow:
+ lastrow = row
+ print "%s:%d:%s" % (filename, row, line),
+ fp.close()
+
+def processdir(dir, listnames):
+ try:
+ names = os.listdir(dir)
+ except os.error, msg:
+ sys.stderr.write("Can't list directory: %s\n" % dir)
+ return 1
+ files = []
+ for name in names:
+ fn = os.path.join(dir, name)
+ if os.path.normcase(fn).endswith(".py") or os.path.isdir(fn):
+ files.append(fn)
+ files.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b)))
+ exit = None
+ for fn in files:
+ x = process(fn, listnames)
+ exit = exit or x
+ return exit
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findlinksto.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findlinksto.py
new file mode 100644
index 0000000000..81bcf876ee
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findlinksto.py
@@ -0,0 +1,43 @@
+#! /usr/bin/env python
+
+# findlinksto
+#
+# find symbolic links to a path matching a regular expression
+
+import os
+import sys
+import re
+import getopt
+
+def main():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], '')
+ if len(args) < 2:
+ raise getopt.GetoptError('not enough arguments', None)
+ except getopt.GetoptError, msg:
+ sys.stdout = sys.stderr
+ print msg
+ print 'usage: findlinksto pattern directory ...'
+ sys.exit(2)
+ pat, dirs = args[0], args[1:]
+ prog = re.compile(pat)
+ for dirname in dirs:
+ os.path.walk(dirname, visit, prog)
+
+def visit(prog, dirname, names):
+ if os.path.islink(dirname):
+ names[:] = []
+ return
+ if os.path.ismount(dirname):
+ print 'descend into', dirname
+ for name in names:
+ name = os.path.join(dirname, name)
+ try:
+ linkto = os.readlink(name)
+ if prog.search(linkto) is not None:
+ print name, '->', linkto
+ except os.error:
+ pass
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findnocoding.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findnocoding.py
new file mode 100644
index 0000000000..7aad516c09
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/findnocoding.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+
+"""List all those Python files that require a coding directive
+
+Usage: nocoding.py dir1 [dir2...]
+"""
+
+__author__ = "Oleg Broytmann, Georg Brandl"
+
+import sys, os, re, getopt
+
+# our pysource module finds Python source files
+try:
+ import pysource
+except ImportError:
+ # emulate the module with a simple os.walk
+ class pysource:
+ has_python_ext = looks_like_python = can_be_compiled = None
+ def walk_python_files(self, paths, *args, **kwargs):
+ for path in paths:
+ if os.path.isfile(path):
+ yield path.endswith(".py")
+ elif os.path.isdir(path):
+ for root, dirs, files in os.walk(path):
+ for filename in files:
+ if filename.endswith(".py"):
+ yield os.path.join(root, filename)
+ pysource = pysource()
+
+
+ print >>sys.stderr, ("The pysource module is not available; "
+ "no sophisticated Python source file search will be done.")
+
+
+decl_re = re.compile(r"coding[=:]\s*([-\w.]+)")
+
+def get_declaration(line):
+ match = decl_re.search(line)
+ if match:
+ return match.group(1)
+ return ''
+
+def has_correct_encoding(text, codec):
+ try:
+ unicode(text, codec)
+ except UnicodeDecodeError:
+ return False
+ else:
+ return True
+
+def needs_declaration(fullpath):
+ try:
+ infile = open(fullpath, 'rU')
+ except IOError: # Oops, the file was removed - ignore it
+ return None
+
+ line1 = infile.readline()
+ line2 = infile.readline()
+
+ if get_declaration(line1) or get_declaration(line2):
+ # the file does have an encoding declaration, so trust it
+ infile.close()
+ return False
+
+ # check the whole file for non-ASCII characters
+ rest = infile.read()
+ infile.close()
+
+ if has_correct_encoding(line1+line2+rest, "ascii"):
+ return False
+
+ return True
+
+
+usage = """Usage: %s [-cd] paths...
+ -c: recognize Python source files trying to compile them
+ -d: debug output""" % sys.argv[0]
+
+try:
+ opts, args = getopt.getopt(sys.argv[1:], 'cd')
+except getopt.error, msg:
+ print >>sys.stderr, msg
+ print >>sys.stderr, usage
+ sys.exit(1)
+
+is_python = pysource.looks_like_python
+debug = False
+
+for o, a in opts:
+ if o == '-c':
+ is_python = pysource.can_be_compiled
+ elif o == '-d':
+ debug = True
+
+if not args:
+ print >>sys.stderr, usage
+ sys.exit(1)
+
+for fullpath in pysource.walk_python_files(args, is_python):
+ if debug:
+ print "Testing for coding: %s" % fullpath
+ result = needs_declaration(fullpath)
+ if result:
+ print fullpath
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixcid.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixcid.py
new file mode 100644
index 0000000000..ee5a9f6ff7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixcid.py
@@ -0,0 +1,314 @@
+#! /usr/bin/env python
+
+# Perform massive identifier substitution on C source files.
+# This actually tokenizes the files (to some extent) so it can
+# avoid making substitutions inside strings or comments.
+# Inside strings, substitutions are never made; inside comments,
+# it is a user option (off by default).
+#
+# The substitutions are read from one or more files whose lines,
+# when not empty, after stripping comments starting with #,
+# must contain exactly two words separated by whitespace: the
+# old identifier and its replacement.
+#
+# The option -r reverses the sense of the substitutions (this may be
+# useful to undo a particular substitution).
+#
+# If the old identifier is prefixed with a '*' (with no intervening
+# whitespace), then it will not be substituted inside comments.
+#
+# Command line arguments are files or directories to be processed.
+# Directories are searched recursively for files whose name looks
+# like a C file (ends in .h or .c). The special filename '-' means
+# operate in filter mode: read stdin, write stdout.
+#
+# Symbolic links are always ignored (except as explicit directory
+# arguments).
+#
+# The original files are kept as back-up with a "~" suffix.
+#
+# Changes made are reported to stdout in a diff-like format.
+#
+# NB: by changing only the function fixline() you can turn this
+# into a program for different changes to C source files; by
+# changing the function wanted() you can make a different selection of
+# files.
+
+import sys
+import re
+import os
+from stat import *
+import getopt
+
+err = sys.stderr.write
+dbg = err
+rep = sys.stdout.write
+
+def usage():
+ progname = sys.argv[0]
+ err('Usage: ' + progname +
+ ' [-c] [-r] [-s file] ... file-or-directory ...\n')
+ err('\n')
+ err('-c : substitute inside comments\n')
+ err('-r : reverse direction for following -s options\n')
+ err('-s substfile : add a file of substitutions\n')
+ err('\n')
+ err('Each non-empty non-comment line in a substitution file must\n')
+ err('contain exactly two words: an identifier and its replacement.\n')
+ err('Comments start with a # character and end at end of line.\n')
+ err('If an identifier is preceded with a *, it is not substituted\n')
+ err('inside a comment even when -c is specified.\n')
+
+def main():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'crs:')
+ except getopt.error, msg:
+ err('Options error: ' + str(msg) + '\n')
+ usage()
+ sys.exit(2)
+ bad = 0
+ if not args: # No arguments
+ usage()
+ sys.exit(2)
+ for opt, arg in opts:
+ if opt == '-c':
+ setdocomments()
+ if opt == '-r':
+ setreverse()
+ if opt == '-s':
+ addsubst(arg)
+ for arg in args:
+ if os.path.isdir(arg):
+ if recursedown(arg): bad = 1
+ elif os.path.islink(arg):
+ err(arg + ': will not process symbolic links\n')
+ bad = 1
+ else:
+ if fix(arg): bad = 1
+ sys.exit(bad)
+
+# Change this regular expression to select a different set of files
+Wanted = '^[a-zA-Z0-9_]+\.[ch]$'
+def wanted(name):
+ return re.match(Wanted, name) >= 0
+
+def recursedown(dirname):
+ dbg('recursedown(%r)\n' % (dirname,))
+ bad = 0
+ try:
+ names = os.listdir(dirname)
+ except os.error, msg:
+ err(dirname + ': cannot list directory: ' + str(msg) + '\n')
+ return 1
+ names.sort()
+ subdirs = []
+ for name in names:
+ if name in (os.curdir, os.pardir): continue
+ fullname = os.path.join(dirname, name)
+ if os.path.islink(fullname): pass
+ elif os.path.isdir(fullname):
+ subdirs.append(fullname)
+ elif wanted(name):
+ if fix(fullname): bad = 1
+ for fullname in subdirs:
+ if recursedown(fullname): bad = 1
+ return bad
+
+def fix(filename):
+## dbg('fix(%r)\n' % (filename,))
+ if filename == '-':
+ # Filter mode
+ f = sys.stdin
+ g = sys.stdout
+ else:
+ # File replacement mode
+ try:
+ f = open(filename, 'r')
+ except IOError, msg:
+ err(filename + ': cannot open: ' + str(msg) + '\n')
+ return 1
+ head, tail = os.path.split(filename)
+ tempname = os.path.join(head, '@' + tail)
+ g = None
+ # If we find a match, we rewind the file and start over but
+ # now copy everything to a temp file.
+ lineno = 0
+ initfixline()
+ while 1:
+ line = f.readline()
+ if not line: break
+ lineno = lineno + 1
+ while line[-2:] == '\\\n':
+ nextline = f.readline()
+ if not nextline: break
+ line = line + nextline
+ lineno = lineno + 1
+ newline = fixline(line)
+ if newline != line:
+ if g is None:
+ try:
+ g = open(tempname, 'w')
+ except IOError, msg:
+ f.close()
+ err(tempname+': cannot create: '+
+ str(msg)+'\n')
+ return 1
+ f.seek(0)
+ lineno = 0
+ initfixline()
+ rep(filename + ':\n')
+ continue # restart from the beginning
+ rep(repr(lineno) + '\n')
+ rep('< ' + line)
+ rep('> ' + newline)
+ if g is not None:
+ g.write(newline)
+
+ # End of file
+ if filename == '-': return 0 # Done in filter mode
+ f.close()
+ if not g: return 0 # No changes
+
+ # Finishing touch -- move files
+
+ # First copy the file's mode to the temp file
+ try:
+ statbuf = os.stat(filename)
+ os.chmod(tempname, statbuf[ST_MODE] & 07777)
+ except os.error, msg:
+ err(tempname + ': warning: chmod failed (' + str(msg) + ')\n')
+ # Then make a backup of the original file as filename~
+ try:
+ os.rename(filename, filename + '~')
+ except os.error, msg:
+ err(filename + ': warning: backup failed (' + str(msg) + ')\n')
+ # Now move the temp file to the original file
+ try:
+ os.rename(tempname, filename)
+ except os.error, msg:
+ err(filename + ': rename failed (' + str(msg) + ')\n')
+ return 1
+ # Return success
+ return 0
+
+# Tokenizing ANSI C (partly)
+
+Identifier = '\(struct \)?[a-zA-Z_][a-zA-Z0-9_]+'
+String = '"\([^\n\\"]\|\\\\.\)*"'
+Char = '\'\([^\n\\\']\|\\\\.\)*\''
+CommentStart = '/\*'
+CommentEnd = '\*/'
+
+Hexnumber = '0[xX][0-9a-fA-F]*[uUlL]*'
+Octnumber = '0[0-7]*[uUlL]*'
+Decnumber = '[1-9][0-9]*[uUlL]*'
+Intnumber = Hexnumber + '\|' + Octnumber + '\|' + Decnumber
+Exponent = '[eE][-+]?[0-9]+'
+Pointfloat = '\([0-9]+\.[0-9]*\|\.[0-9]+\)\(' + Exponent + '\)?'
+Expfloat = '[0-9]+' + Exponent
+Floatnumber = Pointfloat + '\|' + Expfloat
+Number = Floatnumber + '\|' + Intnumber
+
+# Anything else is an operator -- don't list this explicitly because of '/*'
+
+OutsideComment = (Identifier, Number, String, Char, CommentStart)
+OutsideCommentPattern = '(' + '|'.join(OutsideComment) + ')'
+OutsideCommentProgram = re.compile(OutsideCommentPattern)
+
+InsideComment = (Identifier, Number, CommentEnd)
+InsideCommentPattern = '(' + '|'.join(InsideComment) + ')'
+InsideCommentProgram = re.compile(InsideCommentPattern)
+
+def initfixline():
+ global Program
+ Program = OutsideCommentProgram
+
+def fixline(line):
+ global Program
+## print '-->', repr(line)
+ i = 0
+ while i < len(line):
+ i = Program.search(line, i)
+ if i < 0: break
+ found = Program.group(0)
+## if Program is InsideCommentProgram: print '...',
+## else: print ' ',
+## print found
+ if len(found) == 2:
+ if found == '/*':
+ Program = InsideCommentProgram
+ elif found == '*/':
+ Program = OutsideCommentProgram
+ n = len(found)
+ if Dict.has_key(found):
+ subst = Dict[found]
+ if Program is InsideCommentProgram:
+ if not Docomments:
+ print 'Found in comment:', found
+ i = i + n
+ continue
+ if NotInComment.has_key(found):
+## print 'Ignored in comment:',
+## print found, '-->', subst
+## print 'Line:', line,
+ subst = found
+## else:
+## print 'Substituting in comment:',
+## print found, '-->', subst
+## print 'Line:', line,
+ line = line[:i] + subst + line[i+n:]
+ n = len(subst)
+ i = i + n
+ return line
+
+Docomments = 0
+def setdocomments():
+ global Docomments
+ Docomments = 1
+
+Reverse = 0
+def setreverse():
+ global Reverse
+ Reverse = (not Reverse)
+
+Dict = {}
+NotInComment = {}
+def addsubst(substfile):
+ try:
+ fp = open(substfile, 'r')
+ except IOError, msg:
+ err(substfile + ': cannot read substfile: ' + str(msg) + '\n')
+ sys.exit(1)
+ lineno = 0
+ while 1:
+ line = fp.readline()
+ if not line: break
+ lineno = lineno + 1
+ try:
+ i = line.index('#')
+ except ValueError:
+ i = -1 # Happens to delete trailing \n
+ words = line[:i].split()
+ if not words: continue
+ if len(words) == 3 and words[0] == 'struct':
+ words[:2] = [words[0] + ' ' + words[1]]
+ elif len(words) <> 2:
+ err(substfile + '%s:%r: warning: bad line: %r' % (substfile, lineno, line))
+ continue
+ if Reverse:
+ [value, key] = words
+ else:
+ [key, value] = words
+ if value[0] == '*':
+ value = value[1:]
+ if key[0] == '*':
+ key = key[1:]
+ NotInComment[key] = value
+ if Dict.has_key(key):
+ err('%s:%r: warning: overriding: %r %r\n' % (substfile, lineno, key, value))
+ err('%s:%r: warning: previous: %r\n' % (substfile, lineno, Dict[key]))
+ Dict[key] = value
+ fp.close()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixdiv.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixdiv.py
new file mode 100644
index 0000000000..c10f59dc88
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixdiv.py
@@ -0,0 +1,380 @@
+#! /usr/bin/env python
+
+"""fixdiv - tool to fix division operators.
+
+To use this tool, first run `python -Qwarnall yourscript.py 2>warnings'.
+This runs the script `yourscript.py' while writing warning messages
+about all uses of the classic division operator to the file
+`warnings'. The warnings look like this:
+
+ <file>:<line>: DeprecationWarning: classic <type> division
+
+The warnings are written to stderr, so you must use `2>' for the I/O
+redirect. I know of no way to redirect stderr on Windows in a DOS
+box, so you will have to modify the script to set sys.stderr to some
+kind of log file if you want to do this on Windows.
+
+The warnings are not limited to the script; modules imported by the
+script may also trigger warnings. In fact a useful technique is to
+write a test script specifically intended to exercise all code in a
+particular module or set of modules.
+
+Then run `python fixdiv.py warnings'. This first reads the warnings,
+looking for classic division warnings, and sorts them by file name and
+line number. Then, for each file that received at least one warning,
+it parses the file and tries to match the warnings up to the division
+operators found in the source code. If it is successful, it writes
+its findings to stdout, preceded by a line of dashes and a line of the
+form:
+
+ Index: <file>
+
+If the only findings found are suggestions to change a / operator into
+a // operator, the output is acceptable input for the Unix 'patch'
+program.
+
+Here are the possible messages on stdout (N stands for a line number):
+
+- A plain-diff-style change ('NcN', a line marked by '<', a line
+ containing '---', and a line marked by '>'):
+
+ A / operator was found that should be changed to //. This is the
+ recommendation when only int and/or long arguments were seen.
+
+- 'True division / operator at line N' and a line marked by '=':
+
+ A / operator was found that can remain unchanged. This is the
+ recommendation when only float and/or complex arguments were seen.
+
+- 'Ambiguous / operator (..., ...) at line N', line marked by '?':
+
+ A / operator was found for which int or long as well as float or
+ complex arguments were seen. This is highly unlikely; if it occurs,
+ you may have to restructure the code to keep the classic semantics,
+ or maybe you don't care about the classic semantics.
+
+- 'No conclusive evidence on line N', line marked by '*':
+
+ A / operator was found for which no warnings were seen. This could
+ be code that was never executed, or code that was only executed
+ with user-defined objects as arguments. You will have to
+ investigate further. Note that // can be overloaded separately from
+ /, using __floordiv__. True division can also be separately
+ overloaded, using __truediv__. Classic division should be the same
+ as either of those. (XXX should I add a warning for division on
+ user-defined objects, to disambiguate this case from code that was
+ never executed?)
+
+- 'Phantom ... warnings for line N', line marked by '*':
+
+ A warning was seen for a line not containing a / operator. The most
+ likely cause is a warning about code executed by 'exec' or eval()
+ (see note below), or an indirect invocation of the / operator, for
+ example via the div() function in the operator module. It could
+ also be caused by a change to the file between the time the test
+ script was run to collect warnings and the time fixdiv was run.
+
+- 'More than one / operator in line N'; or
+ 'More than one / operator per statement in lines N-N':
+
+ The scanner found more than one / operator on a single line, or in a
+ statement split across multiple lines. Because the warnings
+ framework doesn't (and can't) show the offset within the line, and
+ the code generator doesn't always give the correct line number for
+ operations in a multi-line statement, we can't be sure whether all
+ operators in the statement were executed. To be on the safe side,
+ by default a warning is issued about this case. In practice, these
+ cases are usually safe, and the -m option suppresses these warning.
+
+- 'Can't find the / operator in line N', line marked by '*':
+
+ This really shouldn't happen. It means that the tokenize module
+ reported a '/' operator but the line it returns didn't contain a '/'
+ character at the indicated position.
+
+- 'Bad warning for line N: XYZ', line marked by '*':
+
+ This really shouldn't happen. It means that a 'classic XYZ
+ division' warning was read with XYZ being something other than
+ 'int', 'long', 'float', or 'complex'.
+
+Notes:
+
+- The augmented assignment operator /= is handled the same way as the
+ / operator.
+
+- This tool never looks at the // operator; no warnings are ever
+ generated for use of this operator.
+
+- This tool never looks at the / operator when a future division
+ statement is in effect; no warnings are generated in this case, and
+ because the tool only looks at files for which at least one classic
+ division warning was seen, it will never look at files containing a
+ future division statement.
+
+- Warnings may be issued for code not read from a file, but executed
+ using an exec statement or the eval() function. These may have
+ <string> in the filename position, in which case the fixdiv script
+ will attempt and fail to open a file named '<string>' and issue a
+ warning about this failure; or these may be reported as 'Phantom'
+ warnings (see above). You're on your own to deal with these. You
+ could make all recommended changes and add a future division
+ statement to all affected files, and then re-run the test script; it
+ should not issue any warnings. If there are any, and you have a
+ hard time tracking down where they are generated, you can use the
+ -Werror option to force an error instead of a first warning,
+ generating a traceback.
+
+- The tool should be run from the same directory as that from which
+ the original script was run, otherwise it won't be able to open
+ files given by relative pathnames.
+"""
+
+import sys
+import getopt
+import re
+import tokenize
+
+multi_ok = 0
+
+def main():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "hm")
+ except getopt.error, msg:
+ usage(msg)
+ return 2
+ for o, a in opts:
+ if o == "-h":
+ print __doc__
+ return
+ if o == "-m":
+ global multi_ok
+ multi_ok = 1
+ if not args:
+ usage("at least one file argument is required")
+ return 2
+ if args[1:]:
+ sys.stderr.write("%s: extra file arguments ignored\n", sys.argv[0])
+ warnings = readwarnings(args[0])
+ if warnings is None:
+ return 1
+ files = warnings.keys()
+ if not files:
+ print "No classic division warnings read from", args[0]
+ return
+ files.sort()
+ exit = None
+ for filename in files:
+ x = process(filename, warnings[filename])
+ exit = exit or x
+ return exit
+
+def usage(msg):
+ sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
+ sys.stderr.write("Usage: %s [-m] warnings\n" % sys.argv[0])
+ sys.stderr.write("Try `%s -h' for more information.\n" % sys.argv[0])
+
+PATTERN = ("^(.+?):(\d+): DeprecationWarning: "
+ "classic (int|long|float|complex) division$")
+
+def readwarnings(warningsfile):
+ prog = re.compile(PATTERN)
+ try:
+ f = open(warningsfile)
+ except IOError, msg:
+ sys.stderr.write("can't open: %s\n" % msg)
+ return
+ warnings = {}
+ while 1:
+ line = f.readline()
+ if not line:
+ break
+ m = prog.match(line)
+ if not m:
+ if line.find("division") >= 0:
+ sys.stderr.write("Warning: ignored input " + line)
+ continue
+ filename, lineno, what = m.groups()
+ list = warnings.get(filename)
+ if list is None:
+ warnings[filename] = list = []
+ list.append((int(lineno), intern(what)))
+ f.close()
+ return warnings
+
+def process(filename, list):
+ print "-"*70
+ assert list # if this fails, readwarnings() is broken
+ try:
+ fp = open(filename)
+ except IOError, msg:
+ sys.stderr.write("can't open: %s\n" % msg)
+ return 1
+ print "Index:", filename
+ f = FileContext(fp)
+ list.sort()
+ index = 0 # list[:index] has been processed, list[index:] is still to do
+ g = tokenize.generate_tokens(f.readline)
+ while 1:
+ startlineno, endlineno, slashes = lineinfo = scanline(g)
+ if startlineno is None:
+ break
+ assert startlineno <= endlineno is not None
+ orphans = []
+ while index < len(list) and list[index][0] < startlineno:
+ orphans.append(list[index])
+ index += 1
+ if orphans:
+ reportphantomwarnings(orphans, f)
+ warnings = []
+ while index < len(list) and list[index][0] <= endlineno:
+ warnings.append(list[index])
+ index += 1
+ if not slashes and not warnings:
+ pass
+ elif slashes and not warnings:
+ report(slashes, "No conclusive evidence")
+ elif warnings and not slashes:
+ reportphantomwarnings(warnings, f)
+ else:
+ if len(slashes) > 1:
+ if not multi_ok:
+ rows = []
+ lastrow = None
+ for (row, col), line in slashes:
+ if row == lastrow:
+ continue
+ rows.append(row)
+ lastrow = row
+ assert rows
+ if len(rows) == 1:
+ print "*** More than one / operator in line", rows[0]
+ else:
+ print "*** More than one / operator per statement",
+ print "in lines %d-%d" % (rows[0], rows[-1])
+ intlong = []
+ floatcomplex = []
+ bad = []
+ for lineno, what in warnings:
+ if what in ("int", "long"):
+ intlong.append(what)
+ elif what in ("float", "complex"):
+ floatcomplex.append(what)
+ else:
+ bad.append(what)
+ lastrow = None
+ for (row, col), line in slashes:
+ if row == lastrow:
+ continue
+ lastrow = row
+ line = chop(line)
+ if line[col:col+1] != "/":
+ print "*** Can't find the / operator in line %d:" % row
+ print "*", line
+ continue
+ if bad:
+ print "*** Bad warning for line %d:" % row, bad
+ print "*", line
+ elif intlong and not floatcomplex:
+ print "%dc%d" % (row, row)
+ print "<", line
+ print "---"
+ print ">", line[:col] + "/" + line[col:]
+ elif floatcomplex and not intlong:
+ print "True division / operator at line %d:" % row
+ print "=", line
+ elif intlong and floatcomplex:
+ print "*** Ambiguous / operator (%s, %s) at line %d:" % (
+ "|".join(intlong), "|".join(floatcomplex), row)
+ print "?", line
+ fp.close()
+
+def reportphantomwarnings(warnings, f):
+ blocks = []
+ lastrow = None
+ lastblock = None
+ for row, what in warnings:
+ if row != lastrow:
+ lastblock = [row]
+ blocks.append(lastblock)
+ lastblock.append(what)
+ for block in blocks:
+ row = block[0]
+ whats = "/".join(block[1:])
+ print "*** Phantom %s warnings for line %d:" % (whats, row)
+ f.report(row, mark="*")
+
+def report(slashes, message):
+ lastrow = None
+ for (row, col), line in slashes:
+ if row != lastrow:
+ print "*** %s on line %d:" % (message, row)
+ print "*", chop(line)
+ lastrow = row
+
+class FileContext:
+ def __init__(self, fp, window=5, lineno=1):
+ self.fp = fp
+ self.window = 5
+ self.lineno = 1
+ self.eoflookahead = 0
+ self.lookahead = []
+ self.buffer = []
+ def fill(self):
+ while len(self.lookahead) < self.window and not self.eoflookahead:
+ line = self.fp.readline()
+ if not line:
+ self.eoflookahead = 1
+ break
+ self.lookahead.append(line)
+ def readline(self):
+ self.fill()
+ if not self.lookahead:
+ return ""
+ line = self.lookahead.pop(0)
+ self.buffer.append(line)
+ self.lineno += 1
+ return line
+ def truncate(self):
+ del self.buffer[-window:]
+ def __getitem__(self, index):
+ self.fill()
+ bufstart = self.lineno - len(self.buffer)
+ lookend = self.lineno + len(self.lookahead)
+ if bufstart <= index < self.lineno:
+ return self.buffer[index - bufstart]
+ if self.lineno <= index < lookend:
+ return self.lookahead[index - self.lineno]
+ raise KeyError
+ def report(self, first, last=None, mark="*"):
+ if last is None:
+ last = first
+ for i in range(first, last+1):
+ try:
+ line = self[first]
+ except KeyError:
+ line = "<missing line>"
+ print mark, chop(line)
+
+def scanline(g):
+ slashes = []
+ startlineno = None
+ endlineno = None
+ for type, token, start, end, line in g:
+ endlineno = end[0]
+ if startlineno is None:
+ startlineno = endlineno
+ if token in ("/", "/="):
+ slashes.append((start, line))
+ if type == tokenize.NEWLINE:
+ break
+ return startlineno, endlineno, slashes
+
+def chop(line):
+ if line.endswith("\n"):
+ return line[:-1]
+ else:
+ return line
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixheader.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixheader.py
new file mode 100644
index 0000000000..25abe9abbc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixheader.py
@@ -0,0 +1,49 @@
+#! /usr/bin/env python
+
+# Add some standard cpp magic to a header file
+
+import sys
+
+def main():
+ args = sys.argv[1:]
+ for filename in args:
+ process(filename)
+
+def process(filename):
+ try:
+ f = open(filename, 'r')
+ except IOError, msg:
+ sys.stderr.write('%s: can\'t open: %s\n' % (filename, str(msg)))
+ return
+ data = f.read()
+ f.close()
+ if data[:2] <> '/*':
+ sys.stderr.write('%s does not begin with C comment\n' % filename)
+ return
+ try:
+ f = open(filename, 'w')
+ except IOError, msg:
+ sys.stderr.write('%s: can\'t write: %s\n' % (filename, str(msg)))
+ return
+ sys.stderr.write('Processing %s ...\n' % filename)
+ magic = 'Py_'
+ for c in filename:
+ if ord(c)<=0x80 and c.isalnum():
+ magic = magic + c.upper()
+ else: magic = magic + '_'
+ sys.stdout = f
+ print '#ifndef', magic
+ print '#define', magic
+ print '#ifdef __cplusplus'
+ print 'extern "C" {'
+ print '#endif'
+ print
+ f.write(data)
+ print
+ print '#ifdef __cplusplus'
+ print '}'
+ print '#endif'
+ print '#endif /*', '!'+magic, '*/'
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixnotice.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixnotice.py
new file mode 100644
index 0000000000..270608f51a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixnotice.py
@@ -0,0 +1,113 @@
+#! /usr/bin/env python
+
+"""(Ostensibly) fix copyright notices in files.
+
+Actually, this sript will simply replace a block of text in a file from one
+string to another. It will only do this once though, i.e. not globally
+throughout the file. It writes a backup file and then does an os.rename()
+dance for atomicity.
+
+Usage: fixnotices.py [options] [filenames]
+Options:
+ -h / --help
+ Print this message and exit
+
+ --oldnotice=file
+ Use the notice in the file as the old (to be replaced) string, instead
+ of the hard coded value in the script.
+
+ --newnotice=file
+ Use the notice in the file as the new (replacement) string, instead of
+ the hard coded value in the script.
+
+ --dry-run
+ Don't actually make the changes, but print out the list of files that
+ would change. When used with -v, a status will be printed for every
+ file.
+
+ -v / --verbose
+ Print a message for every file looked at, indicating whether the file
+ is changed or not.
+"""
+
+OLD_NOTICE = """/***********************************************************
+Copyright (c) 2000, BeOpen.com.
+Copyright (c) 1995-2000, Corporation for National Research Initiatives.
+Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
+All rights reserved.
+
+See the file "Misc/COPYRIGHT" for information on usage and
+redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+******************************************************************/
+"""
+import os
+import sys
+import getopt
+
+NEW_NOTICE = ""
+DRYRUN = 0
+VERBOSE = 0
+
+
+def usage(code, msg=''):
+ print __doc__ % globals()
+ if msg:
+ print msg
+ sys.exit(code)
+
+
+def main():
+ global DRYRUN, OLD_NOTICE, NEW_NOTICE, VERBOSE
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'hv',
+ ['help', 'oldnotice=', 'newnotice=',
+ 'dry-run', 'verbose'])
+ except getopt.error, msg:
+ usage(1, msg)
+
+ for opt, arg in opts:
+ if opt in ('-h', '--help'):
+ usage(0)
+ elif opt in ('-v', '--verbose'):
+ VERBOSE = 1
+ elif opt == '--dry-run':
+ DRYRUN = 1
+ elif opt == '--oldnotice':
+ fp = open(arg)
+ OLD_NOTICE = fp.read()
+ fp.close()
+ elif opt == '--newnotice':
+ fp = open(arg)
+ NEW_NOTICE = fp.read()
+ fp.close()
+
+ for arg in args:
+ process(arg)
+
+
+def process(file):
+ f = open(file)
+ data = f.read()
+ f.close()
+ i = data.find(OLD_NOTICE)
+ if i < 0:
+ if VERBOSE:
+ print 'no change:', file
+ return
+ elif DRYRUN or VERBOSE:
+ print ' change:', file
+ if DRYRUN:
+ # Don't actually change the file
+ return
+ data = data[:i] + NEW_NOTICE + data[i+len(OLD_NOTICE):]
+ new = file + ".new"
+ backup = file + ".bak"
+ f = open(new, "w")
+ f.write(data)
+ f.close()
+ os.rename(file, backup)
+ os.rename(new, file)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixps.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixps.py
new file mode 100644
index 0000000000..87c3a0fa5c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/fixps.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+# Fix Python script(s) to reference the interpreter via /usr/bin/env python.
+# Warning: this overwrites the file without making a backup.
+
+import sys
+import re
+
+
+def main():
+ for filename in sys.argv[1:]:
+ try:
+ f = open(filename, 'r')
+ except IOError, msg:
+ print filename, ': can\'t open :', msg
+ continue
+ line = f.readline()
+ if not re.match('^#! */usr/local/bin/python', line):
+ print filename, ': not a /usr/local/bin/python script'
+ f.close()
+ continue
+ rest = f.read()
+ f.close()
+ line = re.sub('/usr/local/bin/python',
+ '/usr/bin/env python', line)
+ print filename, ':', repr(line)
+ f = open(filename, "w")
+ f.write(line)
+ f.write(rest)
+ f.close()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ftpmirror.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ftpmirror.py
new file mode 100644
index 0000000000..b240c9db9b
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ftpmirror.py
@@ -0,0 +1,400 @@
+#! /usr/bin/env python
+
+"""Mirror a remote ftp subtree into a local directory tree.
+
+usage: ftpmirror [-v] [-q] [-i] [-m] [-n] [-r] [-s pat]
+ [-l username [-p passwd [-a account]]]
+ hostname[:port] [remotedir [localdir]]
+-v: verbose
+-q: quiet
+-i: interactive mode
+-m: macintosh server (NCSA telnet 2.4) (implies -n -s '*.o')
+-n: don't log in
+-r: remove local files/directories no longer pertinent
+-l username [-p passwd [-a account]]: login info (default .netrc or anonymous)
+-s pat: skip files matching pattern
+hostname: remote host w/ optional port separated by ':'
+remotedir: remote directory (default initial)
+localdir: local directory (default current)
+"""
+
+import os
+import sys
+import time
+import getopt
+import ftplib
+import netrc
+from fnmatch import fnmatch
+
+# Print usage message and exit
+def usage(*args):
+ sys.stdout = sys.stderr
+ for msg in args: print msg
+ print __doc__
+ sys.exit(2)
+
+verbose = 1 # 0 for -q, 2 for -v
+interactive = 0
+mac = 0
+rmok = 0
+nologin = 0
+skippats = ['.', '..', '.mirrorinfo']
+
+# Main program: parse command line and start processing
+def main():
+ global verbose, interactive, mac, rmok, nologin
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v')
+ except getopt.error, msg:
+ usage(msg)
+ login = ''
+ passwd = ''
+ account = ''
+ if not args: usage('hostname missing')
+ host = args[0]
+ port = 0
+ if ':' in host:
+ host, port = host.split(':', 1)
+ port = int(port)
+ try:
+ auth = netrc.netrc().authenticators(host)
+ if auth is not None:
+ login, account, passwd = auth
+ except (netrc.NetrcParseError, IOError):
+ pass
+ for o, a in opts:
+ if o == '-l': login = a
+ if o == '-p': passwd = a
+ if o == '-a': account = a
+ if o == '-v': verbose = verbose + 1
+ if o == '-q': verbose = 0
+ if o == '-i': interactive = 1
+ if o == '-m': mac = 1; nologin = 1; skippats.append('*.o')
+ if o == '-n': nologin = 1
+ if o == '-r': rmok = 1
+ if o == '-s': skippats.append(a)
+ remotedir = ''
+ localdir = ''
+ if args[1:]:
+ remotedir = args[1]
+ if args[2:]:
+ localdir = args[2]
+ if args[3:]: usage('too many arguments')
+ #
+ f = ftplib.FTP()
+ if verbose: print "Connecting to '%s%s'..." % (host,
+ (port and ":%d"%port or ""))
+ f.connect(host,port)
+ if not nologin:
+ if verbose:
+ print 'Logging in as %r...' % (login or 'anonymous')
+ f.login(login, passwd, account)
+ if verbose: print 'OK.'
+ pwd = f.pwd()
+ if verbose > 1: print 'PWD =', repr(pwd)
+ if remotedir:
+ if verbose > 1: print 'cwd(%s)' % repr(remotedir)
+ f.cwd(remotedir)
+ if verbose > 1: print 'OK.'
+ pwd = f.pwd()
+ if verbose > 1: print 'PWD =', repr(pwd)
+ #
+ mirrorsubdir(f, localdir)
+
+# Core logic: mirror one subdirectory (recursively)
+def mirrorsubdir(f, localdir):
+ pwd = f.pwd()
+ if localdir and not os.path.isdir(localdir):
+ if verbose: print 'Creating local directory', repr(localdir)
+ try:
+ makedir(localdir)
+ except os.error, msg:
+ print "Failed to establish local directory", repr(localdir)
+ return
+ infofilename = os.path.join(localdir, '.mirrorinfo')
+ try:
+ text = open(infofilename, 'r').read()
+ except IOError, msg:
+ text = '{}'
+ try:
+ info = eval(text)
+ except (SyntaxError, NameError):
+ print 'Bad mirror info in', repr(infofilename)
+ info = {}
+ subdirs = []
+ listing = []
+ if verbose: print 'Listing remote directory %r...' % (pwd,)
+ f.retrlines('LIST', listing.append)
+ filesfound = []
+ for line in listing:
+ if verbose > 1: print '-->', repr(line)
+ if mac:
+ # Mac listing has just filenames;
+ # trailing / means subdirectory
+ filename = line.strip()
+ mode = '-'
+ if filename[-1:] == '/':
+ filename = filename[:-1]
+ mode = 'd'
+ infostuff = ''
+ else:
+ # Parse, assuming a UNIX listing
+ words = line.split(None, 8)
+ if len(words) < 6:
+ if verbose > 1: print 'Skipping short line'
+ continue
+ filename = words[-1].lstrip()
+ i = filename.find(" -> ")
+ if i >= 0:
+ # words[0] had better start with 'l'...
+ if verbose > 1:
+ print 'Found symbolic link %r' % (filename,)
+ linkto = filename[i+4:]
+ filename = filename[:i]
+ infostuff = words[-5:-1]
+ mode = words[0]
+ skip = 0
+ for pat in skippats:
+ if fnmatch(filename, pat):
+ if verbose > 1:
+ print 'Skip pattern', repr(pat),
+ print 'matches', repr(filename)
+ skip = 1
+ break
+ if skip:
+ continue
+ if mode[0] == 'd':
+ if verbose > 1:
+ print 'Remembering subdirectory', repr(filename)
+ subdirs.append(filename)
+ continue
+ filesfound.append(filename)
+ if info.has_key(filename) and info[filename] == infostuff:
+ if verbose > 1:
+ print 'Already have this version of',repr(filename)
+ continue
+ fullname = os.path.join(localdir, filename)
+ tempname = os.path.join(localdir, '@'+filename)
+ if interactive:
+ doit = askabout('file', filename, pwd)
+ if not doit:
+ if not info.has_key(filename):
+ info[filename] = 'Not retrieved'
+ continue
+ try:
+ os.unlink(tempname)
+ except os.error:
+ pass
+ if mode[0] == 'l':
+ if verbose:
+ print "Creating symlink %r -> %r" % (filename, linkto)
+ try:
+ os.symlink(linkto, tempname)
+ except IOError, msg:
+ print "Can't create %r: %s" % (tempname, msg)
+ continue
+ else:
+ try:
+ fp = open(tempname, 'wb')
+ except IOError, msg:
+ print "Can't create %r: %s" % (tempname, msg)
+ continue
+ if verbose:
+ print 'Retrieving %r from %r as %r...' % (filename, pwd, fullname)
+ if verbose:
+ fp1 = LoggingFile(fp, 1024, sys.stdout)
+ else:
+ fp1 = fp
+ t0 = time.time()
+ try:
+ f.retrbinary('RETR ' + filename,
+ fp1.write, 8*1024)
+ except ftplib.error_perm, msg:
+ print msg
+ t1 = time.time()
+ bytes = fp.tell()
+ fp.close()
+ if fp1 != fp:
+ fp1.close()
+ try:
+ os.unlink(fullname)
+ except os.error:
+ pass # Ignore the error
+ try:
+ os.rename(tempname, fullname)
+ except os.error, msg:
+ print "Can't rename %r to %r: %s" % (tempname, fullname, msg)
+ continue
+ info[filename] = infostuff
+ writedict(info, infofilename)
+ if verbose and mode[0] != 'l':
+ dt = t1 - t0
+ kbytes = bytes / 1024.0
+ print int(round(kbytes)),
+ print 'Kbytes in',
+ print int(round(dt)),
+ print 'seconds',
+ if t1 > t0:
+ print '(~%d Kbytes/sec)' % \
+ int(round(kbytes/dt),)
+ print
+ #
+ # Remove files from info that are no longer remote
+ deletions = 0
+ for filename in info.keys():
+ if filename not in filesfound:
+ if verbose:
+ print "Removing obsolete info entry for",
+ print repr(filename), "in", repr(localdir or ".")
+ del info[filename]
+ deletions = deletions + 1
+ if deletions:
+ writedict(info, infofilename)
+ #
+ # Remove local files that are no longer in the remote directory
+ try:
+ if not localdir: names = os.listdir(os.curdir)
+ else: names = os.listdir(localdir)
+ except os.error:
+ names = []
+ for name in names:
+ if name[0] == '.' or info.has_key(name) or name in subdirs:
+ continue
+ skip = 0
+ for pat in skippats:
+ if fnmatch(name, pat):
+ if verbose > 1:
+ print 'Skip pattern', repr(pat),
+ print 'matches', repr(name)
+ skip = 1
+ break
+ if skip:
+ continue
+ fullname = os.path.join(localdir, name)
+ if not rmok:
+ if verbose:
+ print 'Local file', repr(fullname),
+ print 'is no longer pertinent'
+ continue
+ if verbose: print 'Removing local file/dir', repr(fullname)
+ remove(fullname)
+ #
+ # Recursively mirror subdirectories
+ for subdir in subdirs:
+ if interactive:
+ doit = askabout('subdirectory', subdir, pwd)
+ if not doit: continue
+ if verbose: print 'Processing subdirectory', repr(subdir)
+ localsubdir = os.path.join(localdir, subdir)
+ pwd = f.pwd()
+ if verbose > 1:
+ print 'Remote directory now:', repr(pwd)
+ print 'Remote cwd', repr(subdir)
+ try:
+ f.cwd(subdir)
+ except ftplib.error_perm, msg:
+ print "Can't chdir to", repr(subdir), ":", repr(msg)
+ else:
+ if verbose: print 'Mirroring as', repr(localsubdir)
+ mirrorsubdir(f, localsubdir)
+ if verbose > 1: print 'Remote cwd ..'
+ f.cwd('..')
+ newpwd = f.pwd()
+ if newpwd != pwd:
+ print 'Ended up in wrong directory after cd + cd ..'
+ print 'Giving up now.'
+ break
+ else:
+ if verbose > 1: print 'OK.'
+
+# Helper to remove a file or directory tree
+def remove(fullname):
+ if os.path.isdir(fullname) and not os.path.islink(fullname):
+ try:
+ names = os.listdir(fullname)
+ except os.error:
+ names = []
+ ok = 1
+ for name in names:
+ if not remove(os.path.join(fullname, name)):
+ ok = 0
+ if not ok:
+ return 0
+ try:
+ os.rmdir(fullname)
+ except os.error, msg:
+ print "Can't remove local directory %r: %s" % (fullname, msg)
+ return 0
+ else:
+ try:
+ os.unlink(fullname)
+ except os.error, msg:
+ print "Can't remove local file %r: %s" % (fullname, msg)
+ return 0
+ return 1
+
+# Wrapper around a file for writing to write a hash sign every block.
+class LoggingFile:
+ def __init__(self, fp, blocksize, outfp):
+ self.fp = fp
+ self.bytes = 0
+ self.hashes = 0
+ self.blocksize = blocksize
+ self.outfp = outfp
+ def write(self, data):
+ self.bytes = self.bytes + len(data)
+ hashes = int(self.bytes) / self.blocksize
+ while hashes > self.hashes:
+ self.outfp.write('#')
+ self.outfp.flush()
+ self.hashes = self.hashes + 1
+ self.fp.write(data)
+ def close(self):
+ self.outfp.write('\n')
+
+# Ask permission to download a file.
+def askabout(filetype, filename, pwd):
+ prompt = 'Retrieve %s %s from %s ? [ny] ' % (filetype, filename, pwd)
+ while 1:
+ reply = raw_input(prompt).strip().lower()
+ if reply in ['y', 'ye', 'yes']:
+ return 1
+ if reply in ['', 'n', 'no', 'nop', 'nope']:
+ return 0
+ print 'Please answer yes or no.'
+
+# Create a directory if it doesn't exist. Recursively create the
+# parent directory as well if needed.
+def makedir(pathname):
+ if os.path.isdir(pathname):
+ return
+ dirname = os.path.dirname(pathname)
+ if dirname: makedir(dirname)
+ os.mkdir(pathname, 0777)
+
+# Write a dictionary to a file in a way that can be read back using
+# rval() but is still somewhat readable (i.e. not a single long line).
+# Also creates a backup file.
+def writedict(dict, filename):
+ dir, fname = os.path.split(filename)
+ tempname = os.path.join(dir, '@' + fname)
+ backup = os.path.join(dir, fname + '~')
+ try:
+ os.unlink(backup)
+ except os.error:
+ pass
+ fp = open(tempname, 'w')
+ fp.write('{\n')
+ for key, value in dict.items():
+ fp.write('%r: %r,\n' % (key, value))
+ fp.write('}\n')
+ fp.close()
+ try:
+ os.rename(filename, backup)
+ except os.error:
+ pass
+ os.rename(tempname, filename)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/google.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/google.py
new file mode 100644
index 0000000000..f81e35a4e3
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/google.py
@@ -0,0 +1,23 @@
+#! /usr/bin/env python
+
+import sys, webbrowser
+
+def main():
+ args = sys.argv[1:]
+ if not args:
+ print "Usage: %s querystring" % sys.argv[0]
+ return
+ list = []
+ for arg in args:
+ if '+' in arg:
+ arg = arg.replace('+', '%2B')
+ if ' ' in arg:
+ arg = '"%s"' % arg
+ arg = arg.replace(' ', '+')
+ list.append(arg)
+ s = '+'.join(list)
+ url = "http://www.google.com/search?q=%s" % s
+ webbrowser.open(url)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/gprof2html.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/gprof2html.py
new file mode 100644
index 0000000000..270252053e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/gprof2html.py
@@ -0,0 +1,79 @@
+#! /usr/bin/env python2.3
+
+"""Transform gprof(1) output into useful HTML."""
+
+import re, os, sys, cgi, webbrowser
+
+header = """\
+<html>
+<head>
+ <title>gprof output (%s)</title>
+</head>
+<body>
+<pre>
+"""
+
+trailer = """\
+</pre>
+</body>
+</html>
+"""
+
+def add_escapes(input):
+ for line in input:
+ yield cgi.escape(line)
+
+def main():
+ filename = "gprof.out"
+ if sys.argv[1:]:
+ filename = sys.argv[1]
+ outputfilename = filename + ".html"
+ input = add_escapes(file(filename))
+ output = file(outputfilename, "w")
+ output.write(header % filename)
+ for line in input:
+ output.write(line)
+ if line.startswith(" time"):
+ break
+ labels = {}
+ for line in input:
+ m = re.match(r"(.* )(\w+)\n", line)
+ if not m:
+ output.write(line)
+ break
+ stuff, fname = m.group(1, 2)
+ labels[fname] = fname
+ output.write('%s<a name="flat:%s" href="#call:%s">%s</a>\n' %
+ (stuff, fname, fname, fname))
+ for line in input:
+ output.write(line)
+ if line.startswith("index % time"):
+ break
+ for line in input:
+ m = re.match(r"(.* )(\w+)(( &lt;cycle.*&gt;)? \[\d+\])\n", line)
+ if not m:
+ output.write(line)
+ if line.startswith("Index by function name"):
+ break
+ continue
+ prefix, fname, suffix = m.group(1, 2, 3)
+ if fname not in labels:
+ output.write(line)
+ continue
+ if line.startswith("["):
+ output.write('%s<a name="call:%s" href="#flat:%s">%s</a>%s\n' %
+ (prefix, fname, fname, fname, suffix))
+ else:
+ output.write('%s<a href="#call:%s">%s</a>%s\n' %
+ (prefix, fname, fname, suffix))
+ for line in input:
+ for part in re.findall(r"(\w+(?:\.c)?|\W+)", line):
+ if part in labels:
+ part = '<a href="#call:%s">%s</a>' % (part, part)
+ output.write(part)
+ output.write(trailer)
+ output.close()
+ webbrowser.open("file:" + os.path.abspath(outputfilename))
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/h2py.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/h2py.py
new file mode 100644
index 0000000000..3cec1ba8b0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/h2py.py
@@ -0,0 +1,175 @@
+#! /usr/bin/env python
+
+# Read #define's and translate to Python code.
+# Handle #include statements.
+# Handle #define macros with one argument.
+# Anything that isn't recognized or doesn't translate into valid
+# Python is ignored.
+
+# Without filename arguments, acts as a filter.
+# If one or more filenames are given, output is written to corresponding
+# filenames in the local directory, translated to all uppercase, with
+# the extension replaced by ".py".
+
+# By passing one or more options of the form "-i regular_expression"
+# you can specify additional strings to be ignored. This is useful
+# e.g. to ignore casts to u_long: simply specify "-i '(u_long)'".
+
+# XXX To do:
+# - turn trailing C comments into Python comments
+# - turn C Boolean operators "&& || !" into Python "and or not"
+# - what to do about #if(def)?
+# - what to do about macros with multiple parameters?
+
+import sys, re, getopt, os
+
+p_define = re.compile('^[\t ]*#[\t ]*define[\t ]+([a-zA-Z0-9_]+)[\t ]+')
+
+p_macro = re.compile(
+ '^[\t ]*#[\t ]*define[\t ]+'
+ '([a-zA-Z0-9_]+)\(([_a-zA-Z][_a-zA-Z0-9]*)\)[\t ]+')
+
+p_include = re.compile('^[\t ]*#[\t ]*include[\t ]+<([a-zA-Z0-9_/\.]+)')
+
+p_comment = re.compile(r'/\*([^*]+|\*+[^/])*(\*+/)?')
+p_cpp_comment = re.compile('//.*')
+
+ignores = [p_comment, p_cpp_comment]
+
+p_char = re.compile(r"'(\\.[^\\]*|[^\\])'")
+
+p_hex = re.compile(r"0x([0-9a-fA-F]+)L?")
+
+filedict = {}
+importable = {}
+
+try:
+ searchdirs=os.environ['include'].split(';')
+except KeyError:
+ try:
+ searchdirs=os.environ['INCLUDE'].split(';')
+ except KeyError:
+ try:
+ if sys.platform.find("beos") == 0:
+ searchdirs=os.environ['BEINCLUDES'].split(';')
+ elif sys.platform.startswith("atheos"):
+ searchdirs=os.environ['C_INCLUDE_PATH'].split(':')
+ else:
+ raise KeyError
+ except KeyError:
+ searchdirs=['/usr/include']
+
+def main():
+ global filedict
+ opts, args = getopt.getopt(sys.argv[1:], 'i:')
+ for o, a in opts:
+ if o == '-i':
+ ignores.append(re.compile(a))
+ if not args:
+ args = ['-']
+ for filename in args:
+ if filename == '-':
+ sys.stdout.write('# Generated by h2py from stdin\n')
+ process(sys.stdin, sys.stdout)
+ else:
+ fp = open(filename, 'r')
+ outfile = os.path.basename(filename)
+ i = outfile.rfind('.')
+ if i > 0: outfile = outfile[:i]
+ modname = outfile.upper()
+ outfile = modname + '.py'
+ outfp = open(outfile, 'w')
+ outfp.write('# Generated by h2py from %s\n' % filename)
+ filedict = {}
+ for dir in searchdirs:
+ if filename[:len(dir)] == dir:
+ filedict[filename[len(dir)+1:]] = None # no '/' trailing
+ importable[filename[len(dir)+1:]] = modname
+ break
+ process(fp, outfp)
+ outfp.close()
+ fp.close()
+
+def pytify(body):
+ # replace ignored patterns by spaces
+ for p in ignores:
+ body = p.sub(' ', body)
+ # replace char literals by ord(...)
+ body = p_char.sub("ord('\\1')", body)
+ # Compute negative hexadecimal constants
+ start = 0
+ UMAX = 2*(sys.maxint+1)
+ while 1:
+ m = p_hex.search(body, start)
+ if not m: break
+ s,e = m.span()
+ val = long(body[slice(*m.span(1))], 16)
+ if val > sys.maxint:
+ val -= UMAX
+ body = body[:s] + "(" + str(val) + ")" + body[e:]
+ start = s + 1
+ return body
+
+def process(fp, outfp, env = {}):
+ lineno = 0
+ while 1:
+ line = fp.readline()
+ if not line: break
+ lineno = lineno + 1
+ match = p_define.match(line)
+ if match:
+ # gobble up continuation lines
+ while line[-2:] == '\\\n':
+ nextline = fp.readline()
+ if not nextline: break
+ lineno = lineno + 1
+ line = line + nextline
+ name = match.group(1)
+ body = line[match.end():]
+ body = pytify(body)
+ ok = 0
+ stmt = '%s = %s\n' % (name, body.strip())
+ try:
+ exec stmt in env
+ except:
+ sys.stderr.write('Skipping: %s' % stmt)
+ else:
+ outfp.write(stmt)
+ match = p_macro.match(line)
+ if match:
+ macro, arg = match.group(1, 2)
+ body = line[match.end():]
+ body = pytify(body)
+ stmt = 'def %s(%s): return %s\n' % (macro, arg, body)
+ try:
+ exec stmt in env
+ except:
+ sys.stderr.write('Skipping: %s' % stmt)
+ else:
+ outfp.write(stmt)
+ match = p_include.match(line)
+ if match:
+ regs = match.regs
+ a, b = regs[1]
+ filename = line[a:b]
+ if importable.has_key(filename):
+ outfp.write('from %s import *\n' % importable[filename])
+ elif not filedict.has_key(filename):
+ filedict[filename] = None
+ inclfp = None
+ for dir in searchdirs:
+ try:
+ inclfp = open(dir + '/' + filename)
+ break
+ except IOError:
+ pass
+ if inclfp:
+ outfp.write(
+ '\n# Included from %s\n' % filename)
+ process(inclfp, outfp, env)
+ else:
+ sys.stderr.write('Warning - could not find file %s\n' %
+ filename)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/hotshotmain.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/hotshotmain.py
new file mode 100644
index 0000000000..d94a2f9f05
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/hotshotmain.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+# -*- coding: iso-8859-1 -*-
+
+"""
+Run a Python script under hotshot's control.
+
+Adapted from a posting on python-dev by Walter Dörwald
+
+usage %prog [ %prog args ] filename [ filename args ]
+
+Any arguments after the filename are used as sys.argv for the filename.
+"""
+
+import sys
+import optparse
+import os
+import hotshot
+import hotshot.stats
+
+PROFILE = "hotshot.prof"
+
+def run_hotshot(filename, profile, args):
+ prof = hotshot.Profile(profile)
+ sys.path.insert(0, os.path.dirname(filename))
+ sys.argv = [filename] + args
+ prof.run("execfile(%r)" % filename)
+ prof.close()
+ stats = hotshot.stats.load(profile)
+ stats.sort_stats("time", "calls")
+
+ # print_stats uses unadorned print statements, so the only way
+ # to force output to stderr is to reassign sys.stdout temporarily
+ save_stdout = sys.stdout
+ sys.stdout = sys.stderr
+ stats.print_stats()
+ sys.stdout = save_stdout
+
+ return 0
+
+def main(args):
+ parser = optparse.OptionParser(__doc__)
+ parser.disable_interspersed_args()
+ parser.add_option("-p", "--profile", action="store", default=PROFILE,
+ dest="profile", help='Specify profile file to use')
+ (options, args) = parser.parse_args(args)
+
+ if len(args) == 0:
+ parser.print_help("missing script to execute")
+ return 1
+
+ filename = args[0]
+ return run_hotshot(filename, options.profile, args[1:])
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/idle b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/idle
new file mode 100644
index 0000000000..bc13a074bc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/idle
@@ -0,0 +1,5 @@
+#! /usr/bin/env python
+
+from idlelib.PyShell import main
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ifdef.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ifdef.py
new file mode 100644
index 0000000000..594c06b66a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ifdef.py
@@ -0,0 +1,112 @@
+#! /usr/bin/env python
+
+# Selectively preprocess #ifdef / #ifndef statements.
+# Usage:
+# ifdef [-Dname] ... [-Uname] ... [file] ...
+#
+# This scans the file(s), looking for #ifdef and #ifndef preprocessor
+# commands that test for one of the names mentioned in the -D and -U
+# options. On standard output it writes a copy of the input file(s)
+# minus those code sections that are suppressed by the selected
+# combination of defined/undefined symbols. The #if(n)def/#else/#else
+# lines themselfs (if the #if(n)def tests for one of the mentioned
+# names) are removed as well.
+
+# Features: Arbitrary nesting of recognized and unrecognized
+# preprocesor statements works correctly. Unrecognized #if* commands
+# are left in place, so it will never remove too much, only too
+# little. It does accept whitespace around the '#' character.
+
+# Restrictions: There should be no comments or other symbols on the
+# #if(n)def lines. The effect of #define/#undef commands in the input
+# file or in included files is not taken into account. Tests using
+# #if and the defined() pseudo function are not recognized. The #elif
+# command is not recognized. Improperly nesting is not detected.
+# Lines that look like preprocessor commands but which are actually
+# part of comments or string literals will be mistaken for
+# preprocessor commands.
+
+import sys
+import getopt
+
+defs = []
+undefs = []
+
+def main():
+ opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
+ for o, a in opts:
+ if o == '-D':
+ defs.append(a)
+ if o == '-U':
+ undefs.append(a)
+ if not args:
+ args = ['-']
+ for filename in args:
+ if filename == '-':
+ process(sys.stdin, sys.stdout)
+ else:
+ f = open(filename, 'r')
+ process(f, sys.stdout)
+ f.close()
+
+def process(fpi, fpo):
+ keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif')
+ ok = 1
+ stack = []
+ while 1:
+ line = fpi.readline()
+ if not line: break
+ while line[-2:] == '\\\n':
+ nextline = fpi.readline()
+ if not nextline: break
+ line = line + nextline
+ tmp = line.strip()
+ if tmp[:1] != '#':
+ if ok: fpo.write(line)
+ continue
+ tmp = tmp[1:].strip()
+ words = tmp.split()
+ keyword = words[0]
+ if keyword not in keywords:
+ if ok: fpo.write(line)
+ continue
+ if keyword in ('ifdef', 'ifndef') and len(words) == 2:
+ if keyword == 'ifdef':
+ ko = 1
+ else:
+ ko = 0
+ word = words[1]
+ if word in defs:
+ stack.append((ok, ko, word))
+ if not ko: ok = 0
+ elif word in undefs:
+ stack.append((ok, not ko, word))
+ if ko: ok = 0
+ else:
+ stack.append((ok, -1, word))
+ if ok: fpo.write(line)
+ elif keyword == 'if':
+ stack.append((ok, -1, ''))
+ if ok: fpo.write(line)
+ elif keyword == 'else' and stack:
+ s_ok, s_ko, s_word = stack[-1]
+ if s_ko < 0:
+ if ok: fpo.write(line)
+ else:
+ s_ko = not s_ko
+ ok = s_ok
+ if not s_ko: ok = 0
+ stack[-1] = s_ok, s_ko, s_word
+ elif keyword == 'endif' and stack:
+ s_ok, s_ko, s_word = stack[-1]
+ if s_ko < 0:
+ if ok: fpo.write(line)
+ del stack[-1]
+ ok = s_ok
+ else:
+ sys.stderr.write('Unknown keyword %s\n' % keyword)
+ if stack:
+ sys.stderr.write('stack: %s\n' % stack)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lfcr.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lfcr.py
new file mode 100644
index 0000000000..10112728aa
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lfcr.py
@@ -0,0 +1,24 @@
+#! /usr/bin/env python
+
+"Replace LF with CRLF in argument files. Print names of changed files."
+
+import sys, re, os
+
+def main():
+ for filename in sys.argv[1:]:
+ if os.path.isdir(filename):
+ print filename, "Directory!"
+ continue
+ data = open(filename, "rb").read()
+ if '\0' in data:
+ print filename, "Binary!"
+ continue
+ newdata = re.sub("\r?\n", "\r\n", data)
+ if newdata != data:
+ print filename
+ f = open(filename, "wb")
+ f.write(newdata)
+ f.close()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/linktree.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/linktree.py
new file mode 100644
index 0000000000..78c1597ab1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/linktree.py
@@ -0,0 +1,80 @@
+#! /usr/bin/env python
+
+# linktree
+#
+# Make a copy of a directory tree with symbolic links to all files in the
+# original tree.
+# All symbolic links go to a special symbolic link at the top, so you
+# can easily fix things if the original source tree moves.
+# See also "mkreal".
+#
+# usage: mklinks oldtree newtree
+
+import sys, os
+
+LINK = '.LINK' # Name of special symlink at the top.
+
+debug = 0
+
+def main():
+ if not 3 <= len(sys.argv) <= 4:
+ print 'usage:', sys.argv[0], 'oldtree newtree [linkto]'
+ return 2
+ oldtree, newtree = sys.argv[1], sys.argv[2]
+ if len(sys.argv) > 3:
+ link = sys.argv[3]
+ link_may_fail = 1
+ else:
+ link = LINK
+ link_may_fail = 0
+ if not os.path.isdir(oldtree):
+ print oldtree + ': not a directory'
+ return 1
+ try:
+ os.mkdir(newtree, 0777)
+ except os.error, msg:
+ print newtree + ': cannot mkdir:', msg
+ return 1
+ linkname = os.path.join(newtree, link)
+ try:
+ os.symlink(os.path.join(os.pardir, oldtree), linkname)
+ except os.error, msg:
+ if not link_may_fail:
+ print linkname + ': cannot symlink:', msg
+ return 1
+ else:
+ print linkname + ': warning: cannot symlink:', msg
+ linknames(oldtree, newtree, link)
+ return 0
+
+def linknames(old, new, link):
+ if debug: print 'linknames', (old, new, link)
+ try:
+ names = os.listdir(old)
+ except os.error, msg:
+ print old + ': warning: cannot listdir:', msg
+ return
+ for name in names:
+ if name not in (os.curdir, os.pardir):
+ oldname = os.path.join(old, name)
+ linkname = os.path.join(link, name)
+ newname = os.path.join(new, name)
+ if debug > 1: print oldname, newname, linkname
+ if os.path.isdir(oldname) and \
+ not os.path.islink(oldname):
+ try:
+ os.mkdir(newname, 0777)
+ ok = 1
+ except:
+ print newname + \
+ ': warning: cannot mkdir:', msg
+ ok = 0
+ if ok:
+ linkname = os.path.join(os.pardir,
+ linkname)
+ linknames(oldname, newname, linkname)
+ else:
+ os.symlink(linkname, newname)
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lll.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lll.py
new file mode 100644
index 0000000000..e95e1fbcae
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/lll.py
@@ -0,0 +1,28 @@
+#! /usr/bin/env python
+
+# Find symbolic links and show where they point to.
+# Arguments are directories to search; default is current directory.
+# No recursion.
+# (This is a totally different program from "findsymlinks.py"!)
+
+import sys, os
+
+def lll(dirname):
+ for name in os.listdir(dirname):
+ if name not in (os.curdir, os.pardir):
+ full = os.path.join(dirname, name)
+ if os.path.islink(full):
+ print name, '->', os.readlink(full)
+def main():
+ args = sys.argv[1:]
+ if not args: args = [os.curdir]
+ first = 1
+ for arg in args:
+ if len(args) > 1:
+ if not first: print
+ first = 0
+ print arg + ':'
+ lll(arg)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/logmerge.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/logmerge.py
new file mode 100644
index 0000000000..2759c9aa18
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/logmerge.py
@@ -0,0 +1,185 @@
+#! /usr/bin/env python
+
+"""Consolidate a bunch of CVS or RCS logs read from stdin.
+
+Input should be the output of a CVS or RCS logging command, e.g.
+
+ cvs log -rrelease14:
+
+which dumps all log messages from release1.4 upwards (assuming that
+release 1.4 was tagged with tag 'release14'). Note the trailing
+colon!
+
+This collects all the revision records and outputs them sorted by date
+rather than by file, collapsing duplicate revision record, i.e.,
+records with the same message for different files.
+
+The -t option causes it to truncate (discard) the last revision log
+entry; this is useful when using something like the above cvs log
+command, which shows the revisions including the given tag, while you
+probably want everything *since* that tag.
+
+The -r option reverses the output (oldest first; the default is oldest
+last).
+
+The -b tag option restricts the output to *only* checkin messages
+belonging to the given branch tag. The form -b HEAD restricts the
+output to checkin messages belonging to the CVS head (trunk). (It
+produces some output if tag is a non-branch tag, but this output is
+not very useful.)
+
+-h prints this message and exits.
+
+XXX This code was created by reverse engineering CVS 1.9 and RCS 5.7
+from their output.
+"""
+
+import sys, errno, getopt, re
+
+sep1 = '='*77 + '\n' # file separator
+sep2 = '-'*28 + '\n' # revision separator
+
+def main():
+ """Main program"""
+ truncate_last = 0
+ reverse = 0
+ branch = None
+ opts, args = getopt.getopt(sys.argv[1:], "trb:h")
+ for o, a in opts:
+ if o == '-t':
+ truncate_last = 1
+ elif o == '-r':
+ reverse = 1
+ elif o == '-b':
+ branch = a
+ elif o == '-h':
+ print __doc__
+ sys.exit(0)
+ database = []
+ while 1:
+ chunk = read_chunk(sys.stdin)
+ if not chunk:
+ break
+ records = digest_chunk(chunk, branch)
+ if truncate_last:
+ del records[-1]
+ database[len(database):] = records
+ database.sort()
+ if not reverse:
+ database.reverse()
+ format_output(database)
+
+def read_chunk(fp):
+ """Read a chunk -- data for one file, ending with sep1.
+
+ Split the chunk in parts separated by sep2.
+
+ """
+ chunk = []
+ lines = []
+ while 1:
+ line = fp.readline()
+ if not line:
+ break
+ if line == sep1:
+ if lines:
+ chunk.append(lines)
+ break
+ if line == sep2:
+ if lines:
+ chunk.append(lines)
+ lines = []
+ else:
+ lines.append(line)
+ return chunk
+
+def digest_chunk(chunk, branch=None):
+ """Digest a chunk -- extract working file name and revisions"""
+ lines = chunk[0]
+ key = 'Working file:'
+ keylen = len(key)
+ for line in lines:
+ if line[:keylen] == key:
+ working_file = line[keylen:].strip()
+ break
+ else:
+ working_file = None
+ if branch is None:
+ pass
+ elif branch == "HEAD":
+ branch = re.compile(r"^\d+\.\d+$")
+ else:
+ revisions = {}
+ key = 'symbolic names:\n'
+ found = 0
+ for line in lines:
+ if line == key:
+ found = 1
+ elif found:
+ if line[0] in '\t ':
+ tag, rev = line.split()
+ if tag[-1] == ':':
+ tag = tag[:-1]
+ revisions[tag] = rev
+ else:
+ found = 0
+ rev = revisions.get(branch)
+ branch = re.compile(r"^<>$") # <> to force a mismatch by default
+ if rev:
+ if rev.find('.0.') >= 0:
+ rev = rev.replace('.0.', '.')
+ branch = re.compile(r"^" + re.escape(rev) + r"\.\d+$")
+ records = []
+ for lines in chunk[1:]:
+ revline = lines[0]
+ dateline = lines[1]
+ text = lines[2:]
+ words = dateline.split()
+ author = None
+ if len(words) >= 3 and words[0] == 'date:':
+ dateword = words[1]
+ timeword = words[2]
+ if timeword[-1:] == ';':
+ timeword = timeword[:-1]
+ date = dateword + ' ' + timeword
+ if len(words) >= 5 and words[3] == 'author:':
+ author = words[4]
+ if author[-1:] == ';':
+ author = author[:-1]
+ else:
+ date = None
+ text.insert(0, revline)
+ words = revline.split()
+ if len(words) >= 2 and words[0] == 'revision':
+ rev = words[1]
+ else:
+ # No 'revision' line -- weird...
+ rev = None
+ text.insert(0, revline)
+ if branch:
+ if rev is None or not branch.match(rev):
+ continue
+ records.append((date, working_file, rev, author, text))
+ return records
+
+def format_output(database):
+ prevtext = None
+ prev = []
+ database.append((None, None, None, None, None)) # Sentinel
+ for (date, working_file, rev, author, text) in database:
+ if text != prevtext:
+ if prev:
+ print sep2,
+ for (p_date, p_working_file, p_rev, p_author) in prev:
+ print p_date, p_author, p_working_file, p_rev
+ sys.stdout.writelines(prevtext)
+ prev = []
+ prev.append((date, working_file, rev, author))
+ prevtext = text
+
+if __name__ == '__main__':
+ try:
+ main()
+ except IOError, e:
+ if e.errno != errno.EPIPE:
+ raise
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mailerdaemon.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mailerdaemon.py
new file mode 100644
index 0000000000..5661cc0947
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mailerdaemon.py
@@ -0,0 +1,237 @@
+"""mailerdaemon - classes to parse mailer-daemon messages"""
+
+import rfc822
+import calendar
+import re
+import os
+import sys
+
+Unparseable = 'mailerdaemon.Unparseable'
+
+class ErrorMessage(rfc822.Message):
+ def __init__(self, fp):
+ rfc822.Message.__init__(self, fp)
+ self.sub = ''
+
+ def is_warning(self):
+ sub = self.getheader('Subject')
+ if not sub:
+ return 0
+ sub = sub.lower()
+ if sub.startswith('waiting mail'): return 1
+ if 'warning' in sub: return 1
+ self.sub = sub
+ return 0
+
+ def get_errors(self):
+ for p in EMPARSERS:
+ self.rewindbody()
+ try:
+ return p(self.fp, self.sub)
+ except Unparseable:
+ pass
+ raise Unparseable
+
+# List of re's or tuples of re's.
+# If a re, it should contain at least a group (?P<email>...) which
+# should refer to the email address. The re can also contain a group
+# (?P<reason>...) which should refer to the reason (error message).
+# If no reason is present, the emparse_list_reason list is used to
+# find a reason.
+# If a tuple, the tuple should contain 2 re's. The first re finds a
+# location, the second re is repeated one or more times to find
+# multiple email addresses. The second re is matched (not searched)
+# where the previous match ended.
+# The re's are compiled using the re module.
+emparse_list_list = [
+ 'error: (?P<reason>unresolvable): (?P<email>.+)',
+ ('----- The following addresses had permanent fatal errors -----\n',
+ '(?P<email>[^ \n].*)\n( .*\n)?'),
+ 'remote execution.*\n.*rmail (?P<email>.+)',
+ ('The following recipients did not receive your message:\n\n',
+ ' +(?P<email>.*)\n(The following recipients did not receive your message:\n\n)?'),
+ '------- Failure Reasons --------\n\n(?P<reason>.*)\n(?P<email>.*)',
+ '^<(?P<email>.*)>:\n(?P<reason>.*)',
+ '^(?P<reason>User mailbox exceeds allowed size): (?P<email>.+)',
+ '^5\\d{2} <(?P<email>[^\n>]+)>\\.\\.\\. (?P<reason>.+)',
+ '^Original-Recipient: rfc822;(?P<email>.*)',
+ '^did not reach the following recipient\\(s\\):\n\n(?P<email>.*) on .*\n +(?P<reason>.*)',
+ '^ <(?P<email>[^\n>]+)> \\.\\.\\. (?P<reason>.*)',
+ '^Report on your message to: (?P<email>.*)\nReason: (?P<reason>.*)',
+ '^Your message was not delivered to +(?P<email>.*)\n +for the following reason:\n +(?P<reason>.*)',
+ '^ was not +(?P<email>[^ \n].*?) *\n.*\n.*\n.*\n because:.*\n +(?P<reason>[^ \n].*?) *\n',
+ ]
+# compile the re's in the list and store them in-place.
+for i in range(len(emparse_list_list)):
+ x = emparse_list_list[i]
+ if type(x) is type(''):
+ x = re.compile(x, re.MULTILINE)
+ else:
+ xl = []
+ for x in x:
+ xl.append(re.compile(x, re.MULTILINE))
+ x = tuple(xl)
+ del xl
+ emparse_list_list[i] = x
+ del x
+del i
+
+# list of re's used to find reasons (error messages).
+# if a string, "<>" is replaced by a copy of the email address.
+# The expressions are searched for in order. After the first match,
+# no more expressions are searched for. So, order is important.
+emparse_list_reason = [
+ r'^5\d{2} <>\.\.\. (?P<reason>.*)',
+ '<>\.\.\. (?P<reason>.*)',
+ re.compile(r'^<<< 5\d{2} (?P<reason>.*)', re.MULTILINE),
+ re.compile('===== stderr was =====\nrmail: (?P<reason>.*)'),
+ re.compile('^Diagnostic-Code: (?P<reason>.*)', re.MULTILINE),
+ ]
+emparse_list_from = re.compile('^From:', re.IGNORECASE|re.MULTILINE)
+def emparse_list(fp, sub):
+ data = fp.read()
+ res = emparse_list_from.search(data)
+ if res is None:
+ from_index = len(data)
+ else:
+ from_index = res.start(0)
+ errors = []
+ emails = []
+ reason = None
+ for regexp in emparse_list_list:
+ if type(regexp) is type(()):
+ res = regexp[0].search(data, 0, from_index)
+ if res is not None:
+ try:
+ reason = res.group('reason')
+ except IndexError:
+ pass
+ while 1:
+ res = regexp[1].match(data, res.end(0), from_index)
+ if res is None:
+ break
+ emails.append(res.group('email'))
+ break
+ else:
+ res = regexp.search(data, 0, from_index)
+ if res is not None:
+ emails.append(res.group('email'))
+ try:
+ reason = res.group('reason')
+ except IndexError:
+ pass
+ break
+ if not emails:
+ raise Unparseable
+ if not reason:
+ reason = sub
+ if reason[:15] == 'returned mail: ':
+ reason = reason[15:]
+ for regexp in emparse_list_reason:
+ if type(regexp) is type(''):
+ for i in range(len(emails)-1,-1,-1):
+ email = emails[i]
+ exp = re.compile(re.escape(email).join(regexp.split('<>')), re.MULTILINE)
+ res = exp.search(data)
+ if res is not None:
+ errors.append(' '.join((email.strip()+': '+res.group('reason')).split()))
+ del emails[i]
+ continue
+ res = regexp.search(data)
+ if res is not None:
+ reason = res.group('reason')
+ break
+ for email in emails:
+ errors.append(' '.join((email.strip()+': '+reason).split()))
+ return errors
+
+EMPARSERS = [emparse_list, ]
+
+def sort_numeric(a, b):
+ a = int(a)
+ b = int(b)
+ if a < b: return -1
+ elif a > b: return 1
+ else: return 0
+
+def parsedir(dir, modify):
+ os.chdir(dir)
+ pat = re.compile('^[0-9]*$')
+ errordict = {}
+ errorfirst = {}
+ errorlast = {}
+ nok = nwarn = nbad = 0
+
+ # find all numeric file names and sort them
+ files = filter(lambda fn, pat=pat: pat.match(fn) is not None, os.listdir('.'))
+ files.sort(sort_numeric)
+
+ for fn in files:
+ # Lets try to parse the file.
+ fp = open(fn)
+ m = ErrorMessage(fp)
+ sender = m.getaddr('From')
+ print '%s\t%-40s\t'%(fn, sender[1]),
+
+ if m.is_warning():
+ fp.close()
+ print 'warning only'
+ nwarn = nwarn + 1
+ if modify:
+ os.rename(fn, ','+fn)
+## os.unlink(fn)
+ continue
+
+ try:
+ errors = m.get_errors()
+ except Unparseable:
+ print '** Not parseable'
+ nbad = nbad + 1
+ fp.close()
+ continue
+ print len(errors), 'errors'
+
+ # Remember them
+ for e in errors:
+ try:
+ mm, dd = m.getdate('date')[1:1+2]
+ date = '%s %02d' % (calendar.month_abbr[mm], dd)
+ except:
+ date = '??????'
+ if not errordict.has_key(e):
+ errordict[e] = 1
+ errorfirst[e] = '%s (%s)' % (fn, date)
+ else:
+ errordict[e] = errordict[e] + 1
+ errorlast[e] = '%s (%s)' % (fn, date)
+
+ fp.close()
+ nok = nok + 1
+ if modify:
+ os.rename(fn, ','+fn)
+## os.unlink(fn)
+
+ print '--------------'
+ print nok, 'files parsed,',nwarn,'files warning-only,',
+ print nbad,'files unparseable'
+ print '--------------'
+ list = []
+ for e in errordict.keys():
+ list.append((errordict[e], errorfirst[e], errorlast[e], e))
+ list.sort()
+ for num, first, last, e in list:
+ print '%d %s - %s\t%s' % (num, first, last, e)
+
+def main():
+ modify = 0
+ if len(sys.argv) > 1 and sys.argv[1] == '-d':
+ modify = 1
+ del sys.argv[1]
+ if len(sys.argv) > 1:
+ for folder in sys.argv[1:]:
+ parsedir(folder, modify)
+ else:
+ parsedir('/ufs/jack/Mail/errorsinbox', modify)
+
+if __name__ == '__main__' or sys.argv[0] == __name__:
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/md5sum.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/md5sum.py
new file mode 100644
index 0000000000..6c8ba669a9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/md5sum.py
@@ -0,0 +1,90 @@
+#! /usr/bin/env python
+
+"""Python utility to print MD5 checksums of argument files.
+"""
+
+
+bufsize = 8096
+fnfilter = None
+rmode = 'rb'
+
+usage = """
+usage: sum5 [-b] [-t] [-l] [-s bufsize] [file ...]
+-b : read files in binary mode (default)
+-t : read files in text mode (you almost certainly don't want this!)
+-l : print last pathname component only
+-s bufsize: read buffer size (default %d)
+file ... : files to sum; '-' or no files means stdin
+""" % bufsize
+
+import sys
+import os
+import getopt
+import md5
+
+def sum(*files):
+ sts = 0
+ if files and isinstance(files[-1], file):
+ out, files = files[-1], files[:-1]
+ else:
+ out = sys.stdout
+ if len(files) == 1 and not isinstance(files[0], str):
+ files = files[0]
+ for f in files:
+ if isinstance(f, str):
+ if f == '-':
+ sts = printsumfp(sys.stdin, '<stdin>', out) or sts
+ else:
+ sts = printsum(f, out) or sts
+ else:
+ sts = sum(f, out) or sts
+ return sts
+
+def printsum(filename, out=sys.stdout):
+ try:
+ fp = open(filename, rmode)
+ except IOError, msg:
+ sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg))
+ return 1
+ if fnfilter:
+ filename = fnfilter(filename)
+ sts = printsumfp(fp, filename, out)
+ fp.close()
+ return sts
+
+def printsumfp(fp, filename, out=sys.stdout):
+ m = md5.new()
+ try:
+ while 1:
+ data = fp.read(bufsize)
+ if not data:
+ break
+ m.update(data)
+ except IOError, msg:
+ sys.stderr.write('%s: I/O error: %s\n' % (filename, msg))
+ return 1
+ out.write('%s %s\n' % (m.hexdigest(), filename))
+ return 0
+
+def main(args = sys.argv[1:], out=sys.stdout):
+ global fnfilter, rmode, bufsize
+ try:
+ opts, args = getopt.getopt(args, 'blts:')
+ except getopt.error, msg:
+ sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage))
+ return 2
+ for o, a in opts:
+ if o == '-l':
+ fnfilter = os.path.basename
+ elif o == '-b':
+ rmode = 'rb'
+ elif o == '-t':
+ rmode = 'r'
+ elif o == '-s':
+ bufsize = int(a)
+ if not args:
+ args = ['-']
+ return sum(args, out)
+
+if __name__ == '__main__' or __name__ == sys.argv[0]:
+ sys.exit(main(sys.argv[1:], sys.stdout))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/methfix.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/methfix.py
new file mode 100644
index 0000000000..585fdb981b
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/methfix.py
@@ -0,0 +1,171 @@
+#! /usr/bin/env python
+
+# Fix Python source files to avoid using
+# def method(self, (arg1, ..., argn)):
+# instead of the more rational
+# def method(self, arg1, ..., argn):
+#
+# Command line arguments are files or directories to be processed.
+# Directories are searched recursively for files whose name looks
+# like a python module.
+# Symbolic links are always ignored (except as explicit directory
+# arguments). Of course, the original file is kept as a back-up
+# (with a "~" attached to its name).
+# It complains about binaries (files containing null bytes)
+# and about files that are ostensibly not Python files: if the first
+# line starts with '#!' and does not contain the string 'python'.
+#
+# Changes made are reported to stdout in a diff-like format.
+#
+# Undoubtedly you can do this using find and sed or perl, but this is
+# a nice example of Python code that recurses down a directory tree
+# and uses regular expressions. Also note several subtleties like
+# preserving the file's mode and avoiding to even write a temp file
+# when no changes are needed for a file.
+#
+# NB: by changing only the function fixline() you can turn this
+# into a program for a different change to Python programs...
+
+import sys
+import re
+import os
+from stat import *
+
+err = sys.stderr.write
+dbg = err
+rep = sys.stdout.write
+
+def main():
+ bad = 0
+ if not sys.argv[1:]: # No arguments
+ err('usage: ' + sys.argv[0] + ' file-or-directory ...\n')
+ sys.exit(2)
+ for arg in sys.argv[1:]:
+ if os.path.isdir(arg):
+ if recursedown(arg): bad = 1
+ elif os.path.islink(arg):
+ err(arg + ': will not process symbolic links\n')
+ bad = 1
+ else:
+ if fix(arg): bad = 1
+ sys.exit(bad)
+
+ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
+def ispython(name):
+ return ispythonprog.match(name) >= 0
+
+def recursedown(dirname):
+ dbg('recursedown(%r)\n' % (dirname,))
+ bad = 0
+ try:
+ names = os.listdir(dirname)
+ except os.error, msg:
+ err('%s: cannot list directory: %r\n' % (dirname, msg))
+ return 1
+ names.sort()
+ subdirs = []
+ for name in names:
+ if name in (os.curdir, os.pardir): continue
+ fullname = os.path.join(dirname, name)
+ if os.path.islink(fullname): pass
+ elif os.path.isdir(fullname):
+ subdirs.append(fullname)
+ elif ispython(name):
+ if fix(fullname): bad = 1
+ for fullname in subdirs:
+ if recursedown(fullname): bad = 1
+ return bad
+
+def fix(filename):
+## dbg('fix(%r)\n' % (filename,))
+ try:
+ f = open(filename, 'r')
+ except IOError, msg:
+ err('%s: cannot open: %r\n' % (filename, msg))
+ return 1
+ head, tail = os.path.split(filename)
+ tempname = os.path.join(head, '@' + tail)
+ g = None
+ # If we find a match, we rewind the file and start over but
+ # now copy everything to a temp file.
+ lineno = 0
+ while 1:
+ line = f.readline()
+ if not line: break
+ lineno = lineno + 1
+ if g is None and '\0' in line:
+ # Check for binary files
+ err(filename + ': contains null bytes; not fixed\n')
+ f.close()
+ return 1
+ if lineno == 1 and g is None and line[:2] == '#!':
+ # Check for non-Python scripts
+ words = line[2:].split()
+ if words and re.search('[pP]ython', words[0]) < 0:
+ msg = filename + ': ' + words[0]
+ msg = msg + ' script; not fixed\n'
+ err(msg)
+ f.close()
+ return 1
+ while line[-2:] == '\\\n':
+ nextline = f.readline()
+ if not nextline: break
+ line = line + nextline
+ lineno = lineno + 1
+ newline = fixline(line)
+ if newline != line:
+ if g is None:
+ try:
+ g = open(tempname, 'w')
+ except IOError, msg:
+ f.close()
+ err('%s: cannot create: %r\n' % (tempname, msg))
+ return 1
+ f.seek(0)
+ lineno = 0
+ rep(filename + ':\n')
+ continue # restart from the beginning
+ rep(repr(lineno) + '\n')
+ rep('< ' + line)
+ rep('> ' + newline)
+ if g is not None:
+ g.write(newline)
+
+ # End of file
+ f.close()
+ if not g: return 0 # No changes
+
+ # Finishing touch -- move files
+
+ # First copy the file's mode to the temp file
+ try:
+ statbuf = os.stat(filename)
+ os.chmod(tempname, statbuf[ST_MODE] & 07777)
+ except os.error, msg:
+ err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
+ # Then make a backup of the original file as filename~
+ try:
+ os.rename(filename, filename + '~')
+ except os.error, msg:
+ err('%s: warning: backup failed (%r)\n' % (filename, msg))
+ # Now move the temp file to the original file
+ try:
+ os.rename(tempname, filename)
+ except os.error, msg:
+ err('%s: rename failed (%r)\n' % (filename, msg))
+ return 1
+ # Return succes
+ return 0
+
+
+fixpat = '^[ \t]+def +[a-zA-Z0-9_]+ *( *self *, *(( *(.*) *)) *) *:'
+fixprog = re.compile(fixpat)
+
+def fixline(line):
+ if fixprog.match(line) >= 0:
+ (a, b), (c, d) = fixprog.regs[1:3]
+ line = line[:a] + line[c:d] + line[b:]
+ return line
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mkreal.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mkreal.py
new file mode 100644
index 0000000000..da2f410b10
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/mkreal.py
@@ -0,0 +1,66 @@
+#! /usr/bin/env python
+
+# mkreal
+#
+# turn a symlink to a directory into a real directory
+
+import sys
+import os
+from stat import *
+
+join = os.path.join
+
+error = 'mkreal error'
+
+BUFSIZE = 32*1024
+
+def mkrealfile(name):
+ st = os.stat(name) # Get the mode
+ mode = S_IMODE(st[ST_MODE])
+ linkto = os.readlink(name) # Make sure again it's a symlink
+ f_in = open(name, 'r') # This ensures it's a file
+ os.unlink(name)
+ f_out = open(name, 'w')
+ while 1:
+ buf = f_in.read(BUFSIZE)
+ if not buf: break
+ f_out.write(buf)
+ del f_out # Flush data to disk before changing mode
+ os.chmod(name, mode)
+
+def mkrealdir(name):
+ st = os.stat(name) # Get the mode
+ mode = S_IMODE(st[ST_MODE])
+ linkto = os.readlink(name)
+ files = os.listdir(name)
+ os.unlink(name)
+ os.mkdir(name, mode)
+ os.chmod(name, mode)
+ linkto = join(os.pardir, linkto)
+ #
+ for filename in files:
+ if filename not in (os.curdir, os.pardir):
+ os.symlink(join(linkto, filename), join(name, filename))
+
+def main():
+ sys.stdout = sys.stderr
+ progname = os.path.basename(sys.argv[0])
+ if progname == '-c': progname = 'mkreal'
+ args = sys.argv[1:]
+ if not args:
+ print 'usage:', progname, 'path ...'
+ sys.exit(2)
+ status = 0
+ for name in args:
+ if not os.path.islink(name):
+ print progname+':', name+':', 'not a symlink'
+ status = 1
+ else:
+ if os.path.isdir(name):
+ mkrealdir(name)
+ else:
+ mkrealfile(name)
+ sys.exit(status)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ndiff.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ndiff.py
new file mode 100644
index 0000000000..c0e79e2f41
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ndiff.py
@@ -0,0 +1,133 @@
+#! /usr/bin/env python
+
+# Module ndiff version 1.7.0
+# Released to the public domain 08-Dec-2000,
+# by Tim Peters (tim.one@home.com).
+
+# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
+
+# ndiff.py is now simply a front-end to the difflib.ndiff() function.
+# Originally, it contained the difflib.SequenceMatcher class as well.
+# This completes the raiding of reusable code from this formerly
+# self-contained script.
+
+"""ndiff [-q] file1 file2
+ or
+ndiff (-r1 | -r2) < ndiff_output > file1_or_file2
+
+Print a human-friendly file difference report to stdout. Both inter-
+and intra-line differences are noted. In the second form, recreate file1
+(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.
+
+In the first form, if -q ("quiet") is not specified, the first two lines
+of output are
+
+-: file1
++: file2
+
+Each remaining line begins with a two-letter code:
+
+ "- " line unique to file1
+ "+ " line unique to file2
+ " " line common to both files
+ "? " line not present in either input file
+
+Lines beginning with "? " attempt to guide the eye to intraline
+differences, and were not present in either input file. These lines can be
+confusing if the source files contain tab characters.
+
+The first file can be recovered by retaining only lines that begin with
+" " or "- ", and deleting those 2-character prefixes; use ndiff with -r1.
+
+The second file can be recovered similarly, but by retaining only " " and
+"+ " lines; use ndiff with -r2; or, on Unix, the second file can be
+recovered by piping the output through
+
+ sed -n '/^[+ ] /s/^..//p'
+"""
+
+__version__ = 1, 7, 0
+
+import difflib, sys
+
+def fail(msg):
+ out = sys.stderr.write
+ out(msg + "\n\n")
+ out(__doc__)
+ return 0
+
+# open a file & return the file object; gripe and return 0 if it
+# couldn't be opened
+def fopen(fname):
+ try:
+ return open(fname, 'U')
+ except IOError, detail:
+ return fail("couldn't open " + fname + ": " + str(detail))
+
+# open two files & spray the diff to stdout; return false iff a problem
+def fcompare(f1name, f2name):
+ f1 = fopen(f1name)
+ f2 = fopen(f2name)
+ if not f1 or not f2:
+ return 0
+
+ a = f1.readlines(); f1.close()
+ b = f2.readlines(); f2.close()
+ for line in difflib.ndiff(a, b):
+ print line,
+
+ return 1
+
+# crack args (sys.argv[1:] is normal) & compare;
+# return false iff a problem
+
+def main(args):
+ import getopt
+ try:
+ opts, args = getopt.getopt(args, "qr:")
+ except getopt.error, detail:
+ return fail(str(detail))
+ noisy = 1
+ qseen = rseen = 0
+ for opt, val in opts:
+ if opt == "-q":
+ qseen = 1
+ noisy = 0
+ elif opt == "-r":
+ rseen = 1
+ whichfile = val
+ if qseen and rseen:
+ return fail("can't specify both -q and -r")
+ if rseen:
+ if args:
+ return fail("no args allowed with -r option")
+ if whichfile in ("1", "2"):
+ restore(whichfile)
+ return 1
+ return fail("-r value must be 1 or 2")
+ if len(args) != 2:
+ return fail("need 2 filename args")
+ f1name, f2name = args
+ if noisy:
+ print '-:', f1name
+ print '+:', f2name
+ return fcompare(f1name, f2name)
+
+# read ndiff output from stdin, and print file1 (which=='1') or
+# file2 (which=='2') to stdout
+
+def restore(which):
+ restored = difflib.restore(sys.stdin.readlines(), which)
+ sys.stdout.writelines(restored)
+
+if __name__ == '__main__':
+ args = sys.argv[1:]
+ if "-profile" in args:
+ import profile, pstats
+ args.remove("-profile")
+ statf = "ndiff.pro"
+ profile.run("main(args)", statf)
+ stats = pstats.Stats(statf)
+ stats.strip_dirs().sort_stats('time').print_stats()
+ else:
+ main(args)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/nm2def.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/nm2def.py
new file mode 100644
index 0000000000..a0b14b5532
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/nm2def.py
@@ -0,0 +1,103 @@
+#! /usr/bin/env python
+"""nm2def.py
+
+Helpers to extract symbols from Unix libs and auto-generate
+Windows definition files from them. Depends on nm(1). Tested
+on Linux and Solaris only (-p option to nm is for Solaris only).
+
+By Marc-Andre Lemburg, Aug 1998.
+
+Additional notes: the output of nm is supposed to look like this:
+
+acceler.o:
+000001fd T PyGrammar_AddAccelerators
+ U PyGrammar_FindDFA
+00000237 T PyGrammar_RemoveAccelerators
+ U _IO_stderr_
+ U exit
+ U fprintf
+ U free
+ U malloc
+ U printf
+
+grammar1.o:
+00000000 T PyGrammar_FindDFA
+00000034 T PyGrammar_LabelRepr
+ U _PyParser_TokenNames
+ U abort
+ U printf
+ U sprintf
+
+...
+
+Even if this isn't the default output of your nm, there is generally an
+option to produce this format (since it is the original v7 Unix format).
+
+"""
+import os, sys
+
+PYTHONLIB = 'libpython'+sys.version[:3]+'.a'
+PC_PYTHONLIB = 'Python'+sys.version[0]+sys.version[2]+'.dll'
+NM = 'nm -p -g %s' # For Linux, use "nm -g %s"
+
+def symbols(lib=PYTHONLIB,types=('T','C','D')):
+
+ lines = os.popen(NM % lib).readlines()
+ lines = [s.strip() for s in lines]
+ symbols = {}
+ for line in lines:
+ if len(line) == 0 or ':' in line:
+ continue
+ items = line.split()
+ if len(items) != 3:
+ continue
+ address, type, name = items
+ if type not in types:
+ continue
+ symbols[name] = address,type
+ return symbols
+
+def export_list(symbols):
+
+ data = []
+ code = []
+ for name,(addr,type) in symbols.items():
+ if type in ('C','D'):
+ data.append('\t'+name)
+ else:
+ code.append('\t'+name)
+ data.sort()
+ data.append('')
+ code.sort()
+ return ' DATA\n'.join(data)+'\n'+'\n'.join(code)
+
+# Definition file template
+DEF_TEMPLATE = """\
+EXPORTS
+%s
+"""
+
+# Special symbols that have to be included even though they don't
+# pass the filter
+SPECIALS = (
+ )
+
+def filter_Python(symbols,specials=SPECIALS):
+
+ for name in symbols.keys():
+ if name[:2] == 'Py' or name[:3] == '_Py':
+ pass
+ elif name not in specials:
+ del symbols[name]
+
+def main():
+
+ s = symbols(PYTHONLIB)
+ filter_Python(s)
+ exports = export_list(s)
+ f = sys.stdout # open('PC/python_nt.def','w')
+ f.write(DEF_TEMPLATE % (exports))
+ f.close()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/objgraph.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/objgraph.py
new file mode 100644
index 0000000000..d20bfdf994
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/objgraph.py
@@ -0,0 +1,215 @@
+#! /usr/bin/env python
+
+# objgraph
+#
+# Read "nm -o" input (on IRIX: "nm -Bo") of a set of libraries or modules
+# and print various interesting listings, such as:
+#
+# - which names are used but not defined in the set (and used where),
+# - which names are defined in the set (and where),
+# - which modules use which other modules,
+# - which modules are used by which other modules.
+#
+# Usage: objgraph [-cdu] [file] ...
+# -c: print callers per objectfile
+# -d: print callees per objectfile
+# -u: print usage of undefined symbols
+# If none of -cdu is specified, all are assumed.
+# Use "nm -o" to generate the input (on IRIX: "nm -Bo"),
+# e.g.: nm -o /lib/libc.a | objgraph
+
+
+import sys
+import os
+import getopt
+import re
+
+# Types of symbols.
+#
+definitions = 'TRGDSBAEC'
+externals = 'UV'
+ignore = 'Nntrgdsbavuc'
+
+# Regular expression to parse "nm -o" output.
+#
+matcher = re.compile('(.*):\t?........ (.) (.*)$')
+
+# Store "item" in "dict" under "key".
+# The dictionary maps keys to lists of items.
+# If there is no list for the key yet, it is created.
+#
+def store(dict, key, item):
+ if dict.has_key(key):
+ dict[key].append(item)
+ else:
+ dict[key] = [item]
+
+# Return a flattened version of a list of strings: the concatenation
+# of its elements with intervening spaces.
+#
+def flat(list):
+ s = ''
+ for item in list:
+ s = s + ' ' + item
+ return s[1:]
+
+# Global variables mapping defined/undefined names to files and back.
+#
+file2undef = {}
+def2file = {}
+file2def = {}
+undef2file = {}
+
+# Read one input file and merge the data into the tables.
+# Argument is an open file.
+#
+def readinput(fp):
+ while 1:
+ s = fp.readline()
+ if not s:
+ break
+ # If you get any output from this line,
+ # it is probably caused by an unexpected input line:
+ if matcher.search(s) < 0: s; continue # Shouldn't happen
+ (ra, rb), (r1a, r1b), (r2a, r2b), (r3a, r3b) = matcher.regs[:4]
+ fn, name, type = s[r1a:r1b], s[r3a:r3b], s[r2a:r2b]
+ if type in definitions:
+ store(def2file, name, fn)
+ store(file2def, fn, name)
+ elif type in externals:
+ store(file2undef, fn, name)
+ store(undef2file, name, fn)
+ elif not type in ignore:
+ print fn + ':' + name + ': unknown type ' + type
+
+# Print all names that were undefined in some module and where they are
+# defined.
+#
+def printcallee():
+ flist = file2undef.keys()
+ flist.sort()
+ for filename in flist:
+ print filename + ':'
+ elist = file2undef[filename]
+ elist.sort()
+ for ext in elist:
+ if len(ext) >= 8:
+ tabs = '\t'
+ else:
+ tabs = '\t\t'
+ if not def2file.has_key(ext):
+ print '\t' + ext + tabs + ' *undefined'
+ else:
+ print '\t' + ext + tabs + flat(def2file[ext])
+
+# Print for each module the names of the other modules that use it.
+#
+def printcaller():
+ files = file2def.keys()
+ files.sort()
+ for filename in files:
+ callers = []
+ for label in file2def[filename]:
+ if undef2file.has_key(label):
+ callers = callers + undef2file[label]
+ if callers:
+ callers.sort()
+ print filename + ':'
+ lastfn = ''
+ for fn in callers:
+ if fn <> lastfn:
+ print '\t' + fn
+ lastfn = fn
+ else:
+ print filename + ': unused'
+
+# Print undefined names and where they are used.
+#
+def printundef():
+ undefs = {}
+ for filename in file2undef.keys():
+ for ext in file2undef[filename]:
+ if not def2file.has_key(ext):
+ store(undefs, ext, filename)
+ elist = undefs.keys()
+ elist.sort()
+ for ext in elist:
+ print ext + ':'
+ flist = undefs[ext]
+ flist.sort()
+ for filename in flist:
+ print '\t' + filename
+
+# Print warning messages about names defined in more than one file.
+#
+def warndups():
+ savestdout = sys.stdout
+ sys.stdout = sys.stderr
+ names = def2file.keys()
+ names.sort()
+ for name in names:
+ if len(def2file[name]) > 1:
+ print 'warning:', name, 'multiply defined:',
+ print flat(def2file[name])
+ sys.stdout = savestdout
+
+# Main program
+#
+def main():
+ try:
+ optlist, args = getopt.getopt(sys.argv[1:], 'cdu')
+ except getopt.error:
+ sys.stdout = sys.stderr
+ print 'Usage:', os.path.basename(sys.argv[0]),
+ print '[-cdu] [file] ...'
+ print '-c: print callers per objectfile'
+ print '-d: print callees per objectfile'
+ print '-u: print usage of undefined symbols'
+ print 'If none of -cdu is specified, all are assumed.'
+ print 'Use "nm -o" to generate the input (on IRIX: "nm -Bo"),'
+ print 'e.g.: nm -o /lib/libc.a | objgraph'
+ return 1
+ optu = optc = optd = 0
+ for opt, void in optlist:
+ if opt == '-u':
+ optu = 1
+ elif opt == '-c':
+ optc = 1
+ elif opt == '-d':
+ optd = 1
+ if optu == optc == optd == 0:
+ optu = optc = optd = 1
+ if not args:
+ args = ['-']
+ for filename in args:
+ if filename == '-':
+ readinput(sys.stdin)
+ else:
+ readinput(open(filename, 'r'))
+ #
+ warndups()
+ #
+ more = (optu + optc + optd > 1)
+ if optd:
+ if more:
+ print '---------------All callees------------------'
+ printcallee()
+ if optu:
+ if more:
+ print '---------------Undefined callees------------'
+ printundef()
+ if optc:
+ if more:
+ print '---------------All Callers------------------'
+ printcaller()
+ return 0
+
+# Call the main program.
+# Use its return value as exit status.
+# Catch interrupts to avoid stack trace.
+#
+if __name__ == '__main__':
+ try:
+ sys.exit(main())
+ except KeyboardInterrupt:
+ sys.exit(1)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/parseentities.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/parseentities.py
new file mode 100644
index 0000000000..5d2f0c6069
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/parseentities.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+""" Utility for parsing HTML entity definitions available from:
+
+ http://www.w3.org/ as e.g.
+ http://www.w3.org/TR/REC-html40/HTMLlat1.ent
+
+ Input is read from stdin, output is written to stdout in form of a
+ Python snippet defining a dictionary "entitydefs" mapping literal
+ entity name to character or numeric entity.
+
+ Marc-Andre Lemburg, mal@lemburg.com, 1999.
+ Use as you like. NO WARRANTIES.
+
+"""
+import re,sys
+import TextTools
+
+entityRE = re.compile('<!ENTITY +(\w+) +CDATA +"([^"]+)" +-- +((?:.|\n)+?) *-->')
+
+def parse(text,pos=0,endpos=None):
+
+ pos = 0
+ if endpos is None:
+ endpos = len(text)
+ d = {}
+ while 1:
+ m = entityRE.search(text,pos,endpos)
+ if not m:
+ break
+ name,charcode,comment = m.groups()
+ d[name] = charcode,comment
+ pos = m.end()
+ return d
+
+def writefile(f,defs):
+
+ f.write("entitydefs = {\n")
+ items = defs.items()
+ items.sort()
+ for name,(charcode,comment) in items:
+ if charcode[:2] == '&#':
+ code = int(charcode[2:-1])
+ if code < 256:
+ charcode = "'\%o'" % code
+ else:
+ charcode = repr(charcode)
+ else:
+ charcode = repr(charcode)
+ comment = TextTools.collapse(comment)
+ f.write(" '%s':\t%s, \t# %s\n" % (name,charcode,comment))
+ f.write('\n}\n')
+
+if __name__ == '__main__':
+ if len(sys.argv) > 1:
+ infile = open(sys.argv[1])
+ else:
+ infile = sys.stdin
+ if len(sys.argv) > 2:
+ outfile = open(sys.argv[2],'w')
+ else:
+ outfile = sys.stdout
+ text = infile.read()
+ defs = parse(text)
+ writefile(outfile,defs)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/patchcheck.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/patchcheck.py
new file mode 100644
index 0000000000..62763a146a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/patchcheck.py
@@ -0,0 +1,158 @@
+import re
+import sys
+import shutil
+import os.path
+import subprocess
+
+import reindent
+import untabify
+
+
+def n_files_str(count):
+ """Return 'N file(s)' with the proper plurality on 'file'."""
+ return "{} file{}".format(count, "s" if count != 1 else "")
+
+
+def status(message, modal=False, info=None):
+ """Decorator to output status info to stdout."""
+ def decorated_fxn(fxn):
+ def call_fxn(*args, **kwargs):
+ sys.stdout.write(message + ' ... ')
+ sys.stdout.flush()
+ result = fxn(*args, **kwargs)
+ if not modal and not info:
+ print "done"
+ elif info:
+ print info(result)
+ else:
+ print "yes" if result else "NO"
+ return result
+ return call_fxn
+ return decorated_fxn
+
+
+@status("Getting the list of files that have been added/changed",
+ info=lambda x: n_files_str(len(x)))
+def changed_files():
+ """Get the list of changed or added files from the VCS."""
+ if os.path.isdir('.hg'):
+ vcs = 'hg'
+ cmd = 'hg status --added --modified --no-status'
+ elif os.path.isdir('.svn'):
+ vcs = 'svn'
+ cmd = 'svn status --quiet --non-interactive --ignore-externals'
+ else:
+ sys.exit('need a checkout to get modified files')
+
+ st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
+ try:
+ st.wait()
+ if vcs == 'hg':
+ return [x.decode().rstrip() for x in st.stdout]
+ else:
+ output = (x.decode().rstrip().rsplit(None, 1)[-1]
+ for x in st.stdout if x[0] in 'AM')
+ return set(path for path in output if os.path.isfile(path))
+ finally:
+ st.stdout.close()
+
+
+def report_modified_files(file_paths):
+ count = len(file_paths)
+ if count == 0:
+ return n_files_str(count)
+ else:
+ lines = ["{}:".format(n_files_str(count))]
+ for path in file_paths:
+ lines.append(" {}".format(path))
+ return "\n".join(lines)
+
+
+@status("Fixing whitespace", info=report_modified_files)
+def normalize_whitespace(file_paths):
+ """Make sure that the whitespace for .py files have been normalized."""
+ reindent.makebackup = False # No need to create backups.
+ fixed = []
+ for path in (x for x in file_paths if x.endswith('.py')):
+ if reindent.check(path):
+ fixed.append(path)
+ return fixed
+
+
+@status("Fixing C file whitespace", info=report_modified_files)
+def normalize_c_whitespace(file_paths):
+ """Report if any C files """
+ fixed = []
+ for path in file_paths:
+ with open(path, 'r') as f:
+ if '\t' not in f.read():
+ continue
+ untabify.process(path, 8, verbose=False)
+ fixed.append(path)
+ return fixed
+
+
+ws_re = re.compile(br'\s+(\r?\n)$')
+
+@status("Fixing docs whitespace", info=report_modified_files)
+def normalize_docs_whitespace(file_paths):
+ fixed = []
+ for path in file_paths:
+ try:
+ with open(path, 'rb') as f:
+ lines = f.readlines()
+ new_lines = [ws_re.sub(br'\1', line) for line in lines]
+ if new_lines != lines:
+ shutil.copyfile(path, path + '.bak')
+ with open(path, 'wb') as f:
+ f.writelines(new_lines)
+ fixed.append(path)
+ except Exception as err:
+ print 'Cannot fix %s: %s' % (path, err)
+ return fixed
+
+
+@status("Docs modified", modal=True)
+def docs_modified(file_paths):
+ """Report if any file in the Doc directory has been changed."""
+ return bool(file_paths)
+
+
+@status("Misc/ACKS updated", modal=True)
+def credit_given(file_paths):
+ """Check if Misc/ACKS has been changed."""
+ return 'Misc/ACKS' in file_paths
+
+
+@status("Misc/NEWS updated", modal=True)
+def reported_news(file_paths):
+ """Check if Misc/NEWS has been changed."""
+ return 'Misc/NEWS' in file_paths
+
+
+def main():
+ file_paths = changed_files()
+ python_files = [fn for fn in file_paths if fn.endswith('.py')]
+ c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
+ doc_files = [fn for fn in file_paths if fn.startswith('Doc')]
+ special_files = {'Misc/ACKS', 'Misc/NEWS'} & set(file_paths)
+ # PEP 8 whitespace rules enforcement.
+ normalize_whitespace(python_files)
+ # C rules enforcement.
+ normalize_c_whitespace(c_files)
+ # Doc whitespace enforcement.
+ normalize_docs_whitespace(doc_files)
+ # Docs updated.
+ docs_modified(doc_files)
+ # Misc/ACKS changed.
+ credit_given(special_files)
+ # Misc/NEWS changed.
+ reported_news(special_files)
+
+ # Test suite run and passed.
+ print
+ print "Did you run the test suite?"
+
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pathfix.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pathfix.py
new file mode 100644
index 0000000000..24a2446237
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pathfix.py
@@ -0,0 +1,149 @@
+#! /usr/bin/env python
+
+# Change the #! line occurring in Python scripts. The new interpreter
+# pathname must be given with a -i option.
+#
+# Command line arguments are files or directories to be processed.
+# Directories are searched recursively for files whose name looks
+# like a python module.
+# Symbolic links are always ignored (except as explicit directory
+# arguments). Of course, the original file is kept as a back-up
+# (with a "~" attached to its name).
+#
+# Undoubtedly you can do this using find and sed or perl, but this is
+# a nice example of Python code that recurses down a directory tree
+# and uses regular expressions. Also note several subtleties like
+# preserving the file's mode and avoiding to even write a temp file
+# when no changes are needed for a file.
+#
+# NB: by changing only the function fixfile() you can turn this
+# into a program for a different change to Python programs...
+
+import sys
+import re
+import os
+from stat import *
+import getopt
+
+err = sys.stderr.write
+dbg = err
+rep = sys.stdout.write
+
+new_interpreter = None
+
+def main():
+ global new_interpreter
+ usage = ('usage: %s -i /interpreter file-or-directory ...\n' %
+ sys.argv[0])
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'i:')
+ except getopt.error, msg:
+ err(msg + '\n')
+ err(usage)
+ sys.exit(2)
+ for o, a in opts:
+ if o == '-i':
+ new_interpreter = a
+ if not new_interpreter or new_interpreter[0] != '/' or not args:
+ err('-i option or file-or-directory missing\n')
+ err(usage)
+ sys.exit(2)
+ bad = 0
+ for arg in args:
+ if os.path.isdir(arg):
+ if recursedown(arg): bad = 1
+ elif os.path.islink(arg):
+ err(arg + ': will not process symbolic links\n')
+ bad = 1
+ else:
+ if fix(arg): bad = 1
+ sys.exit(bad)
+
+ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
+def ispython(name):
+ return ispythonprog.match(name) >= 0
+
+def recursedown(dirname):
+ dbg('recursedown(%r)\n' % (dirname,))
+ bad = 0
+ try:
+ names = os.listdir(dirname)
+ except os.error, msg:
+ err('%s: cannot list directory: %r\n' % (dirname, msg))
+ return 1
+ names.sort()
+ subdirs = []
+ for name in names:
+ if name in (os.curdir, os.pardir): continue
+ fullname = os.path.join(dirname, name)
+ if os.path.islink(fullname): pass
+ elif os.path.isdir(fullname):
+ subdirs.append(fullname)
+ elif ispython(name):
+ if fix(fullname): bad = 1
+ for fullname in subdirs:
+ if recursedown(fullname): bad = 1
+ return bad
+
+def fix(filename):
+## dbg('fix(%r)\n' % (filename,))
+ try:
+ f = open(filename, 'r')
+ except IOError, msg:
+ err('%s: cannot open: %r\n' % (filename, msg))
+ return 1
+ line = f.readline()
+ fixed = fixline(line)
+ if line == fixed:
+ rep(filename+': no change\n')
+ f.close()
+ return
+ head, tail = os.path.split(filename)
+ tempname = os.path.join(head, '@' + tail)
+ try:
+ g = open(tempname, 'w')
+ except IOError, msg:
+ f.close()
+ err('%s: cannot create: %r\n' % (tempname, msg))
+ return 1
+ rep(filename + ': updating\n')
+ g.write(fixed)
+ BUFSIZE = 8*1024
+ while 1:
+ buf = f.read(BUFSIZE)
+ if not buf: break
+ g.write(buf)
+ g.close()
+ f.close()
+
+ # Finishing touch -- move files
+
+ # First copy the file's mode to the temp file
+ try:
+ statbuf = os.stat(filename)
+ os.chmod(tempname, statbuf[ST_MODE] & 07777)
+ except os.error, msg:
+ err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
+ # Then make a backup of the original file as filename~
+ try:
+ os.rename(filename, filename + '~')
+ except os.error, msg:
+ err('%s: warning: backup failed (%r)\n' % (filename, msg))
+ # Now move the temp file to the original file
+ try:
+ os.rename(tempname, filename)
+ except os.error, msg:
+ err('%s: rename failed (%r)\n' % (filename, msg))
+ return 1
+ # Return succes
+ return 0
+
+def fixline(line):
+ if not line.startswith('#!'):
+ return line
+ if "python" not in line:
+ return line
+ return '#! %s\n' % new_interpreter
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pdeps.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pdeps.py
new file mode 100644
index 0000000000..13a1cccaf1
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pdeps.py
@@ -0,0 +1,167 @@
+#! /usr/bin/env python
+
+# pdeps
+#
+# Find dependencies between a bunch of Python modules.
+#
+# Usage:
+# pdeps file1.py file2.py ...
+#
+# Output:
+# Four tables separated by lines like '--- Closure ---':
+# 1) Direct dependencies, listing which module imports which other modules
+# 2) The inverse of (1)
+# 3) Indirect dependencies, or the closure of the above
+# 4) The inverse of (3)
+#
+# To do:
+# - command line options to select output type
+# - option to automatically scan the Python library for referenced modules
+# - option to limit output to particular modules
+
+
+import sys
+import re
+import os
+
+
+# Main program
+#
+def main():
+ args = sys.argv[1:]
+ if not args:
+ print 'usage: pdeps file.py file.py ...'
+ return 2
+ #
+ table = {}
+ for arg in args:
+ process(arg, table)
+ #
+ print '--- Uses ---'
+ printresults(table)
+ #
+ print '--- Used By ---'
+ inv = inverse(table)
+ printresults(inv)
+ #
+ print '--- Closure of Uses ---'
+ reach = closure(table)
+ printresults(reach)
+ #
+ print '--- Closure of Used By ---'
+ invreach = inverse(reach)
+ printresults(invreach)
+ #
+ return 0
+
+
+# Compiled regular expressions to search for import statements
+#
+m_import = re.compile('^[ \t]*from[ \t]+([^ \t]+)[ \t]+')
+m_from = re.compile('^[ \t]*import[ \t]+([^#]+)')
+
+
+# Collect data from one file
+#
+def process(filename, table):
+ fp = open(filename, 'r')
+ mod = os.path.basename(filename)
+ if mod[-3:] == '.py':
+ mod = mod[:-3]
+ table[mod] = list = []
+ while 1:
+ line = fp.readline()
+ if not line: break
+ while line[-1:] == '\\':
+ nextline = fp.readline()
+ if not nextline: break
+ line = line[:-1] + nextline
+ if m_import.match(line) >= 0:
+ (a, b), (a1, b1) = m_import.regs[:2]
+ elif m_from.match(line) >= 0:
+ (a, b), (a1, b1) = m_from.regs[:2]
+ else: continue
+ words = line[a1:b1].split(',')
+ # print '#', line, words
+ for word in words:
+ word = word.strip()
+ if word not in list:
+ list.append(word)
+
+
+# Compute closure (this is in fact totally general)
+#
+def closure(table):
+ modules = table.keys()
+ #
+ # Initialize reach with a copy of table
+ #
+ reach = {}
+ for mod in modules:
+ reach[mod] = table[mod][:]
+ #
+ # Iterate until no more change
+ #
+ change = 1
+ while change:
+ change = 0
+ for mod in modules:
+ for mo in reach[mod]:
+ if mo in modules:
+ for m in reach[mo]:
+ if m not in reach[mod]:
+ reach[mod].append(m)
+ change = 1
+ #
+ return reach
+
+
+# Invert a table (this is again totally general).
+# All keys of the original table are made keys of the inverse,
+# so there may be empty lists in the inverse.
+#
+def inverse(table):
+ inv = {}
+ for key in table.keys():
+ if not inv.has_key(key):
+ inv[key] = []
+ for item in table[key]:
+ store(inv, item, key)
+ return inv
+
+
+# Store "item" in "dict" under "key".
+# The dictionary maps keys to lists of items.
+# If there is no list for the key yet, it is created.
+#
+def store(dict, key, item):
+ if dict.has_key(key):
+ dict[key].append(item)
+ else:
+ dict[key] = [item]
+
+
+# Tabulate results neatly
+#
+def printresults(table):
+ modules = table.keys()
+ maxlen = 0
+ for mod in modules: maxlen = max(maxlen, len(mod))
+ modules.sort()
+ for mod in modules:
+ list = table[mod]
+ list.sort()
+ print mod.ljust(maxlen), ':',
+ if mod in list:
+ print '(*)',
+ for ref in list:
+ print ref,
+ print
+
+
+# Call main and honor exit status
+if __name__ == '__main__':
+ try:
+ sys.exit(main())
+ except KeyboardInterrupt:
+ sys.exit(1)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pickle2db.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pickle2db.py
new file mode 100644
index 0000000000..89b90c5a66
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pickle2db.py
@@ -0,0 +1,147 @@
+#!/usr/bin/env python
+
+"""
+Synopsis: %(prog)s [-h|-b|-g|-r|-a|-d] [ picklefile ] dbfile
+
+Read the given picklefile as a series of key/value pairs and write to a new
+database. If the database already exists, any contents are deleted. The
+optional flags indicate the type of the output database:
+
+ -a - open using anydbm
+ -b - open as bsddb btree file
+ -d - open as dbm file
+ -g - open as gdbm file
+ -h - open as bsddb hash file
+ -r - open as bsddb recno file
+
+The default is hash. If a pickle file is named it is opened for read
+access. If no pickle file is named, the pickle input is read from standard
+input.
+
+Note that recno databases can only contain integer keys, so you can't dump a
+hash or btree database using db2pickle.py and reconstitute it to a recno
+database with %(prog)s unless your keys are integers.
+
+"""
+
+import getopt
+try:
+ import bsddb
+except ImportError:
+ bsddb = None
+try:
+ import dbm
+except ImportError:
+ dbm = None
+try:
+ import gdbm
+except ImportError:
+ gdbm = None
+try:
+ import anydbm
+except ImportError:
+ anydbm = None
+import sys
+try:
+ import cPickle as pickle
+except ImportError:
+ import pickle
+
+prog = sys.argv[0]
+
+def usage():
+ sys.stderr.write(__doc__ % globals())
+
+def main(args):
+ try:
+ opts, args = getopt.getopt(args, "hbrdag",
+ ["hash", "btree", "recno", "dbm", "anydbm",
+ "gdbm"])
+ except getopt.error:
+ usage()
+ return 1
+
+ if len(args) == 0 or len(args) > 2:
+ usage()
+ return 1
+ elif len(args) == 1:
+ pfile = sys.stdin
+ dbfile = args[0]
+ else:
+ try:
+ pfile = open(args[0], 'rb')
+ except IOError:
+ sys.stderr.write("Unable to open %s\n" % args[0])
+ return 1
+ dbfile = args[1]
+
+ dbopen = None
+ for opt, arg in opts:
+ if opt in ("-h", "--hash"):
+ try:
+ dbopen = bsddb.hashopen
+ except AttributeError:
+ sys.stderr.write("bsddb module unavailable.\n")
+ return 1
+ elif opt in ("-b", "--btree"):
+ try:
+ dbopen = bsddb.btopen
+ except AttributeError:
+ sys.stderr.write("bsddb module unavailable.\n")
+ return 1
+ elif opt in ("-r", "--recno"):
+ try:
+ dbopen = bsddb.rnopen
+ except AttributeError:
+ sys.stderr.write("bsddb module unavailable.\n")
+ return 1
+ elif opt in ("-a", "--anydbm"):
+ try:
+ dbopen = anydbm.open
+ except AttributeError:
+ sys.stderr.write("anydbm module unavailable.\n")
+ return 1
+ elif opt in ("-g", "--gdbm"):
+ try:
+ dbopen = gdbm.open
+ except AttributeError:
+ sys.stderr.write("gdbm module unavailable.\n")
+ return 1
+ elif opt in ("-d", "--dbm"):
+ try:
+ dbopen = dbm.open
+ except AttributeError:
+ sys.stderr.write("dbm module unavailable.\n")
+ return 1
+ if dbopen is None:
+ if bsddb is None:
+ sys.stderr.write("bsddb module unavailable - ")
+ sys.stderr.write("must specify dbtype.\n")
+ return 1
+ else:
+ dbopen = bsddb.hashopen
+
+ try:
+ db = dbopen(dbfile, 'c')
+ except bsddb.error:
+ sys.stderr.write("Unable to open %s. " % dbfile)
+ sys.stderr.write("Check for format or version mismatch.\n")
+ return 1
+ else:
+ for k in db.keys():
+ del db[k]
+
+ while 1:
+ try:
+ (key, val) = pickle.load(pfile)
+ except EOFError:
+ break
+ db[key] = val
+
+ db.close()
+ pfile.close()
+
+ return 0
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pindent.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pindent.py
new file mode 100644
index 0000000000..2a031e0839
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pindent.py
@@ -0,0 +1,542 @@
+#! /usr/bin/env python
+
+# This file contains a class and a main program that perform three
+# related (though complimentary) formatting operations on Python
+# programs. When called as "pindent -c", it takes a valid Python
+# program as input and outputs a version augmented with block-closing
+# comments. When called as "pindent -d", it assumes its input is a
+# Python program with block-closing comments and outputs a commentless
+# version. When called as "pindent -r" it assumes its input is a
+# Python program with block-closing comments but with its indentation
+# messed up, and outputs a properly indented version.
+
+# A "block-closing comment" is a comment of the form '# end <keyword>'
+# where <keyword> is the keyword that opened the block. If the
+# opening keyword is 'def' or 'class', the function or class name may
+# be repeated in the block-closing comment as well. Here is an
+# example of a program fully augmented with block-closing comments:
+
+# def foobar(a, b):
+# if a == b:
+# a = a+1
+# elif a < b:
+# b = b-1
+# if b > a: a = a-1
+# # end if
+# else:
+# print 'oops!'
+# # end if
+# # end def foobar
+
+# Note that only the last part of an if...elif...else... block needs a
+# block-closing comment; the same is true for other compound
+# statements (e.g. try...except). Also note that "short-form" blocks
+# like the second 'if' in the example must be closed as well;
+# otherwise the 'else' in the example would be ambiguous (remember
+# that indentation is not significant when interpreting block-closing
+# comments).
+
+# The operations are idempotent (i.e. applied to their own output
+# they yield an identical result). Running first "pindent -c" and
+# then "pindent -r" on a valid Python program produces a program that
+# is semantically identical to the input (though its indentation may
+# be different). Running "pindent -e" on that output produces a
+# program that only differs from the original in indentation.
+
+# Other options:
+# -s stepsize: set the indentation step size (default 8)
+# -t tabsize : set the number of spaces a tab character is worth (default 8)
+# -e : expand TABs into spaces
+# file ... : input file(s) (default standard input)
+# The results always go to standard output
+
+# Caveats:
+# - comments ending in a backslash will be mistaken for continued lines
+# - continuations using backslash are always left unchanged
+# - continuations inside parentheses are not extra indented by -r
+# but must be indented for -c to work correctly (this breaks
+# idempotency!)
+# - continued lines inside triple-quoted strings are totally garbled
+
+# Secret feature:
+# - On input, a block may also be closed with an "end statement" --
+# this is a block-closing comment without the '#' sign.
+
+# Possible improvements:
+# - check syntax based on transitions in 'next' table
+# - better error reporting
+# - better error recovery
+# - check identifier after class/def
+
+# The following wishes need a more complete tokenization of the source:
+# - Don't get fooled by comments ending in backslash
+# - reindent continuation lines indicated by backslash
+# - handle continuation lines inside parentheses/braces/brackets
+# - handle triple quoted strings spanning lines
+# - realign comments
+# - optionally do much more thorough reformatting, a la C indent
+
+# Defaults
+STEPSIZE = 8
+TABSIZE = 8
+EXPANDTABS = 0
+
+import re
+import sys
+
+next = {}
+next['if'] = next['elif'] = 'elif', 'else', 'end'
+next['while'] = next['for'] = 'else', 'end'
+next['try'] = 'except', 'finally'
+next['except'] = 'except', 'else', 'finally', 'end'
+next['else'] = next['finally'] = next['def'] = next['class'] = 'end'
+next['end'] = ()
+start = 'if', 'while', 'for', 'try', 'with', 'def', 'class'
+
+class PythonIndenter:
+
+ def __init__(self, fpi = sys.stdin, fpo = sys.stdout,
+ indentsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ self.fpi = fpi
+ self.fpo = fpo
+ self.indentsize = indentsize
+ self.tabsize = tabsize
+ self.lineno = 0
+ self.expandtabs = expandtabs
+ self._write = fpo.write
+ self.kwprog = re.compile(
+ r'^\s*(?P<kw>[a-z]+)'
+ r'(\s+(?P<id>[a-zA-Z_]\w*))?'
+ r'[^\w]')
+ self.endprog = re.compile(
+ r'^\s*#?\s*end\s+(?P<kw>[a-z]+)'
+ r'(\s+(?P<id>[a-zA-Z_]\w*))?'
+ r'[^\w]')
+ self.wsprog = re.compile(r'^[ \t]*')
+ # end def __init__
+
+ def write(self, line):
+ if self.expandtabs:
+ self._write(line.expandtabs(self.tabsize))
+ else:
+ self._write(line)
+ # end if
+ # end def write
+
+ def readline(self):
+ line = self.fpi.readline()
+ if line: self.lineno = self.lineno + 1
+ # end if
+ return line
+ # end def readline
+
+ def error(self, fmt, *args):
+ if args: fmt = fmt % args
+ # end if
+ sys.stderr.write('Error at line %d: %s\n' % (self.lineno, fmt))
+ self.write('### %s ###\n' % fmt)
+ # end def error
+
+ def getline(self):
+ line = self.readline()
+ while line[-2:] == '\\\n':
+ line2 = self.readline()
+ if not line2: break
+ # end if
+ line = line + line2
+ # end while
+ return line
+ # end def getline
+
+ def putline(self, line, indent = None):
+ if indent is None:
+ self.write(line)
+ return
+ # end if
+ tabs, spaces = divmod(indent*self.indentsize, self.tabsize)
+ i = 0
+ m = self.wsprog.match(line)
+ if m: i = m.end()
+ # end if
+ self.write('\t'*tabs + ' '*spaces + line[i:])
+ # end def putline
+
+ def reformat(self):
+ stack = []
+ while 1:
+ line = self.getline()
+ if not line: break # EOF
+ # end if
+ m = self.endprog.match(line)
+ if m:
+ kw = 'end'
+ kw2 = m.group('kw')
+ if not stack:
+ self.error('unexpected end')
+ elif stack[-1][0] != kw2:
+ self.error('unmatched end')
+ # end if
+ del stack[-1:]
+ self.putline(line, len(stack))
+ continue
+ # end if
+ m = self.kwprog.match(line)
+ if m:
+ kw = m.group('kw')
+ if kw in start:
+ self.putline(line, len(stack))
+ stack.append((kw, kw))
+ continue
+ # end if
+ if next.has_key(kw) and stack:
+ self.putline(line, len(stack)-1)
+ kwa, kwb = stack[-1]
+ stack[-1] = kwa, kw
+ continue
+ # end if
+ # end if
+ self.putline(line, len(stack))
+ # end while
+ if stack:
+ self.error('unterminated keywords')
+ for kwa, kwb in stack:
+ self.write('\t%s\n' % kwa)
+ # end for
+ # end if
+ # end def reformat
+
+ def delete(self):
+ begin_counter = 0
+ end_counter = 0
+ while 1:
+ line = self.getline()
+ if not line: break # EOF
+ # end if
+ m = self.endprog.match(line)
+ if m:
+ end_counter = end_counter + 1
+ continue
+ # end if
+ m = self.kwprog.match(line)
+ if m:
+ kw = m.group('kw')
+ if kw in start:
+ begin_counter = begin_counter + 1
+ # end if
+ # end if
+ self.putline(line)
+ # end while
+ if begin_counter - end_counter < 0:
+ sys.stderr.write('Warning: input contained more end tags than expected\n')
+ elif begin_counter - end_counter > 0:
+ sys.stderr.write('Warning: input contained less end tags than expected\n')
+ # end if
+ # end def delete
+
+ def complete(self):
+ self.indentsize = 1
+ stack = []
+ todo = []
+ thisid = ''
+ current, firstkw, lastkw, topid = 0, '', '', ''
+ while 1:
+ line = self.getline()
+ i = 0
+ m = self.wsprog.match(line)
+ if m: i = m.end()
+ # end if
+ m = self.endprog.match(line)
+ if m:
+ thiskw = 'end'
+ endkw = m.group('kw')
+ thisid = m.group('id')
+ else:
+ m = self.kwprog.match(line)
+ if m:
+ thiskw = m.group('kw')
+ if not next.has_key(thiskw):
+ thiskw = ''
+ # end if
+ if thiskw in ('def', 'class'):
+ thisid = m.group('id')
+ else:
+ thisid = ''
+ # end if
+ elif line[i:i+1] in ('\n', '#'):
+ todo.append(line)
+ continue
+ else:
+ thiskw = ''
+ # end if
+ # end if
+ indent = len(line[:i].expandtabs(self.tabsize))
+ while indent < current:
+ if firstkw:
+ if topid:
+ s = '# end %s %s\n' % (
+ firstkw, topid)
+ else:
+ s = '# end %s\n' % firstkw
+ # end if
+ self.putline(s, current)
+ firstkw = lastkw = ''
+ # end if
+ current, firstkw, lastkw, topid = stack[-1]
+ del stack[-1]
+ # end while
+ if indent == current and firstkw:
+ if thiskw == 'end':
+ if endkw != firstkw:
+ self.error('mismatched end')
+ # end if
+ firstkw = lastkw = ''
+ elif not thiskw or thiskw in start:
+ if topid:
+ s = '# end %s %s\n' % (
+ firstkw, topid)
+ else:
+ s = '# end %s\n' % firstkw
+ # end if
+ self.putline(s, current)
+ firstkw = lastkw = topid = ''
+ # end if
+ # end if
+ if indent > current:
+ stack.append((current, firstkw, lastkw, topid))
+ if thiskw and thiskw not in start:
+ # error
+ thiskw = ''
+ # end if
+ current, firstkw, lastkw, topid = \
+ indent, thiskw, thiskw, thisid
+ # end if
+ if thiskw:
+ if thiskw in start:
+ firstkw = lastkw = thiskw
+ topid = thisid
+ else:
+ lastkw = thiskw
+ # end if
+ # end if
+ for l in todo: self.write(l)
+ # end for
+ todo = []
+ if not line: break
+ # end if
+ self.write(line)
+ # end while
+ # end def complete
+
+# end class PythonIndenter
+
+# Simplified user interface
+# - xxx_filter(input, output): read and write file objects
+# - xxx_string(s): take and return string object
+# - xxx_file(filename): process file in place, return true iff changed
+
+def complete_filter(input = sys.stdin, output = sys.stdout,
+ stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
+ pi.complete()
+# end def complete_filter
+
+def delete_filter(input= sys.stdin, output = sys.stdout,
+ stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
+ pi.delete()
+# end def delete_filter
+
+def reformat_filter(input = sys.stdin, output = sys.stdout,
+ stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
+ pi.reformat()
+# end def reformat_filter
+
+class StringReader:
+ def __init__(self, buf):
+ self.buf = buf
+ self.pos = 0
+ self.len = len(self.buf)
+ # end def __init__
+ def read(self, n = 0):
+ if n <= 0:
+ n = self.len - self.pos
+ else:
+ n = min(n, self.len - self.pos)
+ # end if
+ r = self.buf[self.pos : self.pos + n]
+ self.pos = self.pos + n
+ return r
+ # end def read
+ def readline(self):
+ i = self.buf.find('\n', self.pos)
+ return self.read(i + 1 - self.pos)
+ # end def readline
+ def readlines(self):
+ lines = []
+ line = self.readline()
+ while line:
+ lines.append(line)
+ line = self.readline()
+ # end while
+ return lines
+ # end def readlines
+ # seek/tell etc. are left as an exercise for the reader
+# end class StringReader
+
+class StringWriter:
+ def __init__(self):
+ self.buf = ''
+ # end def __init__
+ def write(self, s):
+ self.buf = self.buf + s
+ # end def write
+ def getvalue(self):
+ return self.buf
+ # end def getvalue
+# end class StringWriter
+
+def complete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ input = StringReader(source)
+ output = StringWriter()
+ pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
+ pi.complete()
+ return output.getvalue()
+# end def complete_string
+
+def delete_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ input = StringReader(source)
+ output = StringWriter()
+ pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
+ pi.delete()
+ return output.getvalue()
+# end def delete_string
+
+def reformat_string(source, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ input = StringReader(source)
+ output = StringWriter()
+ pi = PythonIndenter(input, output, stepsize, tabsize, expandtabs)
+ pi.reformat()
+ return output.getvalue()
+# end def reformat_string
+
+def complete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ source = open(filename, 'r').read()
+ result = complete_string(source, stepsize, tabsize, expandtabs)
+ if source == result: return 0
+ # end if
+ import os
+ try: os.rename(filename, filename + '~')
+ except os.error: pass
+ # end try
+ f = open(filename, 'w')
+ f.write(result)
+ f.close()
+ return 1
+# end def complete_file
+
+def delete_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ source = open(filename, 'r').read()
+ result = delete_string(source, stepsize, tabsize, expandtabs)
+ if source == result: return 0
+ # end if
+ import os
+ try: os.rename(filename, filename + '~')
+ except os.error: pass
+ # end try
+ f = open(filename, 'w')
+ f.write(result)
+ f.close()
+ return 1
+# end def delete_file
+
+def reformat_file(filename, stepsize = STEPSIZE, tabsize = TABSIZE, expandtabs = EXPANDTABS):
+ source = open(filename, 'r').read()
+ result = reformat_string(source, stepsize, tabsize, expandtabs)
+ if source == result: return 0
+ # end if
+ import os
+ try: os.rename(filename, filename + '~')
+ except os.error: pass
+ # end try
+ f = open(filename, 'w')
+ f.write(result)
+ f.close()
+ return 1
+# end def reformat_file
+
+# Test program when called as a script
+
+usage = """
+usage: pindent (-c|-d|-r) [-s stepsize] [-t tabsize] [-e] [file] ...
+-c : complete a correctly indented program (add #end directives)
+-d : delete #end directives
+-r : reformat a completed program (use #end directives)
+-s stepsize: indentation step (default %(STEPSIZE)d)
+-t tabsize : the worth in spaces of a tab (default %(TABSIZE)d)
+-e : expand TABs into spaces (defailt OFF)
+[file] ... : files are changed in place, with backups in file~
+If no files are specified or a single - is given,
+the program acts as a filter (reads stdin, writes stdout).
+""" % vars()
+
+def error_both(op1, op2):
+ sys.stderr.write('Error: You can not specify both '+op1+' and -'+op2[0]+' at the same time\n')
+ sys.stderr.write(usage)
+ sys.exit(2)
+# end def error_both
+
+def test():
+ import getopt
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'cdrs:t:e')
+ except getopt.error, msg:
+ sys.stderr.write('Error: %s\n' % msg)
+ sys.stderr.write(usage)
+ sys.exit(2)
+ # end try
+ action = None
+ stepsize = STEPSIZE
+ tabsize = TABSIZE
+ expandtabs = EXPANDTABS
+ for o, a in opts:
+ if o == '-c':
+ if action: error_both(o, action)
+ # end if
+ action = 'complete'
+ elif o == '-d':
+ if action: error_both(o, action)
+ # end if
+ action = 'delete'
+ elif o == '-r':
+ if action: error_both(o, action)
+ # end if
+ action = 'reformat'
+ elif o == '-s':
+ stepsize = int(a)
+ elif o == '-t':
+ tabsize = int(a)
+ elif o == '-e':
+ expandtabs = 1
+ # end if
+ # end for
+ if not action:
+ sys.stderr.write(
+ 'You must specify -c(omplete), -d(elete) or -r(eformat)\n')
+ sys.stderr.write(usage)
+ sys.exit(2)
+ # end if
+ if not args or args == ['-']:
+ action = eval(action + '_filter')
+ action(sys.stdin, sys.stdout, stepsize, tabsize, expandtabs)
+ else:
+ action = eval(action + '_file')
+ for filename in args:
+ action(filename, stepsize, tabsize, expandtabs)
+ # end for
+ # end if
+# end def test
+
+if __name__ == '__main__':
+ test()
+# end if
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ptags.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ptags.py
new file mode 100644
index 0000000000..9626b7182a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ptags.py
@@ -0,0 +1,53 @@
+#! /usr/bin/env python
+
+# ptags
+#
+# Create a tags file for Python programs, usable with vi.
+# Tagged are:
+# - functions (even inside other defs or classes)
+# - classes
+# - filenames
+# Warns about files it cannot open.
+# No warnings about duplicate tags.
+
+import sys, re, os
+
+tags = [] # Modified global variable!
+
+def main():
+ args = sys.argv[1:]
+ for filename in args:
+ treat_file(filename)
+ if tags:
+ fp = open('tags', 'w')
+ tags.sort()
+ for s in tags: fp.write(s)
+
+
+expr = '^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
+matcher = re.compile(expr)
+
+def treat_file(filename):
+ try:
+ fp = open(filename, 'r')
+ except:
+ sys.stderr.write('Cannot open %s\n' % filename)
+ return
+ base = os.path.basename(filename)
+ if base[-3:] == '.py':
+ base = base[:-3]
+ s = base + '\t' + filename + '\t' + '1\n'
+ tags.append(s)
+ while 1:
+ line = fp.readline()
+ if not line:
+ break
+ m = matcher.match(line)
+ if m:
+ content = m.group(0)
+ name = m.group(2)
+ s = name + '\t' + filename + '\t/^' + content + '/\n'
+ tags.append(s)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydoc b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydoc
new file mode 100644
index 0000000000..a592ce7831
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydoc
@@ -0,0 +1,5 @@
+#!/usr/bin/env python
+
+import pydoc
+if __name__ == '__main__':
+ pydoc.cli()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydocgui.pyw b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydocgui.pyw
new file mode 100644
index 0000000000..8a20567145
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pydocgui.pyw
@@ -0,0 +1,7 @@
+# Note: this file must not be named pydoc.pyw, lest it just end up
+# importing itself (Python began allowing import of .pyw files
+# between 2.2a1 and 2.2a2).
+import pydoc
+
+if __name__ == '__main__':
+ pydoc.gui()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pysource.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pysource.py
new file mode 100644
index 0000000000..2fd3d880c0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/pysource.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python
+
+"""\
+List python source files.
+
+There are three functions to check whether a file is a Python source, listed
+here with increasing complexity:
+
+- has_python_ext() checks whether a file name ends in '.py[w]'.
+- look_like_python() checks whether the file is not binary and either has
+ the '.py[w]' extension or the first line contains the word 'python'.
+- can_be_compiled() checks whether the file can be compiled by compile().
+
+The file also must be of appropriate size - not bigger than a megabyte.
+
+walk_python_files() recursively lists all Python files under the given directories.
+"""
+__author__ = "Oleg Broytmann, Georg Brandl"
+
+__all__ = ["has_python_ext", "looks_like_python", "can_be_compiled", "walk_python_files"]
+
+
+import os, re
+
+binary_re = re.compile('[\x00-\x08\x0E-\x1F\x7F]')
+
+debug = False
+
+def print_debug(msg):
+ if debug: print msg
+
+
+def _open(fullpath):
+ try:
+ size = os.stat(fullpath).st_size
+ except OSError, err: # Permission denied - ignore the file
+ print_debug("%s: permission denied: %s" % (fullpath, err))
+ return None
+
+ if size > 1024*1024: # too big
+ print_debug("%s: the file is too big: %d bytes" % (fullpath, size))
+ return None
+
+ try:
+ return open(fullpath, 'rU')
+ except IOError, err: # Access denied, or a special file - ignore it
+ print_debug("%s: access denied: %s" % (fullpath, err))
+ return None
+
+def has_python_ext(fullpath):
+ return fullpath.endswith(".py") or fullpath.endswith(".pyw")
+
+def looks_like_python(fullpath):
+ infile = _open(fullpath)
+ if infile is None:
+ return False
+
+ line = infile.readline()
+ infile.close()
+
+ if binary_re.search(line):
+ # file appears to be binary
+ print_debug("%s: appears to be binary" % fullpath)
+ return False
+
+ if fullpath.endswith(".py") or fullpath.endswith(".pyw"):
+ return True
+ elif "python" in line:
+ # disguised Python script (e.g. CGI)
+ return True
+
+ return False
+
+def can_be_compiled(fullpath):
+ infile = _open(fullpath)
+ if infile is None:
+ return False
+
+ code = infile.read()
+ infile.close()
+
+ try:
+ compile(code, fullpath, "exec")
+ except Exception, err:
+ print_debug("%s: cannot compile: %s" % (fullpath, err))
+ return False
+
+ return True
+
+
+def walk_python_files(paths, is_python=looks_like_python, exclude_dirs=None):
+ """\
+ Recursively yield all Python source files below the given paths.
+
+ paths: a list of files and/or directories to be checked.
+ is_python: a function that takes a file name and checks whether it is a
+ Python source file
+ exclude_dirs: a list of directory base names that should be excluded in
+ the search
+ """
+ if exclude_dirs is None:
+ exclude_dirs=[]
+
+ for path in paths:
+ print_debug("testing: %s" % path)
+ if os.path.isfile(path):
+ if is_python(path):
+ yield path
+ elif os.path.isdir(path):
+ print_debug(" it is a directory")
+ for dirpath, dirnames, filenames in os.walk(path):
+ for exclude in exclude_dirs:
+ if exclude in dirnames:
+ dirnames.remove(exclude)
+ for filename in filenames:
+ fullpath = os.path.join(dirpath, filename)
+ print_debug("testing: %s" % fullpath)
+ if is_python(fullpath):
+ yield fullpath
+ else:
+ print_debug(" unknown type")
+
+
+if __name__ == "__main__":
+ # Two simple examples/tests
+ for fullpath in walk_python_files(['.']):
+ print fullpath
+ print "----------"
+ for fullpath in walk_python_files(['.'], is_python=can_be_compiled):
+ print fullpath
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/redemo.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/redemo.py
new file mode 100644
index 0000000000..30a1bda312
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/redemo.py
@@ -0,0 +1,171 @@
+"""Basic regular expression demostration facility (Perl style syntax)."""
+
+from Tkinter import *
+import re
+
+class ReDemo:
+
+ def __init__(self, master):
+ self.master = master
+
+ self.promptdisplay = Label(self.master, anchor=W,
+ text="Enter a Perl-style regular expression:")
+ self.promptdisplay.pack(side=TOP, fill=X)
+
+ self.regexdisplay = Entry(self.master)
+ self.regexdisplay.pack(fill=X)
+ self.regexdisplay.focus_set()
+
+ self.addoptions()
+
+ self.statusdisplay = Label(self.master, text="", anchor=W)
+ self.statusdisplay.pack(side=TOP, fill=X)
+
+ self.labeldisplay = Label(self.master, anchor=W,
+ text="Enter a string to search:")
+ self.labeldisplay.pack(fill=X)
+ self.labeldisplay.pack(fill=X)
+
+ self.showframe = Frame(master)
+ self.showframe.pack(fill=X, anchor=W)
+
+ self.showvar = StringVar(master)
+ self.showvar.set("first")
+
+ self.showfirstradio = Radiobutton(self.showframe,
+ text="Highlight first match",
+ variable=self.showvar,
+ value="first",
+ command=self.recompile)
+ self.showfirstradio.pack(side=LEFT)
+
+ self.showallradio = Radiobutton(self.showframe,
+ text="Highlight all matches",
+ variable=self.showvar,
+ value="all",
+ command=self.recompile)
+ self.showallradio.pack(side=LEFT)
+
+ self.stringdisplay = Text(self.master, width=60, height=4)
+ self.stringdisplay.pack(fill=BOTH, expand=1)
+ self.stringdisplay.tag_configure("hit", background="yellow")
+
+ self.grouplabel = Label(self.master, text="Groups:", anchor=W)
+ self.grouplabel.pack(fill=X)
+
+ self.grouplist = Listbox(self.master)
+ self.grouplist.pack(expand=1, fill=BOTH)
+
+ self.regexdisplay.bind('<Key>', self.recompile)
+ self.stringdisplay.bind('<Key>', self.reevaluate)
+
+ self.compiled = None
+ self.recompile()
+
+ btags = self.regexdisplay.bindtags()
+ self.regexdisplay.bindtags(btags[1:] + btags[:1])
+
+ btags = self.stringdisplay.bindtags()
+ self.stringdisplay.bindtags(btags[1:] + btags[:1])
+
+ def addoptions(self):
+ self.frames = []
+ self.boxes = []
+ self.vars = []
+ for name in ('IGNORECASE',
+ 'LOCALE',
+ 'MULTILINE',
+ 'DOTALL',
+ 'VERBOSE'):
+ if len(self.boxes) % 3 == 0:
+ frame = Frame(self.master)
+ frame.pack(fill=X)
+ self.frames.append(frame)
+ val = getattr(re, name)
+ var = IntVar()
+ box = Checkbutton(frame,
+ variable=var, text=name,
+ offvalue=0, onvalue=val,
+ command=self.recompile)
+ box.pack(side=LEFT)
+ self.boxes.append(box)
+ self.vars.append(var)
+
+ def getflags(self):
+ flags = 0
+ for var in self.vars:
+ flags = flags | var.get()
+ flags = flags
+ return flags
+
+ def recompile(self, event=None):
+ try:
+ self.compiled = re.compile(self.regexdisplay.get(),
+ self.getflags())
+ bg = self.promptdisplay['background']
+ self.statusdisplay.config(text="", background=bg)
+ except re.error, msg:
+ self.compiled = None
+ self.statusdisplay.config(
+ text="re.error: %s" % str(msg),
+ background="red")
+ self.reevaluate()
+
+ def reevaluate(self, event=None):
+ try:
+ self.stringdisplay.tag_remove("hit", "1.0", END)
+ except TclError:
+ pass
+ try:
+ self.stringdisplay.tag_remove("hit0", "1.0", END)
+ except TclError:
+ pass
+ self.grouplist.delete(0, END)
+ if not self.compiled:
+ return
+ self.stringdisplay.tag_configure("hit", background="yellow")
+ self.stringdisplay.tag_configure("hit0", background="orange")
+ text = self.stringdisplay.get("1.0", END)
+ last = 0
+ nmatches = 0
+ while last <= len(text):
+ m = self.compiled.search(text, last)
+ if m is None:
+ break
+ first, last = m.span()
+ if last == first:
+ last = first+1
+ tag = "hit0"
+ else:
+ tag = "hit"
+ pfirst = "1.0 + %d chars" % first
+ plast = "1.0 + %d chars" % last
+ self.stringdisplay.tag_add(tag, pfirst, plast)
+ if nmatches == 0:
+ self.stringdisplay.yview_pickplace(pfirst)
+ groups = list(m.groups())
+ groups.insert(0, m.group())
+ for i in range(len(groups)):
+ g = "%2d: %r" % (i, groups[i])
+ self.grouplist.insert(END, g)
+ nmatches = nmatches + 1
+ if self.showvar.get() == "first":
+ break
+
+ if nmatches == 0:
+ self.statusdisplay.config(text="(no match)",
+ background="yellow")
+ else:
+ self.statusdisplay.config(text="")
+
+
+# Main function, run when invoked as a stand-alone Python program.
+
+def main():
+ root = Tk()
+ demo = ReDemo(root)
+ root.protocol('WM_DELETE_WINDOW', root.quit)
+ root.mainloop()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent-rst.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent-rst.py
new file mode 100644
index 0000000000..037f045441
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent-rst.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+
+# Make a reST file compliant to our pre-commit hook.
+# Currently just remove trailing whitespace.
+
+import sys
+
+import patchcheck
+
+def main(argv=sys.argv):
+ patchcheck.normalize_docs_whitespace(argv[1:])
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent.py
new file mode 100644
index 0000000000..f0703620b8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/reindent.py
@@ -0,0 +1,304 @@
+#! /usr/bin/env python
+
+# Released to the public domain, by Tim Peters, 03 October 2000.
+
+"""reindent [-d][-r][-v] [ path ... ]
+
+-d (--dryrun) Dry run. Analyze, but don't make any changes to, files.
+-r (--recurse) Recurse. Search for all .py files in subdirectories too.
+-n (--nobackup) No backup. Does not make a ".bak" file before reindenting.
+-v (--verbose) Verbose. Print informative msgs; else no output.
+-h (--help) Help. Print this usage information and exit.
+
+Change Python (.py) files to use 4-space indents and no hard tab characters.
+Also trim excess spaces and tabs from ends of lines, and remove empty lines
+at the end of files. Also ensure the last line ends with a newline.
+
+If no paths are given on the command line, reindent operates as a filter,
+reading a single source file from standard input and writing the transformed
+source to standard output. In this case, the -d, -r and -v flags are
+ignored.
+
+You can pass one or more file and/or directory paths. When a directory
+path, all .py files within the directory will be examined, and, if the -r
+option is given, likewise recursively for subdirectories.
+
+If output is not to standard output, reindent overwrites files in place,
+renaming the originals with a .bak extension. If it finds nothing to
+change, the file is left alone. If reindent does change a file, the changed
+file is a fixed-point for future runs (i.e., running reindent on the
+resulting .py file won't change it again).
+
+The hard part of reindenting is figuring out what to do with comment
+lines. So long as the input files get a clean bill of health from
+tabnanny.py, reindent should do a good job.
+
+The backup file is a copy of the one that is being reindented. The ".bak"
+file is generated with shutil.copy(), but some corner cases regarding
+user/group and permissions could leave the backup file more readable that
+you'd prefer. You can always use the --nobackup option to prevent this.
+"""
+
+__version__ = "1"
+
+import tokenize
+import os, shutil
+import sys
+
+verbose = 0
+recurse = 0
+dryrun = 0
+makebackup = True
+
+def usage(msg=None):
+ if msg is not None:
+ print >> sys.stderr, msg
+ print >> sys.stderr, __doc__
+
+def errprint(*args):
+ sep = ""
+ for arg in args:
+ sys.stderr.write(sep + str(arg))
+ sep = " "
+ sys.stderr.write("\n")
+
+def main():
+ import getopt
+ global verbose, recurse, dryrun, makebackup
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "drnvh",
+ ["dryrun", "recurse", "nobackup", "verbose", "help"])
+ except getopt.error, msg:
+ usage(msg)
+ return
+ for o, a in opts:
+ if o in ('-d', '--dryrun'):
+ dryrun += 1
+ elif o in ('-r', '--recurse'):
+ recurse += 1
+ elif o in ('-n', '--nobackup'):
+ makebackup = False
+ elif o in ('-v', '--verbose'):
+ verbose += 1
+ elif o in ('-h', '--help'):
+ usage()
+ return
+ if not args:
+ r = Reindenter(sys.stdin)
+ r.run()
+ r.write(sys.stdout)
+ return
+ for arg in args:
+ check(arg)
+
+def check(file):
+ if os.path.isdir(file) and not os.path.islink(file):
+ if verbose:
+ print "listing directory", file
+ names = os.listdir(file)
+ for name in names:
+ fullname = os.path.join(file, name)
+ if ((recurse and os.path.isdir(fullname) and
+ not os.path.islink(fullname) and
+ not os.path.split(fullname)[1].startswith("."))
+ or name.lower().endswith(".py")):
+ check(fullname)
+ return
+
+ if verbose:
+ print "checking", file, "...",
+ try:
+ f = open(file)
+ except IOError, msg:
+ errprint("%s: I/O Error: %s" % (file, str(msg)))
+ return
+
+ r = Reindenter(f)
+ f.close()
+ if r.run():
+ if verbose:
+ print "changed."
+ if dryrun:
+ print "But this is a dry run, so leaving it alone."
+ if not dryrun:
+ bak = file + ".bak"
+ if makebackup:
+ shutil.copyfile(file, bak)
+ if verbose:
+ print "backed up", file, "to", bak
+ f = open(file, "w")
+ r.write(f)
+ f.close()
+ if verbose:
+ print "wrote new", file
+ return True
+ else:
+ if verbose:
+ print "unchanged."
+ return False
+
+def _rstrip(line, JUNK='\n \t'):
+ """Return line stripped of trailing spaces, tabs, newlines.
+
+ Note that line.rstrip() instead also strips sundry control characters,
+ but at least one known Emacs user expects to keep junk like that, not
+ mentioning Barry by name or anything <wink>.
+ """
+
+ i = len(line)
+ while i > 0 and line[i-1] in JUNK:
+ i -= 1
+ return line[:i]
+
+class Reindenter:
+
+ def __init__(self, f):
+ self.find_stmt = 1 # next token begins a fresh stmt?
+ self.level = 0 # current indent level
+
+ # Raw file lines.
+ self.raw = f.readlines()
+
+ # File lines, rstripped & tab-expanded. Dummy at start is so
+ # that we can use tokenize's 1-based line numbering easily.
+ # Note that a line is all-blank iff it's "\n".
+ self.lines = [_rstrip(line).expandtabs() + "\n"
+ for line in self.raw]
+ self.lines.insert(0, None)
+ self.index = 1 # index into self.lines of next line
+
+ # List of (lineno, indentlevel) pairs, one for each stmt and
+ # comment line. indentlevel is -1 for comment lines, as a
+ # signal that tokenize doesn't know what to do about them;
+ # indeed, they're our headache!
+ self.stats = []
+
+ def run(self):
+ tokenize.tokenize(self.getline, self.tokeneater)
+ # Remove trailing empty lines.
+ lines = self.lines
+ while lines and lines[-1] == "\n":
+ lines.pop()
+ # Sentinel.
+ stats = self.stats
+ stats.append((len(lines), 0))
+ # Map count of leading spaces to # we want.
+ have2want = {}
+ # Program after transformation.
+ after = self.after = []
+ # Copy over initial empty lines -- there's nothing to do until
+ # we see a line with *something* on it.
+ i = stats[0][0]
+ after.extend(lines[1:i])
+ for i in range(len(stats)-1):
+ thisstmt, thislevel = stats[i]
+ nextstmt = stats[i+1][0]
+ have = getlspace(lines[thisstmt])
+ want = thislevel * 4
+ if want < 0:
+ # A comment line.
+ if have:
+ # An indented comment line. If we saw the same
+ # indentation before, reuse what it most recently
+ # mapped to.
+ want = have2want.get(have, -1)
+ if want < 0:
+ # Then it probably belongs to the next real stmt.
+ for j in xrange(i+1, len(stats)-1):
+ jline, jlevel = stats[j]
+ if jlevel >= 0:
+ if have == getlspace(lines[jline]):
+ want = jlevel * 4
+ break
+ if want < 0: # Maybe it's a hanging
+ # comment like this one,
+ # in which case we should shift it like its base
+ # line got shifted.
+ for j in xrange(i-1, -1, -1):
+ jline, jlevel = stats[j]
+ if jlevel >= 0:
+ want = have + getlspace(after[jline-1]) - \
+ getlspace(lines[jline])
+ break
+ if want < 0:
+ # Still no luck -- leave it alone.
+ want = have
+ else:
+ want = 0
+ assert want >= 0
+ have2want[have] = want
+ diff = want - have
+ if diff == 0 or have == 0:
+ after.extend(lines[thisstmt:nextstmt])
+ else:
+ for line in lines[thisstmt:nextstmt]:
+ if diff > 0:
+ if line == "\n":
+ after.append(line)
+ else:
+ after.append(" " * diff + line)
+ else:
+ remove = min(getlspace(line), -diff)
+ after.append(line[remove:])
+ return self.raw != self.after
+
+ def write(self, f):
+ f.writelines(self.after)
+
+ # Line-getter for tokenize.
+ def getline(self):
+ if self.index >= len(self.lines):
+ line = ""
+ else:
+ line = self.lines[self.index]
+ self.index += 1
+ return line
+
+ # Line-eater for tokenize.
+ def tokeneater(self, type, token, (sline, scol), end, line,
+ INDENT=tokenize.INDENT,
+ DEDENT=tokenize.DEDENT,
+ NEWLINE=tokenize.NEWLINE,
+ COMMENT=tokenize.COMMENT,
+ NL=tokenize.NL):
+
+ if type == NEWLINE:
+ # A program statement, or ENDMARKER, will eventually follow,
+ # after some (possibly empty) run of tokens of the form
+ # (NL | COMMENT)* (INDENT | DEDENT+)?
+ self.find_stmt = 1
+
+ elif type == INDENT:
+ self.find_stmt = 1
+ self.level += 1
+
+ elif type == DEDENT:
+ self.find_stmt = 1
+ self.level -= 1
+
+ elif type == COMMENT:
+ if self.find_stmt:
+ self.stats.append((sline, -1))
+ # but we're still looking for a new stmt, so leave
+ # find_stmt alone
+
+ elif type == NL:
+ pass
+
+ elif self.find_stmt:
+ # This is the first "real token" following a NEWLINE, so it
+ # must be the first token of the next program statement, or an
+ # ENDMARKER.
+ self.find_stmt = 0
+ if line: # not endmarker
+ self.stats.append((sline, self.level))
+
+# Count number of leading blanks.
+def getlspace(line):
+ i, n = 0, len(line)
+ while i < n and line[i] == " ":
+ i += 1
+ return i
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/rgrep.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/rgrep.py
new file mode 100644
index 0000000000..ef06039d7a
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/rgrep.py
@@ -0,0 +1,64 @@
+#! /usr/bin/env python
+
+"""Reverse grep.
+
+Usage: rgrep [-i] pattern file
+"""
+
+import sys
+import re
+import getopt
+
+def main():
+ bufsize = 64*1024
+ reflags = 0
+ opts, args = getopt.getopt(sys.argv[1:], "i")
+ for o, a in opts:
+ if o == '-i':
+ reflags = reflags | re.IGNORECASE
+ if len(args) < 2:
+ usage("not enough arguments")
+ if len(args) > 2:
+ usage("exactly one file argument required")
+ pattern, filename = args
+ try:
+ prog = re.compile(pattern, reflags)
+ except re.error, msg:
+ usage("error in regular expression: %s" % str(msg))
+ try:
+ f = open(filename)
+ except IOError, msg:
+ usage("can't open %s: %s" % (repr(filename), str(msg)), 1)
+ f.seek(0, 2)
+ pos = f.tell()
+ leftover = None
+ while pos > 0:
+ size = min(pos, bufsize)
+ pos = pos - size
+ f.seek(pos)
+ buffer = f.read(size)
+ lines = buffer.split("\n")
+ del buffer
+ if leftover is None:
+ if not lines[-1]:
+ del lines[-1]
+ else:
+ lines[-1] = lines[-1] + leftover
+ if pos > 0:
+ leftover = lines[0]
+ del lines[0]
+ else:
+ leftover = None
+ lines.reverse()
+ for line in lines:
+ if prog.search(line):
+ print line
+
+def usage(msg, code=2):
+ sys.stdout = sys.stderr
+ print msg
+ print __doc__
+ sys.exit(code)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/serve.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/serve.py
new file mode 100644
index 0000000000..013926317d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/serve.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+'''
+Small wsgiref based web server. Takes a path to serve from and an
+optional port number (defaults to 8000), then tries to serve files.
+Mime types are guessed from the file names, 404 errors are thrown
+if the file is not found. Used for the make serve target in Doc.
+'''
+import sys
+import os
+import mimetypes
+from wsgiref import simple_server, util
+
+def app(environ, respond):
+
+ fn = os.path.join(path, environ['PATH_INFO'][1:])
+ if '.' not in fn.split(os.path.sep)[-1]:
+ fn = os.path.join(fn, 'index.html')
+ type = mimetypes.guess_type(fn)[0]
+
+ if os.path.exists(fn):
+ respond('200 OK', [('Content-Type', type)])
+ return util.FileWrapper(open(fn))
+ else:
+ respond('404 Not Found', [('Content-Type', 'text/plain')])
+ return ['not found']
+
+if __name__ == '__main__':
+ path = sys.argv[1]
+ port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
+ httpd = simple_server.make_server('', port, app)
+ print "Serving %s on port %s, control-C to stop" % (path, port)
+ try:
+ httpd.serve_forever()
+ except KeyboardInterrupt:
+ print "\b\bShutting down."
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/setup.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/setup.py
new file mode 100644
index 0000000000..6cc6a8c9e7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/setup.py
@@ -0,0 +1,20 @@
+from distutils.core import setup
+
+if __name__ == '__main__':
+ setup(
+ scripts=[
+ 'byteyears.py',
+ 'checkpyc.py',
+ 'copytime.py',
+ 'crlf.py',
+ 'dutree.py',
+ 'ftpmirror.py',
+ 'h2py.py',
+ 'lfcr.py',
+ '../i18n/pygettext.py',
+ 'logmerge.py',
+ '../../Lib/tabnanny.py',
+ '../../Lib/timeit.py',
+ 'untabify.py',
+ ],
+ )
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/suff.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/suff.py
new file mode 100644
index 0000000000..599a971555
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/suff.py
@@ -0,0 +1,30 @@
+#! /usr/bin/env python
+
+# suff
+#
+# show different suffixes amongst arguments
+
+import sys
+
+def main():
+ files = sys.argv[1:]
+ suffixes = {}
+ for filename in files:
+ suff = getsuffix(filename)
+ if not suffixes.has_key(suff):
+ suffixes[suff] = []
+ suffixes[suff].append(filename)
+ keys = suffixes.keys()
+ keys.sort()
+ for suff in keys:
+ print repr(suff), len(suffixes[suff])
+
+def getsuffix(filename):
+ suff = ''
+ for i in range(len(filename)):
+ if filename[i] == '.':
+ suff = filename[i:]
+ return suff
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/svneol.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/svneol.py
new file mode 100644
index 0000000000..6a32814c08
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/svneol.py
@@ -0,0 +1,91 @@
+#! /usr/bin/env python
+
+"""
+SVN helper script.
+
+Try to set the svn:eol-style property to "native" on every .py, .txt, .c and
+.h file in the directory tree rooted at the current directory.
+
+Files with the svn:eol-style property already set (to anything) are skipped.
+
+svn will itself refuse to set this property on a file that's not under SVN
+control, or that has a binary mime-type property set. This script inherits
+that behavior, and passes on whatever warning message the failing "svn
+propset" command produces.
+
+In the Python project, it's safe to invoke this script from the root of
+a checkout.
+
+No output is produced for files that are ignored. For a file that gets
+svn:eol-style set, output looks like:
+
+ property 'svn:eol-style' set on 'Lib\ctypes\__init__.py'
+
+For a file not under version control:
+
+ svn: warning: 'patch-finalizer.txt' is not under version control
+
+and for a file with a binary mime-type property:
+
+ svn: File 'Lib\test\test_pep263.py' has binary mime type property
+"""
+
+import re
+import os
+
+def propfiles(root, fn):
+ default = os.path.join(root, ".svn", "props", fn+".svn-work")
+ try:
+ format = int(open(os.path.join(root, ".svn", "format")).read().strip())
+ except IOError:
+ return []
+ if format in (8, 9):
+ # In version 8 and 9, committed props are stored in prop-base, local
+ # modifications in props
+ return [os.path.join(root, ".svn", "prop-base", fn+".svn-base"),
+ os.path.join(root, ".svn", "props", fn+".svn-work")]
+ raise ValueError, "Unknown repository format"
+
+def proplist(root, fn):
+ "Return a list of property names for file fn in directory root"
+ result = []
+ for path in propfiles(root, fn):
+ try:
+ f = open(path)
+ except IOError:
+ # no properties file: not under version control,
+ # or no properties set
+ continue
+ while 1:
+ # key-value pairs, of the form
+ # K <length>
+ # <keyname>NL
+ # V length
+ # <value>NL
+ # END
+ line = f.readline()
+ if line.startswith("END"):
+ break
+ assert line.startswith("K ")
+ L = int(line.split()[1])
+ key = f.read(L)
+ result.append(key)
+ f.readline()
+ line = f.readline()
+ assert line.startswith("V ")
+ L = int(line.split()[1])
+ value = f.read(L)
+ f.readline()
+ f.close()
+ return result
+
+possible_text_file = re.compile(r"\.([hc]|py|txt|sln|vcproj)$").search
+
+for root, dirs, files in os.walk('.'):
+ if '.svn' in dirs:
+ dirs.remove('.svn')
+ for fn in files:
+ if possible_text_file(fn):
+ if 'svn:eol-style' not in proplist(root, fn):
+ path = os.path.join(root, fn)
+ os.system('svn propset svn:eol-style native "%s"' % path)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texcheck.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texcheck.py
new file mode 100644
index 0000000000..af36a37f6c
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texcheck.py
@@ -0,0 +1,233 @@
+""" TeXcheck.py -- rough syntax checking on Python style LaTeX documents.
+
+ Written by Raymond D. Hettinger <python at rcn.com>
+ Copyright (c) 2003 Python Software Foundation. All rights reserved.
+
+Designed to catch common markup errors including:
+* Unbalanced or mismatched parenthesis, brackets, and braces.
+* Unbalanced or mismatched \\begin and \\end blocks.
+* Misspelled or invalid LaTeX commands.
+* Use of forward slashes instead of backslashes for commands.
+* Table line size mismatches.
+
+Sample command line usage:
+ python texcheck.py -k chapterheading -m lib/librandomtex *.tex
+
+Options:
+ -m Munge parenthesis and brackets. [0,n) would normally mismatch.
+ -k keyword: Keyword is a valid LaTeX command. Do not include the backslash.
+ -d: Delimiter check only (useful for non-LaTeX files).
+ -h: Help
+ -s lineno: Start at lineno (useful for skipping complex sections).
+ -v: Verbose. Trace the matching of //begin and //end blocks.
+"""
+
+import re
+import sys
+import getopt
+from itertools import izip, count, islice
+import glob
+
+cmdstr = r"""
+ \section \module \declaremodule \modulesynopsis \moduleauthor
+ \sectionauthor \versionadded \code \class \method \begin
+ \optional \var \ref \end \subsection \lineiii \hline \label
+ \indexii \textrm \ldots \keyword \stindex \index \item \note
+ \withsubitem \ttindex \footnote \citetitle \samp \opindex
+ \noindent \exception \strong \dfn \ctype \obindex \character
+ \indexiii \function \bifuncindex \refmodule \refbimodindex
+ \subsubsection \nodename \member \chapter \emph \ASCII \UNIX
+ \regexp \program \production \token \productioncont \term
+ \grammartoken \lineii \seemodule \file \EOF \documentclass
+ \usepackage \title \input \maketitle \ifhtml \fi \url \Cpp
+ \tableofcontents \kbd \programopt \envvar \refstmodindex
+ \cfunction \constant \NULL \moreargs \cfuncline \cdata
+ \textasciicircum \n \ABC \setindexsubitem \versionchanged
+ \deprecated \seetext \newcommand \POSIX \pep \warning \rfc
+ \verbatiminput \methodline \textgreater \seetitle \lineiv
+ \funclineni \ulink \manpage \funcline \dataline \unspecified
+ \textbackslash \mimetype \mailheader \seepep \textunderscore
+ \longprogramopt \infinity \plusminus \shortversion \version
+ \refmodindex \seerfc \makeindex \makemodindex \renewcommand
+ \indexname \appendix \protect \indexiv \mbox \textasciitilde
+ \platform \seeurl \leftmargin \labelwidth \localmoduletable
+ \LaTeX \copyright \memberline \backslash \pi \centerline
+ \caption \vspace \textwidth \menuselection \textless
+ \makevar \csimplemacro \menuselection \bfcode \sub \release
+ \email \kwindex \refexmodindex \filenq \e \menuselection
+ \exindex \linev \newsgroup \verbatim \setshortversion
+ \author \authoraddress \paragraph \subparagraph \cmemberline
+ \textbar \C \seelink
+"""
+
+def matchclose(c_lineno, c_symbol, openers, pairmap):
+ "Verify that closing delimiter matches most recent opening delimiter"
+ try:
+ o_lineno, o_symbol = openers.pop()
+ except IndexError:
+ print "\nDelimiter mismatch. On line %d, encountered closing '%s' without corresponding open" % (c_lineno, c_symbol)
+ return
+ if o_symbol in pairmap.get(c_symbol, [c_symbol]): return
+ print "\nOpener '%s' on line %d was not closed before encountering '%s' on line %d" % (o_symbol, o_lineno, c_symbol, c_lineno)
+ return
+
+def checkit(source, opts, morecmds=[]):
+ """Check the LaTeX formatting in a sequence of lines.
+
+ Opts is a mapping of options to option values if any:
+ -m munge parenthesis and brackets
+ -d delimiters only checking
+ -v verbose trace of delimiter matching
+ -s lineno: linenumber to start scan (default is 1).
+
+ Morecmds is a sequence of LaTeX commands (without backslashes) that
+ are to be considered valid in the scan.
+ """
+
+ texcmd = re.compile(r'\\[A-Za-z]+')
+ falsetexcmd = re.compile(r'\/([A-Za-z]+)') # Mismarked with forward slash
+
+ validcmds = set(cmdstr.split())
+ for cmd in morecmds:
+ validcmds.add('\\' + cmd)
+
+ if '-m' in opts:
+ pairmap = {']':'[(', ')':'(['} # Munged openers
+ else:
+ pairmap = {']':'[', ')':'('} # Normal opener for a given closer
+ openpunct = set('([') # Set of valid openers
+
+ delimiters = re.compile(r'\\(begin|end){([_a-zA-Z]+)}|([()\[\]])')
+ braces = re.compile(r'({)|(})')
+ doubledwords = re.compile(r'(\b[A-za-z]+\b) \b\1\b')
+ spacingmarkup = re.compile(r'\\(ABC|ASCII|C|Cpp|EOF|infinity|NULL|plusminus|POSIX|UNIX)\s')
+
+ openers = [] # Stack of pending open delimiters
+ bracestack = [] # Stack of pending open braces
+
+ tablestart = re.compile(r'\\begin{(?:long)?table([iv]+)}')
+ tableline = re.compile(r'\\line([iv]+){')
+ tableend = re.compile(r'\\end{(?:long)?table([iv]+)}')
+ tablelevel = ''
+ tablestartline = 0
+
+ startline = int(opts.get('-s', '1'))
+ lineno = 0
+
+ for lineno, line in izip(count(startline), islice(source, startline-1, None)):
+ line = line.rstrip()
+
+ # Check balancing of open/close parenthesis, brackets, and begin/end blocks
+ for begend, name, punct in delimiters.findall(line):
+ if '-v' in opts:
+ print lineno, '|', begend, name, punct,
+ if begend == 'begin' and '-d' not in opts:
+ openers.append((lineno, name))
+ elif punct in openpunct:
+ openers.append((lineno, punct))
+ elif begend == 'end' and '-d' not in opts:
+ matchclose(lineno, name, openers, pairmap)
+ elif punct in pairmap:
+ matchclose(lineno, punct, openers, pairmap)
+ if '-v' in opts:
+ print ' --> ', openers
+
+ # Balance opening and closing braces
+ for open, close in braces.findall(line):
+ if open == '{':
+ bracestack.append(lineno)
+ if close == '}':
+ try:
+ bracestack.pop()
+ except IndexError:
+ print r'Warning, unmatched } on line %s.' % (lineno,)
+
+ # Optionally, skip LaTeX specific checks
+ if '-d' in opts:
+ continue
+
+ # Warn whenever forward slashes encountered with a LaTeX command
+ for cmd in falsetexcmd.findall(line):
+ if '822' in line or '.html' in line:
+ continue # Ignore false positives for urls and for /rfc822
+ if '\\' + cmd in validcmds:
+ print 'Warning, forward slash used on line %d with cmd: /%s' % (lineno, cmd)
+
+ # Check for markup requiring {} for correct spacing
+ for cmd in spacingmarkup.findall(line):
+ print r'Warning, \%s should be written as \%s{} on line %d' % (cmd, cmd, lineno)
+
+ # Validate commands
+ nc = line.find(r'\newcommand')
+ if nc != -1:
+ start = line.find('{', nc)
+ end = line.find('}', start)
+ validcmds.add(line[start+1:end])
+ for cmd in texcmd.findall(line):
+ if cmd not in validcmds:
+ print r'Warning, unknown tex cmd on line %d: \%s' % (lineno, cmd)
+
+ # Check table levels (make sure lineii only inside tableii)
+ m = tablestart.search(line)
+ if m:
+ tablelevel = m.group(1)
+ tablestartline = lineno
+ m = tableline.search(line)
+ if m and m.group(1) != tablelevel:
+ print r'Warning, \line%s on line %d does not match \table%s on line %d' % (m.group(1), lineno, tablelevel, tablestartline)
+ if tableend.search(line):
+ tablelevel = ''
+
+ # Style guide warnings
+ if 'e.g.' in line or 'i.e.' in line:
+ print r'Style warning, avoid use of i.e or e.g. on line %d' % (lineno,)
+
+ for dw in doubledwords.findall(line):
+ print r'Doubled word warning. "%s" on line %d' % (dw, lineno)
+
+ lastline = lineno
+ for lineno, symbol in openers:
+ print "Unmatched open delimiter '%s' on line %d" % (symbol, lineno)
+ for lineno in bracestack:
+ print "Unmatched { on line %d" % (lineno,)
+ print 'Done checking %d lines.' % (lastline,)
+ return 0
+
+def main(args=None):
+ if args is None:
+ args = sys.argv[1:]
+ optitems, arglist = getopt.getopt(args, "k:mdhs:v")
+ opts = dict(optitems)
+ if '-h' in opts or args==[]:
+ print __doc__
+ return 0
+
+ if len(arglist) < 1:
+ print 'Please specify a file to be checked'
+ return 1
+
+ for i, filespec in enumerate(arglist):
+ if '*' in filespec or '?' in filespec:
+ arglist[i:i+1] = glob.glob(filespec)
+
+ morecmds = [v for k,v in optitems if k=='-k']
+ err = []
+
+ for filename in arglist:
+ print '=' * 30
+ print "Checking", filename
+ try:
+ f = open(filename)
+ except IOError:
+ print 'Cannot open file %s.' % arglist[0]
+ return 2
+
+ try:
+ err.append(checkit(f, opts, morecmds))
+ finally:
+ f.close()
+
+ return max(err)
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texi2html.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texi2html.py
new file mode 100644
index 0000000000..9f65c38f05
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/texi2html.py
@@ -0,0 +1,2078 @@
+#! /usr/bin/env python
+
+# Convert GNU texinfo files into HTML, one file per node.
+# Based on Texinfo 2.14.
+# Usage: texi2html [-d] [-d] [-c] inputfile outputdirectory
+# The input file must be a complete texinfo file, e.g. emacs.texi.
+# This creates many files (one per info node) in the output directory,
+# overwriting existing files of the same name. All files created have
+# ".html" as their extension.
+
+
+# XXX To do:
+# - handle @comment*** correctly
+# - handle @xref {some words} correctly
+# - handle @ftable correctly (items aren't indexed?)
+# - handle @itemx properly
+# - handle @exdent properly
+# - add links directly to the proper line from indices
+# - check against the definitive list of @-cmds; we still miss (among others):
+# - @defindex (hard)
+# - @c(omment) in the middle of a line (rarely used)
+# - @this* (not really needed, only used in headers anyway)
+# - @today{} (ever used outside title page?)
+
+# More consistent handling of chapters/sections/etc.
+# Lots of documentation
+# Many more options:
+# -top designate top node
+# -links customize which types of links are included
+# -split split at chapters or sections instead of nodes
+# -name Allow different types of filename handling. Non unix systems
+# will have problems with long node names
+# ...
+# Support the most recent texinfo version and take a good look at HTML 3.0
+# More debugging output (customizable) and more flexible error handling
+# How about icons ?
+
+# rpyron 2002-05-07
+# Robert Pyron <rpyron@alum.mit.edu>
+# 1. BUGFIX: In function makefile(), strip blanks from the nodename.
+# This is necessary to match the behavior of parser.makeref() and
+# parser.do_node().
+# 2. BUGFIX fixed KeyError in end_ifset (well, I may have just made
+# it go away, rather than fix it)
+# 3. BUGFIX allow @menu and menu items inside @ifset or @ifclear
+# 4. Support added for:
+# @uref URL reference
+# @image image file reference (see note below)
+# @multitable output an HTML table
+# @vtable
+# 5. Partial support for accents, to match MAKEINFO output
+# 6. I added a new command-line option, '-H basename', to specify
+# HTML Help output. This will cause three files to be created
+# in the current directory:
+# `basename`.hhp HTML Help Workshop project file
+# `basename`.hhc Contents file for the project
+# `basename`.hhk Index file for the project
+# When fed into HTML Help Workshop, the resulting file will be
+# named `basename`.chm.
+# 7. A new class, HTMLHelp, to accomplish item 6.
+# 8. Various calls to HTMLHelp functions.
+# A NOTE ON IMAGES: Just as 'outputdirectory' must exist before
+# running this program, all referenced images must already exist
+# in outputdirectory.
+
+import os
+import sys
+import string
+import re
+
+MAGIC = '\\input texinfo'
+
+cmprog = re.compile('^@([a-z]+)([ \t]|$)') # Command (line-oriented)
+blprog = re.compile('^[ \t]*$') # Blank line
+kwprog = re.compile('@[a-z]+') # Keyword (embedded, usually
+ # with {} args)
+spprog = re.compile('[\n@{}&<>]') # Special characters in
+ # running text
+ #
+ # menu item (Yuck!)
+miprog = re.compile('^\* ([^:]*):(:|[ \t]*([^\t,\n.]+)([^ \t\n]*))[ \t\n]*')
+# 0 1 1 2 3 34 42 0
+# ----- ---------- ---------
+# -|-----------------------------
+# -----------------------------------------------------
+
+
+
+
+class HTMLNode:
+ """Some of the parser's functionality is separated into this class.
+
+ A Node accumulates its contents, takes care of links to other Nodes
+ and saves itself when it is finished and all links are resolved.
+ """
+
+ DOCTYPE = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'
+
+ type = 0
+ cont = ''
+ epilogue = '</BODY></HTML>\n'
+
+ def __init__(self, dir, name, topname, title, next, prev, up):
+ self.dirname = dir
+ self.name = name
+ if topname:
+ self.topname = topname
+ else:
+ self.topname = name
+ self.title = title
+ self.next = next
+ self.prev = prev
+ self.up = up
+ self.lines = []
+
+ def write(self, *lines):
+ map(self.lines.append, lines)
+
+ def flush(self):
+ fp = open(self.dirname + '/' + makefile(self.name), 'w')
+ fp.write(self.prologue)
+ fp.write(self.text)
+ fp.write(self.epilogue)
+ fp.close()
+
+ def link(self, label, nodename, rel=None, rev=None):
+ if nodename:
+ if nodename.lower() == '(dir)':
+ addr = '../dir.html'
+ title = ''
+ else:
+ addr = makefile(nodename)
+ title = ' TITLE="%s"' % nodename
+ self.write(label, ': <A HREF="', addr, '"', \
+ rel and (' REL=' + rel) or "", \
+ rev and (' REV=' + rev) or "", \
+ title, '>', nodename, '</A> \n')
+
+ def finalize(self):
+ length = len(self.lines)
+ self.text = ''.join(self.lines)
+ self.lines = []
+ self.open_links()
+ self.output_links()
+ self.close_links()
+ links = ''.join(self.lines)
+ self.lines = []
+ self.prologue = (
+ self.DOCTYPE +
+ '\n<HTML><HEAD>\n'
+ ' <!-- Converted with texi2html and Python -->\n'
+ ' <TITLE>' + self.title + '</TITLE>\n'
+ ' <LINK REL=Next HREF="'
+ + makefile(self.next) + '" TITLE="' + self.next + '">\n'
+ ' <LINK REL=Previous HREF="'
+ + makefile(self.prev) + '" TITLE="' + self.prev + '">\n'
+ ' <LINK REL=Up HREF="'
+ + makefile(self.up) + '" TITLE="' + self.up + '">\n'
+ '</HEAD><BODY>\n' +
+ links)
+ if length > 20:
+ self.epilogue = '<P>\n%s</BODY></HTML>\n' % links
+
+ def open_links(self):
+ self.write('<HR>\n')
+
+ def close_links(self):
+ self.write('<HR>\n')
+
+ def output_links(self):
+ if self.cont != self.next:
+ self.link(' Cont', self.cont)
+ self.link(' Next', self.next, rel='Next')
+ self.link(' Prev', self.prev, rel='Previous')
+ self.link(' Up', self.up, rel='Up')
+ if self.name <> self.topname:
+ self.link(' Top', self.topname)
+
+
+class HTML3Node(HTMLNode):
+
+ DOCTYPE = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML Level 3//EN//3.0">'
+
+ def open_links(self):
+ self.write('<DIV CLASS=Navigation>\n <HR>\n')
+
+ def close_links(self):
+ self.write(' <HR>\n</DIV>\n')
+
+
+class TexinfoParser:
+
+ COPYRIGHT_SYMBOL = "&copy;"
+ FN_ID_PATTERN = "(%(id)s)"
+ FN_SOURCE_PATTERN = '<A NAME=footnoteref%(id)s' \
+ ' HREF="#footnotetext%(id)s">' \
+ + FN_ID_PATTERN + '</A>'
+ FN_TARGET_PATTERN = '<A NAME=footnotetext%(id)s' \
+ ' HREF="#footnoteref%(id)s">' \
+ + FN_ID_PATTERN + '</A>\n%(text)s<P>\n'
+ FN_HEADER = '\n<P>\n<HR NOSHADE SIZE=1 WIDTH=200>\n' \
+ '<STRONG><EM>Footnotes</EM></STRONG>\n<P>'
+
+
+ Node = HTMLNode
+
+ # Initialize an instance
+ def __init__(self):
+ self.unknown = {} # statistics about unknown @-commands
+ self.filenames = {} # Check for identical filenames
+ self.debugging = 0 # larger values produce more output
+ self.print_headers = 0 # always print headers?
+ self.nodefp = None # open file we're writing to
+ self.nodelineno = 0 # Linenumber relative to node
+ self.links = None # Links from current node
+ self.savetext = None # If not None, save text head instead
+ self.savestack = [] # If not None, save text head instead
+ self.htmlhelp = None # html help data
+ self.dirname = 'tmp' # directory where files are created
+ self.includedir = '.' # directory to search @include files
+ self.nodename = '' # name of current node
+ self.topname = '' # name of top node (first node seen)
+ self.title = '' # title of this whole Texinfo tree
+ self.resetindex() # Reset all indices
+ self.contents = [] # Reset table of contents
+ self.numbering = [] # Reset section numbering counters
+ self.nofill = 0 # Normal operation: fill paragraphs
+ self.values={'html': 1} # Names that should be parsed in ifset
+ self.stackinfo={} # Keep track of state in the stack
+ # XXX The following should be reset per node?!
+ self.footnotes = [] # Reset list of footnotes
+ self.itemarg = None # Reset command used by @item
+ self.itemnumber = None # Reset number for @item in @enumerate
+ self.itemindex = None # Reset item index name
+ self.node = None
+ self.nodestack = []
+ self.cont = 0
+ self.includedepth = 0
+
+ # Set htmlhelp helper class
+ def sethtmlhelp(self, htmlhelp):
+ self.htmlhelp = htmlhelp
+
+ # Set (output) directory name
+ def setdirname(self, dirname):
+ self.dirname = dirname
+
+ # Set include directory name
+ def setincludedir(self, includedir):
+ self.includedir = includedir
+
+ # Parse the contents of an entire file
+ def parse(self, fp):
+ line = fp.readline()
+ lineno = 1
+ while line and (line[0] == '%' or blprog.match(line)):
+ line = fp.readline()
+ lineno = lineno + 1
+ if line[:len(MAGIC)] <> MAGIC:
+ raise SyntaxError, 'file does not begin with %r' % (MAGIC,)
+ self.parserest(fp, lineno)
+
+ # Parse the contents of a file, not expecting a MAGIC header
+ def parserest(self, fp, initial_lineno):
+ lineno = initial_lineno
+ self.done = 0
+ self.skip = 0
+ self.stack = []
+ accu = []
+ while not self.done:
+ line = fp.readline()
+ self.nodelineno = self.nodelineno + 1
+ if not line:
+ if accu:
+ if not self.skip: self.process(accu)
+ accu = []
+ if initial_lineno > 0:
+ print '*** EOF before @bye'
+ break
+ lineno = lineno + 1
+ mo = cmprog.match(line)
+ if mo:
+ a, b = mo.span(1)
+ cmd = line[a:b]
+ if cmd in ('noindent', 'refill'):
+ accu.append(line)
+ else:
+ if accu:
+ if not self.skip:
+ self.process(accu)
+ accu = []
+ self.command(line, mo)
+ elif blprog.match(line) and \
+ 'format' not in self.stack and \
+ 'example' not in self.stack:
+ if accu:
+ if not self.skip:
+ self.process(accu)
+ if self.nofill:
+ self.write('\n')
+ else:
+ self.write('<P>\n')
+ accu = []
+ else:
+ # Append the line including trailing \n!
+ accu.append(line)
+ #
+ if self.skip:
+ print '*** Still skipping at the end'
+ if self.stack:
+ print '*** Stack not empty at the end'
+ print '***', self.stack
+ if self.includedepth == 0:
+ while self.nodestack:
+ self.nodestack[-1].finalize()
+ self.nodestack[-1].flush()
+ del self.nodestack[-1]
+
+ # Start saving text in a buffer instead of writing it to a file
+ def startsaving(self):
+ if self.savetext <> None:
+ self.savestack.append(self.savetext)
+ # print '*** Recursively saving text, expect trouble'
+ self.savetext = ''
+
+ # Return the text saved so far and start writing to file again
+ def collectsavings(self):
+ savetext = self.savetext
+ if len(self.savestack) > 0:
+ self.savetext = self.savestack[-1]
+ del self.savestack[-1]
+ else:
+ self.savetext = None
+ return savetext or ''
+
+ # Write text to file, or save it in a buffer, or ignore it
+ def write(self, *args):
+ try:
+ text = ''.join(args)
+ except:
+ print args
+ raise TypeError
+ if self.savetext <> None:
+ self.savetext = self.savetext + text
+ elif self.nodefp:
+ self.nodefp.write(text)
+ elif self.node:
+ self.node.write(text)
+
+ # Complete the current node -- write footnotes and close file
+ def endnode(self):
+ if self.savetext <> None:
+ print '*** Still saving text at end of node'
+ dummy = self.collectsavings()
+ if self.footnotes:
+ self.writefootnotes()
+ if self.nodefp:
+ if self.nodelineno > 20:
+ self.write('<HR>\n')
+ [name, next, prev, up] = self.nodelinks[:4]
+ self.link('Next', next)
+ self.link('Prev', prev)
+ self.link('Up', up)
+ if self.nodename <> self.topname:
+ self.link('Top', self.topname)
+ self.write('<HR>\n')
+ self.write('</BODY>\n')
+ self.nodefp.close()
+ self.nodefp = None
+ elif self.node:
+ if not self.cont and \
+ (not self.node.type or \
+ (self.node.next and self.node.prev and self.node.up)):
+ self.node.finalize()
+ self.node.flush()
+ else:
+ self.nodestack.append(self.node)
+ self.node = None
+ self.nodename = ''
+
+ # Process a list of lines, expanding embedded @-commands
+ # This mostly distinguishes between menus and normal text
+ def process(self, accu):
+ if self.debugging > 1:
+ print '!'*self.debugging, 'process:', self.skip, self.stack,
+ if accu: print accu[0][:30],
+ if accu[0][30:] or accu[1:]: print '...',
+ print
+ if self.inmenu():
+ # XXX should be done differently
+ for line in accu:
+ mo = miprog.match(line)
+ if not mo:
+ line = line.strip() + '\n'
+ self.expand(line)
+ continue
+ bgn, end = mo.span(0)
+ a, b = mo.span(1)
+ c, d = mo.span(2)
+ e, f = mo.span(3)
+ g, h = mo.span(4)
+ label = line[a:b]
+ nodename = line[c:d]
+ if nodename[0] == ':': nodename = label
+ else: nodename = line[e:f]
+ punct = line[g:h]
+ self.write(' <LI><A HREF="',
+ makefile(nodename),
+ '">', nodename,
+ '</A>', punct, '\n')
+ self.htmlhelp.menuitem(nodename)
+ self.expand(line[end:])
+ else:
+ text = ''.join(accu)
+ self.expand(text)
+
+ # find 'menu' (we might be inside 'ifset' or 'ifclear')
+ def inmenu(self):
+ #if 'menu' in self.stack:
+ # print 'inmenu :', self.skip, self.stack, self.stackinfo
+ stack = self.stack
+ while stack and stack[-1] in ('ifset','ifclear'):
+ try:
+ if self.stackinfo[len(stack)]:
+ return 0
+ except KeyError:
+ pass
+ stack = stack[:-1]
+ return (stack and stack[-1] == 'menu')
+
+ # Write a string, expanding embedded @-commands
+ def expand(self, text):
+ stack = []
+ i = 0
+ n = len(text)
+ while i < n:
+ start = i
+ mo = spprog.search(text, i)
+ if mo:
+ i = mo.start()
+ else:
+ self.write(text[start:])
+ break
+ self.write(text[start:i])
+ c = text[i]
+ i = i+1
+ if c == '\n':
+ self.write('\n')
+ continue
+ if c == '<':
+ self.write('&lt;')
+ continue
+ if c == '>':
+ self.write('&gt;')
+ continue
+ if c == '&':
+ self.write('&amp;')
+ continue
+ if c == '{':
+ stack.append('')
+ continue
+ if c == '}':
+ if not stack:
+ print '*** Unmatched }'
+ self.write('}')
+ continue
+ cmd = stack[-1]
+ del stack[-1]
+ try:
+ method = getattr(self, 'close_' + cmd)
+ except AttributeError:
+ self.unknown_close(cmd)
+ continue
+ method()
+ continue
+ if c <> '@':
+ # Cannot happen unless spprog is changed
+ raise RuntimeError, 'unexpected funny %r' % c
+ start = i
+ while i < n and text[i] in string.ascii_letters: i = i+1
+ if i == start:
+ # @ plus non-letter: literal next character
+ i = i+1
+ c = text[start:i]
+ if c == ':':
+ # `@:' means no extra space after
+ # preceding `.', `?', `!' or `:'
+ pass
+ else:
+ # `@.' means a sentence-ending period;
+ # `@@', `@{', `@}' quote `@', `{', `}'
+ self.write(c)
+ continue
+ cmd = text[start:i]
+ if i < n and text[i] == '{':
+ i = i+1
+ stack.append(cmd)
+ try:
+ method = getattr(self, 'open_' + cmd)
+ except AttributeError:
+ self.unknown_open(cmd)
+ continue
+ method()
+ continue
+ try:
+ method = getattr(self, 'handle_' + cmd)
+ except AttributeError:
+ self.unknown_handle(cmd)
+ continue
+ method()
+ if stack:
+ print '*** Stack not empty at para:', stack
+
+ # --- Handle unknown embedded @-commands ---
+
+ def unknown_open(self, cmd):
+ print '*** No open func for @' + cmd + '{...}'
+ cmd = cmd + '{'
+ self.write('@', cmd)
+ if not self.unknown.has_key(cmd):
+ self.unknown[cmd] = 1
+ else:
+ self.unknown[cmd] = self.unknown[cmd] + 1
+
+ def unknown_close(self, cmd):
+ print '*** No close func for @' + cmd + '{...}'
+ cmd = '}' + cmd
+ self.write('}')
+ if not self.unknown.has_key(cmd):
+ self.unknown[cmd] = 1
+ else:
+ self.unknown[cmd] = self.unknown[cmd] + 1
+
+ def unknown_handle(self, cmd):
+ print '*** No handler for @' + cmd
+ self.write('@', cmd)
+ if not self.unknown.has_key(cmd):
+ self.unknown[cmd] = 1
+ else:
+ self.unknown[cmd] = self.unknown[cmd] + 1
+
+ # XXX The following sections should be ordered as the texinfo docs
+
+ # --- Embedded @-commands without {} argument list --
+
+ def handle_noindent(self): pass
+
+ def handle_refill(self): pass
+
+ # --- Include file handling ---
+
+ def do_include(self, args):
+ file = args
+ file = os.path.join(self.includedir, file)
+ try:
+ fp = open(file, 'r')
+ except IOError, msg:
+ print '*** Can\'t open include file', repr(file)
+ return
+ print '!'*self.debugging, '--> file', repr(file)
+ save_done = self.done
+ save_skip = self.skip
+ save_stack = self.stack
+ self.includedepth = self.includedepth + 1
+ self.parserest(fp, 0)
+ self.includedepth = self.includedepth - 1
+ fp.close()
+ self.done = save_done
+ self.skip = save_skip
+ self.stack = save_stack
+ print '!'*self.debugging, '<-- file', repr(file)
+
+ # --- Special Insertions ---
+
+ def open_dmn(self): pass
+ def close_dmn(self): pass
+
+ def open_dots(self): self.write('...')
+ def close_dots(self): pass
+
+ def open_bullet(self): pass
+ def close_bullet(self): pass
+
+ def open_TeX(self): self.write('TeX')
+ def close_TeX(self): pass
+
+ def handle_copyright(self): self.write(self.COPYRIGHT_SYMBOL)
+ def open_copyright(self): self.write(self.COPYRIGHT_SYMBOL)
+ def close_copyright(self): pass
+
+ def open_minus(self): self.write('-')
+ def close_minus(self): pass
+
+ # --- Accents ---
+
+ # rpyron 2002-05-07
+ # I would like to do at least as well as makeinfo when
+ # it is producing HTML output:
+ #
+ # input output
+ # @"o @"o umlaut accent
+ # @'o 'o acute accent
+ # @,{c} @,{c} cedilla accent
+ # @=o @=o macron/overbar accent
+ # @^o @^o circumflex accent
+ # @`o `o grave accent
+ # @~o @~o tilde accent
+ # @dotaccent{o} @dotaccent{o} overdot accent
+ # @H{o} @H{o} long Hungarian umlaut
+ # @ringaccent{o} @ringaccent{o} ring accent
+ # @tieaccent{oo} @tieaccent{oo} tie-after accent
+ # @u{o} @u{o} breve accent
+ # @ubaraccent{o} @ubaraccent{o} underbar accent
+ # @udotaccent{o} @udotaccent{o} underdot accent
+ # @v{o} @v{o} hacek or check accent
+ # @exclamdown{} &#161; upside-down !
+ # @questiondown{} &#191; upside-down ?
+ # @aa{},@AA{} &#229;,&#197; a,A with circle
+ # @ae{},@AE{} &#230;,&#198; ae,AE ligatures
+ # @dotless{i} @dotless{i} dotless i
+ # @dotless{j} @dotless{j} dotless j
+ # @l{},@L{} l/,L/ suppressed-L,l
+ # @o{},@O{} &#248;,&#216; O,o with slash
+ # @oe{},@OE{} oe,OE oe,OE ligatures
+ # @ss{} &#223; es-zet or sharp S
+ #
+ # The following character codes and approximations have been
+ # copied from makeinfo's HTML output.
+
+ def open_exclamdown(self): self.write('&#161;') # upside-down !
+ def close_exclamdown(self): pass
+ def open_questiondown(self): self.write('&#191;') # upside-down ?
+ def close_questiondown(self): pass
+ def open_aa(self): self.write('&#229;') # a with circle
+ def close_aa(self): pass
+ def open_AA(self): self.write('&#197;') # A with circle
+ def close_AA(self): pass
+ def open_ae(self): self.write('&#230;') # ae ligatures
+ def close_ae(self): pass
+ def open_AE(self): self.write('&#198;') # AE ligatures
+ def close_AE(self): pass
+ def open_o(self): self.write('&#248;') # o with slash
+ def close_o(self): pass
+ def open_O(self): self.write('&#216;') # O with slash
+ def close_O(self): pass
+ def open_ss(self): self.write('&#223;') # es-zet or sharp S
+ def close_ss(self): pass
+ def open_oe(self): self.write('oe') # oe ligatures
+ def close_oe(self): pass
+ def open_OE(self): self.write('OE') # OE ligatures
+ def close_OE(self): pass
+ def open_l(self): self.write('l/') # suppressed-l
+ def close_l(self): pass
+ def open_L(self): self.write('L/') # suppressed-L
+ def close_L(self): pass
+
+ # --- Special Glyphs for Examples ---
+
+ def open_result(self): self.write('=&gt;')
+ def close_result(self): pass
+
+ def open_expansion(self): self.write('==&gt;')
+ def close_expansion(self): pass
+
+ def open_print(self): self.write('-|')
+ def close_print(self): pass
+
+ def open_error(self): self.write('error--&gt;')
+ def close_error(self): pass
+
+ def open_equiv(self): self.write('==')
+ def close_equiv(self): pass
+
+ def open_point(self): self.write('-!-')
+ def close_point(self): pass
+
+ # --- Cross References ---
+
+ def open_pxref(self):
+ self.write('see ')
+ self.startsaving()
+ def close_pxref(self):
+ self.makeref()
+
+ def open_xref(self):
+ self.write('See ')
+ self.startsaving()
+ def close_xref(self):
+ self.makeref()
+
+ def open_ref(self):
+ self.startsaving()
+ def close_ref(self):
+ self.makeref()
+
+ def open_inforef(self):
+ self.write('See info file ')
+ self.startsaving()
+ def close_inforef(self):
+ text = self.collectsavings()
+ args = [s.strip() for s in text.split(',')]
+ while len(args) < 3: args.append('')
+ node = args[0]
+ file = args[2]
+ self.write('`', file, '\', node `', node, '\'')
+
+ def makeref(self):
+ text = self.collectsavings()
+ args = [s.strip() for s in text.split(',')]
+ while len(args) < 5: args.append('')
+ nodename = label = args[0]
+ if args[2]: label = args[2]
+ file = args[3]
+ title = args[4]
+ href = makefile(nodename)
+ if file:
+ href = '../' + file + '/' + href
+ self.write('<A HREF="', href, '">', label, '</A>')
+
+ # rpyron 2002-05-07 uref support
+ def open_uref(self):
+ self.startsaving()
+ def close_uref(self):
+ text = self.collectsavings()
+ args = [s.strip() for s in text.split(',')]
+ while len(args) < 2: args.append('')
+ href = args[0]
+ label = args[1]
+ if not label: label = href
+ self.write('<A HREF="', href, '">', label, '</A>')
+
+ # rpyron 2002-05-07 image support
+ # GNU makeinfo producing HTML output tries `filename.png'; if
+ # that does not exist, it tries `filename.jpg'. If that does
+ # not exist either, it complains. GNU makeinfo does not handle
+ # GIF files; however, I include GIF support here because
+ # MySQL documentation uses GIF files.
+
+ def open_image(self):
+ self.startsaving()
+ def close_image(self):
+ self.makeimage()
+ def makeimage(self):
+ text = self.collectsavings()
+ args = [s.strip() for s in text.split(',')]
+ while len(args) < 5: args.append('')
+ filename = args[0]
+ width = args[1]
+ height = args[2]
+ alt = args[3]
+ ext = args[4]
+
+ # The HTML output will have a reference to the image
+ # that is relative to the HTML output directory,
+ # which is what 'filename' gives us. However, we need
+ # to find it relative to our own current directory,
+ # so we construct 'imagename'.
+ imagelocation = self.dirname + '/' + filename
+
+ if os.path.exists(imagelocation+'.png'):
+ filename += '.png'
+ elif os.path.exists(imagelocation+'.jpg'):
+ filename += '.jpg'
+ elif os.path.exists(imagelocation+'.gif'): # MySQL uses GIF files
+ filename += '.gif'
+ else:
+ print "*** Cannot find image " + imagelocation
+ #TODO: what is 'ext'?
+ self.write('<IMG SRC="', filename, '"', \
+ width and (' WIDTH="' + width + '"') or "", \
+ height and (' HEIGHT="' + height + '"') or "", \
+ alt and (' ALT="' + alt + '"') or "", \
+ '/>' )
+ self.htmlhelp.addimage(imagelocation)
+
+
+ # --- Marking Words and Phrases ---
+
+ # --- Other @xxx{...} commands ---
+
+ def open_(self): pass # Used by {text enclosed in braces}
+ def close_(self): pass
+
+ open_asis = open_
+ close_asis = close_
+
+ def open_cite(self): self.write('<CITE>')
+ def close_cite(self): self.write('</CITE>')
+
+ def open_code(self): self.write('<CODE>')
+ def close_code(self): self.write('</CODE>')
+
+ def open_t(self): self.write('<TT>')
+ def close_t(self): self.write('</TT>')
+
+ def open_dfn(self): self.write('<DFN>')
+ def close_dfn(self): self.write('</DFN>')
+
+ def open_emph(self): self.write('<EM>')
+ def close_emph(self): self.write('</EM>')
+
+ def open_i(self): self.write('<I>')
+ def close_i(self): self.write('</I>')
+
+ def open_footnote(self):
+ # if self.savetext <> None:
+ # print '*** Recursive footnote -- expect weirdness'
+ id = len(self.footnotes) + 1
+ self.write(self.FN_SOURCE_PATTERN % {'id': repr(id)})
+ self.startsaving()
+
+ def close_footnote(self):
+ id = len(self.footnotes) + 1
+ self.footnotes.append((id, self.collectsavings()))
+
+ def writefootnotes(self):
+ self.write(self.FN_HEADER)
+ for id, text in self.footnotes:
+ self.write(self.FN_TARGET_PATTERN
+ % {'id': repr(id), 'text': text})
+ self.footnotes = []
+
+ def open_file(self): self.write('<CODE>')
+ def close_file(self): self.write('</CODE>')
+
+ def open_kbd(self): self.write('<KBD>')
+ def close_kbd(self): self.write('</KBD>')
+
+ def open_key(self): self.write('<KEY>')
+ def close_key(self): self.write('</KEY>')
+
+ def open_r(self): self.write('<R>')
+ def close_r(self): self.write('</R>')
+
+ def open_samp(self): self.write('`<SAMP>')
+ def close_samp(self): self.write('</SAMP>\'')
+
+ def open_sc(self): self.write('<SMALLCAPS>')
+ def close_sc(self): self.write('</SMALLCAPS>')
+
+ def open_strong(self): self.write('<STRONG>')
+ def close_strong(self): self.write('</STRONG>')
+
+ def open_b(self): self.write('<B>')
+ def close_b(self): self.write('</B>')
+
+ def open_var(self): self.write('<VAR>')
+ def close_var(self): self.write('</VAR>')
+
+ def open_w(self): self.write('<NOBREAK>')
+ def close_w(self): self.write('</NOBREAK>')
+
+ def open_url(self): self.startsaving()
+ def close_url(self):
+ text = self.collectsavings()
+ self.write('<A HREF="', text, '">', text, '</A>')
+
+ def open_email(self): self.startsaving()
+ def close_email(self):
+ text = self.collectsavings()
+ self.write('<A HREF="mailto:', text, '">', text, '</A>')
+
+ open_titlefont = open_
+ close_titlefont = close_
+
+ def open_small(self): pass
+ def close_small(self): pass
+
+ def command(self, line, mo):
+ a, b = mo.span(1)
+ cmd = line[a:b]
+ args = line[b:].strip()
+ if self.debugging > 1:
+ print '!'*self.debugging, 'command:', self.skip, self.stack, \
+ '@' + cmd, args
+ try:
+ func = getattr(self, 'do_' + cmd)
+ except AttributeError:
+ try:
+ func = getattr(self, 'bgn_' + cmd)
+ except AttributeError:
+ # don't complain if we are skipping anyway
+ if not self.skip:
+ self.unknown_cmd(cmd, args)
+ return
+ self.stack.append(cmd)
+ func(args)
+ return
+ if not self.skip or cmd == 'end':
+ func(args)
+
+ def unknown_cmd(self, cmd, args):
+ print '*** unknown', '@' + cmd, args
+ if not self.unknown.has_key(cmd):
+ self.unknown[cmd] = 1
+ else:
+ self.unknown[cmd] = self.unknown[cmd] + 1
+
+ def do_end(self, args):
+ words = args.split()
+ if not words:
+ print '*** @end w/o args'
+ else:
+ cmd = words[0]
+ if not self.stack or self.stack[-1] <> cmd:
+ print '*** @end', cmd, 'unexpected'
+ else:
+ del self.stack[-1]
+ try:
+ func = getattr(self, 'end_' + cmd)
+ except AttributeError:
+ self.unknown_end(cmd)
+ return
+ func()
+
+ def unknown_end(self, cmd):
+ cmd = 'end ' + cmd
+ print '*** unknown', '@' + cmd
+ if not self.unknown.has_key(cmd):
+ self.unknown[cmd] = 1
+ else:
+ self.unknown[cmd] = self.unknown[cmd] + 1
+
+ # --- Comments ---
+
+ def do_comment(self, args): pass
+ do_c = do_comment
+
+ # --- Conditional processing ---
+
+ def bgn_ifinfo(self, args): pass
+ def end_ifinfo(self): pass
+
+ def bgn_iftex(self, args): self.skip = self.skip + 1
+ def end_iftex(self): self.skip = self.skip - 1
+
+ def bgn_ignore(self, args): self.skip = self.skip + 1
+ def end_ignore(self): self.skip = self.skip - 1
+
+ def bgn_tex(self, args): self.skip = self.skip + 1
+ def end_tex(self): self.skip = self.skip - 1
+
+ def do_set(self, args):
+ fields = args.split(' ')
+ key = fields[0]
+ if len(fields) == 1:
+ value = 1
+ else:
+ value = ' '.join(fields[1:])
+ self.values[key] = value
+
+ def do_clear(self, args):
+ self.values[args] = None
+
+ def bgn_ifset(self, args):
+ if args not in self.values.keys() \
+ or self.values[args] is None:
+ self.skip = self.skip + 1
+ self.stackinfo[len(self.stack)] = 1
+ else:
+ self.stackinfo[len(self.stack)] = 0
+ def end_ifset(self):
+ try:
+ if self.stackinfo[len(self.stack) + 1]:
+ self.skip = self.skip - 1
+ del self.stackinfo[len(self.stack) + 1]
+ except KeyError:
+ print '*** end_ifset: KeyError :', len(self.stack) + 1
+
+ def bgn_ifclear(self, args):
+ if args in self.values.keys() \
+ and self.values[args] is not None:
+ self.skip = self.skip + 1
+ self.stackinfo[len(self.stack)] = 1
+ else:
+ self.stackinfo[len(self.stack)] = 0
+ def end_ifclear(self):
+ try:
+ if self.stackinfo[len(self.stack) + 1]:
+ self.skip = self.skip - 1
+ del self.stackinfo[len(self.stack) + 1]
+ except KeyError:
+ print '*** end_ifclear: KeyError :', len(self.stack) + 1
+
+ def open_value(self):
+ self.startsaving()
+
+ def close_value(self):
+ key = self.collectsavings()
+ if key in self.values.keys():
+ self.write(self.values[key])
+ else:
+ print '*** Undefined value: ', key
+
+ # --- Beginning a file ---
+
+ do_finalout = do_comment
+ do_setchapternewpage = do_comment
+ do_setfilename = do_comment
+
+ def do_settitle(self, args):
+ self.startsaving()
+ self.expand(args)
+ self.title = self.collectsavings()
+ def do_parskip(self, args): pass
+
+ # --- Ending a file ---
+
+ def do_bye(self, args):
+ self.endnode()
+ self.done = 1
+
+ # --- Title page ---
+
+ def bgn_titlepage(self, args): self.skip = self.skip + 1
+ def end_titlepage(self): self.skip = self.skip - 1
+ def do_shorttitlepage(self, args): pass
+
+ def do_center(self, args):
+ # Actually not used outside title page...
+ self.write('<H1>')
+ self.expand(args)
+ self.write('</H1>\n')
+ do_title = do_center
+ do_subtitle = do_center
+ do_author = do_center
+
+ do_vskip = do_comment
+ do_vfill = do_comment
+ do_smallbook = do_comment
+
+ do_paragraphindent = do_comment
+ do_setchapternewpage = do_comment
+ do_headings = do_comment
+ do_footnotestyle = do_comment
+
+ do_evenheading = do_comment
+ do_evenfooting = do_comment
+ do_oddheading = do_comment
+ do_oddfooting = do_comment
+ do_everyheading = do_comment
+ do_everyfooting = do_comment
+
+ # --- Nodes ---
+
+ def do_node(self, args):
+ self.endnode()
+ self.nodelineno = 0
+ parts = [s.strip() for s in args.split(',')]
+ while len(parts) < 4: parts.append('')
+ self.nodelinks = parts
+ [name, next, prev, up] = parts[:4]
+ file = self.dirname + '/' + makefile(name)
+ if self.filenames.has_key(file):
+ print '*** Filename already in use: ', file
+ else:
+ if self.debugging: print '!'*self.debugging, '--- writing', file
+ self.filenames[file] = 1
+ # self.nodefp = open(file, 'w')
+ self.nodename = name
+ if self.cont and self.nodestack:
+ self.nodestack[-1].cont = self.nodename
+ if not self.topname: self.topname = name
+ title = name
+ if self.title: title = title + ' -- ' + self.title
+ self.node = self.Node(self.dirname, self.nodename, self.topname,
+ title, next, prev, up)
+ self.htmlhelp.addnode(self.nodename,next,prev,up,file)
+
+ def link(self, label, nodename):
+ if nodename:
+ if nodename.lower() == '(dir)':
+ addr = '../dir.html'
+ else:
+ addr = makefile(nodename)
+ self.write(label, ': <A HREF="', addr, '" TYPE="',
+ label, '">', nodename, '</A> \n')
+
+ # --- Sectioning commands ---
+
+ def popstack(self, type):
+ if (self.node):
+ self.node.type = type
+ while self.nodestack:
+ if self.nodestack[-1].type > type:
+ self.nodestack[-1].finalize()
+ self.nodestack[-1].flush()
+ del self.nodestack[-1]
+ elif self.nodestack[-1].type == type:
+ if not self.nodestack[-1].next:
+ self.nodestack[-1].next = self.node.name
+ if not self.node.prev:
+ self.node.prev = self.nodestack[-1].name
+ self.nodestack[-1].finalize()
+ self.nodestack[-1].flush()
+ del self.nodestack[-1]
+ else:
+ if type > 1 and not self.node.up:
+ self.node.up = self.nodestack[-1].name
+ break
+
+ def do_chapter(self, args):
+ self.heading('H1', args, 0)
+ self.popstack(1)
+
+ def do_unnumbered(self, args):
+ self.heading('H1', args, -1)
+ self.popstack(1)
+ def do_appendix(self, args):
+ self.heading('H1', args, -1)
+ self.popstack(1)
+ def do_top(self, args):
+ self.heading('H1', args, -1)
+ def do_chapheading(self, args):
+ self.heading('H1', args, -1)
+ def do_majorheading(self, args):
+ self.heading('H1', args, -1)
+
+ def do_section(self, args):
+ self.heading('H1', args, 1)
+ self.popstack(2)
+
+ def do_unnumberedsec(self, args):
+ self.heading('H1', args, -1)
+ self.popstack(2)
+ def do_appendixsec(self, args):
+ self.heading('H1', args, -1)
+ self.popstack(2)
+ do_appendixsection = do_appendixsec
+ def do_heading(self, args):
+ self.heading('H1', args, -1)
+
+ def do_subsection(self, args):
+ self.heading('H2', args, 2)
+ self.popstack(3)
+ def do_unnumberedsubsec(self, args):
+ self.heading('H2', args, -1)
+ self.popstack(3)
+ def do_appendixsubsec(self, args):
+ self.heading('H2', args, -1)
+ self.popstack(3)
+ def do_subheading(self, args):
+ self.heading('H2', args, -1)
+
+ def do_subsubsection(self, args):
+ self.heading('H3', args, 3)
+ self.popstack(4)
+ def do_unnumberedsubsubsec(self, args):
+ self.heading('H3', args, -1)
+ self.popstack(4)
+ def do_appendixsubsubsec(self, args):
+ self.heading('H3', args, -1)
+ self.popstack(4)
+ def do_subsubheading(self, args):
+ self.heading('H3', args, -1)
+
+ def heading(self, type, args, level):
+ if level >= 0:
+ while len(self.numbering) <= level:
+ self.numbering.append(0)
+ del self.numbering[level+1:]
+ self.numbering[level] = self.numbering[level] + 1
+ x = ''
+ for i in self.numbering:
+ x = x + repr(i) + '.'
+ args = x + ' ' + args
+ self.contents.append((level, args, self.nodename))
+ self.write('<', type, '>')
+ self.expand(args)
+ self.write('</', type, '>\n')
+ if self.debugging or self.print_headers:
+ print '---', args
+
+ def do_contents(self, args):
+ # pass
+ self.listcontents('Table of Contents', 999)
+
+ def do_shortcontents(self, args):
+ pass
+ # self.listcontents('Short Contents', 0)
+ do_summarycontents = do_shortcontents
+
+ def listcontents(self, title, maxlevel):
+ self.write('<H1>', title, '</H1>\n<UL COMPACT PLAIN>\n')
+ prevlevels = [0]
+ for level, title, node in self.contents:
+ if level > maxlevel:
+ continue
+ if level > prevlevels[-1]:
+ # can only advance one level at a time
+ self.write(' '*prevlevels[-1], '<UL PLAIN>\n')
+ prevlevels.append(level)
+ elif level < prevlevels[-1]:
+ # might drop back multiple levels
+ while level < prevlevels[-1]:
+ del prevlevels[-1]
+ self.write(' '*prevlevels[-1],
+ '</UL>\n')
+ self.write(' '*level, '<LI> <A HREF="',
+ makefile(node), '">')
+ self.expand(title)
+ self.write('</A>\n')
+ self.write('</UL>\n' * len(prevlevels))
+
+ # --- Page lay-out ---
+
+ # These commands are only meaningful in printed text
+
+ def do_page(self, args): pass
+
+ def do_need(self, args): pass
+
+ def bgn_group(self, args): pass
+ def end_group(self): pass
+
+ # --- Line lay-out ---
+
+ def do_sp(self, args):
+ if self.nofill:
+ self.write('\n')
+ else:
+ self.write('<P>\n')
+
+ def do_hline(self, args):
+ self.write('<HR>')
+
+ # --- Function and variable definitions ---
+
+ def bgn_deffn(self, args):
+ self.write('<DL>')
+ self.do_deffnx(args)
+
+ def end_deffn(self):
+ self.write('</DL>\n')
+
+ def do_deffnx(self, args):
+ self.write('<DT>')
+ words = splitwords(args, 2)
+ [category, name], rest = words[:2], words[2:]
+ self.expand('@b{%s}' % name)
+ for word in rest: self.expand(' ' + makevar(word))
+ #self.expand(' -- ' + category)
+ self.write('\n<DD>')
+ self.index('fn', name)
+
+ def bgn_defun(self, args): self.bgn_deffn('Function ' + args)
+ end_defun = end_deffn
+ def do_defunx(self, args): self.do_deffnx('Function ' + args)
+
+ def bgn_defmac(self, args): self.bgn_deffn('Macro ' + args)
+ end_defmac = end_deffn
+ def do_defmacx(self, args): self.do_deffnx('Macro ' + args)
+
+ def bgn_defspec(self, args): self.bgn_deffn('{Special Form} ' + args)
+ end_defspec = end_deffn
+ def do_defspecx(self, args): self.do_deffnx('{Special Form} ' + args)
+
+ def bgn_defvr(self, args):
+ self.write('<DL>')
+ self.do_defvrx(args)
+
+ end_defvr = end_deffn
+
+ def do_defvrx(self, args):
+ self.write('<DT>')
+ words = splitwords(args, 2)
+ [category, name], rest = words[:2], words[2:]
+ self.expand('@code{%s}' % name)
+ # If there are too many arguments, show them
+ for word in rest: self.expand(' ' + word)
+ #self.expand(' -- ' + category)
+ self.write('\n<DD>')
+ self.index('vr', name)
+
+ def bgn_defvar(self, args): self.bgn_defvr('Variable ' + args)
+ end_defvar = end_defvr
+ def do_defvarx(self, args): self.do_defvrx('Variable ' + args)
+
+ def bgn_defopt(self, args): self.bgn_defvr('{User Option} ' + args)
+ end_defopt = end_defvr
+ def do_defoptx(self, args): self.do_defvrx('{User Option} ' + args)
+
+ # --- Ditto for typed languages ---
+
+ def bgn_deftypefn(self, args):
+ self.write('<DL>')
+ self.do_deftypefnx(args)
+
+ end_deftypefn = end_deffn
+
+ def do_deftypefnx(self, args):
+ self.write('<DT>')
+ words = splitwords(args, 3)
+ [category, datatype, name], rest = words[:3], words[3:]
+ self.expand('@code{%s} @b{%s}' % (datatype, name))
+ for word in rest: self.expand(' ' + makevar(word))
+ #self.expand(' -- ' + category)
+ self.write('\n<DD>')
+ self.index('fn', name)
+
+
+ def bgn_deftypefun(self, args): self.bgn_deftypefn('Function ' + args)
+ end_deftypefun = end_deftypefn
+ def do_deftypefunx(self, args): self.do_deftypefnx('Function ' + args)
+
+ def bgn_deftypevr(self, args):
+ self.write('<DL>')
+ self.do_deftypevrx(args)
+
+ end_deftypevr = end_deftypefn
+
+ def do_deftypevrx(self, args):
+ self.write('<DT>')
+ words = splitwords(args, 3)
+ [category, datatype, name], rest = words[:3], words[3:]
+ self.expand('@code{%s} @b{%s}' % (datatype, name))
+ # If there are too many arguments, show them
+ for word in rest: self.expand(' ' + word)
+ #self.expand(' -- ' + category)
+ self.write('\n<DD>')
+ self.index('fn', name)
+
+ def bgn_deftypevar(self, args):
+ self.bgn_deftypevr('Variable ' + args)
+ end_deftypevar = end_deftypevr
+ def do_deftypevarx(self, args):
+ self.do_deftypevrx('Variable ' + args)
+
+ # --- Ditto for object-oriented languages ---
+
+ def bgn_defcv(self, args):
+ self.write('<DL>')
+ self.do_defcvx(args)
+
+ end_defcv = end_deftypevr
+
+ def do_defcvx(self, args):
+ self.write('<DT>')
+ words = splitwords(args, 3)
+ [category, classname, name], rest = words[:3], words[3:]
+ self.expand('@b{%s}' % name)
+ # If there are too many arguments, show them
+ for word in rest: self.expand(' ' + word)
+ #self.expand(' -- %s of @code{%s}' % (category, classname))
+ self.write('\n<DD>')
+ self.index('vr', '%s @r{on %s}' % (name, classname))
+
+ def bgn_defivar(self, args):
+ self.bgn_defcv('{Instance Variable} ' + args)
+ end_defivar = end_defcv
+ def do_defivarx(self, args):
+ self.do_defcvx('{Instance Variable} ' + args)
+
+ def bgn_defop(self, args):
+ self.write('<DL>')
+ self.do_defopx(args)
+
+ end_defop = end_defcv
+
+ def do_defopx(self, args):
+ self.write('<DT>')
+ words = splitwords(args, 3)
+ [category, classname, name], rest = words[:3], words[3:]
+ self.expand('@b{%s}' % name)
+ for word in rest: self.expand(' ' + makevar(word))
+ #self.expand(' -- %s of @code{%s}' % (category, classname))
+ self.write('\n<DD>')
+ self.index('fn', '%s @r{on %s}' % (name, classname))
+
+ def bgn_defmethod(self, args):
+ self.bgn_defop('Method ' + args)
+ end_defmethod = end_defop
+ def do_defmethodx(self, args):
+ self.do_defopx('Method ' + args)
+
+ # --- Ditto for data types ---
+
+ def bgn_deftp(self, args):
+ self.write('<DL>')
+ self.do_deftpx(args)
+
+ end_deftp = end_defcv
+
+ def do_deftpx(self, args):
+ self.write('<DT>')
+ words = splitwords(args, 2)
+ [category, name], rest = words[:2], words[2:]
+ self.expand('@b{%s}' % name)
+ for word in rest: self.expand(' ' + word)
+ #self.expand(' -- ' + category)
+ self.write('\n<DD>')
+ self.index('tp', name)
+
+ # --- Making Lists and Tables
+
+ def bgn_enumerate(self, args):
+ if not args:
+ self.write('<OL>\n')
+ self.stackinfo[len(self.stack)] = '</OL>\n'
+ else:
+ self.itemnumber = args
+ self.write('<UL>\n')
+ self.stackinfo[len(self.stack)] = '</UL>\n'
+ def end_enumerate(self):
+ self.itemnumber = None
+ self.write(self.stackinfo[len(self.stack) + 1])
+ del self.stackinfo[len(self.stack) + 1]
+
+ def bgn_itemize(self, args):
+ self.itemarg = args
+ self.write('<UL>\n')
+ def end_itemize(self):
+ self.itemarg = None
+ self.write('</UL>\n')
+
+ def bgn_table(self, args):
+ self.itemarg = args
+ self.write('<DL>\n')
+ def end_table(self):
+ self.itemarg = None
+ self.write('</DL>\n')
+
+ def bgn_ftable(self, args):
+ self.itemindex = 'fn'
+ self.bgn_table(args)
+ def end_ftable(self):
+ self.itemindex = None
+ self.end_table()
+
+ def bgn_vtable(self, args):
+ self.itemindex = 'vr'
+ self.bgn_table(args)
+ def end_vtable(self):
+ self.itemindex = None
+ self.end_table()
+
+ def do_item(self, args):
+ if self.itemindex: self.index(self.itemindex, args)
+ if self.itemarg:
+ if self.itemarg[0] == '@' and self.itemarg[1] and \
+ self.itemarg[1] in string.ascii_letters:
+ args = self.itemarg + '{' + args + '}'
+ else:
+ # some other character, e.g. '-'
+ args = self.itemarg + ' ' + args
+ if self.itemnumber <> None:
+ args = self.itemnumber + '. ' + args
+ self.itemnumber = increment(self.itemnumber)
+ if self.stack and self.stack[-1] == 'table':
+ self.write('<DT>')
+ self.expand(args)
+ self.write('\n<DD>')
+ elif self.stack and self.stack[-1] == 'multitable':
+ self.write('<TR><TD>')
+ self.expand(args)
+ self.write('</TD>\n</TR>\n')
+ else:
+ self.write('<LI>')
+ self.expand(args)
+ self.write(' ')
+ do_itemx = do_item # XXX Should suppress leading blank line
+
+ # rpyron 2002-05-07 multitable support
+ def bgn_multitable(self, args):
+ self.itemarg = None # should be handled by columnfractions
+ self.write('<TABLE BORDER="">\n')
+ def end_multitable(self):
+ self.itemarg = None
+ self.write('</TABLE>\n<BR>\n')
+ def handle_columnfractions(self):
+ # It would be better to handle this, but for now it's in the way...
+ self.itemarg = None
+ def handle_tab(self):
+ self.write('</TD>\n <TD>')
+
+ # --- Enumerations, displays, quotations ---
+ # XXX Most of these should increase the indentation somehow
+
+ def bgn_quotation(self, args): self.write('<BLOCKQUOTE>')
+ def end_quotation(self): self.write('</BLOCKQUOTE>\n')
+
+ def bgn_example(self, args):
+ self.nofill = self.nofill + 1
+ self.write('<PRE>')
+ def end_example(self):
+ self.write('</PRE>\n')
+ self.nofill = self.nofill - 1
+
+ bgn_lisp = bgn_example # Synonym when contents are executable lisp code
+ end_lisp = end_example
+
+ bgn_smallexample = bgn_example # XXX Should use smaller font
+ end_smallexample = end_example
+
+ bgn_smalllisp = bgn_lisp # Ditto
+ end_smalllisp = end_lisp
+
+ bgn_display = bgn_example
+ end_display = end_example
+
+ bgn_format = bgn_display
+ end_format = end_display
+
+ def do_exdent(self, args): self.expand(args + '\n')
+ # XXX Should really mess with indentation
+
+ def bgn_flushleft(self, args):
+ self.nofill = self.nofill + 1
+ self.write('<PRE>\n')
+ def end_flushleft(self):
+ self.write('</PRE>\n')
+ self.nofill = self.nofill - 1
+
+ def bgn_flushright(self, args):
+ self.nofill = self.nofill + 1
+ self.write('<ADDRESS COMPACT>\n')
+ def end_flushright(self):
+ self.write('</ADDRESS>\n')
+ self.nofill = self.nofill - 1
+
+ def bgn_menu(self, args):
+ self.write('<DIR>\n')
+ self.write(' <STRONG><EM>Menu</EM></STRONG><P>\n')
+ self.htmlhelp.beginmenu()
+ def end_menu(self):
+ self.write('</DIR>\n')
+ self.htmlhelp.endmenu()
+
+ def bgn_cartouche(self, args): pass
+ def end_cartouche(self): pass
+
+ # --- Indices ---
+
+ def resetindex(self):
+ self.noncodeindices = ['cp']
+ self.indextitle = {}
+ self.indextitle['cp'] = 'Concept'
+ self.indextitle['fn'] = 'Function'
+ self.indextitle['ky'] = 'Keyword'
+ self.indextitle['pg'] = 'Program'
+ self.indextitle['tp'] = 'Type'
+ self.indextitle['vr'] = 'Variable'
+ #
+ self.whichindex = {}
+ for name in self.indextitle.keys():
+ self.whichindex[name] = []
+
+ def user_index(self, name, args):
+ if self.whichindex.has_key(name):
+ self.index(name, args)
+ else:
+ print '*** No index named', repr(name)
+
+ def do_cindex(self, args): self.index('cp', args)
+ def do_findex(self, args): self.index('fn', args)
+ def do_kindex(self, args): self.index('ky', args)
+ def do_pindex(self, args): self.index('pg', args)
+ def do_tindex(self, args): self.index('tp', args)
+ def do_vindex(self, args): self.index('vr', args)
+
+ def index(self, name, args):
+ self.whichindex[name].append((args, self.nodename))
+ self.htmlhelp.index(args, self.nodename)
+
+ def do_synindex(self, args):
+ words = args.split()
+ if len(words) <> 2:
+ print '*** bad @synindex', args
+ return
+ [old, new] = words
+ if not self.whichindex.has_key(old) or \
+ not self.whichindex.has_key(new):
+ print '*** bad key(s) in @synindex', args
+ return
+ if old <> new and \
+ self.whichindex[old] is not self.whichindex[new]:
+ inew = self.whichindex[new]
+ inew[len(inew):] = self.whichindex[old]
+ self.whichindex[old] = inew
+ do_syncodeindex = do_synindex # XXX Should use code font
+
+ def do_printindex(self, args):
+ words = args.split()
+ for name in words:
+ if self.whichindex.has_key(name):
+ self.prindex(name)
+ else:
+ print '*** No index named', repr(name)
+
+ def prindex(self, name):
+ iscodeindex = (name not in self.noncodeindices)
+ index = self.whichindex[name]
+ if not index: return
+ if self.debugging:
+ print '!'*self.debugging, '--- Generating', \
+ self.indextitle[name], 'index'
+ # The node already provides a title
+ index1 = []
+ junkprog = re.compile('^(@[a-z]+)?{')
+ for key, node in index:
+ sortkey = key.lower()
+ # Remove leading `@cmd{' from sort key
+ # -- don't bother about the matching `}'
+ oldsortkey = sortkey
+ while 1:
+ mo = junkprog.match(sortkey)
+ if not mo:
+ break
+ i = mo.end()
+ sortkey = sortkey[i:]
+ index1.append((sortkey, key, node))
+ del index[:]
+ index1.sort()
+ self.write('<DL COMPACT>\n')
+ prevkey = prevnode = None
+ for sortkey, key, node in index1:
+ if (key, node) == (prevkey, prevnode):
+ continue
+ if self.debugging > 1: print '!'*self.debugging, key, ':', node
+ self.write('<DT>')
+ if iscodeindex: key = '@code{' + key + '}'
+ if key != prevkey:
+ self.expand(key)
+ self.write('\n<DD><A HREF="%s">%s</A>\n' % (makefile(node), node))
+ prevkey, prevnode = key, node
+ self.write('</DL>\n')
+
+ # --- Final error reports ---
+
+ def report(self):
+ if self.unknown:
+ print '--- Unrecognized commands ---'
+ cmds = self.unknown.keys()
+ cmds.sort()
+ for cmd in cmds:
+ print cmd.ljust(20), self.unknown[cmd]
+
+
+class TexinfoParserHTML3(TexinfoParser):
+
+ COPYRIGHT_SYMBOL = "&copy;"
+ FN_ID_PATTERN = "[%(id)s]"
+ FN_SOURCE_PATTERN = '<A ID=footnoteref%(id)s ' \
+ 'HREF="#footnotetext%(id)s">' + FN_ID_PATTERN + '</A>'
+ FN_TARGET_PATTERN = '<FN ID=footnotetext%(id)s>\n' \
+ '<P><A HREF="#footnoteref%(id)s">' + FN_ID_PATTERN \
+ + '</A>\n%(text)s</P></FN>\n'
+ FN_HEADER = '<DIV CLASS=footnotes>\n <HR NOSHADE WIDTH=200>\n' \
+ ' <STRONG><EM>Footnotes</EM></STRONG>\n <P>\n'
+
+ Node = HTML3Node
+
+ def bgn_quotation(self, args): self.write('<BQ>')
+ def end_quotation(self): self.write('</BQ>\n')
+
+ def bgn_example(self, args):
+ # this use of <CODE> would not be legal in HTML 2.0,
+ # but is in more recent DTDs.
+ self.nofill = self.nofill + 1
+ self.write('<PRE CLASS=example><CODE>')
+ def end_example(self):
+ self.write("</CODE></PRE>\n")
+ self.nofill = self.nofill - 1
+
+ def bgn_flushleft(self, args):
+ self.nofill = self.nofill + 1
+ self.write('<PRE CLASS=flushleft>\n')
+
+ def bgn_flushright(self, args):
+ self.nofill = self.nofill + 1
+ self.write('<DIV ALIGN=right CLASS=flushright><ADDRESS COMPACT>\n')
+ def end_flushright(self):
+ self.write('</ADDRESS></DIV>\n')
+ self.nofill = self.nofill - 1
+
+ def bgn_menu(self, args):
+ self.write('<UL PLAIN CLASS=menu>\n')
+ self.write(' <LH>Menu</LH>\n')
+ def end_menu(self):
+ self.write('</UL>\n')
+
+
+# rpyron 2002-05-07
+class HTMLHelp:
+ """
+ This class encapsulates support for HTML Help. Node names,
+ file names, menu items, index items, and image file names are
+ accumulated until a call to finalize(). At that time, three
+ output files are created in the current directory:
+
+ `helpbase`.hhp is a HTML Help Workshop project file.
+ It contains various information, some of
+ which I do not understand; I just copied
+ the default project info from a fresh
+ installation.
+ `helpbase`.hhc is the Contents file for the project.
+ `helpbase`.hhk is the Index file for the project.
+
+ When these files are used as input to HTML Help Workshop,
+ the resulting file will be named:
+
+ `helpbase`.chm
+
+ If none of the defaults in `helpbase`.hhp are changed,
+ the .CHM file will have Contents, Index, Search, and
+ Favorites tabs.
+ """
+
+ codeprog = re.compile('@code{(.*?)}')
+
+ def __init__(self,helpbase,dirname):
+ self.helpbase = helpbase
+ self.dirname = dirname
+ self.projectfile = None
+ self.contentfile = None
+ self.indexfile = None
+ self.nodelist = []
+ self.nodenames = {} # nodename : index
+ self.nodeindex = {}
+ self.filenames = {} # filename : filename
+ self.indexlist = [] # (args,nodename) == (key,location)
+ self.current = ''
+ self.menudict = {}
+ self.dumped = {}
+
+
+ def addnode(self,name,next,prev,up,filename):
+ node = (name,next,prev,up,filename)
+ # add this file to dict
+ # retrieve list with self.filenames.values()
+ self.filenames[filename] = filename
+ # add this node to nodelist
+ self.nodeindex[name] = len(self.nodelist)
+ self.nodelist.append(node)
+ # set 'current' for menu items
+ self.current = name
+ self.menudict[self.current] = []
+
+ def menuitem(self,nodename):
+ menu = self.menudict[self.current]
+ menu.append(nodename)
+
+
+ def addimage(self,imagename):
+ self.filenames[imagename] = imagename
+
+ def index(self, args, nodename):
+ self.indexlist.append((args,nodename))
+
+ def beginmenu(self):
+ pass
+
+ def endmenu(self):
+ pass
+
+ def finalize(self):
+ if not self.helpbase:
+ return
+
+ # generate interesting filenames
+ resultfile = self.helpbase + '.chm'
+ projectfile = self.helpbase + '.hhp'
+ contentfile = self.helpbase + '.hhc'
+ indexfile = self.helpbase + '.hhk'
+
+ # generate a reasonable title
+ title = self.helpbase
+
+ # get the default topic file
+ (topname,topnext,topprev,topup,topfile) = self.nodelist[0]
+ defaulttopic = topfile
+
+ # PROJECT FILE
+ try:
+ fp = open(projectfile,'w')
+ print>>fp, '[OPTIONS]'
+ print>>fp, 'Auto Index=Yes'
+ print>>fp, 'Binary TOC=No'
+ print>>fp, 'Binary Index=Yes'
+ print>>fp, 'Compatibility=1.1'
+ print>>fp, 'Compiled file=' + resultfile + ''
+ print>>fp, 'Contents file=' + contentfile + ''
+ print>>fp, 'Default topic=' + defaulttopic + ''
+ print>>fp, 'Error log file=ErrorLog.log'
+ print>>fp, 'Index file=' + indexfile + ''
+ print>>fp, 'Title=' + title + ''
+ print>>fp, 'Display compile progress=Yes'
+ print>>fp, 'Full-text search=Yes'
+ print>>fp, 'Default window=main'
+ print>>fp, ''
+ print>>fp, '[WINDOWS]'
+ print>>fp, ('main=,"' + contentfile + '","' + indexfile
+ + '","","",,,,,0x23520,222,0x1046,[10,10,780,560],'
+ '0xB0000,,,,,,0')
+ print>>fp, ''
+ print>>fp, '[FILES]'
+ print>>fp, ''
+ self.dumpfiles(fp)
+ fp.close()
+ except IOError, msg:
+ print projectfile, ':', msg
+ sys.exit(1)
+
+ # CONTENT FILE
+ try:
+ fp = open(contentfile,'w')
+ print>>fp, '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">'
+ print>>fp, '<!-- This file defines the table of contents -->'
+ print>>fp, '<HTML>'
+ print>>fp, '<HEAD>'
+ print>>fp, ('<meta name="GENERATOR"'
+ 'content="Microsoft&reg; HTML Help Workshop 4.1">')
+ print>>fp, '<!-- Sitemap 1.0 -->'
+ print>>fp, '</HEAD>'
+ print>>fp, '<BODY>'
+ print>>fp, ' <OBJECT type="text/site properties">'
+ print>>fp, ' <param name="Window Styles" value="0x800025">'
+ print>>fp, ' <param name="comment" value="title:">'
+ print>>fp, ' <param name="comment" value="base:">'
+ print>>fp, ' </OBJECT>'
+ self.dumpnodes(fp)
+ print>>fp, '</BODY>'
+ print>>fp, '</HTML>'
+ fp.close()
+ except IOError, msg:
+ print contentfile, ':', msg
+ sys.exit(1)
+
+ # INDEX FILE
+ try:
+ fp = open(indexfile ,'w')
+ print>>fp, '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">'
+ print>>fp, '<!-- This file defines the index -->'
+ print>>fp, '<HTML>'
+ print>>fp, '<HEAD>'
+ print>>fp, ('<meta name="GENERATOR"'
+ 'content="Microsoft&reg; HTML Help Workshop 4.1">')
+ print>>fp, '<!-- Sitemap 1.0 -->'
+ print>>fp, '</HEAD>'
+ print>>fp, '<BODY>'
+ print>>fp, '<OBJECT type="text/site properties">'
+ print>>fp, '</OBJECT>'
+ self.dumpindex(fp)
+ print>>fp, '</BODY>'
+ print>>fp, '</HTML>'
+ fp.close()
+ except IOError, msg:
+ print indexfile , ':', msg
+ sys.exit(1)
+
+ def dumpfiles(self, outfile=sys.stdout):
+ filelist = self.filenames.values()
+ filelist.sort()
+ for filename in filelist:
+ print>>outfile, filename
+
+ def dumpnodes(self, outfile=sys.stdout):
+ self.dumped = {}
+ if self.nodelist:
+ nodename, dummy, dummy, dummy, dummy = self.nodelist[0]
+ self.topnode = nodename
+
+ print>>outfile, '<UL>'
+ for node in self.nodelist:
+ self.dumpnode(node,0,outfile)
+ print>>outfile, '</UL>'
+
+ def dumpnode(self, node, indent=0, outfile=sys.stdout):
+ if node:
+ # Retrieve info for this node
+ (nodename,next,prev,up,filename) = node
+ self.current = nodename
+
+ # Have we been dumped already?
+ if self.dumped.has_key(nodename):
+ return
+ self.dumped[nodename] = 1
+
+ # Print info for this node
+ print>>outfile, ' '*indent,
+ print>>outfile, '<LI><OBJECT type="text/sitemap">',
+ print>>outfile, '<param name="Name" value="' + nodename +'">',
+ print>>outfile, '<param name="Local" value="'+ filename +'">',
+ print>>outfile, '</OBJECT>'
+
+ # Does this node have menu items?
+ try:
+ menu = self.menudict[nodename]
+ self.dumpmenu(menu,indent+2,outfile)
+ except KeyError:
+ pass
+
+ def dumpmenu(self, menu, indent=0, outfile=sys.stdout):
+ if menu:
+ currentnode = self.current
+ if currentnode != self.topnode: # XXX this is a hack
+ print>>outfile, ' '*indent + '<UL>'
+ indent += 2
+ for item in menu:
+ menunode = self.getnode(item)
+ self.dumpnode(menunode,indent,outfile)
+ if currentnode != self.topnode: # XXX this is a hack
+ print>>outfile, ' '*indent + '</UL>'
+ indent -= 2
+
+ def getnode(self, nodename):
+ try:
+ index = self.nodeindex[nodename]
+ return self.nodelist[index]
+ except KeyError:
+ return None
+ except IndexError:
+ return None
+
+ # (args,nodename) == (key,location)
+ def dumpindex(self, outfile=sys.stdout):
+ print>>outfile, '<UL>'
+ for (key,location) in self.indexlist:
+ key = self.codeexpand(key)
+ location = makefile(location)
+ location = self.dirname + '/' + location
+ print>>outfile, '<LI><OBJECT type="text/sitemap">',
+ print>>outfile, '<param name="Name" value="' + key + '">',
+ print>>outfile, '<param name="Local" value="' + location + '">',
+ print>>outfile, '</OBJECT>'
+ print>>outfile, '</UL>'
+
+ def codeexpand(self, line):
+ co = self.codeprog.match(line)
+ if not co:
+ return line
+ bgn, end = co.span(0)
+ a, b = co.span(1)
+ line = line[:bgn] + line[a:b] + line[end:]
+ return line
+
+
+# Put @var{} around alphabetic substrings
+def makevar(str):
+ return '@var{'+str+'}'
+
+
+# Split a string in "words" according to findwordend
+def splitwords(str, minlength):
+ words = []
+ i = 0
+ n = len(str)
+ while i < n:
+ while i < n and str[i] in ' \t\n': i = i+1
+ if i >= n: break
+ start = i
+ i = findwordend(str, i, n)
+ words.append(str[start:i])
+ while len(words) < minlength: words.append('')
+ return words
+
+
+# Find the end of a "word", matching braces and interpreting @@ @{ @}
+fwprog = re.compile('[@{} ]')
+def findwordend(str, i, n):
+ level = 0
+ while i < n:
+ mo = fwprog.search(str, i)
+ if not mo:
+ break
+ i = mo.start()
+ c = str[i]; i = i+1
+ if c == '@': i = i+1 # Next character is not special
+ elif c == '{': level = level+1
+ elif c == '}': level = level-1
+ elif c == ' ' and level <= 0: return i-1
+ return n
+
+
+# Convert a node name into a file name
+def makefile(nodename):
+ nodename = nodename.strip()
+ return fixfunnychars(nodename) + '.html'
+
+
+# Characters that are perfectly safe in filenames and hyperlinks
+goodchars = string.ascii_letters + string.digits + '!@-=+.'
+
+# Replace characters that aren't perfectly safe by dashes
+# Underscores are bad since Cern HTTPD treats them as delimiters for
+# encoding times, so you get mismatches if you compress your files:
+# a.html.gz will map to a_b.html.gz
+def fixfunnychars(addr):
+ i = 0
+ while i < len(addr):
+ c = addr[i]
+ if c not in goodchars:
+ c = '-'
+ addr = addr[:i] + c + addr[i+1:]
+ i = i + len(c)
+ return addr
+
+
+# Increment a string used as an enumeration
+def increment(s):
+ if not s:
+ return '1'
+ for sequence in string.digits, string.lowercase, string.uppercase:
+ lastc = s[-1]
+ if lastc in sequence:
+ i = sequence.index(lastc) + 1
+ if i >= len(sequence):
+ if len(s) == 1:
+ s = sequence[0]*2
+ if s == '00':
+ s = '10'
+ else:
+ s = increment(s[:-1]) + sequence[0]
+ else:
+ s = s[:-1] + sequence[i]
+ return s
+ return s # Don't increment
+
+
+def test():
+ import sys
+ debugging = 0
+ print_headers = 0
+ cont = 0
+ html3 = 0
+ htmlhelp = ''
+
+ while sys.argv[1] == ['-d']:
+ debugging = debugging + 1
+ del sys.argv[1]
+ if sys.argv[1] == '-p':
+ print_headers = 1
+ del sys.argv[1]
+ if sys.argv[1] == '-c':
+ cont = 1
+ del sys.argv[1]
+ if sys.argv[1] == '-3':
+ html3 = 1
+ del sys.argv[1]
+ if sys.argv[1] == '-H':
+ helpbase = sys.argv[2]
+ del sys.argv[1:3]
+ if len(sys.argv) <> 3:
+ print 'usage: texi2hh [-d [-d]] [-p] [-c] [-3] [-H htmlhelp]', \
+ 'inputfile outputdirectory'
+ sys.exit(2)
+
+ if html3:
+ parser = TexinfoParserHTML3()
+ else:
+ parser = TexinfoParser()
+ parser.cont = cont
+ parser.debugging = debugging
+ parser.print_headers = print_headers
+
+ file = sys.argv[1]
+ dirname = sys.argv[2]
+ parser.setdirname(dirname)
+ parser.setincludedir(os.path.dirname(file))
+
+ htmlhelp = HTMLHelp(helpbase, dirname)
+ parser.sethtmlhelp(htmlhelp)
+
+ try:
+ fp = open(file, 'r')
+ except IOError, msg:
+ print file, ':', msg
+ sys.exit(1)
+
+ parser.parse(fp)
+ fp.close()
+ parser.report()
+
+ htmlhelp.finalize()
+
+
+if __name__ == "__main__":
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/treesync.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/treesync.py
new file mode 100644
index 0000000000..936f1a04e2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/treesync.py
@@ -0,0 +1,205 @@
+#! /usr/bin/env python
+
+"""Script to synchronize two source trees.
+
+Invoke with two arguments:
+
+python treesync.py slave master
+
+The assumption is that "master" contains CVS administration while
+slave doesn't. All files in the slave tree that have a CVS/Entries
+entry in the master tree are synchronized. This means:
+
+ If the files differ:
+ if the slave file is newer:
+ normalize the slave file
+ if the files still differ:
+ copy the slave to the master
+ else (the master is newer):
+ copy the master to the slave
+
+ normalizing the slave means replacing CRLF with LF when the master
+ doesn't use CRLF
+
+"""
+
+import os, sys, stat, getopt
+
+# Interactivity options
+default_answer = "ask"
+create_files = "yes"
+create_directories = "no"
+write_slave = "ask"
+write_master = "ask"
+
+def main():
+ global always_no, always_yes
+ global create_directories, write_master, write_slave
+ opts, args = getopt.getopt(sys.argv[1:], "nym:s:d:f:a:")
+ for o, a in opts:
+ if o == '-y':
+ default_answer = "yes"
+ if o == '-n':
+ default_answer = "no"
+ if o == '-s':
+ write_slave = a
+ if o == '-m':
+ write_master = a
+ if o == '-d':
+ create_directories = a
+ if o == '-f':
+ create_files = a
+ if o == '-a':
+ create_files = create_directories = write_slave = write_master = a
+ try:
+ [slave, master] = args
+ except ValueError:
+ print "usage: python", sys.argv[0] or "treesync.py",
+ print "[-n] [-y] [-m y|n|a] [-s y|n|a] [-d y|n|a] [-f n|y|a]",
+ print "slavedir masterdir"
+ return
+ process(slave, master)
+
+def process(slave, master):
+ cvsdir = os.path.join(master, "CVS")
+ if not os.path.isdir(cvsdir):
+ print "skipping master subdirectory", master
+ print "-- not under CVS"
+ return
+ print "-"*40
+ print "slave ", slave
+ print "master", master
+ if not os.path.isdir(slave):
+ if not okay("create slave directory %s?" % slave,
+ answer=create_directories):
+ print "skipping master subdirectory", master
+ print "-- no corresponding slave", slave
+ return
+ print "creating slave directory", slave
+ try:
+ os.mkdir(slave)
+ except os.error, msg:
+ print "can't make slave directory", slave, ":", msg
+ return
+ else:
+ print "made slave directory", slave
+ cvsdir = None
+ subdirs = []
+ names = os.listdir(master)
+ for name in names:
+ mastername = os.path.join(master, name)
+ slavename = os.path.join(slave, name)
+ if name == "CVS":
+ cvsdir = mastername
+ else:
+ if os.path.isdir(mastername) and not os.path.islink(mastername):
+ subdirs.append((slavename, mastername))
+ if cvsdir:
+ entries = os.path.join(cvsdir, "Entries")
+ for e in open(entries).readlines():
+ words = e.split('/')
+ if words[0] == '' and words[1:]:
+ name = words[1]
+ s = os.path.join(slave, name)
+ m = os.path.join(master, name)
+ compare(s, m)
+ for (s, m) in subdirs:
+ process(s, m)
+
+def compare(slave, master):
+ try:
+ sf = open(slave, 'r')
+ except IOError:
+ sf = None
+ try:
+ mf = open(master, 'rb')
+ except IOError:
+ mf = None
+ if not sf:
+ if not mf:
+ print "Neither master nor slave exists", master
+ return
+ print "Creating missing slave", slave
+ copy(master, slave, answer=create_files)
+ return
+ if not mf:
+ print "Not updating missing master", master
+ return
+ if sf and mf:
+ if identical(sf, mf):
+ return
+ sft = mtime(sf)
+ mft = mtime(mf)
+ if mft > sft:
+ # Master is newer -- copy master to slave
+ sf.close()
+ mf.close()
+ print "Master ", master
+ print "is newer than slave", slave
+ copy(master, slave, answer=write_slave)
+ return
+ # Slave is newer -- copy slave to master
+ print "Slave is", sft-mft, "seconds newer than master"
+ # But first check what to do about CRLF
+ mf.seek(0)
+ fun = funnychars(mf)
+ mf.close()
+ sf.close()
+ if fun:
+ print "***UPDATING MASTER (BINARY COPY)***"
+ copy(slave, master, "rb", answer=write_master)
+ else:
+ print "***UPDATING MASTER***"
+ copy(slave, master, "r", answer=write_master)
+
+BUFSIZE = 16*1024
+
+def identical(sf, mf):
+ while 1:
+ sd = sf.read(BUFSIZE)
+ md = mf.read(BUFSIZE)
+ if sd != md: return 0
+ if not sd: break
+ return 1
+
+def mtime(f):
+ st = os.fstat(f.fileno())
+ return st[stat.ST_MTIME]
+
+def funnychars(f):
+ while 1:
+ buf = f.read(BUFSIZE)
+ if not buf: break
+ if '\r' in buf or '\0' in buf: return 1
+ return 0
+
+def copy(src, dst, rmode="rb", wmode="wb", answer='ask'):
+ print "copying", src
+ print " to", dst
+ if not okay("okay to copy? ", answer):
+ return
+ f = open(src, rmode)
+ g = open(dst, wmode)
+ while 1:
+ buf = f.read(BUFSIZE)
+ if not buf: break
+ g.write(buf)
+ f.close()
+ g.close()
+
+def okay(prompt, answer='ask'):
+ answer = answer.strip().lower()
+ if not answer or answer[0] not in 'ny':
+ answer = raw_input(prompt)
+ answer = answer.strip().lower()
+ if not answer:
+ answer = default_answer
+ if answer[:1] == 'y':
+ return 1
+ if answer[:1] == 'n':
+ return 0
+ print "Yes or No please -- try again:"
+ return okay(prompt)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/untabify.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/untabify.py
new file mode 100644
index 0000000000..56e8250741
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/untabify.py
@@ -0,0 +1,52 @@
+#! /usr/bin/env python
+
+"Replace tabs with spaces in argument files. Print names of changed files."
+
+import os
+import sys
+import getopt
+
+def main():
+ tabsize = 8
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "t:")
+ if not args:
+ raise getopt.error, "At least one file argument required"
+ except getopt.error, msg:
+ print msg
+ print "usage:", sys.argv[0], "[-t tabwidth] file ..."
+ return
+ for optname, optvalue in opts:
+ if optname == '-t':
+ tabsize = int(optvalue)
+
+ for filename in args:
+ process(filename, tabsize)
+
+def process(filename, tabsize, verbose=True):
+ try:
+ f = open(filename)
+ text = f.read()
+ f.close()
+ except IOError, msg:
+ print "%r: I/O error: %s" % (filename, msg)
+ return
+ newtext = text.expandtabs(tabsize)
+ if newtext == text:
+ return
+ backup = filename + "~"
+ try:
+ os.unlink(backup)
+ except os.error:
+ pass
+ try:
+ os.rename(filename, backup)
+ except os.error:
+ pass
+ with open(filename, "w") as f:
+ f.write(newtext)
+ if verbose:
+ print filename
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/which.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/which.py
new file mode 100644
index 0000000000..388935aa73
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/which.py
@@ -0,0 +1,60 @@
+#! /usr/bin/env python
+
+# Variant of "which".
+# On stderr, near and total misses are reported.
+# '-l<flags>' argument adds ls -l<flags> of each file found.
+
+import sys
+if sys.path[0] in (".", ""): del sys.path[0]
+
+import sys, os
+from stat import *
+
+def msg(str):
+ sys.stderr.write(str + '\n')
+
+def main():
+ pathlist = os.environ['PATH'].split(os.pathsep)
+
+ sts = 0
+ longlist = ''
+
+ if sys.argv[1:] and sys.argv[1][:2] == '-l':
+ longlist = sys.argv[1]
+ del sys.argv[1]
+
+ for prog in sys.argv[1:]:
+ ident = ()
+ for dir in pathlist:
+ filename = os.path.join(dir, prog)
+ try:
+ st = os.stat(filename)
+ except os.error:
+ continue
+ if not S_ISREG(st[ST_MODE]):
+ msg(filename + ': not a disk file')
+ else:
+ mode = S_IMODE(st[ST_MODE])
+ if mode & 0111:
+ if not ident:
+ print filename
+ ident = st[:3]
+ else:
+ if st[:3] == ident:
+ s = 'same as: '
+ else:
+ s = 'also: '
+ msg(s + filename)
+ else:
+ msg(filename + ': not executable')
+ if longlist:
+ sts = os.system('ls ' + longlist + ' ' + filename)
+ if sts: msg('"ls -l" exit status: ' + repr(sts))
+ if not ident:
+ msg(prog + ': not found')
+ sts = 1
+
+ sys.exit(sts)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/win_add2path.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/win_add2path.py
new file mode 100644
index 0000000000..1f69a33e88
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/win_add2path.py
@@ -0,0 +1,57 @@
+"""Add Python to the search path on Windows
+
+This is a simple script to add Python to the Windows search path. It
+modifies the current user (HKCU) tree of the registry.
+
+Copyright (c) 2008 by Christian Heimes <christian@cheimes.de>
+Licensed to PSF under a Contributor Agreement.
+"""
+
+import sys
+import site
+import os
+import _winreg
+
+HKCU = _winreg.HKEY_CURRENT_USER
+ENV = "Environment"
+PATH = "PATH"
+DEFAULT = u"%PATH%"
+
+def modify():
+ pythonpath = os.path.dirname(os.path.normpath(sys.executable))
+ scripts = os.path.join(pythonpath, "Scripts")
+ appdata = os.environ["APPDATA"]
+ if hasattr(site, "USER_SITE"):
+ userpath = site.USER_SITE.replace(appdata, "%APPDATA%")
+ userscripts = os.path.join(userpath, "Scripts")
+ else:
+ userscripts = None
+
+ with _winreg.CreateKey(HKCU, ENV) as key:
+ try:
+ envpath = _winreg.QueryValueEx(key, PATH)[0]
+ except WindowsError:
+ envpath = DEFAULT
+
+ paths = [envpath]
+ for path in (pythonpath, scripts, userscripts):
+ if path and path not in envpath and os.path.isdir(path):
+ paths.append(path)
+
+ envpath = os.pathsep.join(paths)
+ _winreg.SetValueEx(key, PATH, 0, _winreg.REG_EXPAND_SZ, envpath)
+ return paths, envpath
+
+def main():
+ paths, envpath = modify()
+ if len(paths) > 1:
+ print "Path(s) added:"
+ print '\n'.join(paths[1:])
+ else:
+ print "No path was added"
+ print "\nPATH is now:\n%s\n" % envpath
+ print "Expanded:"
+ print _winreg.ExpandEnvironmentStrings(envpath)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/xxci.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/xxci.py
new file mode 100644
index 0000000000..ff574c3333
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/xxci.py
@@ -0,0 +1,116 @@
+#! /usr/bin/env python
+
+# xxci
+#
+# check in files for which rcsdiff returns nonzero exit status
+
+import sys
+import os
+from stat import *
+import fnmatch
+
+EXECMAGIC = '\001\140\000\010'
+
+MAXSIZE = 200*1024 # Files this big must be binaries and are skipped.
+
+def getargs():
+ args = sys.argv[1:]
+ if args:
+ return args
+ print 'No arguments, checking almost *, in "ls -t" order'
+ list = []
+ for file in os.listdir(os.curdir):
+ if not skipfile(file):
+ list.append((getmtime(file), file))
+ list.sort()
+ if not list:
+ print 'Nothing to do -- exit 1'
+ sys.exit(1)
+ list.sort()
+ list.reverse()
+ for mtime, file in list: args.append(file)
+ return args
+
+def getmtime(file):
+ try:
+ st = os.stat(file)
+ return st[ST_MTIME]
+ except os.error:
+ return -1
+
+badnames = ['tags', 'TAGS', 'xyzzy', 'nohup.out', 'core']
+badprefixes = ['.', ',', '@', '#', 'o.']
+badsuffixes = \
+ ['~', '.a', '.o', '.old', '.bak', '.orig', '.new', '.prev', '.not', \
+ '.pyc', '.fdc', '.rgb', '.elc', ',v']
+ignore = []
+
+def setup():
+ ignore[:] = badnames
+ for p in badprefixes:
+ ignore.append(p + '*')
+ for p in badsuffixes:
+ ignore.append('*' + p)
+ try:
+ f = open('.xxcign', 'r')
+ except IOError:
+ return
+ ignore[:] = ignore + f.read().split()
+
+def skipfile(file):
+ for p in ignore:
+ if fnmatch.fnmatch(file, p): return 1
+ try:
+ st = os.lstat(file)
+ except os.error:
+ return 1 # Doesn't exist -- skip it
+ # Skip non-plain files.
+ if not S_ISREG(st[ST_MODE]): return 1
+ # Skip huge files -- probably binaries.
+ if st[ST_SIZE] >= MAXSIZE: return 1
+ # Skip executables
+ try:
+ data = open(file, 'r').read(len(EXECMAGIC))
+ if data == EXECMAGIC: return 1
+ except:
+ pass
+ return 0
+
+def badprefix(file):
+ for bad in badprefixes:
+ if file[:len(bad)] == bad: return 1
+ return 0
+
+def badsuffix(file):
+ for bad in badsuffixes:
+ if file[-len(bad):] == bad: return 1
+ return 0
+
+def go(args):
+ for file in args:
+ print file + ':'
+ if differing(file):
+ showdiffs(file)
+ if askyesno('Check in ' + file + ' ? '):
+ sts = os.system('rcs -l ' + file) # ignored
+ sts = os.system('ci -l ' + file)
+
+def differing(file):
+ cmd = 'co -p ' + file + ' 2>/dev/null | cmp -s - ' + file
+ sts = os.system(cmd)
+ return sts != 0
+
+def showdiffs(file):
+ cmd = 'rcsdiff ' + file + ' 2>&1 | ${PAGER-more}'
+ sts = os.system(cmd)
+
+def askyesno(prompt):
+ s = raw_input(prompt)
+ return s in ['y', 'yes']
+
+if __name__ == '__main__':
+ try:
+ setup()
+ go(getargs())
+ except KeyboardInterrupt:
+ print '[Intr]'
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/ssl/get-remote-certificate.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/ssl/get-remote-certificate.py
new file mode 100644
index 0000000000..9e50853f36
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/ssl/get-remote-certificate.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python
+#
+# fetch the certificate that the server(s) are providing in PEM form
+#
+# args are HOST:PORT [, HOST:PORT...]
+#
+# By Bill Janssen.
+
+import sys
+
+def fetch_server_certificate (host, port):
+
+ import re, tempfile, os, ssl
+
+ def subproc(cmd):
+ from subprocess import Popen, PIPE, STDOUT
+ proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
+ status = proc.wait()
+ output = proc.stdout.read()
+ return status, output
+
+ def strip_to_x509_cert(certfile_contents, outfile=None):
+ m = re.search(r"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n"
+ r".*[\r]*^[-]+END CERTIFICATE[-]+)$",
+ certfile_contents, re.MULTILINE | re.DOTALL)
+ if not m:
+ return None
+ else:
+ tn = tempfile.mktemp()
+ fp = open(tn, "w")
+ fp.write(m.group(1) + "\n")
+ fp.close()
+ try:
+ tn2 = (outfile or tempfile.mktemp())
+ status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
+ (tn, tn2))
+ if status != 0:
+ raise OperationError(status, tsig, output)
+ fp = open(tn2, 'rb')
+ data = fp.read()
+ fp.close()
+ os.unlink(tn2)
+ return data
+ finally:
+ os.unlink(tn)
+
+ if sys.platform.startswith("win"):
+ tfile = tempfile.mktemp()
+ fp = open(tfile, "w")
+ fp.write("quit\n")
+ fp.close()
+ try:
+ status, output = subproc(
+ 'openssl s_client -connect "%s:%s" -showcerts < "%s"' %
+ (host, port, tfile))
+ finally:
+ os.unlink(tfile)
+ else:
+ status, output = subproc(
+ 'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
+ (host, port))
+ if status != 0:
+ raise OSError(status)
+ certtext = strip_to_x509_cert(output)
+ if not certtext:
+ raise ValueError("Invalid response received from server at %s:%s" %
+ (host, port))
+ return certtext
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ sys.stderr.write(
+ "Usage: %s HOSTNAME:PORTNUMBER [, HOSTNAME:PORTNUMBER...]\n" %
+ sys.argv[0])
+ sys.exit(1)
+ for arg in sys.argv[1:]:
+ host, port = arg.split(":")
+ sys.stdout.write(fetch_server_certificate(host, int(port)))
+ sys.exit(0)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/Makefile b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/Makefile
new file mode 100644
index 0000000000..2fc88b9c5e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/Makefile
@@ -0,0 +1,84 @@
+#
+# Recreate the Python charmap codecs from the Unicode mapping
+# files available at ftp://ftp.unicode.org/
+#
+#(c) Copyright Marc-Andre Lemburg, 2005.
+# Licensed to PSF under a Contributor Agreement.
+
+# Python binary to use
+PYTHON = python
+
+# Remove tool to use
+RM = /bin/rm
+
+### Generic targets
+
+all: distclean mappings codecs
+
+codecs: misc windows iso apple ebcdic custom-mappings cjk
+
+### Mappings
+
+mappings:
+ ncftpget -R ftp.unicode.org . Public/MAPPINGS
+
+### Codecs
+
+build/:
+ mkdir build
+
+misc: build/
+ $(PYTHON) gencodec.py MAPPINGS/VENDORS/MISC/ build/
+ $(RM) build/atarist.*
+ $(RM) build/us_ascii_quotes.*
+ $(RM) build/ibmgraph.*
+ $(RM) build/sgml.*
+ $(RM) -f build/readme.*
+
+custom-mappings: build/
+ $(PYTHON) gencodec.py python-mappings/ build/
+
+windows: build/
+ $(PYTHON) gencodec.py MAPPINGS/VENDORS/MICSFT/WINDOWS/ build/
+ $(RM) build/cp9*
+ $(RM) -f build/readme.*
+
+iso: build/
+ $(PYTHON) gencodec.py MAPPINGS/ISO8859/ build/ iso
+ $(RM) -f build/isoreadme.*
+
+apple: build/
+ $(PYTHON) gencodec.py MAPPINGS/VENDORS/APPLE/ build/ mac_
+ $(RM) build/mac_dingbats.*
+ $(RM) build/mac_japanese.*
+ $(RM) build/mac_chin*
+ $(RM) build/mac_korean.*
+ $(RM) build/mac_symbol.*
+ $(RM) build/mac_corpchar.*
+ $(RM) build/mac_devanaga.*
+ $(RM) build/mac_gaelic.*
+ $(RM) build/mac_gurmukhi.*
+ $(RM) build/mac_hebrew.*
+ $(RM) build/mac_inuit.*
+ $(RM) build/mac_thai.*
+ $(RM) build/mac_ukraine.*
+ $(RM) build/mac_arabic.py
+ $(RM) build/mac_celtic.*
+ $(RM) build/mac_gujarati.*
+ $(RM) build/mac_keyboard.*
+ $(RM) -f build/mac_readme.*
+
+ebcdic: build/
+ $(PYTHON) gencodec.py MAPPINGS/VENDORS/MICSFT/EBCDIC/ build/
+ $(RM) -f build/readme.*
+
+cjk: build/
+ $(PYTHON) gencjkcodecs.py build/
+
+### Cleanup
+
+clean:
+ $(RM) -f build/*
+
+distclean: clean
+ $(RM) -rf MAPPINGS/
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/comparecodecs.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/comparecodecs.py
new file mode 100644
index 0000000000..a6f3102f1d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/comparecodecs.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+
+""" Compare the output of two codecs.
+
+(c) Copyright 2005, Marc-Andre Lemburg (mal@lemburg.com).
+
+ Licensed to PSF under a Contributor Agreement.
+
+"""
+import sys
+
+def compare_codecs(encoding1, encoding2):
+
+ print 'Comparing encoding/decoding of %r and %r' % (encoding1, encoding2)
+ mismatch = 0
+ # Check encoding
+ for i in range(sys.maxunicode):
+ u = unichr(i)
+ try:
+ c1 = u.encode(encoding1)
+ except UnicodeError, reason:
+ c1 = '<undefined>'
+ try:
+ c2 = u.encode(encoding2)
+ except UnicodeError, reason:
+ c2 = '<undefined>'
+ if c1 != c2:
+ print ' * encoding mismatch for 0x%04X: %-14r != %r' % \
+ (i, c1, c2)
+ mismatch += 1
+ # Check decoding
+ for i in range(256):
+ c = chr(i)
+ try:
+ u1 = c.decode(encoding1)
+ except UnicodeError:
+ u1 = u'<undefined>'
+ try:
+ u2 = c.decode(encoding2)
+ except UnicodeError:
+ u2 = u'<undefined>'
+ if u1 != u2:
+ print ' * decoding mismatch for 0x%04X: %-14r != %r' % \
+ (i, u1, u2)
+ mismatch += 1
+ if mismatch:
+ print
+ print 'Found %i mismatches' % mismatch
+ else:
+ print '-> Codecs are identical.'
+
+if __name__ == '__main__':
+ compare_codecs(sys.argv[1], sys.argv[2])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencjkcodecs.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencjkcodecs.py
new file mode 100644
index 0000000000..5ac97d4d9d
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencjkcodecs.py
@@ -0,0 +1,68 @@
+import os, string
+
+codecs = {
+ 'cn': ('gb2312', 'gbk', 'gb18030', 'hz'),
+ 'tw': ('big5', 'cp950'),
+ 'hk': ('big5hkscs',),
+ 'jp': ('cp932', 'shift_jis', 'euc_jp', 'euc_jisx0213', 'shift_jisx0213',
+ 'euc_jis_2004', 'shift_jis_2004'),
+ 'kr': ('cp949', 'euc_kr', 'johab'),
+ 'iso2022': ('iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2',
+ 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext',
+ 'iso2022_kr'),
+}
+
+TEMPLATE = string.Template("""\
+#
+# $encoding.py: Python Unicode Codec for $ENCODING
+#
+# Written by Hye-Shik Chang <perky@FreeBSD.org>
+#
+
+import _codecs_$owner, codecs
+import _multibytecodec as mbc
+
+codec = _codecs_$owner.getcodec('$encoding')
+
+class Codec(codecs.Codec):
+ encode = codec.encode
+ decode = codec.decode
+
+class IncrementalEncoder(mbc.MultibyteIncrementalEncoder,
+ codecs.IncrementalEncoder):
+ codec = codec
+
+class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
+ codecs.IncrementalDecoder):
+ codec = codec
+
+class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
+ codec = codec
+
+class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
+ codec = codec
+
+def getregentry():
+ return codecs.CodecInfo(
+ name='$encoding',
+ encode=Codec().encode,
+ decode=Codec().decode,
+ incrementalencoder=IncrementalEncoder,
+ incrementaldecoder=IncrementalDecoder,
+ streamreader=StreamReader,
+ streamwriter=StreamWriter,
+ )
+""")
+
+def gencodecs(prefix):
+ for loc, encodings in codecs.iteritems():
+ for enc in encodings:
+ code = TEMPLATE.substitute(ENCODING=enc.upper(),
+ encoding=enc.lower(),
+ owner=loc)
+ codecpath = os.path.join(prefix, enc + '.py')
+ open(codecpath, 'w').write(code)
+
+if __name__ == '__main__':
+ import sys
+ gencodecs(sys.argv[1])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencodec.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencodec.py
new file mode 100644
index 0000000000..2626279d1e
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/gencodec.py
@@ -0,0 +1,423 @@
+""" Unicode Mapping Parser and Codec Generator.
+
+This script parses Unicode mapping files as available from the Unicode
+site (ftp://ftp.unicode.org/Public/MAPPINGS/) and creates Python codec
+modules from them. The codecs use the standard character mapping codec
+to actually apply the mapping.
+
+Synopsis: gencodec.py dir codec_prefix
+
+All files in dir are scanned and those producing non-empty mappings
+will be written to <codec_prefix><mapname>.py with <mapname> being the
+first part of the map's filename ('a' in a.b.c.txt) converted to
+lowercase with hyphens replaced by underscores.
+
+The tool also writes marshalled versions of the mapping tables to the
+same location (with .mapping extension).
+
+Written by Marc-Andre Lemburg (mal@lemburg.com).
+
+(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
+(c) Copyright Guido van Rossum, 2000.
+
+Table generation:
+(c) Copyright Marc-Andre Lemburg, 2005.
+ Licensed to PSF under a Contributor Agreement.
+
+"""#"
+
+import re, os, marshal, codecs
+
+# Maximum allowed size of charmap tables
+MAX_TABLE_SIZE = 8192
+
+# Standard undefined Unicode code point
+UNI_UNDEFINED = unichr(0xFFFE)
+
+mapRE = re.compile('((?:0x[0-9a-fA-F]+\+?)+)'
+ '\s+'
+ '((?:(?:0x[0-9a-fA-Z]+|<[A-Za-z]+>)\+?)*)'
+ '\s*'
+ '(#.+)?')
+
+def parsecodes(codes, len=len, range=range):
+
+ """ Converts code combinations to either a single code integer
+ or a tuple of integers.
+
+ meta-codes (in angular brackets, e.g. <LR> and <RL>) are
+ ignored.
+
+ Empty codes or illegal ones are returned as None.
+
+ """
+ if not codes:
+ return None
+ l = codes.split('+')
+ if len(l) == 1:
+ return int(l[0],16)
+ for i in range(len(l)):
+ try:
+ l[i] = int(l[i],16)
+ except ValueError:
+ l[i] = None
+ l = [x for x in l if x is not None]
+ if len(l) == 1:
+ return l[0]
+ else:
+ return tuple(l)
+
+def readmap(filename):
+
+ f = open(filename,'r')
+ lines = f.readlines()
+ f.close()
+ enc2uni = {}
+ identity = []
+ unmapped = range(256)
+
+ # UTC mapping tables per convention don't include the identity
+ # mappings for code points 0x00 - 0x1F and 0x7F, unless these are
+ # explicitly mapped to different characters or undefined
+ for i in range(32) + [127]:
+ identity.append(i)
+ unmapped.remove(i)
+ enc2uni[i] = (i, 'CONTROL CHARACTER')
+
+ for line in lines:
+ line = line.strip()
+ if not line or line[0] == '#':
+ continue
+ m = mapRE.match(line)
+ if not m:
+ #print '* not matched: %s' % repr(line)
+ continue
+ enc,uni,comment = m.groups()
+ enc = parsecodes(enc)
+ uni = parsecodes(uni)
+ if comment is None:
+ comment = ''
+ else:
+ comment = comment[1:].strip()
+ if enc < 256:
+ if enc in unmapped:
+ unmapped.remove(enc)
+ if enc == uni:
+ identity.append(enc)
+ enc2uni[enc] = (uni,comment)
+ else:
+ enc2uni[enc] = (uni,comment)
+
+ # If there are more identity-mapped entries than unmapped entries,
+ # it pays to generate an identity dictionary first, and add explicit
+ # mappings to None for the rest
+ if len(identity) >= len(unmapped):
+ for enc in unmapped:
+ enc2uni[enc] = (None, "")
+ enc2uni['IDENTITY'] = 256
+
+ return enc2uni
+
+def hexrepr(t, precision=4):
+
+ if t is None:
+ return 'None'
+ try:
+ len(t)
+ except:
+ return '0x%0*X' % (precision, t)
+ try:
+ return '(' + ', '.join(['0x%0*X' % (precision, item)
+ for item in t]) + ')'
+ except TypeError, why:
+ print '* failed to convert %r: %s' % (t, why)
+ raise
+
+def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)):
+
+ l = []
+ append = l.append
+ if "IDENTITY" in map:
+ append("%s = codecs.make_identity_dict(range(%d))" %
+ (varname, map["IDENTITY"]))
+ append("%s.update({" % varname)
+ splits = 1
+ del map["IDENTITY"]
+ identity = 1
+ else:
+ append("%s = {" % varname)
+ splits = 0
+ identity = 0
+
+ mappings = sorted(map.items())
+ i = 0
+ key_precision, value_precision = precisions
+ for mapkey, mapvalue in mappings:
+ mapcomment = ''
+ if isinstance(mapkey, tuple):
+ (mapkey, mapcomment) = mapkey
+ if isinstance(mapvalue, tuple):
+ (mapvalue, mapcomment) = mapvalue
+ if mapkey is None:
+ continue
+ if (identity and
+ mapkey == mapvalue and
+ mapkey < 256):
+ # No need to include identity mappings, since these
+ # are already set for the first 256 code points.
+ continue
+ key = hexrepr(mapkey, key_precision)
+ value = hexrepr(mapvalue, value_precision)
+ if mapcomment and comments:
+ append(' %s: %s,\t# %s' % (key, value, mapcomment))
+ else:
+ append(' %s: %s,' % (key, value))
+ i += 1
+ if i == 4096:
+ # Split the definition into parts to that the Python
+ # parser doesn't dump core
+ if splits == 0:
+ append('}')
+ else:
+ append('})')
+ append('%s.update({' % varname)
+ i = 0
+ splits = splits + 1
+ if splits == 0:
+ append('}')
+ else:
+ append('})')
+
+ return l
+
+def python_tabledef_code(varname, map, comments=1, key_precision=2):
+
+ l = []
+ append = l.append
+ append('%s = (' % varname)
+
+ # Analyze map and create table dict
+ mappings = sorted(map.items())
+ table = {}
+ maxkey = 0
+ if 'IDENTITY' in map:
+ for key in range(256):
+ table[key] = (key, '')
+ maxkey = 255
+ del map['IDENTITY']
+ for mapkey, mapvalue in mappings:
+ mapcomment = ''
+ if isinstance(mapkey, tuple):
+ (mapkey, mapcomment) = mapkey
+ if isinstance(mapvalue, tuple):
+ (mapvalue, mapcomment) = mapvalue
+ if mapkey is None:
+ continue
+ table[mapkey] = (mapvalue, mapcomment)
+ if mapkey > maxkey:
+ maxkey = mapkey
+ if maxkey > MAX_TABLE_SIZE:
+ # Table too large
+ return None
+
+ # Create table code
+ for key in range(maxkey + 1):
+ if key not in table:
+ mapvalue = None
+ mapcomment = 'UNDEFINED'
+ else:
+ mapvalue, mapcomment = table[key]
+ if mapvalue is None:
+ mapchar = UNI_UNDEFINED
+ else:
+ if isinstance(mapvalue, tuple):
+ # 1-n mappings not supported
+ return None
+ else:
+ mapchar = unichr(mapvalue)
+ if mapcomment and comments:
+ append(' %r\t# %s -> %s' % (mapchar,
+ hexrepr(key, key_precision),
+ mapcomment))
+ else:
+ append(' %r' % mapchar)
+
+ append(')')
+ return l
+
+def codegen(name, map, encodingname, comments=1):
+
+ """ Returns Python source for the given map.
+
+ Comments are included in the source, if comments is true (default).
+
+ """
+ # Generate code
+ decoding_map_code = python_mapdef_code(
+ 'decoding_map',
+ map,
+ comments=comments)
+ decoding_table_code = python_tabledef_code(
+ 'decoding_table',
+ map,
+ comments=comments)
+ encoding_map_code = python_mapdef_code(
+ 'encoding_map',
+ codecs.make_encoding_map(map),
+ comments=comments,
+ precisions=(4, 2))
+
+ if decoding_table_code:
+ suffix = 'table'
+ else:
+ suffix = 'map'
+
+ l = [
+ '''\
+""" Python Character Mapping Codec %s generated from '%s' with gencodec.py.
+
+"""#"
+
+import codecs
+
+### Codec APIs
+
+class Codec(codecs.Codec):
+
+ def encode(self,input,errors='strict'):
+ return codecs.charmap_encode(input,errors,encoding_%s)
+
+ def decode(self,input,errors='strict'):
+ return codecs.charmap_decode(input,errors,decoding_%s)
+''' % (encodingname, name, suffix, suffix)]
+ l.append('''\
+class IncrementalEncoder(codecs.IncrementalEncoder):
+ def encode(self, input, final=False):
+ return codecs.charmap_encode(input,self.errors,encoding_%s)[0]
+
+class IncrementalDecoder(codecs.IncrementalDecoder):
+ def decode(self, input, final=False):
+ return codecs.charmap_decode(input,self.errors,decoding_%s)[0]''' %
+ (suffix, suffix))
+
+ l.append('''
+class StreamWriter(Codec,codecs.StreamWriter):
+ pass
+
+class StreamReader(Codec,codecs.StreamReader):
+ pass
+
+### encodings module API
+
+def getregentry():
+ return codecs.CodecInfo(
+ name=%r,
+ encode=Codec().encode,
+ decode=Codec().decode,
+ incrementalencoder=IncrementalEncoder,
+ incrementaldecoder=IncrementalDecoder,
+ streamreader=StreamReader,
+ streamwriter=StreamWriter,
+ )
+''' % encodingname.replace('_', '-'))
+
+ # Add decoding table or map (with preference to the table)
+ if not decoding_table_code:
+ l.append('''
+### Decoding Map
+''')
+ l.extend(decoding_map_code)
+ else:
+ l.append('''
+### Decoding Table
+''')
+ l.extend(decoding_table_code)
+
+ # Add encoding map
+ if decoding_table_code:
+ l.append('''
+### Encoding table
+encoding_table=codecs.charmap_build(decoding_table)
+''')
+ else:
+ l.append('''
+### Encoding Map
+''')
+ l.extend(encoding_map_code)
+
+ # Final new-line
+ l.append('')
+
+ return '\n'.join(l).expandtabs()
+
+def pymap(name,map,pyfile,encodingname,comments=1):
+
+ code = codegen(name,map,encodingname,comments)
+ f = open(pyfile,'w')
+ f.write(code)
+ f.close()
+
+def marshalmap(name,map,marshalfile):
+
+ d = {}
+ for e,(u,c) in map.items():
+ d[e] = (u,c)
+ f = open(marshalfile,'wb')
+ marshal.dump(d,f)
+ f.close()
+
+def convertdir(dir, dirprefix='', nameprefix='', comments=1):
+
+ mapnames = os.listdir(dir)
+ for mapname in mapnames:
+ mappathname = os.path.join(dir, mapname)
+ if not os.path.isfile(mappathname):
+ continue
+ name = os.path.split(mapname)[1]
+ name = name.replace('-','_')
+ name = name.split('.')[0]
+ name = name.lower()
+ name = nameprefix + name
+ codefile = name + '.py'
+ marshalfile = name + '.mapping'
+ print 'converting %s to %s and %s' % (mapname,
+ dirprefix + codefile,
+ dirprefix + marshalfile)
+ try:
+ map = readmap(os.path.join(dir,mapname))
+ if not map:
+ print '* map is empty; skipping'
+ else:
+ pymap(mappathname, map, dirprefix + codefile,name,comments)
+ marshalmap(mappathname, map, dirprefix + marshalfile)
+ except ValueError, why:
+ print '* conversion failed: %s' % why
+ raise
+
+def rewritepythondir(dir, dirprefix='', comments=1):
+
+ mapnames = os.listdir(dir)
+ for mapname in mapnames:
+ if not mapname.endswith('.mapping'):
+ continue
+ name = mapname[:-len('.mapping')]
+ codefile = name + '.py'
+ print 'converting %s to %s' % (mapname,
+ dirprefix + codefile)
+ try:
+ map = marshal.load(open(os.path.join(dir,mapname),
+ 'rb'))
+ if not map:
+ print '* map is empty; skipping'
+ else:
+ pymap(mapname, map, dirprefix + codefile,name,comments)
+ except ValueError, why:
+ print '* conversion failed: %s' % why
+
+if __name__ == '__main__':
+
+ import sys
+ if 1:
+ convertdir(*sys.argv[1:])
+ else:
+ rewritepythondir(*sys.argv[1:])
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodec.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodec.py
new file mode 100644
index 0000000000..32dcadabf2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodec.py
@@ -0,0 +1,61 @@
+"""This script generates a Python codec module from a Windows Code Page.
+
+It uses the function MultiByteToWideChar to generate a decoding table.
+"""
+
+import ctypes
+from ctypes import wintypes
+from gencodec import codegen
+import unicodedata
+
+def genwinmap(codepage):
+ MultiByteToWideChar = ctypes.windll.kernel32.MultiByteToWideChar
+ MultiByteToWideChar.argtypes = [wintypes.UINT, wintypes.DWORD,
+ wintypes.LPCSTR, ctypes.c_int,
+ wintypes.LPWSTR, ctypes.c_int]
+ MultiByteToWideChar.restype = ctypes.c_int
+
+ enc2uni = {}
+
+ for i in range(32) + [127]:
+ enc2uni[i] = (i, 'CONTROL CHARACTER')
+
+ for i in range(256):
+ buf = ctypes.create_unicode_buffer(2)
+ ret = MultiByteToWideChar(
+ codepage, 0,
+ chr(i), 1,
+ buf, 2)
+ assert ret == 1, "invalid code page"
+ assert buf[1] == '\x00'
+ try:
+ name = unicodedata.name(buf[0])
+ except ValueError:
+ try:
+ name = enc2uni[i][1]
+ except KeyError:
+ name = ''
+
+ enc2uni[i] = (ord(buf[0]), name)
+
+ return enc2uni
+
+def genwincodec(codepage):
+ import platform
+ map = genwinmap(codepage)
+ encodingname = 'cp%d' % codepage
+ code = codegen("", map, encodingname)
+ # Replace first lines with our own docstring
+ code = '''\
+"""Python Character Mapping Codec %s generated on Windows:
+%s with the command:
+ python Tools/unicode/genwincodec.py %s
+"""#"
+''' % (encodingname, ' '.join(platform.win32_ver()), codepage
+ ) + code.split('"""#"', 1)[1]
+
+ print code
+
+if __name__ == '__main__':
+ import sys
+ genwincodec(int(sys.argv[1]))
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodecs.bat b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodecs.bat
new file mode 100644
index 0000000000..6a6a671f81
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/genwincodecs.bat
@@ -0,0 +1,7 @@
+@rem Recreate some python charmap codecs from the Windows function
+@rem MultiByteToWideChar.
+
+@cd /d %~dp0
+@mkdir build
+@rem Arabic DOS code page
+c:\python26\python genwincodec.py 720 > build/cp720.py
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/listcodecs.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/listcodecs.py
new file mode 100644
index 0000000000..5ad4309be0
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/listcodecs.py
@@ -0,0 +1,41 @@
+""" List all available codec modules.
+
+(c) Copyright 2005, Marc-Andre Lemburg (mal@lemburg.com).
+
+ Licensed to PSF under a Contributor Agreement.
+
+"""
+
+import os, codecs, encodings
+
+_debug = 0
+
+def listcodecs(dir):
+ names = []
+ for filename in os.listdir(dir):
+ if filename[-3:] != '.py':
+ continue
+ name = filename[:-3]
+ # Check whether we've found a true codec
+ try:
+ codecs.lookup(name)
+ except LookupError:
+ # Codec not found
+ continue
+ except Exception, reason:
+ # Probably an error from importing the codec; still it's
+ # a valid code name
+ if _debug:
+ print '* problem importing codec %r: %s' % \
+ (name, reason)
+ names.append(name)
+ return names
+
+
+if __name__ == '__main__':
+ names = listcodecs(encodings.__path__[0])
+ names.sort()
+ print 'all_codecs = ['
+ for name in names:
+ print ' %r,' % name
+ print ']'
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/makeunicodedata.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/makeunicodedata.py
new file mode 100644
index 0000000000..37b9f6eb21
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/makeunicodedata.py
@@ -0,0 +1,1135 @@
+#
+# (re)generate unicode property and type databases
+#
+# this script converts a unicode 3.2 database file to
+# Modules/unicodedata_db.h, Modules/unicodename_db.h,
+# and Objects/unicodetype_db.h
+#
+# history:
+# 2000-09-24 fl created (based on bits and pieces from unidb)
+# 2000-09-25 fl merged tim's splitbin fixes, separate decomposition table
+# 2000-09-25 fl added character type table
+# 2000-09-26 fl added LINEBREAK, DECIMAL, and DIGIT flags/fields (2.0)
+# 2000-11-03 fl expand first/last ranges
+# 2001-01-19 fl added character name tables (2.1)
+# 2001-01-21 fl added decomp compression; dynamic phrasebook threshold
+# 2002-09-11 wd use string methods
+# 2002-10-18 mvl update to Unicode 3.2
+# 2002-10-22 mvl generate NFC tables
+# 2002-11-24 mvl expand all ranges, sort names version-independently
+# 2002-11-25 mvl add UNIDATA_VERSION
+# 2004-05-29 perky add east asian width information
+# 2006-03-10 mvl update to Unicode 4.1; add UCD 3.2 delta
+#
+# written by Fredrik Lundh (fredrik@pythonware.com)
+#
+
+import sys
+
+SCRIPT = sys.argv[0]
+VERSION = "2.6"
+
+# The Unicode Database
+UNIDATA_VERSION = "5.2.0"
+UNICODE_DATA = "UnicodeData%s.txt"
+COMPOSITION_EXCLUSIONS = "CompositionExclusions%s.txt"
+EASTASIAN_WIDTH = "EastAsianWidth%s.txt"
+UNIHAN = "Unihan%s.txt"
+DERIVEDNORMALIZATION_PROPS = "DerivedNormalizationProps%s.txt"
+LINE_BREAK = "LineBreak%s.txt"
+
+old_versions = ["3.2.0"]
+
+CATEGORY_NAMES = [ "Cn", "Lu", "Ll", "Lt", "Mn", "Mc", "Me", "Nd",
+ "Nl", "No", "Zs", "Zl", "Zp", "Cc", "Cf", "Cs", "Co", "Cn", "Lm",
+ "Lo", "Pc", "Pd", "Ps", "Pe", "Pi", "Pf", "Po", "Sm", "Sc", "Sk",
+ "So" ]
+
+BIDIRECTIONAL_NAMES = [ "", "L", "LRE", "LRO", "R", "AL", "RLE", "RLO",
+ "PDF", "EN", "ES", "ET", "AN", "CS", "NSM", "BN", "B", "S", "WS",
+ "ON" ]
+
+EASTASIANWIDTH_NAMES = [ "F", "H", "W", "Na", "A", "N" ]
+
+MANDATORY_LINE_BREAKS = [ "BK", "CR", "LF", "NL" ]
+
+# note: should match definitions in Objects/unicodectype.c
+ALPHA_MASK = 0x01
+DECIMAL_MASK = 0x02
+DIGIT_MASK = 0x04
+LOWER_MASK = 0x08
+LINEBREAK_MASK = 0x10
+SPACE_MASK = 0x20
+TITLE_MASK = 0x40
+UPPER_MASK = 0x80
+NODELTA_MASK = 0x100
+NUMERIC_MASK = 0x200
+
+def maketables(trace=0):
+
+ print "--- Reading", UNICODE_DATA % "", "..."
+
+ version = ""
+ unicode = UnicodeData(UNICODE_DATA % version,
+ COMPOSITION_EXCLUSIONS % version,
+ EASTASIAN_WIDTH % version,
+ UNIHAN % version,
+ DERIVEDNORMALIZATION_PROPS % version,
+ LINE_BREAK % version)
+
+ print len(filter(None, unicode.table)), "characters"
+
+ for version in old_versions:
+ print "--- Reading", UNICODE_DATA % ("-"+version), "..."
+ old_unicode = UnicodeData(UNICODE_DATA % ("-"+version),
+ COMPOSITION_EXCLUSIONS % ("-"+version),
+ EASTASIAN_WIDTH % ("-"+version),
+ UNIHAN % ("-"+version))
+ print len(filter(None, old_unicode.table)), "characters"
+ merge_old_version(version, unicode, old_unicode)
+
+ makeunicodename(unicode, trace)
+ makeunicodedata(unicode, trace)
+ makeunicodetype(unicode, trace)
+
+# --------------------------------------------------------------------
+# unicode character properties
+
+def makeunicodedata(unicode, trace):
+
+ dummy = (0, 0, 0, 0, 0, 0)
+ table = [dummy]
+ cache = {0: dummy}
+ index = [0] * len(unicode.chars)
+
+ FILE = "Modules/unicodedata_db.h"
+
+ print "--- Preparing", FILE, "..."
+
+ # 1) database properties
+
+ for char in unicode.chars:
+ record = unicode.table[char]
+ if record:
+ # extract database properties
+ category = CATEGORY_NAMES.index(record[2])
+ combining = int(record[3])
+ bidirectional = BIDIRECTIONAL_NAMES.index(record[4])
+ mirrored = record[9] == "Y"
+ eastasianwidth = EASTASIANWIDTH_NAMES.index(record[15])
+ normalizationquickcheck = record[17]
+ item = (
+ category, combining, bidirectional, mirrored, eastasianwidth,
+ normalizationquickcheck
+ )
+ # add entry to index and item tables
+ i = cache.get(item)
+ if i is None:
+ cache[item] = i = len(table)
+ table.append(item)
+ index[char] = i
+
+ # 2) decomposition data
+
+ decomp_data = [0]
+ decomp_prefix = [""]
+ decomp_index = [0] * len(unicode.chars)
+ decomp_size = 0
+
+ comp_pairs = []
+ comp_first = [None] * len(unicode.chars)
+ comp_last = [None] * len(unicode.chars)
+
+ for char in unicode.chars:
+ record = unicode.table[char]
+ if record:
+ if record[5]:
+ decomp = record[5].split()
+ if len(decomp) > 19:
+ raise Exception, "character %x has a decomposition too large for nfd_nfkd" % char
+ # prefix
+ if decomp[0][0] == "<":
+ prefix = decomp.pop(0)
+ else:
+ prefix = ""
+ try:
+ i = decomp_prefix.index(prefix)
+ except ValueError:
+ i = len(decomp_prefix)
+ decomp_prefix.append(prefix)
+ prefix = i
+ assert prefix < 256
+ # content
+ decomp = [prefix + (len(decomp)<<8)] + [int(s, 16) for s in decomp]
+ # Collect NFC pairs
+ if not prefix and len(decomp) == 3 and \
+ char not in unicode.exclusions and \
+ unicode.table[decomp[1]][3] == "0":
+ p, l, r = decomp
+ comp_first[l] = 1
+ comp_last[r] = 1
+ comp_pairs.append((l,r,char))
+ try:
+ i = decomp_data.index(decomp)
+ except ValueError:
+ i = len(decomp_data)
+ decomp_data.extend(decomp)
+ decomp_size = decomp_size + len(decomp) * 2
+ else:
+ i = 0
+ decomp_index[char] = i
+
+ f = l = 0
+ comp_first_ranges = []
+ comp_last_ranges = []
+ prev_f = prev_l = None
+ for i in unicode.chars:
+ if comp_first[i] is not None:
+ comp_first[i] = f
+ f += 1
+ if prev_f is None:
+ prev_f = (i,i)
+ elif prev_f[1]+1 == i:
+ prev_f = prev_f[0],i
+ else:
+ comp_first_ranges.append(prev_f)
+ prev_f = (i,i)
+ if comp_last[i] is not None:
+ comp_last[i] = l
+ l += 1
+ if prev_l is None:
+ prev_l = (i,i)
+ elif prev_l[1]+1 == i:
+ prev_l = prev_l[0],i
+ else:
+ comp_last_ranges.append(prev_l)
+ prev_l = (i,i)
+ comp_first_ranges.append(prev_f)
+ comp_last_ranges.append(prev_l)
+ total_first = f
+ total_last = l
+
+ comp_data = [0]*(total_first*total_last)
+ for f,l,char in comp_pairs:
+ f = comp_first[f]
+ l = comp_last[l]
+ comp_data[f*total_last+l] = char
+
+ print len(table), "unique properties"
+ print len(decomp_prefix), "unique decomposition prefixes"
+ print len(decomp_data), "unique decomposition entries:",
+ print decomp_size, "bytes"
+ print total_first, "first characters in NFC"
+ print total_last, "last characters in NFC"
+ print len(comp_pairs), "NFC pairs"
+
+ print "--- Writing", FILE, "..."
+
+ fp = open(FILE, "w")
+ print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
+ print >>fp
+ print >>fp, '#define UNIDATA_VERSION "%s"' % UNIDATA_VERSION
+ print >>fp, "/* a list of unique database records */"
+ print >>fp, \
+ "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {"
+ for item in table:
+ print >>fp, " {%d, %d, %d, %d, %d, %d}," % item
+ print >>fp, "};"
+ print >>fp
+
+ print >>fp, "/* Reindexing of NFC first characters. */"
+ print >>fp, "#define TOTAL_FIRST",total_first
+ print >>fp, "#define TOTAL_LAST",total_last
+ print >>fp, "struct reindex{int start;short count,index;};"
+ print >>fp, "static struct reindex nfc_first[] = {"
+ for start,end in comp_first_ranges:
+ print >>fp," { %d, %d, %d}," % (start,end-start,comp_first[start])
+ print >>fp," {0,0,0}"
+ print >>fp,"};\n"
+ print >>fp, "static struct reindex nfc_last[] = {"
+ for start,end in comp_last_ranges:
+ print >>fp," { %d, %d, %d}," % (start,end-start,comp_last[start])
+ print >>fp," {0,0,0}"
+ print >>fp,"};\n"
+
+ # FIXME: <fl> the following tables could be made static, and
+ # the support code moved into unicodedatabase.c
+
+ print >>fp, "/* string literals */"
+ print >>fp, "const char *_PyUnicode_CategoryNames[] = {"
+ for name in CATEGORY_NAMES:
+ print >>fp, " \"%s\"," % name
+ print >>fp, " NULL"
+ print >>fp, "};"
+
+ print >>fp, "const char *_PyUnicode_BidirectionalNames[] = {"
+ for name in BIDIRECTIONAL_NAMES:
+ print >>fp, " \"%s\"," % name
+ print >>fp, " NULL"
+ print >>fp, "};"
+
+ print >>fp, "const char *_PyUnicode_EastAsianWidthNames[] = {"
+ for name in EASTASIANWIDTH_NAMES:
+ print >>fp, " \"%s\"," % name
+ print >>fp, " NULL"
+ print >>fp, "};"
+
+ print >>fp, "static const char *decomp_prefix[] = {"
+ for name in decomp_prefix:
+ print >>fp, " \"%s\"," % name
+ print >>fp, " NULL"
+ print >>fp, "};"
+
+ # split record index table
+ index1, index2, shift = splitbins(index, trace)
+
+ print >>fp, "/* index tables for the database records */"
+ print >>fp, "#define SHIFT", shift
+ Array("index1", index1).dump(fp, trace)
+ Array("index2", index2).dump(fp, trace)
+
+ # split decomposition index table
+ index1, index2, shift = splitbins(decomp_index, trace)
+
+ print >>fp, "/* decomposition data */"
+ Array("decomp_data", decomp_data).dump(fp, trace)
+
+ print >>fp, "/* index tables for the decomposition data */"
+ print >>fp, "#define DECOMP_SHIFT", shift
+ Array("decomp_index1", index1).dump(fp, trace)
+ Array("decomp_index2", index2).dump(fp, trace)
+
+ index, index2, shift = splitbins(comp_data, trace)
+ print >>fp, "/* NFC pairs */"
+ print >>fp, "#define COMP_SHIFT", shift
+ Array("comp_index", index).dump(fp, trace)
+ Array("comp_data", index2).dump(fp, trace)
+
+ # Generate delta tables for old versions
+ for version, table, normalization in unicode.changed:
+ cversion = version.replace(".","_")
+ records = [table[0]]
+ cache = {table[0]:0}
+ index = [0] * len(table)
+ for i, record in enumerate(table):
+ try:
+ index[i] = cache[record]
+ except KeyError:
+ index[i] = cache[record] = len(records)
+ records.append(record)
+ index1, index2, shift = splitbins(index, trace)
+ print >>fp, "static const change_record change_records_%s[] = {" % cversion
+ for record in records:
+ print >>fp, "\t{ %s }," % ", ".join(map(str,record))
+ print >>fp, "};"
+ Array("changes_%s_index" % cversion, index1).dump(fp, trace)
+ Array("changes_%s_data" % cversion, index2).dump(fp, trace)
+ print >>fp, "static const change_record* get_change_%s(Py_UCS4 n)" % cversion
+ print >>fp, "{"
+ print >>fp, "\tint index;"
+ print >>fp, "\tif (n >= 0x110000) index = 0;"
+ print >>fp, "\telse {"
+ print >>fp, "\t\tindex = changes_%s_index[n>>%d];" % (cversion, shift)
+ print >>fp, "\t\tindex = changes_%s_data[(index<<%d)+(n & %d)];" % \
+ (cversion, shift, ((1<<shift)-1))
+ print >>fp, "\t}"
+ print >>fp, "\treturn change_records_%s+index;" % cversion
+ print >>fp, "}\n"
+ print >>fp, "static Py_UCS4 normalization_%s(Py_UCS4 n)" % cversion
+ print >>fp, "{"
+ print >>fp, "\tswitch(n) {"
+ for k, v in normalization:
+ print >>fp, "\tcase %s: return 0x%s;" % (hex(k), v)
+ print >>fp, "\tdefault: return 0;"
+ print >>fp, "\t}\n}\n"
+
+ fp.close()
+
+# --------------------------------------------------------------------
+# unicode character type tables
+
+def makeunicodetype(unicode, trace):
+
+ FILE = "Objects/unicodetype_db.h"
+
+ print "--- Preparing", FILE, "..."
+
+ # extract unicode types
+ dummy = (0, 0, 0, 0, 0, 0)
+ table = [dummy]
+ cache = {0: dummy}
+ index = [0] * len(unicode.chars)
+ numeric = {}
+ spaces = []
+ linebreaks = []
+
+ for char in unicode.chars:
+ record = unicode.table[char]
+ if record:
+ # extract database properties
+ category = record[2]
+ bidirectional = record[4]
+ properties = record[16]
+ flags = 0
+ delta = True
+ if category in ["Lm", "Lt", "Lu", "Ll", "Lo"]:
+ flags |= ALPHA_MASK
+ if category == "Ll":
+ flags |= LOWER_MASK
+ if 'Line_Break' in properties or bidirectional == "B":
+ flags |= LINEBREAK_MASK
+ linebreaks.append(char)
+ if category == "Zs" or bidirectional in ("WS", "B", "S"):
+ flags |= SPACE_MASK
+ spaces.append(char)
+ if category == "Lt":
+ flags |= TITLE_MASK
+ if category == "Lu":
+ flags |= UPPER_MASK
+ # use delta predictor for upper/lower/title if it fits
+ if record[12]:
+ upper = int(record[12], 16)
+ else:
+ upper = char
+ if record[13]:
+ lower = int(record[13], 16)
+ else:
+ lower = char
+ if record[14]:
+ title = int(record[14], 16)
+ else:
+ # UCD.html says that a missing title char means that
+ # it defaults to the uppercase character, not to the
+ # character itself. Apparently, in the current UCD (5.x)
+ # this feature is never used
+ title = upper
+ upper_d = upper - char
+ lower_d = lower - char
+ title_d = title - char
+ if -32768 <= upper_d <= 32767 and \
+ -32768 <= lower_d <= 32767 and \
+ -32768 <= title_d <= 32767:
+ # use deltas
+ upper = upper_d & 0xffff
+ lower = lower_d & 0xffff
+ title = title_d & 0xffff
+ else:
+ flags |= NODELTA_MASK
+ # decimal digit, integer digit
+ decimal = 0
+ if record[6]:
+ flags |= DECIMAL_MASK
+ decimal = int(record[6])
+ digit = 0
+ if record[7]:
+ flags |= DIGIT_MASK
+ digit = int(record[7])
+ if record[8]:
+ flags |= NUMERIC_MASK
+ numeric.setdefault(record[8], []).append(char)
+ item = (
+ upper, lower, title, decimal, digit, flags
+ )
+ # add entry to index and item tables
+ i = cache.get(item)
+ if i is None:
+ cache[item] = i = len(table)
+ table.append(item)
+ index[char] = i
+
+ print len(table), "unique character type entries"
+ print sum(map(len, numeric.values())), "numeric code points"
+ print len(spaces), "whitespace code points"
+ print len(linebreaks), "linebreak code points"
+
+ print "--- Writing", FILE, "..."
+
+ fp = open(FILE, "w")
+ print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
+ print >>fp
+ print >>fp, "/* a list of unique character type descriptors */"
+ print >>fp, "const _PyUnicode_TypeRecord _PyUnicode_TypeRecords[] = {"
+ for item in table:
+ print >>fp, " {%d, %d, %d, %d, %d, %d}," % item
+ print >>fp, "};"
+ print >>fp
+
+ # split decomposition index table
+ index1, index2, shift = splitbins(index, trace)
+
+ print >>fp, "/* type indexes */"
+ print >>fp, "#define SHIFT", shift
+ Array("index1", index1).dump(fp, trace)
+ Array("index2", index2).dump(fp, trace)
+
+ # Generate code for _PyUnicode_ToNumeric()
+ numeric_items = sorted(numeric.items())
+ print >>fp, '/* Returns the numeric value as double for Unicode characters'
+ print >>fp, ' * having this property, -1.0 otherwise.'
+ print >>fp, ' */'
+ print >>fp, 'double _PyUnicode_ToNumeric(Py_UNICODE ch)'
+ print >>fp, '{'
+ print >>fp, ' switch (ch) {'
+ for value, codepoints in numeric_items:
+ # Turn text into float literals
+ parts = value.split('/')
+ parts = [repr(float(part)) for part in parts]
+ value = '/'.join(parts)
+
+ haswide = False
+ hasnonewide = False
+ codepoints.sort()
+ for codepoint in codepoints:
+ if codepoint < 0x10000:
+ hasnonewide = True
+ if codepoint >= 0x10000 and not haswide:
+ print >>fp, '#ifdef Py_UNICODE_WIDE'
+ haswide = True
+ print >>fp, ' case 0x%04X:' % (codepoint,)
+ if haswide and hasnonewide:
+ print >>fp, '#endif'
+ print >>fp, ' return (double) %s;' % (value,)
+ if haswide and not hasnonewide:
+ print >>fp, '#endif'
+ print >>fp,' }'
+ print >>fp,' return -1.0;'
+ print >>fp,'}'
+ print >>fp
+
+ # Generate code for _PyUnicode_IsWhitespace()
+ print >>fp, "/* Returns 1 for Unicode characters having the bidirectional"
+ print >>fp, " * type 'WS', 'B' or 'S' or the category 'Zs', 0 otherwise."
+ print >>fp, " */"
+ print >>fp, 'int _PyUnicode_IsWhitespace(register const Py_UNICODE ch)'
+ print >>fp, '{'
+ print >>fp, '#ifdef WANT_WCTYPE_FUNCTIONS'
+ print >>fp, ' return iswspace(ch);'
+ print >>fp, '#else'
+ print >>fp, ' switch (ch) {'
+
+ haswide = False
+ hasnonewide = False
+ for codepoint in sorted(spaces):
+ if codepoint < 0x10000:
+ hasnonewide = True
+ if codepoint >= 0x10000 and not haswide:
+ print >>fp, '#ifdef Py_UNICODE_WIDE'
+ haswide = True
+ print >>fp, ' case 0x%04X:' % (codepoint,)
+ if haswide and hasnonewide:
+ print >>fp, '#endif'
+ print >>fp, ' return 1;'
+ if haswide and not hasnonewide:
+ print >>fp, '#endif'
+
+ print >>fp,' }'
+ print >>fp,' return 0;'
+ print >>fp, '#endif'
+ print >>fp,'}'
+ print >>fp
+
+ # Generate code for _PyUnicode_IsLinebreak()
+ print >>fp, "/* Returns 1 for Unicode characters having the line break"
+ print >>fp, " * property 'BK', 'CR', 'LF' or 'NL' or having bidirectional"
+ print >>fp, " * type 'B', 0 otherwise."
+ print >>fp, " */"
+ print >>fp, 'int _PyUnicode_IsLinebreak(register const Py_UNICODE ch)'
+ print >>fp, '{'
+ print >>fp, ' switch (ch) {'
+ haswide = False
+ hasnonewide = False
+ for codepoint in sorted(linebreaks):
+ if codepoint < 0x10000:
+ hasnonewide = True
+ if codepoint >= 0x10000 and not haswide:
+ print >>fp, '#ifdef Py_UNICODE_WIDE'
+ haswide = True
+ print >>fp, ' case 0x%04X:' % (codepoint,)
+ if haswide and hasnonewide:
+ print >>fp, '#endif'
+ print >>fp, ' return 1;'
+ if haswide and not hasnonewide:
+ print >>fp, '#endif'
+
+ print >>fp,' }'
+ print >>fp,' return 0;'
+ print >>fp,'}'
+ print >>fp
+
+ fp.close()
+
+# --------------------------------------------------------------------
+# unicode name database
+
+def makeunicodename(unicode, trace):
+
+ FILE = "Modules/unicodename_db.h"
+
+ print "--- Preparing", FILE, "..."
+
+ # collect names
+ names = [None] * len(unicode.chars)
+
+ for char in unicode.chars:
+ record = unicode.table[char]
+ if record:
+ name = record[1].strip()
+ if name and name[0] != "<":
+ names[char] = name + chr(0)
+
+ print len(filter(lambda n: n is not None, names)), "distinct names"
+
+ # collect unique words from names (note that we differ between
+ # words inside a sentence, and words ending a sentence. the
+ # latter includes the trailing null byte.
+
+ words = {}
+ n = b = 0
+ for char in unicode.chars:
+ name = names[char]
+ if name:
+ w = name.split()
+ b = b + len(name)
+ n = n + len(w)
+ for w in w:
+ l = words.get(w)
+ if l:
+ l.append(None)
+ else:
+ words[w] = [len(words)]
+
+ print n, "words in text;", b, "bytes"
+
+ wordlist = words.items()
+
+ # sort on falling frequency, then by name
+ def word_key(a):
+ aword, alist = a
+ return -len(alist), aword
+ wordlist.sort(key=word_key)
+
+ # figure out how many phrasebook escapes we need
+ escapes = 0
+ while escapes * 256 < len(wordlist):
+ escapes = escapes + 1
+ print escapes, "escapes"
+
+ short = 256 - escapes
+
+ assert short > 0
+
+ print short, "short indexes in lexicon"
+
+ # statistics
+ n = 0
+ for i in range(short):
+ n = n + len(wordlist[i][1])
+ print n, "short indexes in phrasebook"
+
+ # pick the most commonly used words, and sort the rest on falling
+ # length (to maximize overlap)
+
+ wordlist, wordtail = wordlist[:short], wordlist[short:]
+ wordtail.sort(key=lambda a: a[0], reverse=True)
+ wordlist.extend(wordtail)
+
+ # generate lexicon from words
+
+ lexicon_offset = [0]
+ lexicon = ""
+ words = {}
+
+ # build a lexicon string
+ offset = 0
+ for w, x in wordlist:
+ # encoding: bit 7 indicates last character in word (chr(128)
+ # indicates the last character in an entire string)
+ ww = w[:-1] + chr(ord(w[-1])+128)
+ # reuse string tails, when possible
+ o = lexicon.find(ww)
+ if o < 0:
+ o = offset
+ lexicon = lexicon + ww
+ offset = offset + len(w)
+ words[w] = len(lexicon_offset)
+ lexicon_offset.append(o)
+
+ lexicon = map(ord, lexicon)
+
+ # generate phrasebook from names and lexicon
+ phrasebook = [0]
+ phrasebook_offset = [0] * len(unicode.chars)
+ for char in unicode.chars:
+ name = names[char]
+ if name:
+ w = name.split()
+ phrasebook_offset[char] = len(phrasebook)
+ for w in w:
+ i = words[w]
+ if i < short:
+ phrasebook.append(i)
+ else:
+ # store as two bytes
+ phrasebook.append((i>>8) + short)
+ phrasebook.append(i&255)
+
+ assert getsize(phrasebook) == 1
+
+ #
+ # unicode name hash table
+
+ # extract names
+ data = []
+ for char in unicode.chars:
+ record = unicode.table[char]
+ if record:
+ name = record[1].strip()
+ if name and name[0] != "<":
+ data.append((name, char))
+
+ # the magic number 47 was chosen to minimize the number of
+ # collisions on the current data set. if you like, change it
+ # and see what happens...
+
+ codehash = Hash("code", data, 47)
+
+ print "--- Writing", FILE, "..."
+
+ fp = open(FILE, "w")
+ print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
+ print >>fp
+ print >>fp, "#define NAME_MAXLEN", 256
+ print >>fp
+ print >>fp, "/* lexicon */"
+ Array("lexicon", lexicon).dump(fp, trace)
+ Array("lexicon_offset", lexicon_offset).dump(fp, trace)
+
+ # split decomposition index table
+ offset1, offset2, shift = splitbins(phrasebook_offset, trace)
+
+ print >>fp, "/* code->name phrasebook */"
+ print >>fp, "#define phrasebook_shift", shift
+ print >>fp, "#define phrasebook_short", short
+
+ Array("phrasebook", phrasebook).dump(fp, trace)
+ Array("phrasebook_offset1", offset1).dump(fp, trace)
+ Array("phrasebook_offset2", offset2).dump(fp, trace)
+
+ print >>fp, "/* name->code dictionary */"
+ codehash.dump(fp, trace)
+
+ fp.close()
+
+
+def merge_old_version(version, new, old):
+ # Changes to exclusion file not implemented yet
+ if old.exclusions != new.exclusions:
+ raise NotImplementedError, "exclusions differ"
+
+ # In these change records, 0xFF means "no change"
+ bidir_changes = [0xFF]*0x110000
+ category_changes = [0xFF]*0x110000
+ decimal_changes = [0xFF]*0x110000
+ mirrored_changes = [0xFF]*0x110000
+ # In numeric data, 0 means "no change",
+ # -1 means "did not have a numeric value
+ numeric_changes = [0] * 0x110000
+ # normalization_changes is a list of key-value pairs
+ normalization_changes = []
+ for i in range(0x110000):
+ if new.table[i] is None:
+ # Characters unassigned in the new version ought to
+ # be unassigned in the old one
+ assert old.table[i] is None
+ continue
+ # check characters unassigned in the old version
+ if old.table[i] is None:
+ # category 0 is "unassigned"
+ category_changes[i] = 0
+ continue
+ # check characters that differ
+ if old.table[i] != new.table[i]:
+ for k in range(len(old.table[i])):
+ if old.table[i][k] != new.table[i][k]:
+ value = old.table[i][k]
+ if k == 2:
+ #print "CATEGORY",hex(i), old.table[i][k], new.table[i][k]
+ category_changes[i] = CATEGORY_NAMES.index(value)
+ elif k == 4:
+ #print "BIDIR",hex(i), old.table[i][k], new.table[i][k]
+ bidir_changes[i] = BIDIRECTIONAL_NAMES.index(value)
+ elif k == 5:
+ #print "DECOMP",hex(i), old.table[i][k], new.table[i][k]
+ # We assume that all normalization changes are in 1:1 mappings
+ assert " " not in value
+ normalization_changes.append((i, value))
+ elif k == 6:
+ #print "DECIMAL",hex(i), old.table[i][k], new.table[i][k]
+ # we only support changes where the old value is a single digit
+ assert value in "0123456789"
+ decimal_changes[i] = int(value)
+ elif k == 8:
+ # print "NUMERIC",hex(i), `old.table[i][k]`, new.table[i][k]
+ # Since 0 encodes "no change", the old value is better not 0
+ if not value:
+ numeric_changes[i] = -1
+ else:
+ numeric_changes[i] = float(value)
+ assert numeric_changes[i] not in (0, -1)
+ elif k == 9:
+ if value == 'Y':
+ mirrored_changes[i] = '1'
+ else:
+ mirrored_changes[i] = '0'
+ elif k == 11:
+ # change to ISO comment, ignore
+ pass
+ elif k == 12:
+ # change to simple uppercase mapping; ignore
+ pass
+ elif k == 13:
+ # change to simple lowercase mapping; ignore
+ pass
+ elif k == 14:
+ # change to simple titlecase mapping; ignore
+ pass
+ elif k == 16:
+ # change to properties; not yet
+ pass
+ else:
+ class Difference(Exception):pass
+ raise Difference, (hex(i), k, old.table[i], new.table[i])
+ new.changed.append((version, zip(bidir_changes, category_changes,
+ decimal_changes, mirrored_changes,
+ numeric_changes),
+ normalization_changes))
+
+
+# --------------------------------------------------------------------
+# the following support code is taken from the unidb utilities
+# Copyright (c) 1999-2000 by Secret Labs AB
+
+# load a unicode-data file from disk
+
+class UnicodeData:
+ # Record structure:
+ # [ID, name, category, combining, bidi, decomp, (6)
+ # decimal, digit, numeric, bidi-mirrored, Unicode-1-name, (11)
+ # ISO-comment, uppercase, lowercase, titlecase, ea-width, (16)
+ # properties] (17)
+
+ def __init__(self, filename, exclusions, eastasianwidth, unihan,
+ derivednormalizationprops=None, linebreakprops=None,
+ expand=1):
+ self.changed = []
+ file = open(filename)
+ table = [None] * 0x110000
+ while 1:
+ s = file.readline()
+ if not s:
+ break
+ s = s.strip().split(";")
+ char = int(s[0], 16)
+ table[char] = s
+
+ # expand first-last ranges
+ if expand:
+ field = None
+ for i in range(0, 0x110000):
+ s = table[i]
+ if s:
+ if s[1][-6:] == "First>":
+ s[1] = ""
+ field = s
+ elif s[1][-5:] == "Last>":
+ s[1] = ""
+ field = None
+ elif field:
+ f2 = field[:]
+ f2[0] = "%X" % i
+ table[i] = f2
+
+ # public attributes
+ self.filename = filename
+ self.table = table
+ self.chars = range(0x110000) # unicode 3.2
+
+ file = open(exclusions)
+ self.exclusions = {}
+ for s in file:
+ s = s.strip()
+ if not s:
+ continue
+ if s[0] == '#':
+ continue
+ char = int(s.split()[0],16)
+ self.exclusions[char] = 1
+
+ widths = [None] * 0x110000
+ for s in open(eastasianwidth):
+ s = s.strip()
+ if not s:
+ continue
+ if s[0] == '#':
+ continue
+ s = s.split()[0].split(';')
+ if '..' in s[0]:
+ first, last = [int(c, 16) for c in s[0].split('..')]
+ chars = range(first, last+1)
+ else:
+ chars = [int(s[0], 16)]
+ for char in chars:
+ widths[char] = s[1]
+ for i in range(0, 0x110000):
+ if table[i] is not None:
+ table[i].append(widths[i])
+
+ for i in range(0, 0x110000):
+ if table[i] is not None:
+ table[i].append(set())
+ if linebreakprops:
+ for s in open(linebreakprops):
+ s = s.partition('#')[0]
+ s = [i.strip() for i in s.split(';')]
+ if len(s) < 2 or s[1] not in MANDATORY_LINE_BREAKS:
+ continue
+ if '..' not in s[0]:
+ first = last = int(s[0], 16)
+ else:
+ first, last = [int(c, 16) for c in s[0].split('..')]
+ for char in range(first, last+1):
+ table[char][-1].add('Line_Break')
+
+ if derivednormalizationprops:
+ quickchecks = [0] * 0x110000 # default is Yes
+ qc_order = 'NFD_QC NFKD_QC NFC_QC NFKC_QC'.split()
+ for s in open(derivednormalizationprops):
+ if '#' in s:
+ s = s[:s.index('#')]
+ s = [i.strip() for i in s.split(';')]
+ if len(s) < 2 or s[1] not in qc_order:
+ continue
+ quickcheck = 'MN'.index(s[2]) + 1 # Maybe or No
+ quickcheck_shift = qc_order.index(s[1])*2
+ quickcheck <<= quickcheck_shift
+ if '..' not in s[0]:
+ first = last = int(s[0], 16)
+ else:
+ first, last = [int(c, 16) for c in s[0].split('..')]
+ for char in range(first, last+1):
+ assert not (quickchecks[char]>>quickcheck_shift)&3
+ quickchecks[char] |= quickcheck
+ for i in range(0, 0x110000):
+ if table[i] is not None:
+ table[i].append(quickchecks[i])
+
+ for line in open(unihan):
+ if not line.startswith('U+'):
+ continue
+ code, tag, value = line.split(None, 3)[:3]
+ if tag not in ('kAccountingNumeric', 'kPrimaryNumeric',
+ 'kOtherNumeric'):
+ continue
+ value = value.strip().replace(',', '')
+ i = int(code[2:], 16)
+ # Patch the numeric field
+ if table[i] is not None:
+ table[i][8] = value
+
+ def uselatin1(self):
+ # restrict character range to ISO Latin 1
+ self.chars = range(256)
+
+# hash table tools
+
+# this is a straight-forward reimplementation of Python's built-in
+# dictionary type, using a static data structure, and a custom string
+# hash algorithm.
+
+def myhash(s, magic):
+ h = 0
+ for c in map(ord, s.upper()):
+ h = (h * magic) + c
+ ix = h & 0xff000000L
+ if ix:
+ h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff
+ return h
+
+SIZES = [
+ (4,3), (8,3), (16,3), (32,5), (64,3), (128,3), (256,29), (512,17),
+ (1024,9), (2048,5), (4096,83), (8192,27), (16384,43), (32768,3),
+ (65536,45), (131072,9), (262144,39), (524288,39), (1048576,9),
+ (2097152,5), (4194304,3), (8388608,33), (16777216,27)
+]
+
+class Hash:
+ def __init__(self, name, data, magic):
+ # turn a (key, value) list into a static hash table structure
+
+ # determine table size
+ for size, poly in SIZES:
+ if size > len(data):
+ poly = size + poly
+ break
+ else:
+ raise AssertionError, "ran out of polynominals"
+
+ print size, "slots in hash table"
+
+ table = [None] * size
+
+ mask = size-1
+
+ n = 0
+
+ hash = myhash
+
+ # initialize hash table
+ for key, value in data:
+ h = hash(key, magic)
+ i = (~h) & mask
+ v = table[i]
+ if v is None:
+ table[i] = value
+ continue
+ incr = (h ^ (h >> 3)) & mask;
+ if not incr:
+ incr = mask
+ while 1:
+ n = n + 1
+ i = (i + incr) & mask
+ v = table[i]
+ if v is None:
+ table[i] = value
+ break
+ incr = incr << 1
+ if incr > mask:
+ incr = incr ^ poly
+
+ print n, "collisions"
+ self.collisions = n
+
+ for i in range(len(table)):
+ if table[i] is None:
+ table[i] = 0
+
+ self.data = Array(name + "_hash", table)
+ self.magic = magic
+ self.name = name
+ self.size = size
+ self.poly = poly
+
+ def dump(self, file, trace):
+ # write data to file, as a C array
+ self.data.dump(file, trace)
+ file.write("#define %s_magic %d\n" % (self.name, self.magic))
+ file.write("#define %s_size %d\n" % (self.name, self.size))
+ file.write("#define %s_poly %d\n" % (self.name, self.poly))
+
+# stuff to deal with arrays of unsigned integers
+
+class Array:
+
+ def __init__(self, name, data):
+ self.name = name
+ self.data = data
+
+ def dump(self, file, trace=0):
+ # write data to file, as a C array
+ size = getsize(self.data)
+ if trace:
+ print >>sys.stderr, self.name+":", size*len(self.data), "bytes"
+ file.write("static ")
+ if size == 1:
+ file.write("unsigned char")
+ elif size == 2:
+ file.write("unsigned short")
+ else:
+ file.write("unsigned int")
+ file.write(" " + self.name + "[] = {\n")
+ if self.data:
+ s = " "
+ for item in self.data:
+ i = str(item) + ", "
+ if len(s) + len(i) > 78:
+ file.write(s + "\n")
+ s = " " + i
+ else:
+ s = s + i
+ if s.strip():
+ file.write(s + "\n")
+ file.write("};\n\n")
+
+def getsize(data):
+ # return smallest possible integer size for the given array
+ maxdata = max(data)
+ if maxdata < 256:
+ return 1
+ elif maxdata < 65536:
+ return 2
+ else:
+ return 4
+
+def splitbins(t, trace=0):
+ """t, trace=0 -> (t1, t2, shift). Split a table to save space.
+
+ t is a sequence of ints. This function can be useful to save space if
+ many of the ints are the same. t1 and t2 are lists of ints, and shift
+ is an int, chosen to minimize the combined size of t1 and t2 (in C
+ code), and where for each i in range(len(t)),
+ t[i] == t2[(t1[i >> shift] << shift) + (i & mask)]
+ where mask is a bitmask isolating the last "shift" bits.
+
+ If optional arg trace is non-zero (default zero), progress info
+ is printed to sys.stderr. The higher the value, the more info
+ you'll get.
+ """
+
+ if trace:
+ def dump(t1, t2, shift, bytes):
+ print >>sys.stderr, "%d+%d bins at shift %d; %d bytes" % (
+ len(t1), len(t2), shift, bytes)
+ print >>sys.stderr, "Size of original table:", len(t)*getsize(t), \
+ "bytes"
+ n = len(t)-1 # last valid index
+ maxshift = 0 # the most we can shift n and still have something left
+ if n > 0:
+ while n >> 1:
+ n >>= 1
+ maxshift += 1
+ del n
+ bytes = sys.maxint # smallest total size so far
+ t = tuple(t) # so slices can be dict keys
+ for shift in range(maxshift + 1):
+ t1 = []
+ t2 = []
+ size = 2**shift
+ bincache = {}
+ for i in range(0, len(t), size):
+ bin = t[i:i+size]
+ index = bincache.get(bin)
+ if index is None:
+ index = len(t2)
+ bincache[bin] = index
+ t2.extend(bin)
+ t1.append(index >> shift)
+ # determine memory size
+ b = len(t1)*getsize(t1) + len(t2)*getsize(t2)
+ if trace > 1:
+ dump(t1, t2, shift, b)
+ if b < bytes:
+ best = t1, t2, shift
+ bytes = b
+ t1, t2, shift = best
+ if trace:
+ print >>sys.stderr, "Best:",
+ dump(t1, t2, shift, bytes)
+ if __debug__:
+ # exhaustively verify that the decomposition is correct
+ mask = ~((~0) << shift) # i.e., low-bit mask of shift bits
+ for i in xrange(len(t)):
+ assert t[i] == t2[(t1[i >> shift] << shift) + (i & mask)]
+ return best
+
+if __name__ == "__main__":
+ maketables(1)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/mkstringprep.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/mkstringprep.py
new file mode 100644
index 0000000000..49d1393386
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/mkstringprep.py
@@ -0,0 +1,425 @@
+import re, unicodedata, sys
+
+if sys.maxunicode == 65535:
+ raise RuntimeError("need UCS-4 Python")
+
+def gen_category(cats):
+ for i in range(0, 0x110000):
+ if unicodedata.category(unichr(i)) in cats:
+ yield(i)
+
+def gen_bidirectional(cats):
+ for i in range(0, 0x110000):
+ if unicodedata.bidirectional(unichr(i)) in cats:
+ yield(i)
+
+def compact_set(l):
+ single = []
+ tuple = []
+ prev = None
+ span = 0
+ for e in l:
+ if prev is None:
+ prev = e
+ span = 0
+ continue
+ if prev+span+1 != e:
+ if span > 2:
+ tuple.append((prev,prev+span+1))
+ else:
+ for i in range(prev, prev+span+1):
+ single.append(i)
+ prev = e
+ span = 0
+ else:
+ span += 1
+ if span:
+ tuple.append((prev,prev+span+1))
+ else:
+ single.append(prev)
+ tuple = " + ".join(["range(%d,%d)" % t for t in tuple])
+ if not single:
+ return "set(%s)" % tuple
+ if not tuple:
+ return "set(%s)" % repr(single)
+ return "set(%s + %s)" % (repr(single),tuple)
+
+############## Read the tables in the RFC #######################
+
+data = open("rfc3454.txt").readlines()
+
+tables = []
+curname = None
+for l in data:
+ l = l.strip()
+ if not l:
+ continue
+ # Skip RFC page breaks
+ if l.startswith("Hoffman & Blanchet") or\
+ l.startswith("RFC 3454"):
+ continue
+ # Find start/end lines
+ m = re.match("----- (Start|End) Table ([A-Z](.[0-9])+) -----", l)
+ if m:
+ if m.group(1) == "Start":
+ if curname:
+ raise RuntimeError("Double Start", (curname, l))
+ curname = m.group(2)
+ table = {}
+ tables.append((curname, table))
+ continue
+ else:
+ if not curname:
+ raise RuntimeError("End without start", l)
+ curname = None
+ continue
+ if not curname:
+ continue
+ # Now we are in a table
+ fields = l.split(";")
+ if len(fields) > 1:
+ # Drop comment field
+ fields = fields[:-1]
+ if len(fields) == 1:
+ fields = fields[0].split("-")
+ if len(fields) > 1:
+ # range
+ try:
+ start, end = fields
+ except ValueError:
+ raise RuntimeError("Unpacking problem", l)
+ else:
+ start = end = fields[0]
+ start = int(start, 16)
+ end = int(end, 16)
+ for i in range(start, end+1):
+ table[i] = i
+ else:
+ code, value = fields
+ value = value.strip()
+ if value:
+ value = [int(v, 16) for v in value.split(" ")]
+ else:
+ # table B.1
+ value = None
+ table[int(code, 16)] = value
+
+########### Generate compact Python versions of the tables #############
+
+print """# This file is generated by mkstringprep.py. DO NOT EDIT.
+\"\"\"Library that exposes various tables found in the StringPrep RFC 3454.
+
+There are two kinds of tables: sets, for which a member test is provided,
+and mappings, for which a mapping function is provided.
+\"\"\"
+
+import unicodedata
+"""
+
+print "assert unicodedata.unidata_version == %s" % repr(unicodedata.unidata_version)
+
+# A.1 is the table of unassigned characters
+# XXX Plane 15 PUA is listed as unassigned in Python.
+name, table = tables[0]
+del tables[0]
+assert name == "A.1"
+table = set(table.keys())
+Cn = set(gen_category(["Cn"]))
+
+# FDD0..FDEF are process internal codes
+Cn -= set(range(0xFDD0, 0xFDF0))
+# not a character
+Cn -= set(range(0xFFFE, 0x110000, 0x10000))
+Cn -= set(range(0xFFFF, 0x110000, 0x10000))
+
+# assert table == Cn
+
+print """
+def in_table_a1(code):
+ if unicodedata.category(code) != 'Cn': return False
+ c = ord(code)
+ if 0xFDD0 <= c < 0xFDF0: return False
+ return (c & 0xFFFF) not in (0xFFFE, 0xFFFF)
+"""
+
+# B.1 cannot easily be derived
+name, table = tables[0]
+del tables[0]
+assert name == "B.1"
+table = sorted(table.keys())
+print """
+b1_set = """ + compact_set(table) + """
+def in_table_b1(code):
+ return ord(code) in b1_set
+"""
+
+# B.2 and B.3 is case folding.
+# It takes CaseFolding.txt into account, which is
+# not available in the Python database. Since
+# B.2 is derived from B.3, we process B.3 first.
+# B.3 supposedly *is* CaseFolding-3.2.0.txt.
+
+name, table_b2 = tables[0]
+del tables[0]
+assert name == "B.2"
+
+name, table_b3 = tables[0]
+del tables[0]
+assert name == "B.3"
+
+# B.3 is mostly Python's .lower, except for a number
+# of special cases, e.g. considering canonical forms.
+
+b3_exceptions = {}
+
+for k,v in table_b2.items():
+ if map(ord, unichr(k).lower()) != v:
+ b3_exceptions[k] = u"".join(map(unichr,v))
+
+b3 = sorted(b3_exceptions.items())
+
+print """
+b3_exceptions = {"""
+for i,(k,v) in enumerate(b3):
+ print "0x%x:%s," % (k, repr(v)),
+ if i % 4 == 3:
+ print
+print "}"
+
+print """
+def map_table_b3(code):
+ r = b3_exceptions.get(ord(code))
+ if r is not None: return r
+ return code.lower()
+"""
+
+def map_table_b3(code):
+ r = b3_exceptions.get(ord(code))
+ if r is not None: return r
+ return code.lower()
+
+# B.2 is case folding for NFKC. This is the same as B.3,
+# except where NormalizeWithKC(Fold(a)) !=
+# NormalizeWithKC(Fold(NormalizeWithKC(Fold(a))))
+
+def map_table_b2(a):
+ al = map_table_b3(a)
+ b = unicodedata.normalize("NFKC", al)
+ bl = u"".join([map_table_b3(ch) for ch in b])
+ c = unicodedata.normalize("NFKC", bl)
+ if b != c:
+ return c
+ else:
+ return al
+
+specials = {}
+for k,v in table_b2.items():
+ if map(ord, map_table_b2(unichr(k))) != v:
+ specials[k] = v
+
+# B.3 should not add any additional special cases
+assert specials == {}
+
+print """
+def map_table_b2(a):
+ al = map_table_b3(a)
+ b = unicodedata.normalize("NFKC", al)
+ bl = u"".join([map_table_b3(ch) for ch in b])
+ c = unicodedata.normalize("NFKC", bl)
+ if b != c:
+ return c
+ else:
+ return al
+"""
+
+# C.1.1 is a table with a single character
+name, table = tables[0]
+del tables[0]
+assert name == "C.1.1"
+assert table == {0x20:0x20}
+
+print """
+def in_table_c11(code):
+ return code == u" "
+"""
+
+# C.1.2 is the rest of all space characters
+name, table = tables[0]
+del tables[0]
+assert name == "C.1.2"
+
+# table = set(table.keys())
+# Zs = set(gen_category(["Zs"])) - set([0x20])
+# assert Zs == table
+
+print """
+def in_table_c12(code):
+ return unicodedata.category(code) == "Zs" and code != u" "
+
+def in_table_c11_c12(code):
+ return unicodedata.category(code) == "Zs"
+"""
+
+# C.2.1 ASCII control characters
+name, table_c21 = tables[0]
+del tables[0]
+assert name == "C.2.1"
+
+Cc = set(gen_category(["Cc"]))
+Cc_ascii = Cc & set(range(128))
+table_c21 = set(table_c21.keys())
+assert Cc_ascii == table_c21
+
+print """
+def in_table_c21(code):
+ return ord(code) < 128 and unicodedata.category(code) == "Cc"
+"""
+
+# C.2.2 Non-ASCII control characters. It also includes
+# a number of characters in category Cf.
+name, table_c22 = tables[0]
+del tables[0]
+assert name == "C.2.2"
+
+Cc_nonascii = Cc - Cc_ascii
+table_c22 = set(table_c22.keys())
+assert len(Cc_nonascii - table_c22) == 0
+
+specials = list(table_c22 - Cc_nonascii)
+specials.sort()
+
+print """c22_specials = """ + compact_set(specials) + """
+def in_table_c22(code):
+ c = ord(code)
+ if c < 128: return False
+ if unicodedata.category(code) == "Cc": return True
+ return c in c22_specials
+
+def in_table_c21_c22(code):
+ return unicodedata.category(code) == "Cc" or \\
+ ord(code) in c22_specials
+"""
+
+# C.3 Private use
+name, table = tables[0]
+del tables[0]
+assert name == "C.3"
+
+Co = set(gen_category(["Co"]))
+assert set(table.keys()) == Co
+
+print """
+def in_table_c3(code):
+ return unicodedata.category(code) == "Co"
+"""
+
+# C.4 Non-character code points, xFFFE, xFFFF
+# plus process internal codes
+name, table = tables[0]
+del tables[0]
+assert name == "C.4"
+
+nonchar = set(range(0xFDD0,0xFDF0) +
+ range(0xFFFE,0x110000,0x10000) +
+ range(0xFFFF,0x110000,0x10000))
+table = set(table.keys())
+assert table == nonchar
+
+print """
+def in_table_c4(code):
+ c = ord(code)
+ if c < 0xFDD0: return False
+ if c < 0xFDF0: return True
+ return (ord(code) & 0xFFFF) in (0xFFFE, 0xFFFF)
+"""
+
+# C.5 Surrogate codes
+name, table = tables[0]
+del tables[0]
+assert name == "C.5"
+
+Cs = set(gen_category(["Cs"]))
+assert set(table.keys()) == Cs
+
+print """
+def in_table_c5(code):
+ return unicodedata.category(code) == "Cs"
+"""
+
+# C.6 Inappropriate for plain text
+name, table = tables[0]
+del tables[0]
+assert name == "C.6"
+
+table = sorted(table.keys())
+
+print """
+c6_set = """ + compact_set(table) + """
+def in_table_c6(code):
+ return ord(code) in c6_set
+"""
+
+# C.7 Inappropriate for canonical representation
+name, table = tables[0]
+del tables[0]
+assert name == "C.7"
+
+table = sorted(table.keys())
+
+print """
+c7_set = """ + compact_set(table) + """
+def in_table_c7(code):
+ return ord(code) in c7_set
+"""
+
+# C.8 Change display properties or are deprecated
+name, table = tables[0]
+del tables[0]
+assert name == "C.8"
+
+table = sorted(table.keys())
+
+print """
+c8_set = """ + compact_set(table) + """
+def in_table_c8(code):
+ return ord(code) in c8_set
+"""
+
+# C.9 Tagging characters
+name, table = tables[0]
+del tables[0]
+assert name == "C.9"
+
+table = sorted(table.keys())
+
+print """
+c9_set = """ + compact_set(table) + """
+def in_table_c9(code):
+ return ord(code) in c9_set
+"""
+
+# D.1 Characters with bidirectional property "R" or "AL"
+name, table = tables[0]
+del tables[0]
+assert name == "D.1"
+
+RandAL = set(gen_bidirectional(["R","AL"]))
+assert set(table.keys()) == RandAL
+
+print """
+def in_table_d1(code):
+ return unicodedata.bidirectional(code) in ("R","AL")
+"""
+
+# D.2 Characters with bidirectional property "L"
+name, table = tables[0]
+del tables[0]
+assert name == "D.2"
+
+L = set(gen_bidirectional(["L"]))
+assert set(table.keys()) == L
+
+print """
+def in_table_d2(code):
+ return unicodedata.bidirectional(code) == "L"
+"""
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/CP1140.TXT b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/CP1140.TXT
new file mode 100644
index 0000000000..68e0fdc3d2
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/CP1140.TXT
@@ -0,0 +1,291 @@
+#
+# Name: CP1140
+# Unicode version: 3.2
+# Table version: 1.0
+# Table format: Format A
+# Date: 2005-10-25
+# Authors: Marc-Andre Lemburg <mal@egenix.com>
+#
+# This encoding is a modified CP037 encoding (with added Euro
+# currency sign).
+#
+# (c) Copyright Marc-Andre Lemburg, 2005.
+# Licensed to PSF under a Contributor Agreement.
+#
+# Based on the file
+# ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/EBCDIC/CP037.TXT
+# which is:
+#
+# Copyright (c) 2002 Unicode, Inc. All Rights reserved.
+#
+# This file is provided as-is by Unicode, Inc. (The Unicode Consortium).
+# No claims are made as to fitness for any particular purpose. No
+# warranties of any kind are expressed or implied. The recipient
+# agrees to determine applicability of information provided. If this
+# file has been provided on optical media by Unicode, Inc., the sole
+# remedy for any claim will be exchange of defective media within 90
+# days of receipt.
+#
+# Unicode, Inc. hereby grants the right to freely use the information
+# supplied in this file in the creation of products supporting the
+# Unicode Standard, and to make copies of this file in any form for
+# internal or external distribution as long as this notice remains
+# attached.
+#
+0x00 0x0000 #NULL
+0x01 0x0001 #START OF HEADING
+0x02 0x0002 #START OF TEXT
+0x03 0x0003 #END OF TEXT
+0x04 0x009C #CONTROL
+0x05 0x0009 #HORIZONTAL TABULATION
+0x06 0x0086 #CONTROL
+0x07 0x007F #DELETE
+0x08 0x0097 #CONTROL
+0x09 0x008D #CONTROL
+0x0A 0x008E #CONTROL
+0x0B 0x000B #VERTICAL TABULATION
+0x0C 0x000C #FORM FEED
+0x0D 0x000D #CARRIAGE RETURN
+0x0E 0x000E #SHIFT OUT
+0x0F 0x000F #SHIFT IN
+0x10 0x0010 #DATA LINK ESCAPE
+0x11 0x0011 #DEVICE CONTROL ONE
+0x12 0x0012 #DEVICE CONTROL TWO
+0x13 0x0013 #DEVICE CONTROL THREE
+0x14 0x009D #CONTROL
+0x15 0x0085 #CONTROL
+0x16 0x0008 #BACKSPACE
+0x17 0x0087 #CONTROL
+0x18 0x0018 #CANCEL
+0x19 0x0019 #END OF MEDIUM
+0x1A 0x0092 #CONTROL
+0x1B 0x008F #CONTROL
+0x1C 0x001C #FILE SEPARATOR
+0x1D 0x001D #GROUP SEPARATOR
+0x1E 0x001E #RECORD SEPARATOR
+0x1F 0x001F #UNIT SEPARATOR
+0x20 0x0080 #CONTROL
+0x21 0x0081 #CONTROL
+0x22 0x0082 #CONTROL
+0x23 0x0083 #CONTROL
+0x24 0x0084 #CONTROL
+0x25 0x000A #LINE FEED
+0x26 0x0017 #END OF TRANSMISSION BLOCK
+0x27 0x001B #ESCAPE
+0x28 0x0088 #CONTROL
+0x29 0x0089 #CONTROL
+0x2A 0x008A #CONTROL
+0x2B 0x008B #CONTROL
+0x2C 0x008C #CONTROL
+0x2D 0x0005 #ENQUIRY
+0x2E 0x0006 #ACKNOWLEDGE
+0x2F 0x0007 #BELL
+0x30 0x0090 #CONTROL
+0x31 0x0091 #CONTROL
+0x32 0x0016 #SYNCHRONOUS IDLE
+0x33 0x0093 #CONTROL
+0x34 0x0094 #CONTROL
+0x35 0x0095 #CONTROL
+0x36 0x0096 #CONTROL
+0x37 0x0004 #END OF TRANSMISSION
+0x38 0x0098 #CONTROL
+0x39 0x0099 #CONTROL
+0x3A 0x009A #CONTROL
+0x3B 0x009B #CONTROL
+0x3C 0x0014 #DEVICE CONTROL FOUR
+0x3D 0x0015 #NEGATIVE ACKNOWLEDGE
+0x3E 0x009E #CONTROL
+0x3F 0x001A #SUBSTITUTE
+0x40 0x0020 #SPACE
+0x41 0x00A0 #NO-BREAK SPACE
+0x42 0x00E2 #LATIN SMALL LETTER A WITH CIRCUMFLEX
+0x43 0x00E4 #LATIN SMALL LETTER A WITH DIAERESIS
+0x44 0x00E0 #LATIN SMALL LETTER A WITH GRAVE
+0x45 0x00E1 #LATIN SMALL LETTER A WITH ACUTE
+0x46 0x00E3 #LATIN SMALL LETTER A WITH TILDE
+0x47 0x00E5 #LATIN SMALL LETTER A WITH RING ABOVE
+0x48 0x00E7 #LATIN SMALL LETTER C WITH CEDILLA
+0x49 0x00F1 #LATIN SMALL LETTER N WITH TILDE
+0x4A 0x00A2 #CENT SIGN
+0x4B 0x002E #FULL STOP
+0x4C 0x003C #LESS-THAN SIGN
+0x4D 0x0028 #LEFT PARENTHESIS
+0x4E 0x002B #PLUS SIGN
+0x4F 0x007C #VERTICAL LINE
+0x50 0x0026 #AMPERSAND
+0x51 0x00E9 #LATIN SMALL LETTER E WITH ACUTE
+0x52 0x00EA #LATIN SMALL LETTER E WITH CIRCUMFLEX
+0x53 0x00EB #LATIN SMALL LETTER E WITH DIAERESIS
+0x54 0x00E8 #LATIN SMALL LETTER E WITH GRAVE
+0x55 0x00ED #LATIN SMALL LETTER I WITH ACUTE
+0x56 0x00EE #LATIN SMALL LETTER I WITH CIRCUMFLEX
+0x57 0x00EF #LATIN SMALL LETTER I WITH DIAERESIS
+0x58 0x00EC #LATIN SMALL LETTER I WITH GRAVE
+0x59 0x00DF #LATIN SMALL LETTER SHARP S (GERMAN)
+0x5A 0x0021 #EXCLAMATION MARK
+0x5B 0x0024 #DOLLAR SIGN
+0x5C 0x002A #ASTERISK
+0x5D 0x0029 #RIGHT PARENTHESIS
+0x5E 0x003B #SEMICOLON
+0x5F 0x00AC #NOT SIGN
+0x60 0x002D #HYPHEN-MINUS
+0x61 0x002F #SOLIDUS
+0x62 0x00C2 #LATIN CAPITAL LETTER A WITH CIRCUMFLEX
+0x63 0x00C4 #LATIN CAPITAL LETTER A WITH DIAERESIS
+0x64 0x00C0 #LATIN CAPITAL LETTER A WITH GRAVE
+0x65 0x00C1 #LATIN CAPITAL LETTER A WITH ACUTE
+0x66 0x00C3 #LATIN CAPITAL LETTER A WITH TILDE
+0x67 0x00C5 #LATIN CAPITAL LETTER A WITH RING ABOVE
+0x68 0x00C7 #LATIN CAPITAL LETTER C WITH CEDILLA
+0x69 0x00D1 #LATIN CAPITAL LETTER N WITH TILDE
+0x6A 0x00A6 #BROKEN BAR
+0x6B 0x002C #COMMA
+0x6C 0x0025 #PERCENT SIGN
+0x6D 0x005F #LOW LINE
+0x6E 0x003E #GREATER-THAN SIGN
+0x6F 0x003F #QUESTION MARK
+0x70 0x00F8 #LATIN SMALL LETTER O WITH STROKE
+0x71 0x00C9 #LATIN CAPITAL LETTER E WITH ACUTE
+0x72 0x00CA #LATIN CAPITAL LETTER E WITH CIRCUMFLEX
+0x73 0x00CB #LATIN CAPITAL LETTER E WITH DIAERESIS
+0x74 0x00C8 #LATIN CAPITAL LETTER E WITH GRAVE
+0x75 0x00CD #LATIN CAPITAL LETTER I WITH ACUTE
+0x76 0x00CE #LATIN CAPITAL LETTER I WITH CIRCUMFLEX
+0x77 0x00CF #LATIN CAPITAL LETTER I WITH DIAERESIS
+0x78 0x00CC #LATIN CAPITAL LETTER I WITH GRAVE
+0x79 0x0060 #GRAVE ACCENT
+0x7A 0x003A #COLON
+0x7B 0x0023 #NUMBER SIGN
+0x7C 0x0040 #COMMERCIAL AT
+0x7D 0x0027 #APOSTROPHE
+0x7E 0x003D #EQUALS SIGN
+0x7F 0x0022 #QUOTATION MARK
+0x80 0x00D8 #LATIN CAPITAL LETTER O WITH STROKE
+0x81 0x0061 #LATIN SMALL LETTER A
+0x82 0x0062 #LATIN SMALL LETTER B
+0x83 0x0063 #LATIN SMALL LETTER C
+0x84 0x0064 #LATIN SMALL LETTER D
+0x85 0x0065 #LATIN SMALL LETTER E
+0x86 0x0066 #LATIN SMALL LETTER F
+0x87 0x0067 #LATIN SMALL LETTER G
+0x88 0x0068 #LATIN SMALL LETTER H
+0x89 0x0069 #LATIN SMALL LETTER I
+0x8A 0x00AB #LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
+0x8B 0x00BB #RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
+0x8C 0x00F0 #LATIN SMALL LETTER ETH (ICELANDIC)
+0x8D 0x00FD #LATIN SMALL LETTER Y WITH ACUTE
+0x8E 0x00FE #LATIN SMALL LETTER THORN (ICELANDIC)
+0x8F 0x00B1 #PLUS-MINUS SIGN
+0x90 0x00B0 #DEGREE SIGN
+0x91 0x006A #LATIN SMALL LETTER J
+0x92 0x006B #LATIN SMALL LETTER K
+0x93 0x006C #LATIN SMALL LETTER L
+0x94 0x006D #LATIN SMALL LETTER M
+0x95 0x006E #LATIN SMALL LETTER N
+0x96 0x006F #LATIN SMALL LETTER O
+0x97 0x0070 #LATIN SMALL LETTER P
+0x98 0x0071 #LATIN SMALL LETTER Q
+0x99 0x0072 #LATIN SMALL LETTER R
+0x9A 0x00AA #FEMININE ORDINAL INDICATOR
+0x9B 0x00BA #MASCULINE ORDINAL INDICATOR
+0x9C 0x00E6 #LATIN SMALL LIGATURE AE
+0x9D 0x00B8 #CEDILLA
+0x9E 0x00C6 #LATIN CAPITAL LIGATURE AE
+#0x9F 0x00A4 #CURRENCY SIGN
+0x9F 0x20AC # EURO SIGN
+0xA0 0x00B5 #MICRO SIGN
+0xA1 0x007E #TILDE
+0xA2 0x0073 #LATIN SMALL LETTER S
+0xA3 0x0074 #LATIN SMALL LETTER T
+0xA4 0x0075 #LATIN SMALL LETTER U
+0xA5 0x0076 #LATIN SMALL LETTER V
+0xA6 0x0077 #LATIN SMALL LETTER W
+0xA7 0x0078 #LATIN SMALL LETTER X
+0xA8 0x0079 #LATIN SMALL LETTER Y
+0xA9 0x007A #LATIN SMALL LETTER Z
+0xAA 0x00A1 #INVERTED EXCLAMATION MARK
+0xAB 0x00BF #INVERTED QUESTION MARK
+0xAC 0x00D0 #LATIN CAPITAL LETTER ETH (ICELANDIC)
+0xAD 0x00DD #LATIN CAPITAL LETTER Y WITH ACUTE
+0xAE 0x00DE #LATIN CAPITAL LETTER THORN (ICELANDIC)
+0xAF 0x00AE #REGISTERED SIGN
+0xB0 0x005E #CIRCUMFLEX ACCENT
+0xB1 0x00A3 #POUND SIGN
+0xB2 0x00A5 #YEN SIGN
+0xB3 0x00B7 #MIDDLE DOT
+0xB4 0x00A9 #COPYRIGHT SIGN
+0xB5 0x00A7 #SECTION SIGN
+0xB6 0x00B6 #PILCROW SIGN
+0xB7 0x00BC #VULGAR FRACTION ONE QUARTER
+0xB8 0x00BD #VULGAR FRACTION ONE HALF
+0xB9 0x00BE #VULGAR FRACTION THREE QUARTERS
+0xBA 0x005B #LEFT SQUARE BRACKET
+0xBB 0x005D #RIGHT SQUARE BRACKET
+0xBC 0x00AF #MACRON
+0xBD 0x00A8 #DIAERESIS
+0xBE 0x00B4 #ACUTE ACCENT
+0xBF 0x00D7 #MULTIPLICATION SIGN
+0xC0 0x007B #LEFT CURLY BRACKET
+0xC1 0x0041 #LATIN CAPITAL LETTER A
+0xC2 0x0042 #LATIN CAPITAL LETTER B
+0xC3 0x0043 #LATIN CAPITAL LETTER C
+0xC4 0x0044 #LATIN CAPITAL LETTER D
+0xC5 0x0045 #LATIN CAPITAL LETTER E
+0xC6 0x0046 #LATIN CAPITAL LETTER F
+0xC7 0x0047 #LATIN CAPITAL LETTER G
+0xC8 0x0048 #LATIN CAPITAL LETTER H
+0xC9 0x0049 #LATIN CAPITAL LETTER I
+0xCA 0x00AD #SOFT HYPHEN
+0xCB 0x00F4 #LATIN SMALL LETTER O WITH CIRCUMFLEX
+0xCC 0x00F6 #LATIN SMALL LETTER O WITH DIAERESIS
+0xCD 0x00F2 #LATIN SMALL LETTER O WITH GRAVE
+0xCE 0x00F3 #LATIN SMALL LETTER O WITH ACUTE
+0xCF 0x00F5 #LATIN SMALL LETTER O WITH TILDE
+0xD0 0x007D #RIGHT CURLY BRACKET
+0xD1 0x004A #LATIN CAPITAL LETTER J
+0xD2 0x004B #LATIN CAPITAL LETTER K
+0xD3 0x004C #LATIN CAPITAL LETTER L
+0xD4 0x004D #LATIN CAPITAL LETTER M
+0xD5 0x004E #LATIN CAPITAL LETTER N
+0xD6 0x004F #LATIN CAPITAL LETTER O
+0xD7 0x0050 #LATIN CAPITAL LETTER P
+0xD8 0x0051 #LATIN CAPITAL LETTER Q
+0xD9 0x0052 #LATIN CAPITAL LETTER R
+0xDA 0x00B9 #SUPERSCRIPT ONE
+0xDB 0x00FB #LATIN SMALL LETTER U WITH CIRCUMFLEX
+0xDC 0x00FC #LATIN SMALL LETTER U WITH DIAERESIS
+0xDD 0x00F9 #LATIN SMALL LETTER U WITH GRAVE
+0xDE 0x00FA #LATIN SMALL LETTER U WITH ACUTE
+0xDF 0x00FF #LATIN SMALL LETTER Y WITH DIAERESIS
+0xE0 0x005C #REVERSE SOLIDUS
+0xE1 0x00F7 #DIVISION SIGN
+0xE2 0x0053 #LATIN CAPITAL LETTER S
+0xE3 0x0054 #LATIN CAPITAL LETTER T
+0xE4 0x0055 #LATIN CAPITAL LETTER U
+0xE5 0x0056 #LATIN CAPITAL LETTER V
+0xE6 0x0057 #LATIN CAPITAL LETTER W
+0xE7 0x0058 #LATIN CAPITAL LETTER X
+0xE8 0x0059 #LATIN CAPITAL LETTER Y
+0xE9 0x005A #LATIN CAPITAL LETTER Z
+0xEA 0x00B2 #SUPERSCRIPT TWO
+0xEB 0x00D4 #LATIN CAPITAL LETTER O WITH CIRCUMFLEX
+0xEC 0x00D6 #LATIN CAPITAL LETTER O WITH DIAERESIS
+0xED 0x00D2 #LATIN CAPITAL LETTER O WITH GRAVE
+0xEE 0x00D3 #LATIN CAPITAL LETTER O WITH ACUTE
+0xEF 0x00D5 #LATIN CAPITAL LETTER O WITH TILDE
+0xF0 0x0030 #DIGIT ZERO
+0xF1 0x0031 #DIGIT ONE
+0xF2 0x0032 #DIGIT TWO
+0xF3 0x0033 #DIGIT THREE
+0xF4 0x0034 #DIGIT FOUR
+0xF5 0x0035 #DIGIT FIVE
+0xF6 0x0036 #DIGIT SIX
+0xF7 0x0037 #DIGIT SEVEN
+0xF8 0x0038 #DIGIT EIGHT
+0xF9 0x0039 #DIGIT NINE
+0xFA 0x00B3 #SUPERSCRIPT THREE
+0xFB 0x00DB #LATIN CAPITAL LETTER U WITH CIRCUMFLEX
+0xFC 0x00DC #LATIN CAPITAL LETTER U WITH DIAERESIS
+0xFD 0x00D9 #LATIN CAPITAL LETTER U WITH GRAVE
+0xFE 0x00DA #LATIN CAPITAL LETTER U WITH ACUTE
+0xFF 0x009F #CONTROL
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/KOI8-U.TXT b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/KOI8-U.TXT
new file mode 100644
index 0000000000..77160cf7e6
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/KOI8-U.TXT
@@ -0,0 +1,298 @@
+#
+# Name: KOI8-U (RFC2319) to Unicode
+# Unicode version: 3.2
+# Table version: 1.0
+# Table format: Format A
+# Date: 2005-10-25
+# Authors: Marc-Andre Lemburg <mal@egenix.com>
+#
+# See RFC2319 for details. This encoding is a modified KOI8-R
+# encoding.
+#
+# (c) Copyright Marc-Andre Lemburg, 2005.
+# Licensed to PSF under a Contributor Agreement.
+#
+# Based on the file
+# ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/MISC/KOI8-R.TXT
+# which is:
+#
+# Copyright (c) 1991-1999 Unicode, Inc. All Rights reserved.
+#
+# This file is provided as-is by Unicode, Inc. (The Unicode Consortium).
+# No claims are made as to fitness for any particular purpose. No
+# warranties of any kind are expressed or implied. The recipient
+# agrees to determine applicability of information provided. If this
+# file has been provided on optical media by Unicode, Inc., the sole
+# remedy for any claim will be exchange of defective media within 90
+# days of receipt.
+#
+# Unicode, Inc. hereby grants the right to freely use the information
+# supplied in this file in the creation of products supporting the
+# Unicode Standard, and to make copies of this file in any form for
+# internal or external distribution as long as this notice remains
+# attached.
+#
+0x00 0x0000 # NULL
+0x01 0x0001 # START OF HEADING
+0x02 0x0002 # START OF TEXT
+0x03 0x0003 # END OF TEXT
+0x04 0x0004 # END OF TRANSMISSION
+0x05 0x0005 # ENQUIRY
+0x06 0x0006 # ACKNOWLEDGE
+0x07 0x0007 # BELL
+0x08 0x0008 # BACKSPACE
+0x09 0x0009 # HORIZONTAL TABULATION
+0x0A 0x000A # LINE FEED
+0x0B 0x000B # VERTICAL TABULATION
+0x0C 0x000C # FORM FEED
+0x0D 0x000D # CARRIAGE RETURN
+0x0E 0x000E # SHIFT OUT
+0x0F 0x000F # SHIFT IN
+0x10 0x0010 # DATA LINK ESCAPE
+0x11 0x0011 # DEVICE CONTROL ONE
+0x12 0x0012 # DEVICE CONTROL TWO
+0x13 0x0013 # DEVICE CONTROL THREE
+0x14 0x0014 # DEVICE CONTROL FOUR
+0x15 0x0015 # NEGATIVE ACKNOWLEDGE
+0x16 0x0016 # SYNCHRONOUS IDLE
+0x17 0x0017 # END OF TRANSMISSION BLOCK
+0x18 0x0018 # CANCEL
+0x19 0x0019 # END OF MEDIUM
+0x1A 0x001A # SUBSTITUTE
+0x1B 0x001B # ESCAPE
+0x1C 0x001C # FILE SEPARATOR
+0x1D 0x001D # GROUP SEPARATOR
+0x1E 0x001E # RECORD SEPARATOR
+0x1F 0x001F # UNIT SEPARATOR
+0x20 0x0020 # SPACE
+0x21 0x0021 # EXCLAMATION MARK
+0x22 0x0022 # QUOTATION MARK
+0x23 0x0023 # NUMBER SIGN
+0x24 0x0024 # DOLLAR SIGN
+0x25 0x0025 # PERCENT SIGN
+0x26 0x0026 # AMPERSAND
+0x27 0x0027 # APOSTROPHE
+0x28 0x0028 # LEFT PARENTHESIS
+0x29 0x0029 # RIGHT PARENTHESIS
+0x2A 0x002A # ASTERISK
+0x2B 0x002B # PLUS SIGN
+0x2C 0x002C # COMMA
+0x2D 0x002D # HYPHEN-MINUS
+0x2E 0x002E # FULL STOP
+0x2F 0x002F # SOLIDUS
+0x30 0x0030 # DIGIT ZERO
+0x31 0x0031 # DIGIT ONE
+0x32 0x0032 # DIGIT TWO
+0x33 0x0033 # DIGIT THREE
+0x34 0x0034 # DIGIT FOUR
+0x35 0x0035 # DIGIT FIVE
+0x36 0x0036 # DIGIT SIX
+0x37 0x0037 # DIGIT SEVEN
+0x38 0x0038 # DIGIT EIGHT
+0x39 0x0039 # DIGIT NINE
+0x3A 0x003A # COLON
+0x3B 0x003B # SEMICOLON
+0x3C 0x003C # LESS-THAN SIGN
+0x3D 0x003D # EQUALS SIGN
+0x3E 0x003E # GREATER-THAN SIGN
+0x3F 0x003F # QUESTION MARK
+0x40 0x0040 # COMMERCIAL AT
+0x41 0x0041 # LATIN CAPITAL LETTER A
+0x42 0x0042 # LATIN CAPITAL LETTER B
+0x43 0x0043 # LATIN CAPITAL LETTER C
+0x44 0x0044 # LATIN CAPITAL LETTER D
+0x45 0x0045 # LATIN CAPITAL LETTER E
+0x46 0x0046 # LATIN CAPITAL LETTER F
+0x47 0x0047 # LATIN CAPITAL LETTER G
+0x48 0x0048 # LATIN CAPITAL LETTER H
+0x49 0x0049 # LATIN CAPITAL LETTER I
+0x4A 0x004A # LATIN CAPITAL LETTER J
+0x4B 0x004B # LATIN CAPITAL LETTER K
+0x4C 0x004C # LATIN CAPITAL LETTER L
+0x4D 0x004D # LATIN CAPITAL LETTER M
+0x4E 0x004E # LATIN CAPITAL LETTER N
+0x4F 0x004F # LATIN CAPITAL LETTER O
+0x50 0x0050 # LATIN CAPITAL LETTER P
+0x51 0x0051 # LATIN CAPITAL LETTER Q
+0x52 0x0052 # LATIN CAPITAL LETTER R
+0x53 0x0053 # LATIN CAPITAL LETTER S
+0x54 0x0054 # LATIN CAPITAL LETTER T
+0x55 0x0055 # LATIN CAPITAL LETTER U
+0x56 0x0056 # LATIN CAPITAL LETTER V
+0x57 0x0057 # LATIN CAPITAL LETTER W
+0x58 0x0058 # LATIN CAPITAL LETTER X
+0x59 0x0059 # LATIN CAPITAL LETTER Y
+0x5A 0x005A # LATIN CAPITAL LETTER Z
+0x5B 0x005B # LEFT SQUARE BRACKET
+0x5C 0x005C # REVERSE SOLIDUS
+0x5D 0x005D # RIGHT SQUARE BRACKET
+0x5E 0x005E # CIRCUMFLEX ACCENT
+0x5F 0x005F # LOW LINE
+0x60 0x0060 # GRAVE ACCENT
+0x61 0x0061 # LATIN SMALL LETTER A
+0x62 0x0062 # LATIN SMALL LETTER B
+0x63 0x0063 # LATIN SMALL LETTER C
+0x64 0x0064 # LATIN SMALL LETTER D
+0x65 0x0065 # LATIN SMALL LETTER E
+0x66 0x0066 # LATIN SMALL LETTER F
+0x67 0x0067 # LATIN SMALL LETTER G
+0x68 0x0068 # LATIN SMALL LETTER H
+0x69 0x0069 # LATIN SMALL LETTER I
+0x6A 0x006A # LATIN SMALL LETTER J
+0x6B 0x006B # LATIN SMALL LETTER K
+0x6C 0x006C # LATIN SMALL LETTER L
+0x6D 0x006D # LATIN SMALL LETTER M
+0x6E 0x006E # LATIN SMALL LETTER N
+0x6F 0x006F # LATIN SMALL LETTER O
+0x70 0x0070 # LATIN SMALL LETTER P
+0x71 0x0071 # LATIN SMALL LETTER Q
+0x72 0x0072 # LATIN SMALL LETTER R
+0x73 0x0073 # LATIN SMALL LETTER S
+0x74 0x0074 # LATIN SMALL LETTER T
+0x75 0x0075 # LATIN SMALL LETTER U
+0x76 0x0076 # LATIN SMALL LETTER V
+0x77 0x0077 # LATIN SMALL LETTER W
+0x78 0x0078 # LATIN SMALL LETTER X
+0x79 0x0079 # LATIN SMALL LETTER Y
+0x7A 0x007A # LATIN SMALL LETTER Z
+0x7B 0x007B # LEFT CURLY BRACKET
+0x7C 0x007C # VERTICAL LINE
+0x7D 0x007D # RIGHT CURLY BRACKET
+0x7E 0x007E # TILDE
+0x7F 0x007F # DELETE
+0x80 0x2500 # BOX DRAWINGS LIGHT HORIZONTAL
+0x81 0x2502 # BOX DRAWINGS LIGHT VERTICAL
+0x82 0x250C # BOX DRAWINGS LIGHT DOWN AND RIGHT
+0x83 0x2510 # BOX DRAWINGS LIGHT DOWN AND LEFT
+0x84 0x2514 # BOX DRAWINGS LIGHT UP AND RIGHT
+0x85 0x2518 # BOX DRAWINGS LIGHT UP AND LEFT
+0x86 0x251C # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
+0x87 0x2524 # BOX DRAWINGS LIGHT VERTICAL AND LEFT
+0x88 0x252C # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
+0x89 0x2534 # BOX DRAWINGS LIGHT UP AND HORIZONTAL
+0x8A 0x253C # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
+0x8B 0x2580 # UPPER HALF BLOCK
+0x8C 0x2584 # LOWER HALF BLOCK
+0x8D 0x2588 # FULL BLOCK
+0x8E 0x258C # LEFT HALF BLOCK
+0x8F 0x2590 # RIGHT HALF BLOCK
+0x90 0x2591 # LIGHT SHADE
+0x91 0x2592 # MEDIUM SHADE
+0x92 0x2593 # DARK SHADE
+0x93 0x2320 # TOP HALF INTEGRAL
+0x94 0x25A0 # BLACK SQUARE
+0x95 0x2219 # BULLET OPERATOR
+0x96 0x221A # SQUARE ROOT
+0x97 0x2248 # ALMOST EQUAL TO
+0x98 0x2264 # LESS-THAN OR EQUAL TO
+0x99 0x2265 # GREATER-THAN OR EQUAL TO
+0x9A 0x00A0 # NO-BREAK SPACE
+0x9B 0x2321 # BOTTOM HALF INTEGRAL
+0x9C 0x00B0 # DEGREE SIGN
+0x9D 0x00B2 # SUPERSCRIPT TWO
+0x9E 0x00B7 # MIDDLE DOT
+0x9F 0x00F7 # DIVISION SIGN
+0xA0 0x2550 # BOX DRAWINGS DOUBLE HORIZONTAL
+0xA1 0x2551 # BOX DRAWINGS DOUBLE VERTICAL
+0xA2 0x2552 # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
+0xA3 0x0451 # CYRILLIC SMALL LETTER IO
+#0xA4 0x2553 # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
+0xA4 0x0454 # CYRILLIC SMALL LETTER UKRAINIAN IE
+0xA5 0x2554 # BOX DRAWINGS DOUBLE DOWN AND RIGHT
+#0xA6 0x2555 # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
+0xA6 0x0456 # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I
+#0xA7 0x2556 # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
+0xA7 0x0457 # CYRILLIC SMALL LETTER YI (UKRAINIAN)
+0xA8 0x2557 # BOX DRAWINGS DOUBLE DOWN AND LEFT
+0xA9 0x2558 # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
+0xAA 0x2559 # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
+0xAB 0x255A # BOX DRAWINGS DOUBLE UP AND RIGHT
+0xAC 0x255B # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
+#0xAD 0x255C # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
+0xAD 0x0491 # CYRILLIC SMALL LETTER UKRAINIAN GHE WITH UPTURN
+0xAE 0x255D # BOX DRAWINGS DOUBLE UP AND LEFT
+0xAF 0x255E # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
+0xB0 0x255F # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
+0xB1 0x2560 # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
+0xB2 0x2561 # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
+0xB3 0x0401 # CYRILLIC CAPITAL LETTER IO
+#0xB4 0x2562 # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
+0xB4 0x0404 # CYRILLIC CAPITAL LETTER UKRAINIAN IE
+0xB5 0x2563 # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
+#0xB6 0x2564 # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
+0xB6 0x0406 # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I
+#0xB7 0x2565 # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
+0xB7 0x0407 # CYRILLIC CAPITAL LETTER YI (UKRAINIAN)
+0xB8 0x2566 # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
+0xB9 0x2567 # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
+0xBA 0x2568 # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
+0xBB 0x2569 # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
+0xBC 0x256A # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
+#0xBD 0x256B # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
+0xBD 0x0490 # CYRILLIC CAPITAL LETTER UKRAINIAN GHE WITH UPTURN
+0xBE 0x256C # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
+0xBF 0x00A9 # COPYRIGHT SIGN
+0xC0 0x044E # CYRILLIC SMALL LETTER YU
+0xC1 0x0430 # CYRILLIC SMALL LETTER A
+0xC2 0x0431 # CYRILLIC SMALL LETTER BE
+0xC3 0x0446 # CYRILLIC SMALL LETTER TSE
+0xC4 0x0434 # CYRILLIC SMALL LETTER DE
+0xC5 0x0435 # CYRILLIC SMALL LETTER IE
+0xC6 0x0444 # CYRILLIC SMALL LETTER EF
+0xC7 0x0433 # CYRILLIC SMALL LETTER GHE
+0xC8 0x0445 # CYRILLIC SMALL LETTER HA
+0xC9 0x0438 # CYRILLIC SMALL LETTER I
+0xCA 0x0439 # CYRILLIC SMALL LETTER SHORT I
+0xCB 0x043A # CYRILLIC SMALL LETTER KA
+0xCC 0x043B # CYRILLIC SMALL LETTER EL
+0xCD 0x043C # CYRILLIC SMALL LETTER EM
+0xCE 0x043D # CYRILLIC SMALL LETTER EN
+0xCF 0x043E # CYRILLIC SMALL LETTER O
+0xD0 0x043F # CYRILLIC SMALL LETTER PE
+0xD1 0x044F # CYRILLIC SMALL LETTER YA
+0xD2 0x0440 # CYRILLIC SMALL LETTER ER
+0xD3 0x0441 # CYRILLIC SMALL LETTER ES
+0xD4 0x0442 # CYRILLIC SMALL LETTER TE
+0xD5 0x0443 # CYRILLIC SMALL LETTER U
+0xD6 0x0436 # CYRILLIC SMALL LETTER ZHE
+0xD7 0x0432 # CYRILLIC SMALL LETTER VE
+0xD8 0x044C # CYRILLIC SMALL LETTER SOFT SIGN
+0xD9 0x044B # CYRILLIC SMALL LETTER YERU
+0xDA 0x0437 # CYRILLIC SMALL LETTER ZE
+0xDB 0x0448 # CYRILLIC SMALL LETTER SHA
+0xDC 0x044D # CYRILLIC SMALL LETTER E
+0xDD 0x0449 # CYRILLIC SMALL LETTER SHCHA
+0xDE 0x0447 # CYRILLIC SMALL LETTER CHE
+0xDF 0x044A # CYRILLIC SMALL LETTER HARD SIGN
+0xE0 0x042E # CYRILLIC CAPITAL LETTER YU
+0xE1 0x0410 # CYRILLIC CAPITAL LETTER A
+0xE2 0x0411 # CYRILLIC CAPITAL LETTER BE
+0xE3 0x0426 # CYRILLIC CAPITAL LETTER TSE
+0xE4 0x0414 # CYRILLIC CAPITAL LETTER DE
+0xE5 0x0415 # CYRILLIC CAPITAL LETTER IE
+0xE6 0x0424 # CYRILLIC CAPITAL LETTER EF
+0xE7 0x0413 # CYRILLIC CAPITAL LETTER GHE
+0xE8 0x0425 # CYRILLIC CAPITAL LETTER HA
+0xE9 0x0418 # CYRILLIC CAPITAL LETTER I
+0xEA 0x0419 # CYRILLIC CAPITAL LETTER SHORT I
+0xEB 0x041A # CYRILLIC CAPITAL LETTER KA
+0xEC 0x041B # CYRILLIC CAPITAL LETTER EL
+0xED 0x041C # CYRILLIC CAPITAL LETTER EM
+0xEE 0x041D # CYRILLIC CAPITAL LETTER EN
+0xEF 0x041E # CYRILLIC CAPITAL LETTER O
+0xF0 0x041F # CYRILLIC CAPITAL LETTER PE
+0xF1 0x042F # CYRILLIC CAPITAL LETTER YA
+0xF2 0x0420 # CYRILLIC CAPITAL LETTER ER
+0xF3 0x0421 # CYRILLIC CAPITAL LETTER ES
+0xF4 0x0422 # CYRILLIC CAPITAL LETTER TE
+0xF5 0x0423 # CYRILLIC CAPITAL LETTER U
+0xF6 0x0416 # CYRILLIC CAPITAL LETTER ZHE
+0xF7 0x0412 # CYRILLIC CAPITAL LETTER VE
+0xF8 0x042C # CYRILLIC CAPITAL LETTER SOFT SIGN
+0xF9 0x042B # CYRILLIC CAPITAL LETTER YERU
+0xFA 0x0417 # CYRILLIC CAPITAL LETTER ZE
+0xFB 0x0428 # CYRILLIC CAPITAL LETTER SHA
+0xFC 0x042D # CYRILLIC CAPITAL LETTER E
+0xFD 0x0429 # CYRILLIC CAPITAL LETTER SHCHA
+0xFE 0x0427 # CYRILLIC CAPITAL LETTER CHE
+0xFF 0x042A # CYRILLIC CAPITAL LETTER HARD SIGN
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/TIS-620.TXT b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/TIS-620.TXT
new file mode 100644
index 0000000000..05173e9720
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/unicode/python-mappings/TIS-620.TXT
@@ -0,0 +1,284 @@
+#
+# Name: TIS-620
+# Unicode version: 3.2
+# Table version: 1.0
+# Table format: Format A
+# Date: 2005-10-25
+# Authors: Marc-Andre Lemburg <mal@egenix.com>
+#
+# According to
+# ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/8859-11.TXT the
+# TIS-620 is the identical to ISO_8859-11 with the 0xA0
+# (no-break space) mapping removed.
+#
+# (c) Copyright Marc-Andre Lemburg, 2005.
+# Licensed to PSF under a Contributor Agreement.
+#
+# Based on the file
+# ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/8859-11.TXT
+# which is:
+#
+# Copyright (c) 2002 Unicode, Inc. All Rights reserved.
+#
+# This file is provided as-is by Unicode, Inc. (The Unicode Consortium).
+# No claims are made as to fitness for any particular purpose. No
+# warranties of any kind are expressed or implied. The recipient
+# agrees to determine applicability of information provided. If this
+# file has been provided on optical media by Unicode, Inc., the sole
+# remedy for any claim will be exchange of defective media within 90
+# days of receipt.
+#
+# Unicode, Inc. hereby grants the right to freely use the information
+# supplied in this file in the creation of products supporting the
+# Unicode Standard, and to make copies of this file in any form for
+# internal or external distribution as long as this notice remains
+# attached.
+#
+0x00 0x0000 # NULL
+0x01 0x0001 # START OF HEADING
+0x02 0x0002 # START OF TEXT
+0x03 0x0003 # END OF TEXT
+0x04 0x0004 # END OF TRANSMISSION
+0x05 0x0005 # ENQUIRY
+0x06 0x0006 # ACKNOWLEDGE
+0x07 0x0007 # BELL
+0x08 0x0008 # BACKSPACE
+0x09 0x0009 # HORIZONTAL TABULATION
+0x0A 0x000A # LINE FEED
+0x0B 0x000B # VERTICAL TABULATION
+0x0C 0x000C # FORM FEED
+0x0D 0x000D # CARRIAGE RETURN
+0x0E 0x000E # SHIFT OUT
+0x0F 0x000F # SHIFT IN
+0x10 0x0010 # DATA LINK ESCAPE
+0x11 0x0011 # DEVICE CONTROL ONE
+0x12 0x0012 # DEVICE CONTROL TWO
+0x13 0x0013 # DEVICE CONTROL THREE
+0x14 0x0014 # DEVICE CONTROL FOUR
+0x15 0x0015 # NEGATIVE ACKNOWLEDGE
+0x16 0x0016 # SYNCHRONOUS IDLE
+0x17 0x0017 # END OF TRANSMISSION BLOCK
+0x18 0x0018 # CANCEL
+0x19 0x0019 # END OF MEDIUM
+0x1A 0x001A # SUBSTITUTE
+0x1B 0x001B # ESCAPE
+0x1C 0x001C # FILE SEPARATOR
+0x1D 0x001D # GROUP SEPARATOR
+0x1E 0x001E # RECORD SEPARATOR
+0x1F 0x001F # UNIT SEPARATOR
+0x20 0x0020 # SPACE
+0x21 0x0021 # EXCLAMATION MARK
+0x22 0x0022 # QUOTATION MARK
+0x23 0x0023 # NUMBER SIGN
+0x24 0x0024 # DOLLAR SIGN
+0x25 0x0025 # PERCENT SIGN
+0x26 0x0026 # AMPERSAND
+0x27 0x0027 # APOSTROPHE
+0x28 0x0028 # LEFT PARENTHESIS
+0x29 0x0029 # RIGHT PARENTHESIS
+0x2A 0x002A # ASTERISK
+0x2B 0x002B # PLUS SIGN
+0x2C 0x002C # COMMA
+0x2D 0x002D # HYPHEN-MINUS
+0x2E 0x002E # FULL STOP
+0x2F 0x002F # SOLIDUS
+0x30 0x0030 # DIGIT ZERO
+0x31 0x0031 # DIGIT ONE
+0x32 0x0032 # DIGIT TWO
+0x33 0x0033 # DIGIT THREE
+0x34 0x0034 # DIGIT FOUR
+0x35 0x0035 # DIGIT FIVE
+0x36 0x0036 # DIGIT SIX
+0x37 0x0037 # DIGIT SEVEN
+0x38 0x0038 # DIGIT EIGHT
+0x39 0x0039 # DIGIT NINE
+0x3A 0x003A # COLON
+0x3B 0x003B # SEMICOLON
+0x3C 0x003C # LESS-THAN SIGN
+0x3D 0x003D # EQUALS SIGN
+0x3E 0x003E # GREATER-THAN SIGN
+0x3F 0x003F # QUESTION MARK
+0x40 0x0040 # COMMERCIAL AT
+0x41 0x0041 # LATIN CAPITAL LETTER A
+0x42 0x0042 # LATIN CAPITAL LETTER B
+0x43 0x0043 # LATIN CAPITAL LETTER C
+0x44 0x0044 # LATIN CAPITAL LETTER D
+0x45 0x0045 # LATIN CAPITAL LETTER E
+0x46 0x0046 # LATIN CAPITAL LETTER F
+0x47 0x0047 # LATIN CAPITAL LETTER G
+0x48 0x0048 # LATIN CAPITAL LETTER H
+0x49 0x0049 # LATIN CAPITAL LETTER I
+0x4A 0x004A # LATIN CAPITAL LETTER J
+0x4B 0x004B # LATIN CAPITAL LETTER K
+0x4C 0x004C # LATIN CAPITAL LETTER L
+0x4D 0x004D # LATIN CAPITAL LETTER M
+0x4E 0x004E # LATIN CAPITAL LETTER N
+0x4F 0x004F # LATIN CAPITAL LETTER O
+0x50 0x0050 # LATIN CAPITAL LETTER P
+0x51 0x0051 # LATIN CAPITAL LETTER Q
+0x52 0x0052 # LATIN CAPITAL LETTER R
+0x53 0x0053 # LATIN CAPITAL LETTER S
+0x54 0x0054 # LATIN CAPITAL LETTER T
+0x55 0x0055 # LATIN CAPITAL LETTER U
+0x56 0x0056 # LATIN CAPITAL LETTER V
+0x57 0x0057 # LATIN CAPITAL LETTER W
+0x58 0x0058 # LATIN CAPITAL LETTER X
+0x59 0x0059 # LATIN CAPITAL LETTER Y
+0x5A 0x005A # LATIN CAPITAL LETTER Z
+0x5B 0x005B # LEFT SQUARE BRACKET
+0x5C 0x005C # REVERSE SOLIDUS
+0x5D 0x005D # RIGHT SQUARE BRACKET
+0x5E 0x005E # CIRCUMFLEX ACCENT
+0x5F 0x005F # LOW LINE
+0x60 0x0060 # GRAVE ACCENT
+0x61 0x0061 # LATIN SMALL LETTER A
+0x62 0x0062 # LATIN SMALL LETTER B
+0x63 0x0063 # LATIN SMALL LETTER C
+0x64 0x0064 # LATIN SMALL LETTER D
+0x65 0x0065 # LATIN SMALL LETTER E
+0x66 0x0066 # LATIN SMALL LETTER F
+0x67 0x0067 # LATIN SMALL LETTER G
+0x68 0x0068 # LATIN SMALL LETTER H
+0x69 0x0069 # LATIN SMALL LETTER I
+0x6A 0x006A # LATIN SMALL LETTER J
+0x6B 0x006B # LATIN SMALL LETTER K
+0x6C 0x006C # LATIN SMALL LETTER L
+0x6D 0x006D # LATIN SMALL LETTER M
+0x6E 0x006E # LATIN SMALL LETTER N
+0x6F 0x006F # LATIN SMALL LETTER O
+0x70 0x0070 # LATIN SMALL LETTER P
+0x71 0x0071 # LATIN SMALL LETTER Q
+0x72 0x0072 # LATIN SMALL LETTER R
+0x73 0x0073 # LATIN SMALL LETTER S
+0x74 0x0074 # LATIN SMALL LETTER T
+0x75 0x0075 # LATIN SMALL LETTER U
+0x76 0x0076 # LATIN SMALL LETTER V
+0x77 0x0077 # LATIN SMALL LETTER W
+0x78 0x0078 # LATIN SMALL LETTER X
+0x79 0x0079 # LATIN SMALL LETTER Y
+0x7A 0x007A # LATIN SMALL LETTER Z
+0x7B 0x007B # LEFT CURLY BRACKET
+0x7C 0x007C # VERTICAL LINE
+0x7D 0x007D # RIGHT CURLY BRACKET
+0x7E 0x007E # TILDE
+0x7F 0x007F # DELETE
+0x80 0x0080 # <control>
+0x81 0x0081 # <control>
+0x82 0x0082 # <control>
+0x83 0x0083 # <control>
+0x84 0x0084 # <control>
+0x85 0x0085 # <control>
+0x86 0x0086 # <control>
+0x87 0x0087 # <control>
+0x88 0x0088 # <control>
+0x89 0x0089 # <control>
+0x8A 0x008A # <control>
+0x8B 0x008B # <control>
+0x8C 0x008C # <control>
+0x8D 0x008D # <control>
+0x8E 0x008E # <control>
+0x8F 0x008F # <control>
+0x90 0x0090 # <control>
+0x91 0x0091 # <control>
+0x92 0x0092 # <control>
+0x93 0x0093 # <control>
+0x94 0x0094 # <control>
+0x95 0x0095 # <control>
+0x96 0x0096 # <control>
+0x97 0x0097 # <control>
+0x98 0x0098 # <control>
+0x99 0x0099 # <control>
+0x9A 0x009A # <control>
+0x9B 0x009B # <control>
+0x9C 0x009C # <control>
+0x9D 0x009D # <control>
+0x9E 0x009E # <control>
+0x9F 0x009F # <control>
+#0xA0 0x00A0 # NO-BREAK SPACE
+0xA1 0x0E01 # THAI CHARACTER KO KAI
+0xA2 0x0E02 # THAI CHARACTER KHO KHAI
+0xA3 0x0E03 # THAI CHARACTER KHO KHUAT
+0xA4 0x0E04 # THAI CHARACTER KHO KHWAI
+0xA5 0x0E05 # THAI CHARACTER KHO KHON
+0xA6 0x0E06 # THAI CHARACTER KHO RAKHANG
+0xA7 0x0E07 # THAI CHARACTER NGO NGU
+0xA8 0x0E08 # THAI CHARACTER CHO CHAN
+0xA9 0x0E09 # THAI CHARACTER CHO CHING
+0xAA 0x0E0A # THAI CHARACTER CHO CHANG
+0xAB 0x0E0B # THAI CHARACTER SO SO
+0xAC 0x0E0C # THAI CHARACTER CHO CHOE
+0xAD 0x0E0D # THAI CHARACTER YO YING
+0xAE 0x0E0E # THAI CHARACTER DO CHADA
+0xAF 0x0E0F # THAI CHARACTER TO PATAK
+0xB0 0x0E10 # THAI CHARACTER THO THAN
+0xB1 0x0E11 # THAI CHARACTER THO NANGMONTHO
+0xB2 0x0E12 # THAI CHARACTER THO PHUTHAO
+0xB3 0x0E13 # THAI CHARACTER NO NEN
+0xB4 0x0E14 # THAI CHARACTER DO DEK
+0xB5 0x0E15 # THAI CHARACTER TO TAO
+0xB6 0x0E16 # THAI CHARACTER THO THUNG
+0xB7 0x0E17 # THAI CHARACTER THO THAHAN
+0xB8 0x0E18 # THAI CHARACTER THO THONG
+0xB9 0x0E19 # THAI CHARACTER NO NU
+0xBA 0x0E1A # THAI CHARACTER BO BAIMAI
+0xBB 0x0E1B # THAI CHARACTER PO PLA
+0xBC 0x0E1C # THAI CHARACTER PHO PHUNG
+0xBD 0x0E1D # THAI CHARACTER FO FA
+0xBE 0x0E1E # THAI CHARACTER PHO PHAN
+0xBF 0x0E1F # THAI CHARACTER FO FAN
+0xC0 0x0E20 # THAI CHARACTER PHO SAMPHAO
+0xC1 0x0E21 # THAI CHARACTER MO MA
+0xC2 0x0E22 # THAI CHARACTER YO YAK
+0xC3 0x0E23 # THAI CHARACTER RO RUA
+0xC4 0x0E24 # THAI CHARACTER RU
+0xC5 0x0E25 # THAI CHARACTER LO LING
+0xC6 0x0E26 # THAI CHARACTER LU
+0xC7 0x0E27 # THAI CHARACTER WO WAEN
+0xC8 0x0E28 # THAI CHARACTER SO SALA
+0xC9 0x0E29 # THAI CHARACTER SO RUSI
+0xCA 0x0E2A # THAI CHARACTER SO SUA
+0xCB 0x0E2B # THAI CHARACTER HO HIP
+0xCC 0x0E2C # THAI CHARACTER LO CHULA
+0xCD 0x0E2D # THAI CHARACTER O ANG
+0xCE 0x0E2E # THAI CHARACTER HO NOKHUK
+0xCF 0x0E2F # THAI CHARACTER PAIYANNOI
+0xD0 0x0E30 # THAI CHARACTER SARA A
+0xD1 0x0E31 # THAI CHARACTER MAI HAN-AKAT
+0xD2 0x0E32 # THAI CHARACTER SARA AA
+0xD3 0x0E33 # THAI CHARACTER SARA AM
+0xD4 0x0E34 # THAI CHARACTER SARA I
+0xD5 0x0E35 # THAI CHARACTER SARA II
+0xD6 0x0E36 # THAI CHARACTER SARA UE
+0xD7 0x0E37 # THAI CHARACTER SARA UEE
+0xD8 0x0E38 # THAI CHARACTER SARA U
+0xD9 0x0E39 # THAI CHARACTER SARA UU
+0xDA 0x0E3A # THAI CHARACTER PHINTHU
+0xDF 0x0E3F # THAI CURRENCY SYMBOL BAHT
+0xE0 0x0E40 # THAI CHARACTER SARA E
+0xE1 0x0E41 # THAI CHARACTER SARA AE
+0xE2 0x0E42 # THAI CHARACTER SARA O
+0xE3 0x0E43 # THAI CHARACTER SARA AI MAIMUAN
+0xE4 0x0E44 # THAI CHARACTER SARA AI MAIMALAI
+0xE5 0x0E45 # THAI CHARACTER LAKKHANGYAO
+0xE6 0x0E46 # THAI CHARACTER MAIYAMOK
+0xE7 0x0E47 # THAI CHARACTER MAITAIKHU
+0xE8 0x0E48 # THAI CHARACTER MAI EK
+0xE9 0x0E49 # THAI CHARACTER MAI THO
+0xEA 0x0E4A # THAI CHARACTER MAI TRI
+0xEB 0x0E4B # THAI CHARACTER MAI CHATTAWA
+0xEC 0x0E4C # THAI CHARACTER THANTHAKHAT
+0xED 0x0E4D # THAI CHARACTER NIKHAHIT
+0xEE 0x0E4E # THAI CHARACTER YAMAKKAN
+0xEF 0x0E4F # THAI CHARACTER FONGMAN
+0xF0 0x0E50 # THAI DIGIT ZERO
+0xF1 0x0E51 # THAI DIGIT ONE
+0xF2 0x0E52 # THAI DIGIT TWO
+0xF3 0x0E53 # THAI DIGIT THREE
+0xF4 0x0E54 # THAI DIGIT FOUR
+0xF5 0x0E55 # THAI DIGIT FIVE
+0xF6 0x0E56 # THAI DIGIT SIX
+0xF7 0x0E57 # THAI DIGIT SEVEN
+0xF8 0x0E58 # THAI DIGIT EIGHT
+0xF9 0x0E59 # THAI DIGIT NINE
+0xFA 0x0E5A # THAI CHARACTER ANGKHANKHU
+0xFB 0x0E5B # THAI CHARACTER KHOMUT
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/README
new file mode 100644
index 0000000000..07d1804cf5
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/README
@@ -0,0 +1,41 @@
+This is versioncheck 1.0, a first stab at automatic checking of versions of
+Python extension packages installed on your system.
+
+The basic idea is that each package contains a _checkversion.py
+somewhere, probably at the root level of the package. In addition, each
+package maintainer makes a file available on the net, through ftp or
+http, which contains the version number of the most recent distribution
+and some readable text explaining the differences with previous
+versions, where to download the package, etc.
+
+The checkversions.py script walks through the installed Python tree (or
+through a tree of choice), and runs each _checkversion.py script. These
+scripts retrieve the current-version file over the net, compares version
+numbers and tells the user about new versions of packages available.
+
+A boilerplate for the _checkversion.py file can be found here. Replace
+package name, version and the URL of the version-check file and put it in
+your distribution. In stead of a single URL you can also specify a list
+of URLs. Each of these will be checked in order until one is available,
+this is handy for distributions that live in multiple places. Put the
+primary distribution site (the most up-to-date site) before others.
+The script is executed with execfile(), not imported, and the current
+directory is the checkversion directory, so be careful with globals,
+importing, etc.
+
+The version-check file consists of an rfc822-style header followed by
+plaintext. The only header field checked currently is
+'Current-Version:', which should contain te current version and is
+matched against the string contained in the _checkversion.py script.
+The rest of the file is human-readable text and presented to the user if
+there is a version mismatch. It should contain at the very least a URL
+of either the current distribution or a webpage describing it.
+
+Pycheckversion.py is the module that does the actual checking of versions.
+It should be fine where it is, it is imported by checkversion before anything
+else is done, but if imports fail you may want to move it to somewhere
+along sys.path.
+
+ Jack Jansen, CWI, 23-Dec-97.
+ <jack@cwi.nl>
+
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/_checkversion.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/_checkversion.py
new file mode 100644
index 0000000000..f466a80900
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/_checkversion.py
@@ -0,0 +1,16 @@
+"""This file (which is sourced, not imported) checks the version of the
+"versioncheck" package. It is also an example of how to format your own
+_checkversion.py file"""
+
+import pyversioncheck
+
+_PACKAGE="versioncheck"
+_VERSION="1.0"
+_URL="http://www.cwi.nl/~jack/versioncheck/curversion.txt"
+
+try:
+ _myverbose=VERBOSE
+except NameError:
+ _myverbose=1
+
+pyversioncheck.versioncheck(_PACKAGE, _URL, _VERSION, verbose=_myverbose)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/checkversions.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/checkversions.py
new file mode 100644
index 0000000000..2455f30c61
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/checkversions.py
@@ -0,0 +1,52 @@
+"""Checkversions - recursively search a directory (default: sys.prefix)
+for _checkversion.py files, and run each of them. This will tell you of
+new versions available for any packages you have installed."""
+
+import os
+import getopt
+import sys
+import pyversioncheck
+
+CHECKNAME="_checkversion.py"
+
+VERBOSE=1
+
+USAGE="""Usage: checkversions [-v verboselevel] [dir ...]
+Recursively examine a tree (default: sys.prefix) and for each package
+with a _checkversion.py file compare the installed version against the current
+version.
+
+Values for verboselevel:
+0 - Minimal output, one line per package
+1 - Also print descriptions for outdated packages (default)
+2 - Print information on each URL checked
+3 - Check every URL for packages with multiple locations"""
+
+def check1dir(dummy, dir, files):
+ if CHECKNAME in files:
+ fullname = os.path.join(dir, CHECKNAME)
+ try:
+ execfile(fullname)
+ except:
+ print '** Exception in', fullname
+
+def walk1tree(tree):
+ os.path.walk(tree, check1dir, None)
+
+def main():
+ global VERBOSE
+ try:
+ options, arguments = getopt.getopt(sys.argv[1:], 'v:')
+ except getopt.error:
+ print USAGE
+ sys.exit(1)
+ for o, a in options:
+ if o == '-v':
+ VERBOSE = int(a)
+ if not arguments:
+ arguments = [sys.prefix]
+ for dir in arguments:
+ walk1tree(dir)
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/pyversioncheck.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/pyversioncheck.py
new file mode 100644
index 0000000000..1a9d10e3ab
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/versioncheck/pyversioncheck.py
@@ -0,0 +1,98 @@
+"""pyversioncheck - Module to help with checking versions"""
+import types
+import rfc822
+import urllib
+import sys
+
+# Verbose options
+VERBOSE_SILENT=0 # Single-line reports per package
+VERBOSE_NORMAL=1 # Single-line reports per package, more info if outdated
+VERBOSE_EACHFILE=2 # Report on each URL checked
+VERBOSE_CHECKALL=3 # Check each URL for each package
+
+# Test directory
+## urllib bug: _TESTDIR="ftp://ftp.cwi.nl/pub/jack/python/versiontestdir/"
+_TESTDIR="http://www.cwi.nl/~jack/versiontestdir/"
+
+def versioncheck(package, url, version, verbose=0):
+ ok, newversion, fp = checkonly(package, url, version, verbose)
+ if verbose > VERBOSE_NORMAL:
+ return ok
+ if ok < 0:
+ print '%s: No correctly formatted current version file found'%(package)
+ elif ok == 1:
+ print '%s: up-to-date (version %s)'%(package, version)
+ else:
+ print '%s: version %s installed, version %s found:' % \
+ (package, version, newversion)
+ if verbose > VERBOSE_SILENT:
+ while 1:
+ line = fp.readline()
+ if not line: break
+ sys.stdout.write('\t'+line)
+ return ok
+
+def checkonly(package, url, version, verbose=0):
+ if verbose >= VERBOSE_EACHFILE:
+ print '%s:'%package
+ if type(url) == types.StringType:
+ ok, newversion, fp = _check1version(package, url, version, verbose)
+ else:
+ for u in url:
+ ok, newversion, fp = _check1version(package, u, version, verbose)
+ if ok >= 0 and verbose < VERBOSE_CHECKALL:
+ break
+ return ok, newversion, fp
+
+def _check1version(package, url, version, verbose=0):
+ if verbose >= VERBOSE_EACHFILE:
+ print ' Checking %s'%url
+ try:
+ fp = urllib.urlopen(url)
+ except IOError, arg:
+ if verbose >= VERBOSE_EACHFILE:
+ print ' Cannot open:', arg
+ return -1, None, None
+ msg = rfc822.Message(fp, seekable=0)
+ newversion = msg.getheader('current-version')
+ if not newversion:
+ if verbose >= VERBOSE_EACHFILE:
+ print ' No "Current-Version:" header in URL or URL not found'
+ return -1, None, None
+ version = version.lower().strip()
+ newversion = newversion.lower().strip()
+ if version == newversion:
+ if verbose >= VERBOSE_EACHFILE:
+ print ' Version identical (%s)'%newversion
+ return 1, version, fp
+ else:
+ if verbose >= VERBOSE_EACHFILE:
+ print ' Versions different (installed: %s, new: %s)'% \
+ (version, newversion)
+ return 0, newversion, fp
+
+
+def _test():
+ print '--- TEST VERBOSE=1'
+ print '--- Testing existing and identical version file'
+ versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=1)
+ print '--- Testing existing package with new version'
+ versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=1)
+ print '--- Testing package with non-existing version file'
+ versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=1)
+ print '--- Test package with 2 locations, first non-existing second ok'
+ versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt']
+ versioncheck('VersionTestPackage', versfiles, '1.0', verbose=1)
+ print '--- TEST VERBOSE=2'
+ print '--- Testing existing and identical version file'
+ versioncheck('VersionTestPackage', _TESTDIR+'Version10.txt', '1.0', verbose=2)
+ print '--- Testing existing package with new version'
+ versioncheck('VersionTestPackage', _TESTDIR+'Version11.txt', '1.0', verbose=2)
+ print '--- Testing package with non-existing version file'
+ versioncheck('VersionTestPackage', _TESTDIR+'nonexistent.txt', '1.0', verbose=2)
+ print '--- Test package with 2 locations, first non-existing second ok'
+ versfiles = [_TESTDIR+'nonexistent.txt', _TESTDIR+'Version10.txt']
+ versioncheck('VersionTestPackage', versfiles, '1.0', verbose=2)
+
+if __name__ == '__main__':
+ _test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/README
new file mode 100644
index 0000000000..542081c7bc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/README
@@ -0,0 +1,23 @@
+Webchecker
+----------
+
+This is a simple web tree checker, useful to find bad links in a web
+tree. It currently checks links pointing within the same subweb for
+validity. The main program is "webchecker.py". See its doc string
+(or invoke it with the option "-?") for more defails.
+
+History:
+
+- Jan 1997. First release. The module robotparser.py was written by
+Skip Montanaro; the rest is original work by Guido van Rossum.
+
+- May 1999. Sam Bayer contributed a new version, wcnew.py, which
+supports checking internal links (#spam fragments in URLs) and some
+other options.
+
+- Nov 1999. Sam Bayer contributed patches to reintegrate wcnew.py
+into webchecker.py, and corresponding mods to wcgui.py and
+websucker.py.
+
+- Mar 2004. Chris Herborth contributed a patch to let webchecker.py
+handle XHTML's 'id' attribute.
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/tktools.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/tktools.py
new file mode 100644
index 0000000000..af6437a9c4
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/tktools.py
@@ -0,0 +1,366 @@
+"""Assorted Tk-related subroutines used in Grail."""
+
+
+from types import *
+from Tkinter import *
+
+def _clear_entry_widget(event):
+ try:
+ widget = event.widget
+ widget.delete(0, INSERT)
+ except: pass
+def install_keybindings(root):
+ root.bind_class('Entry', '<Control-u>', _clear_entry_widget)
+
+
+def make_toplevel(master, title=None, class_=None):
+ """Create a Toplevel widget.
+
+ This is a shortcut for a Toplevel() instantiation plus calls to
+ set the title and icon name of the widget.
+
+ """
+
+ if class_:
+ widget = Toplevel(master, class_=class_)
+ else:
+ widget = Toplevel(master)
+ if title:
+ widget.title(title)
+ widget.iconname(title)
+ return widget
+
+def set_transient(widget, master, relx=0.5, rely=0.3, expose=1):
+ """Make an existing toplevel widget transient for a master.
+
+ The widget must exist but should not yet have been placed; in
+ other words, this should be called after creating all the
+ subwidget but before letting the user interact.
+ """
+
+ widget.withdraw() # Remain invisible while we figure out the geometry
+ widget.transient(master)
+ widget.update_idletasks() # Actualize geometry information
+ if master.winfo_ismapped():
+ m_width = master.winfo_width()
+ m_height = master.winfo_height()
+ m_x = master.winfo_rootx()
+ m_y = master.winfo_rooty()
+ else:
+ m_width = master.winfo_screenwidth()
+ m_height = master.winfo_screenheight()
+ m_x = m_y = 0
+ w_width = widget.winfo_reqwidth()
+ w_height = widget.winfo_reqheight()
+ x = m_x + (m_width - w_width) * relx
+ y = m_y + (m_height - w_height) * rely
+ widget.geometry("+%d+%d" % (x, y))
+ if expose:
+ widget.deiconify() # Become visible at the desired location
+ return widget
+
+
+def make_scrollbars(parent, hbar, vbar, pack=1, class_=None, name=None,
+ takefocus=0):
+
+ """Subroutine to create a frame with scrollbars.
+
+ This is used by make_text_box and similar routines.
+
+ Note: the caller is responsible for setting the x/y scroll command
+ properties (e.g. by calling set_scroll_commands()).
+
+ Return a tuple containing the hbar, the vbar, and the frame, where
+ hbar and vbar are None if not requested.
+
+ """
+ if class_:
+ if name: frame = Frame(parent, class_=class_, name=name)
+ else: frame = Frame(parent, class_=class_)
+ else:
+ if name: frame = Frame(parent, name=name)
+ else: frame = Frame(parent)
+
+ if pack:
+ frame.pack(fill=BOTH, expand=1)
+
+ corner = None
+ if vbar:
+ if not hbar:
+ vbar = Scrollbar(frame, takefocus=takefocus)
+ vbar.pack(fill=Y, side=RIGHT)
+ else:
+ vbarframe = Frame(frame, borderwidth=0)
+ vbarframe.pack(fill=Y, side=RIGHT)
+ vbar = Scrollbar(frame, name="vbar", takefocus=takefocus)
+ vbar.pack(in_=vbarframe, expand=1, fill=Y, side=TOP)
+ sbwidth = vbar.winfo_reqwidth()
+ corner = Frame(vbarframe, width=sbwidth, height=sbwidth)
+ corner.propagate(0)
+ corner.pack(side=BOTTOM)
+ else:
+ vbar = None
+
+ if hbar:
+ hbar = Scrollbar(frame, orient=HORIZONTAL, name="hbar",
+ takefocus=takefocus)
+ hbar.pack(fill=X, side=BOTTOM)
+ else:
+ hbar = None
+
+ return hbar, vbar, frame
+
+
+def set_scroll_commands(widget, hbar, vbar):
+
+ """Link a scrollable widget to its scroll bars.
+
+ The scroll bars may be empty.
+
+ """
+
+ if vbar:
+ widget['yscrollcommand'] = (vbar, 'set')
+ vbar['command'] = (widget, 'yview')
+
+ if hbar:
+ widget['xscrollcommand'] = (hbar, 'set')
+ hbar['command'] = (widget, 'xview')
+
+ widget.vbar = vbar
+ widget.hbar = hbar
+
+
+def make_text_box(parent, width=0, height=0, hbar=0, vbar=1,
+ fill=BOTH, expand=1, wrap=WORD, pack=1,
+ class_=None, name=None, takefocus=None):
+
+ """Subroutine to create a text box.
+
+ Create:
+ - a both-ways filling and expanding frame, containing:
+ - a text widget on the left, and
+ - possibly a vertical scroll bar on the right.
+ - possibly a horizonta; scroll bar at the bottom.
+
+ Return the text widget and the frame widget.
+
+ """
+ hbar, vbar, frame = make_scrollbars(parent, hbar, vbar, pack,
+ class_=class_, name=name,
+ takefocus=takefocus)
+
+ widget = Text(frame, wrap=wrap, name="text")
+ if width: widget.config(width=width)
+ if height: widget.config(height=height)
+ widget.pack(expand=expand, fill=fill, side=LEFT)
+
+ set_scroll_commands(widget, hbar, vbar)
+
+ return widget, frame
+
+
+def make_list_box(parent, width=0, height=0, hbar=0, vbar=1,
+ fill=BOTH, expand=1, pack=1, class_=None, name=None,
+ takefocus=None):
+
+ """Subroutine to create a list box.
+
+ Like make_text_box().
+ """
+ hbar, vbar, frame = make_scrollbars(parent, hbar, vbar, pack,
+ class_=class_, name=name,
+ takefocus=takefocus)
+
+ widget = Listbox(frame, name="listbox")
+ if width: widget.config(width=width)
+ if height: widget.config(height=height)
+ widget.pack(expand=expand, fill=fill, side=LEFT)
+
+ set_scroll_commands(widget, hbar, vbar)
+
+ return widget, frame
+
+
+def make_canvas(parent, width=0, height=0, hbar=1, vbar=1,
+ fill=BOTH, expand=1, pack=1, class_=None, name=None,
+ takefocus=None):
+
+ """Subroutine to create a canvas.
+
+ Like make_text_box().
+
+ """
+
+ hbar, vbar, frame = make_scrollbars(parent, hbar, vbar, pack,
+ class_=class_, name=name,
+ takefocus=takefocus)
+
+ widget = Canvas(frame, scrollregion=(0, 0, width, height), name="canvas")
+ if width: widget.config(width=width)
+ if height: widget.config(height=height)
+ widget.pack(expand=expand, fill=fill, side=LEFT)
+
+ set_scroll_commands(widget, hbar, vbar)
+
+ return widget, frame
+
+
+
+def make_form_entry(parent, label, borderwidth=None):
+
+ """Subroutine to create a form entry.
+
+ Create:
+ - a horizontally filling and expanding frame, containing:
+ - a label on the left, and
+ - a text entry on the right.
+
+ Return the entry widget and the frame widget.
+
+ """
+
+ frame = Frame(parent)
+ frame.pack(fill=X)
+
+ label = Label(frame, text=label)
+ label.pack(side=LEFT)
+
+ if borderwidth is None:
+ entry = Entry(frame, relief=SUNKEN)
+ else:
+ entry = Entry(frame, relief=SUNKEN, borderwidth=borderwidth)
+ entry.pack(side=LEFT, fill=X, expand=1)
+
+ return entry, frame
+
+# This is a slightly modified version of the function above. This
+# version does the proper alighnment of labels with their fields. It
+# should probably eventually replace make_form_entry altogether.
+#
+# The one annoying bug is that the text entry field should be
+# expandable while still aligning the colons. This doesn't work yet.
+#
+def make_labeled_form_entry(parent, label, entrywidth=20, entryheight=1,
+ labelwidth=0, borderwidth=None,
+ takefocus=None):
+ """Subroutine to create a form entry.
+
+ Create:
+ - a horizontally filling and expanding frame, containing:
+ - a label on the left, and
+ - a text entry on the right.
+
+ Return the entry widget and the frame widget.
+ """
+ if label and label[-1] != ':': label = label + ':'
+
+ frame = Frame(parent)
+
+ label = Label(frame, text=label, width=labelwidth, anchor=E)
+ label.pack(side=LEFT)
+ if entryheight == 1:
+ if borderwidth is None:
+ entry = Entry(frame, relief=SUNKEN, width=entrywidth)
+ else:
+ entry = Entry(frame, relief=SUNKEN, width=entrywidth,
+ borderwidth=borderwidth)
+ entry.pack(side=RIGHT, expand=1, fill=X)
+ frame.pack(fill=X)
+ else:
+ entry = make_text_box(frame, entrywidth, entryheight, 1, 1,
+ takefocus=takefocus)
+ frame.pack(fill=BOTH, expand=1)
+
+ return entry, frame, label
+
+
+def make_double_frame(master=None, class_=None, name=None, relief=RAISED,
+ borderwidth=1):
+ """Create a pair of frames suitable for 'hosting' a dialog."""
+ if name:
+ if class_: frame = Frame(master, class_=class_, name=name)
+ else: frame = Frame(master, name=name)
+ else:
+ if class_: frame = Frame(master, class_=class_)
+ else: frame = Frame(master)
+ top = Frame(frame, name="topframe", relief=relief,
+ borderwidth=borderwidth)
+ bottom = Frame(frame, name="bottomframe")
+ bottom.pack(fill=X, padx='1m', pady='1m', side=BOTTOM)
+ top.pack(expand=1, fill=BOTH, padx='1m', pady='1m')
+ frame.pack(expand=1, fill=BOTH)
+ top = Frame(top)
+ top.pack(expand=1, fill=BOTH, padx='2m', pady='2m')
+
+ return frame, top, bottom
+
+
+def make_group_frame(master, name=None, label=None, fill=Y,
+ side=None, expand=None, font=None):
+ """Create nested frames with a border and optional label.
+
+ The outer frame is only used to provide the decorative border, to
+ control packing, and to host the label. The inner frame is packed
+ to fill the outer frame and should be used as the parent of all
+ sub-widgets. Only the inner frame is returned.
+
+ """
+ font = font or "-*-helvetica-medium-r-normal-*-*-100-*-*-*-*-*-*"
+ outer = Frame(master, borderwidth=2, relief=GROOVE)
+ outer.pack(expand=expand, fill=fill, side=side)
+ if label:
+ Label(outer, text=label, font=font, anchor=W).pack(fill=X)
+ inner = Frame(master, borderwidth='1m', name=name)
+ inner.pack(expand=1, fill=BOTH, in_=outer)
+ inner.forget = outer.forget
+ return inner
+
+
+def unify_button_widths(*buttons):
+ """Make buttons passed in all have the same width.
+
+ Works for labels and other widgets with the 'text' option.
+
+ """
+ wid = 0
+ for btn in buttons:
+ wid = max(wid, len(btn["text"]))
+ for btn in buttons:
+ btn["width"] = wid
+
+
+def flatten(msg):
+ """Turn a list or tuple into a single string -- recursively."""
+ t = type(msg)
+ if t in (ListType, TupleType):
+ msg = ' '.join(map(flatten, msg))
+ elif t is ClassType:
+ msg = msg.__name__
+ else:
+ msg = str(msg)
+ return msg
+
+
+def boolean(s):
+ """Test whether a string is a Tk boolean, without error checking."""
+ if s.lower() in ('', '0', 'no', 'off', 'false'): return 0
+ else: return 1
+
+
+def test():
+ """Test make_text_box(), make_form_entry(), flatten(), boolean()."""
+ import sys
+ root = Tk()
+ entry, eframe = make_form_entry(root, 'Boolean:')
+ text, tframe = make_text_box(root)
+ def enter(event, entry=entry, text=text):
+ s = boolean(entry.get()) and '\nyes' or '\nno'
+ text.insert('end', s)
+ entry.bind('<Return>', enter)
+ entry.insert(END, flatten(sys.argv))
+ root.mainloop()
+
+
+if __name__ == '__main__':
+ test()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcgui.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcgui.py
new file mode 100644
index 0000000000..03004855bc
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcgui.py
@@ -0,0 +1,456 @@
+#! /usr/bin/env python
+
+"""GUI interface to webchecker.
+
+This works as a Grail applet too! E.g.
+
+ <APPLET CODE=wcgui.py NAME=CheckerWindow></APPLET>
+
+Checkpoints are not (yet??? ever???) supported.
+
+User interface:
+
+Enter a root to check in the text entry box. To enter more than one root,
+enter them one at a time and press <Return> for each one.
+
+Command buttons Start, Stop and "Check one" govern the checking process in
+the obvious way. Start and "Check one" also enter the root from the text
+entry box if one is present. There's also a check box (enabled by default)
+to decide whether actually to follow external links (since this can slow
+the checking down considerably). Finally there's a Quit button.
+
+A series of checkbuttons determines whether the corresponding output panel
+is shown. List panels are also automatically shown or hidden when their
+status changes between empty to non-empty. There are six panels:
+
+Log -- raw output from the checker (-v, -q affect this)
+To check -- links discovered but not yet checked
+Checked -- links that have been checked
+Bad links -- links that failed upon checking
+Errors -- pages containing at least one bad link
+Details -- details about one URL; double click on a URL in any of
+ the above list panels (not in Log) will show details
+ for that URL
+
+Use your window manager's Close command to quit.
+
+Command line options:
+
+-m bytes -- skip HTML pages larger than this size (default %(MAXPAGE)d)
+-q -- quiet operation (also suppresses external links report)
+-v -- verbose operation; repeating -v will increase verbosity
+-t root -- specify root dir which should be treated as internal (can repeat)
+-a -- don't check name anchors
+
+Command line arguments:
+
+rooturl -- URL to start checking
+ (default %(DEFROOT)s)
+
+XXX The command line options (-m, -q, -v) should be GUI accessible.
+
+XXX The roots should be visible as a list (?).
+
+XXX The multipanel user interface is clumsy.
+
+"""
+
+# ' Emacs bait
+
+
+import sys
+import getopt
+from Tkinter import *
+import tktools
+import webchecker
+
+def main():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 't:m:qva')
+ except getopt.error, msg:
+ sys.stdout = sys.stderr
+ print msg
+ print __doc__%vars(webchecker)
+ sys.exit(2)
+ webchecker.verbose = webchecker.VERBOSE
+ webchecker.nonames = webchecker.NONAMES
+ webchecker.maxpage = webchecker.MAXPAGE
+ extra_roots = []
+ for o, a in opts:
+ if o == '-m':
+ webchecker.maxpage = int(a)
+ if o == '-q':
+ webchecker.verbose = 0
+ if o == '-v':
+ webchecker.verbose = webchecker.verbose + 1
+ if o == '-t':
+ extra_roots.append(a)
+ if o == '-a':
+ webchecker.nonames = not webchecker.nonames
+ root = Tk(className='Webchecker')
+ root.protocol("WM_DELETE_WINDOW", root.quit)
+ c = CheckerWindow(root)
+ c.setflags(verbose=webchecker.verbose, maxpage=webchecker.maxpage,
+ nonames=webchecker.nonames)
+ if args:
+ for arg in args[:-1]:
+ c.addroot(arg)
+ c.suggestroot(args[-1])
+ # Usually conditioned on whether external links
+ # will be checked, but since that's not a command
+ # line option, just toss them in.
+ for url_root in extra_roots:
+ # Make sure it's terminated by a slash,
+ # so that addroot doesn't discard the last
+ # directory component.
+ if url_root[-1] != "/":
+ url_root = url_root + "/"
+ c.addroot(url_root, add_to_do = 0)
+ root.mainloop()
+
+
+class CheckerWindow(webchecker.Checker):
+
+ def __init__(self, parent, root=webchecker.DEFROOT):
+ self.__parent = parent
+
+ self.__topcontrols = Frame(parent)
+ self.__topcontrols.pack(side=TOP, fill=X)
+ self.__label = Label(self.__topcontrols, text="Root URL:")
+ self.__label.pack(side=LEFT)
+ self.__rootentry = Entry(self.__topcontrols, width=60)
+ self.__rootentry.pack(side=LEFT)
+ self.__rootentry.bind('<Return>', self.enterroot)
+ self.__rootentry.focus_set()
+
+ self.__controls = Frame(parent)
+ self.__controls.pack(side=TOP, fill=X)
+ self.__running = 0
+ self.__start = Button(self.__controls, text="Run", command=self.start)
+ self.__start.pack(side=LEFT)
+ self.__stop = Button(self.__controls, text="Stop", command=self.stop,
+ state=DISABLED)
+ self.__stop.pack(side=LEFT)
+ self.__step = Button(self.__controls, text="Check one",
+ command=self.step)
+ self.__step.pack(side=LEFT)
+ self.__cv = BooleanVar(parent)
+ self.__cv.set(self.checkext)
+ self.__checkext = Checkbutton(self.__controls, variable=self.__cv,
+ command=self.update_checkext,
+ text="Check nonlocal links",)
+ self.__checkext.pack(side=LEFT)
+ self.__reset = Button(self.__controls, text="Start over", command=self.reset)
+ self.__reset.pack(side=LEFT)
+ if __name__ == '__main__': # No Quit button under Grail!
+ self.__quit = Button(self.__controls, text="Quit",
+ command=self.__parent.quit)
+ self.__quit.pack(side=RIGHT)
+
+ self.__status = Label(parent, text="Status: initial", anchor=W)
+ self.__status.pack(side=TOP, fill=X)
+ self.__checking = Label(parent, text="Idle", anchor=W)
+ self.__checking.pack(side=TOP, fill=X)
+ self.__mp = mp = MultiPanel(parent)
+ sys.stdout = self.__log = LogPanel(mp, "Log")
+ self.__todo = ListPanel(mp, "To check", self, self.showinfo)
+ self.__done = ListPanel(mp, "Checked", self, self.showinfo)
+ self.__bad = ListPanel(mp, "Bad links", self, self.showinfo)
+ self.__errors = ListPanel(mp, "Pages w/ bad links", self, self.showinfo)
+ self.__details = LogPanel(mp, "Details")
+ self.root_seed = None
+ webchecker.Checker.__init__(self)
+ if root:
+ root = str(root).strip()
+ if root:
+ self.suggestroot(root)
+ self.newstatus()
+
+ def reset(self):
+ webchecker.Checker.reset(self)
+ for p in self.__todo, self.__done, self.__bad, self.__errors:
+ p.clear()
+ if self.root_seed:
+ self.suggestroot(self.root_seed)
+
+ def suggestroot(self, root):
+ self.__rootentry.delete(0, END)
+ self.__rootentry.insert(END, root)
+ self.__rootentry.select_range(0, END)
+ self.root_seed = root
+
+ def enterroot(self, event=None):
+ root = self.__rootentry.get()
+ root = root.strip()
+ if root:
+ self.__checking.config(text="Adding root "+root)
+ self.__checking.update_idletasks()
+ self.addroot(root)
+ self.__checking.config(text="Idle")
+ try:
+ i = self.__todo.items.index(root)
+ except (ValueError, IndexError):
+ pass
+ else:
+ self.__todo.list.select_clear(0, END)
+ self.__todo.list.select_set(i)
+ self.__todo.list.yview(i)
+ self.__rootentry.delete(0, END)
+
+ def start(self):
+ self.__start.config(state=DISABLED, relief=SUNKEN)
+ self.__stop.config(state=NORMAL)
+ self.__step.config(state=DISABLED)
+ self.enterroot()
+ self.__running = 1
+ self.go()
+
+ def stop(self):
+ self.__stop.config(state=DISABLED, relief=SUNKEN)
+ self.__running = 0
+
+ def step(self):
+ self.__start.config(state=DISABLED)
+ self.__step.config(state=DISABLED, relief=SUNKEN)
+ self.enterroot()
+ self.__running = 0
+ self.dosomething()
+
+ def go(self):
+ if self.__running:
+ self.__parent.after_idle(self.dosomething)
+ else:
+ self.__checking.config(text="Idle")
+ self.__start.config(state=NORMAL, relief=RAISED)
+ self.__stop.config(state=DISABLED, relief=RAISED)
+ self.__step.config(state=NORMAL, relief=RAISED)
+
+ __busy = 0
+
+ def dosomething(self):
+ if self.__busy: return
+ self.__busy = 1
+ if self.todo:
+ l = self.__todo.selectedindices()
+ if l:
+ i = l[0]
+ else:
+ i = 0
+ self.__todo.list.select_set(i)
+ self.__todo.list.yview(i)
+ url = self.__todo.items[i]
+ self.__checking.config(text="Checking "+self.format_url(url))
+ self.__parent.update()
+ self.dopage(url)
+ else:
+ self.stop()
+ self.__busy = 0
+ self.go()
+
+ def showinfo(self, url):
+ d = self.__details
+ d.clear()
+ d.put("URL: %s\n" % self.format_url(url))
+ if self.bad.has_key(url):
+ d.put("Error: %s\n" % str(self.bad[url]))
+ if url in self.roots:
+ d.put("Note: This is a root URL\n")
+ if self.done.has_key(url):
+ d.put("Status: checked\n")
+ o = self.done[url]
+ elif self.todo.has_key(url):
+ d.put("Status: to check\n")
+ o = self.todo[url]
+ else:
+ d.put("Status: unknown (!)\n")
+ o = []
+ if (not url[1]) and self.errors.has_key(url[0]):
+ d.put("Bad links from this page:\n")
+ for triple in self.errors[url[0]]:
+ link, rawlink, msg = triple
+ d.put(" HREF %s" % self.format_url(link))
+ if self.format_url(link) != rawlink: d.put(" (%s)" %rawlink)
+ d.put("\n")
+ d.put(" error %s\n" % str(msg))
+ self.__mp.showpanel("Details")
+ for source, rawlink in o:
+ d.put("Origin: %s" % source)
+ if rawlink != self.format_url(url):
+ d.put(" (%s)" % rawlink)
+ d.put("\n")
+ d.text.yview("1.0")
+
+ def setbad(self, url, msg):
+ webchecker.Checker.setbad(self, url, msg)
+ self.__bad.insert(url)
+ self.newstatus()
+
+ def setgood(self, url):
+ webchecker.Checker.setgood(self, url)
+ self.__bad.remove(url)
+ self.newstatus()
+
+ def newlink(self, url, origin):
+ webchecker.Checker.newlink(self, url, origin)
+ if self.done.has_key(url):
+ self.__done.insert(url)
+ elif self.todo.has_key(url):
+ self.__todo.insert(url)
+ self.newstatus()
+
+ def markdone(self, url):
+ webchecker.Checker.markdone(self, url)
+ self.__done.insert(url)
+ self.__todo.remove(url)
+ self.newstatus()
+
+ def seterror(self, url, triple):
+ webchecker.Checker.seterror(self, url, triple)
+ self.__errors.insert((url, ''))
+ self.newstatus()
+
+ def newstatus(self):
+ self.__status.config(text="Status: "+self.status())
+ self.__parent.update()
+
+ def update_checkext(self):
+ self.checkext = self.__cv.get()
+
+
+class ListPanel:
+
+ def __init__(self, mp, name, checker, showinfo=None):
+ self.mp = mp
+ self.name = name
+ self.showinfo = showinfo
+ self.checker = checker
+ self.panel = mp.addpanel(name)
+ self.list, self.frame = tktools.make_list_box(
+ self.panel, width=60, height=5)
+ self.list.config(exportselection=0)
+ if showinfo:
+ self.list.bind('<Double-Button-1>', self.doubleclick)
+ self.items = []
+
+ def clear(self):
+ self.items = []
+ self.list.delete(0, END)
+ self.mp.hidepanel(self.name)
+
+ def doubleclick(self, event):
+ l = self.selectedindices()
+ if l:
+ self.showinfo(self.items[l[0]])
+
+ def selectedindices(self):
+ l = self.list.curselection()
+ if not l: return []
+ return map(int, l)
+
+ def insert(self, url):
+ if url not in self.items:
+ if not self.items:
+ self.mp.showpanel(self.name)
+ # (I tried sorting alphabetically, but the display is too jumpy)
+ i = len(self.items)
+ self.list.insert(i, self.checker.format_url(url))
+ self.list.yview(i)
+ self.items.insert(i, url)
+
+ def remove(self, url):
+ try:
+ i = self.items.index(url)
+ except (ValueError, IndexError):
+ pass
+ else:
+ was_selected = i in self.selectedindices()
+ self.list.delete(i)
+ del self.items[i]
+ if not self.items:
+ self.mp.hidepanel(self.name)
+ elif was_selected:
+ if i >= len(self.items):
+ i = len(self.items) - 1
+ self.list.select_set(i)
+
+
+class LogPanel:
+
+ def __init__(self, mp, name):
+ self.mp = mp
+ self.name = name
+ self.panel = mp.addpanel(name)
+ self.text, self.frame = tktools.make_text_box(self.panel, height=10)
+ self.text.config(wrap=NONE)
+
+ def clear(self):
+ self.text.delete("1.0", END)
+ self.text.yview("1.0")
+
+ def put(self, s):
+ self.text.insert(END, s)
+ if '\n' in s:
+ self.text.yview(END)
+
+ def write(self, s):
+ self.text.insert(END, s)
+ if '\n' in s:
+ self.text.yview(END)
+ self.panel.update()
+
+
+class MultiPanel:
+
+ def __init__(self, parent):
+ self.parent = parent
+ self.frame = Frame(self.parent)
+ self.frame.pack(expand=1, fill=BOTH)
+ self.topframe = Frame(self.frame, borderwidth=2, relief=RAISED)
+ self.topframe.pack(fill=X)
+ self.botframe = Frame(self.frame)
+ self.botframe.pack(expand=1, fill=BOTH)
+ self.panelnames = []
+ self.panels = {}
+
+ def addpanel(self, name, on=0):
+ v = StringVar(self.parent)
+ if on:
+ v.set(name)
+ else:
+ v.set("")
+ check = Checkbutton(self.topframe, text=name,
+ offvalue="", onvalue=name, variable=v,
+ command=self.checkpanel)
+ check.pack(side=LEFT)
+ panel = Frame(self.botframe)
+ label = Label(panel, text=name, borderwidth=2, relief=RAISED, anchor=W)
+ label.pack(side=TOP, fill=X)
+ t = v, check, panel
+ self.panelnames.append(name)
+ self.panels[name] = t
+ if on:
+ panel.pack(expand=1, fill=BOTH)
+ return panel
+
+ def showpanel(self, name):
+ v, check, panel = self.panels[name]
+ v.set(name)
+ panel.pack(expand=1, fill=BOTH)
+
+ def hidepanel(self, name):
+ v, check, panel = self.panels[name]
+ v.set("")
+ panel.pack_forget()
+
+ def checkpanel(self):
+ for name in self.panelnames:
+ v, check, panel = self.panels[name]
+ panel.pack_forget()
+ for name in self.panelnames:
+ v, check, panel = self.panels[name]
+ if v.get():
+ panel.pack(expand=1, fill=BOTH)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcmac.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcmac.py
new file mode 100644
index 0000000000..efab29d6cb
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wcmac.py
@@ -0,0 +1,7 @@
+import webchecker, sys
+webchecker.DEFROOT = "http://www.python.org/python/"
+webchecker.MAXPAGE = 50000
+webchecker.verbose = 2
+sys.argv.append('-x')
+webchecker.main()
+raw_input("\nCR to exit: ")
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/webchecker.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/webchecker.py
new file mode 100644
index 0000000000..9a0a6e63e7
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/webchecker.py
@@ -0,0 +1,892 @@
+#! /usr/bin/env python
+
+# Original code by Guido van Rossum; extensive changes by Sam Bayer,
+# including code to check URL fragments.
+
+"""Web tree checker.
+
+This utility is handy to check a subweb of the world-wide web for
+errors. A subweb is specified by giving one or more ``root URLs''; a
+page belongs to the subweb if one of the root URLs is an initial
+prefix of it.
+
+File URL extension:
+
+In order to easy the checking of subwebs via the local file system,
+the interpretation of ``file:'' URLs is extended to mimic the behavior
+of your average HTTP daemon: if a directory pathname is given, the
+file index.html in that directory is returned if it exists, otherwise
+a directory listing is returned. Now, you can point webchecker to the
+document tree in the local file system of your HTTP daemon, and have
+most of it checked. In fact the default works this way if your local
+web tree is located at /usr/local/etc/httpd/htdpcs (the default for
+the NCSA HTTP daemon and probably others).
+
+Report printed:
+
+When done, it reports pages with bad links within the subweb. When
+interrupted, it reports for the pages that it has checked already.
+
+In verbose mode, additional messages are printed during the
+information gathering phase. By default, it prints a summary of its
+work status every 50 URLs (adjustable with the -r option), and it
+reports errors as they are encountered. Use the -q option to disable
+this output.
+
+Checkpoint feature:
+
+Whether interrupted or not, it dumps its state (a Python pickle) to a
+checkpoint file and the -R option allows it to restart from the
+checkpoint (assuming that the pages on the subweb that were already
+processed haven't changed). Even when it has run till completion, -R
+can still be useful -- it will print the reports again, and -Rq prints
+the errors only. In this case, the checkpoint file is not written
+again. The checkpoint file can be set with the -d option.
+
+The checkpoint file is written as a Python pickle. Remember that
+Python's pickle module is currently quite slow. Give it the time it
+needs to load and save the checkpoint file. When interrupted while
+writing the checkpoint file, the old checkpoint file is not
+overwritten, but all work done in the current run is lost.
+
+Miscellaneous:
+
+- You may find the (Tk-based) GUI version easier to use. See wcgui.py.
+
+- Webchecker honors the "robots.txt" convention. Thanks to Skip
+Montanaro for his robotparser.py module (included in this directory)!
+The agent name is hardwired to "webchecker". URLs that are disallowed
+by the robots.txt file are reported as external URLs.
+
+- Because the SGML parser is a bit slow, very large SGML files are
+skipped. The size limit can be set with the -m option.
+
+- When the server or protocol does not tell us a file's type, we guess
+it based on the URL's suffix. The mimetypes.py module (also in this
+directory) has a built-in table mapping most currently known suffixes,
+and in addition attempts to read the mime.types configuration files in
+the default locations of Netscape and the NCSA HTTP daemon.
+
+- We follow links indicated by <A>, <FRAME> and <IMG> tags. We also
+honor the <BASE> tag.
+
+- We now check internal NAME anchor links, as well as toplevel links.
+
+- Checking external links is now done by default; use -x to *disable*
+this feature. External links are now checked during normal
+processing. (XXX The status of a checked link could be categorized
+better. Later...)
+
+- If external links are not checked, you can use the -t flag to
+provide specific overrides to -x.
+
+Usage: webchecker.py [option] ... [rooturl] ...
+
+Options:
+
+-R -- restart from checkpoint file
+-d file -- checkpoint filename (default %(DUMPFILE)s)
+-m bytes -- skip HTML pages larger than this size (default %(MAXPAGE)d)
+-n -- reports only, no checking (use with -R)
+-q -- quiet operation (also suppresses external links report)
+-r number -- number of links processed per round (default %(ROUNDSIZE)d)
+-t root -- specify root dir which should be treated as internal (can repeat)
+-v -- verbose operation; repeating -v will increase verbosity
+-x -- don't check external links (these are often slow to check)
+-a -- don't check name anchors
+
+Arguments:
+
+rooturl -- URL to start checking
+ (default %(DEFROOT)s)
+
+"""
+
+
+__version__ = "$Revision$"
+
+
+import sys
+import os
+from types import *
+import StringIO
+import getopt
+import pickle
+
+import urllib
+import urlparse
+import sgmllib
+import cgi
+
+import mimetypes
+import robotparser
+
+# Extract real version number if necessary
+if __version__[0] == '$':
+ _v = __version__.split()
+ if len(_v) == 3:
+ __version__ = _v[1]
+
+
+# Tunable parameters
+DEFROOT = "file:/usr/local/etc/httpd/htdocs/" # Default root URL
+CHECKEXT = 1 # Check external references (1 deep)
+VERBOSE = 1 # Verbosity level (0-3)
+MAXPAGE = 150000 # Ignore files bigger than this
+ROUNDSIZE = 50 # Number of links processed per round
+DUMPFILE = "@webchecker.pickle" # Pickled checkpoint
+AGENTNAME = "webchecker" # Agent name for robots.txt parser
+NONAMES = 0 # Force name anchor checking
+
+
+# Global variables
+
+
+def main():
+ checkext = CHECKEXT
+ verbose = VERBOSE
+ maxpage = MAXPAGE
+ roundsize = ROUNDSIZE
+ dumpfile = DUMPFILE
+ restart = 0
+ norun = 0
+
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')
+ except getopt.error, msg:
+ sys.stdout = sys.stderr
+ print msg
+ print __doc__%globals()
+ sys.exit(2)
+
+ # The extra_roots variable collects extra roots.
+ extra_roots = []
+ nonames = NONAMES
+
+ for o, a in opts:
+ if o == '-R':
+ restart = 1
+ if o == '-d':
+ dumpfile = a
+ if o == '-m':
+ maxpage = int(a)
+ if o == '-n':
+ norun = 1
+ if o == '-q':
+ verbose = 0
+ if o == '-r':
+ roundsize = int(a)
+ if o == '-t':
+ extra_roots.append(a)
+ if o == '-a':
+ nonames = not nonames
+ if o == '-v':
+ verbose = verbose + 1
+ if o == '-x':
+ checkext = not checkext
+
+ if verbose > 0:
+ print AGENTNAME, "version", __version__
+
+ if restart:
+ c = load_pickle(dumpfile=dumpfile, verbose=verbose)
+ else:
+ c = Checker()
+
+ c.setflags(checkext=checkext, verbose=verbose,
+ maxpage=maxpage, roundsize=roundsize,
+ nonames=nonames
+ )
+
+ if not restart and not args:
+ args.append(DEFROOT)
+
+ for arg in args:
+ c.addroot(arg)
+
+ # The -t flag is only needed if external links are not to be
+ # checked. So -t values are ignored unless -x was specified.
+ if not checkext:
+ for root in extra_roots:
+ # Make sure it's terminated by a slash,
+ # so that addroot doesn't discard the last
+ # directory component.
+ if root[-1] != "/":
+ root = root + "/"
+ c.addroot(root, add_to_do = 0)
+
+ try:
+
+ if not norun:
+ try:
+ c.run()
+ except KeyboardInterrupt:
+ if verbose > 0:
+ print "[run interrupted]"
+
+ try:
+ c.report()
+ except KeyboardInterrupt:
+ if verbose > 0:
+ print "[report interrupted]"
+
+ finally:
+ if c.save_pickle(dumpfile):
+ if dumpfile == DUMPFILE:
+ print "Use ``%s -R'' to restart." % sys.argv[0]
+ else:
+ print "Use ``%s -R -d %s'' to restart." % (sys.argv[0],
+ dumpfile)
+
+
+def load_pickle(dumpfile=DUMPFILE, verbose=VERBOSE):
+ if verbose > 0:
+ print "Loading checkpoint from %s ..." % dumpfile
+ f = open(dumpfile, "rb")
+ c = pickle.load(f)
+ f.close()
+ if verbose > 0:
+ print "Done."
+ print "Root:", "\n ".join(c.roots)
+ return c
+
+
+class Checker:
+
+ checkext = CHECKEXT
+ verbose = VERBOSE
+ maxpage = MAXPAGE
+ roundsize = ROUNDSIZE
+ nonames = NONAMES
+
+ validflags = tuple(dir())
+
+ def __init__(self):
+ self.reset()
+
+ def setflags(self, **kw):
+ for key in kw.keys():
+ if key not in self.validflags:
+ raise NameError, "invalid keyword argument: %s" % str(key)
+ for key, value in kw.items():
+ setattr(self, key, value)
+
+ def reset(self):
+ self.roots = []
+ self.todo = {}
+ self.done = {}
+ self.bad = {}
+
+ # Add a name table, so that the name URLs can be checked. Also
+ # serves as an implicit cache for which URLs are done.
+ self.name_table = {}
+
+ self.round = 0
+ # The following are not pickled:
+ self.robots = {}
+ self.errors = {}
+ self.urlopener = MyURLopener()
+ self.changed = 0
+
+ def note(self, level, format, *args):
+ if self.verbose > level:
+ if args:
+ format = format%args
+ self.message(format)
+
+ def message(self, format, *args):
+ if args:
+ format = format%args
+ print format
+
+ def __getstate__(self):
+ return (self.roots, self.todo, self.done, self.bad, self.round)
+
+ def __setstate__(self, state):
+ self.reset()
+ (self.roots, self.todo, self.done, self.bad, self.round) = state
+ for root in self.roots:
+ self.addrobot(root)
+ for url in self.bad.keys():
+ self.markerror(url)
+
+ def addroot(self, root, add_to_do = 1):
+ if root not in self.roots:
+ troot = root
+ scheme, netloc, path, params, query, fragment = \
+ urlparse.urlparse(root)
+ i = path.rfind("/") + 1
+ if 0 < i < len(path):
+ path = path[:i]
+ troot = urlparse.urlunparse((scheme, netloc, path,
+ params, query, fragment))
+ self.roots.append(troot)
+ self.addrobot(root)
+ if add_to_do:
+ self.newlink((root, ""), ("<root>", root))
+
+ def addrobot(self, root):
+ root = urlparse.urljoin(root, "/")
+ if self.robots.has_key(root): return
+ url = urlparse.urljoin(root, "/robots.txt")
+ self.robots[root] = rp = robotparser.RobotFileParser()
+ self.note(2, "Parsing %s", url)
+ rp.debug = self.verbose > 3
+ rp.set_url(url)
+ try:
+ rp.read()
+ except (OSError, IOError), msg:
+ self.note(1, "I/O error parsing %s: %s", url, msg)
+
+ def run(self):
+ while self.todo:
+ self.round = self.round + 1
+ self.note(0, "\nRound %d (%s)\n", self.round, self.status())
+ urls = self.todo.keys()
+ urls.sort()
+ del urls[self.roundsize:]
+ for url in urls:
+ self.dopage(url)
+
+ def status(self):
+ return "%d total, %d to do, %d done, %d bad" % (
+ len(self.todo)+len(self.done),
+ len(self.todo), len(self.done),
+ len(self.bad))
+
+ def report(self):
+ self.message("")
+ if not self.todo: s = "Final"
+ else: s = "Interim"
+ self.message("%s Report (%s)", s, self.status())
+ self.report_errors()
+
+ def report_errors(self):
+ if not self.bad:
+ self.message("\nNo errors")
+ return
+ self.message("\nError Report:")
+ sources = self.errors.keys()
+ sources.sort()
+ for source in sources:
+ triples = self.errors[source]
+ self.message("")
+ if len(triples) > 1:
+ self.message("%d Errors in %s", len(triples), source)
+ else:
+ self.message("Error in %s", source)
+ # Call self.format_url() instead of referring
+ # to the URL directly, since the URLs in these
+ # triples is now a (URL, fragment) pair. The value
+ # of the "source" variable comes from the list of
+ # origins, and is a URL, not a pair.
+ for url, rawlink, msg in triples:
+ if rawlink != self.format_url(url): s = " (%s)" % rawlink
+ else: s = ""
+ self.message(" HREF %s%s\n msg %s",
+ self.format_url(url), s, msg)
+
+ def dopage(self, url_pair):
+
+ # All printing of URLs uses format_url(); argument changed to
+ # url_pair for clarity.
+ if self.verbose > 1:
+ if self.verbose > 2:
+ self.show("Check ", self.format_url(url_pair),
+ " from", self.todo[url_pair])
+ else:
+ self.message("Check %s", self.format_url(url_pair))
+ url, local_fragment = url_pair
+ if local_fragment and self.nonames:
+ self.markdone(url_pair)
+ return
+ try:
+ page = self.getpage(url_pair)
+ except sgmllib.SGMLParseError, msg:
+ msg = self.sanitize(msg)
+ self.note(0, "Error parsing %s: %s",
+ self.format_url(url_pair), msg)
+ # Dont actually mark the URL as bad - it exists, just
+ # we can't parse it!
+ page = None
+ if page:
+ # Store the page which corresponds to this URL.
+ self.name_table[url] = page
+ # If there is a fragment in this url_pair, and it's not
+ # in the list of names for the page, call setbad(), since
+ # it's a missing anchor.
+ if local_fragment and local_fragment not in page.getnames():
+ self.setbad(url_pair, ("Missing name anchor `%s'" % local_fragment))
+ for info in page.getlinkinfos():
+ # getlinkinfos() now returns the fragment as well,
+ # and we store that fragment here in the "todo" dictionary.
+ link, rawlink, fragment = info
+ # However, we don't want the fragment as the origin, since
+ # the origin is logically a page.
+ origin = url, rawlink
+ self.newlink((link, fragment), origin)
+ else:
+ # If no page has been created yet, we want to
+ # record that fact.
+ self.name_table[url_pair[0]] = None
+ self.markdone(url_pair)
+
+ def newlink(self, url, origin):
+ if self.done.has_key(url):
+ self.newdonelink(url, origin)
+ else:
+ self.newtodolink(url, origin)
+
+ def newdonelink(self, url, origin):
+ if origin not in self.done[url]:
+ self.done[url].append(origin)
+
+ # Call self.format_url(), since the URL here
+ # is now a (URL, fragment) pair.
+ self.note(3, " Done link %s", self.format_url(url))
+
+ # Make sure that if it's bad, that the origin gets added.
+ if self.bad.has_key(url):
+ source, rawlink = origin
+ triple = url, rawlink, self.bad[url]
+ self.seterror(source, triple)
+
+ def newtodolink(self, url, origin):
+ # Call self.format_url(), since the URL here
+ # is now a (URL, fragment) pair.
+ if self.todo.has_key(url):
+ if origin not in self.todo[url]:
+ self.todo[url].append(origin)
+ self.note(3, " Seen todo link %s", self.format_url(url))
+ else:
+ self.todo[url] = [origin]
+ self.note(3, " New todo link %s", self.format_url(url))
+
+ def format_url(self, url):
+ link, fragment = url
+ if fragment: return link + "#" + fragment
+ else: return link
+
+ def markdone(self, url):
+ self.done[url] = self.todo[url]
+ del self.todo[url]
+ self.changed = 1
+
+ def inroots(self, url):
+ for root in self.roots:
+ if url[:len(root)] == root:
+ return self.isallowed(root, url)
+ return 0
+
+ def isallowed(self, root, url):
+ root = urlparse.urljoin(root, "/")
+ return self.robots[root].can_fetch(AGENTNAME, url)
+
+ def getpage(self, url_pair):
+ # Incoming argument name is a (URL, fragment) pair.
+ # The page may have been cached in the name_table variable.
+ url, fragment = url_pair
+ if self.name_table.has_key(url):
+ return self.name_table[url]
+
+ scheme, path = urllib.splittype(url)
+ if scheme in ('mailto', 'news', 'javascript', 'telnet'):
+ self.note(1, " Not checking %s URL" % scheme)
+ return None
+ isint = self.inroots(url)
+
+ # Ensure that openpage gets the URL pair to
+ # print out its error message and record the error pair
+ # correctly.
+ if not isint:
+ if not self.checkext:
+ self.note(1, " Not checking ext link")
+ return None
+ f = self.openpage(url_pair)
+ if f:
+ self.safeclose(f)
+ return None
+ text, nurl = self.readhtml(url_pair)
+
+ if nurl != url:
+ self.note(1, " Redirected to %s", nurl)
+ url = nurl
+ if text:
+ return Page(text, url, maxpage=self.maxpage, checker=self)
+
+ # These next three functions take (URL, fragment) pairs as
+ # arguments, so that openpage() receives the appropriate tuple to
+ # record error messages.
+ def readhtml(self, url_pair):
+ url, fragment = url_pair
+ text = None
+ f, url = self.openhtml(url_pair)
+ if f:
+ text = f.read()
+ f.close()
+ return text, url
+
+ def openhtml(self, url_pair):
+ url, fragment = url_pair
+ f = self.openpage(url_pair)
+ if f:
+ url = f.geturl()
+ info = f.info()
+ if not self.checkforhtml(info, url):
+ self.safeclose(f)
+ f = None
+ return f, url
+
+ def openpage(self, url_pair):
+ url, fragment = url_pair
+ try:
+ return self.urlopener.open(url)
+ except (OSError, IOError), msg:
+ msg = self.sanitize(msg)
+ self.note(0, "Error %s", msg)
+ if self.verbose > 0:
+ self.show(" HREF ", url, " from", self.todo[url_pair])
+ self.setbad(url_pair, msg)
+ return None
+
+ def checkforhtml(self, info, url):
+ if info.has_key('content-type'):
+ ctype = cgi.parse_header(info['content-type'])[0].lower()
+ if ';' in ctype:
+ # handle content-type: text/html; charset=iso8859-1 :
+ ctype = ctype.split(';', 1)[0].strip()
+ else:
+ if url[-1:] == "/":
+ return 1
+ ctype, encoding = mimetypes.guess_type(url)
+ if ctype == 'text/html':
+ return 1
+ else:
+ self.note(1, " Not HTML, mime type %s", ctype)
+ return 0
+
+ def setgood(self, url):
+ if self.bad.has_key(url):
+ del self.bad[url]
+ self.changed = 1
+ self.note(0, "(Clear previously seen error)")
+
+ def setbad(self, url, msg):
+ if self.bad.has_key(url) and self.bad[url] == msg:
+ self.note(0, "(Seen this error before)")
+ return
+ self.bad[url] = msg
+ self.changed = 1
+ self.markerror(url)
+
+ def markerror(self, url):
+ try:
+ origins = self.todo[url]
+ except KeyError:
+ origins = self.done[url]
+ for source, rawlink in origins:
+ triple = url, rawlink, self.bad[url]
+ self.seterror(source, triple)
+
+ def seterror(self, url, triple):
+ try:
+ # Because of the way the URLs are now processed, I need to
+ # check to make sure the URL hasn't been entered in the
+ # error list. The first element of the triple here is a
+ # (URL, fragment) pair, but the URL key is not, since it's
+ # from the list of origins.
+ if triple not in self.errors[url]:
+ self.errors[url].append(triple)
+ except KeyError:
+ self.errors[url] = [triple]
+
+ # The following used to be toplevel functions; they have been
+ # changed into methods so they can be overridden in subclasses.
+
+ def show(self, p1, link, p2, origins):
+ self.message("%s %s", p1, link)
+ i = 0
+ for source, rawlink in origins:
+ i = i+1
+ if i == 2:
+ p2 = ' '*len(p2)
+ if rawlink != link: s = " (%s)" % rawlink
+ else: s = ""
+ self.message("%s %s%s", p2, source, s)
+
+ def sanitize(self, msg):
+ if isinstance(IOError, ClassType) and isinstance(msg, IOError):
+ # Do the other branch recursively
+ msg.args = self.sanitize(msg.args)
+ elif isinstance(msg, TupleType):
+ if len(msg) >= 4 and msg[0] == 'http error' and \
+ isinstance(msg[3], InstanceType):
+ # Remove the Message instance -- it may contain
+ # a file object which prevents pickling.
+ msg = msg[:3] + msg[4:]
+ return msg
+
+ def safeclose(self, f):
+ try:
+ url = f.geturl()
+ except AttributeError:
+ pass
+ else:
+ if url[:4] == 'ftp:' or url[:7] == 'file://':
+ # Apparently ftp connections don't like to be closed
+ # prematurely...
+ text = f.read()
+ f.close()
+
+ def save_pickle(self, dumpfile=DUMPFILE):
+ if not self.changed:
+ self.note(0, "\nNo need to save checkpoint")
+ elif not dumpfile:
+ self.note(0, "No dumpfile, won't save checkpoint")
+ else:
+ self.note(0, "\nSaving checkpoint to %s ...", dumpfile)
+ newfile = dumpfile + ".new"
+ f = open(newfile, "wb")
+ pickle.dump(self, f)
+ f.close()
+ try:
+ os.unlink(dumpfile)
+ except os.error:
+ pass
+ os.rename(newfile, dumpfile)
+ self.note(0, "Done.")
+ return 1
+
+
+class Page:
+
+ def __init__(self, text, url, verbose=VERBOSE, maxpage=MAXPAGE, checker=None):
+ self.text = text
+ self.url = url
+ self.verbose = verbose
+ self.maxpage = maxpage
+ self.checker = checker
+
+ # The parsing of the page is done in the __init__() routine in
+ # order to initialize the list of names the file
+ # contains. Stored the parser in an instance variable. Passed
+ # the URL to MyHTMLParser().
+ size = len(self.text)
+ if size > self.maxpage:
+ self.note(0, "Skip huge file %s (%.0f Kbytes)", self.url, (size*0.001))
+ self.parser = None
+ return
+ self.checker.note(2, " Parsing %s (%d bytes)", self.url, size)
+ self.parser = MyHTMLParser(url, verbose=self.verbose,
+ checker=self.checker)
+ self.parser.feed(self.text)
+ self.parser.close()
+
+ def note(self, level, msg, *args):
+ if self.checker:
+ apply(self.checker.note, (level, msg) + args)
+ else:
+ if self.verbose >= level:
+ if args:
+ msg = msg%args
+ print msg
+
+ # Method to retrieve names.
+ def getnames(self):
+ if self.parser:
+ return self.parser.names
+ else:
+ return []
+
+ def getlinkinfos(self):
+ # File reading is done in __init__() routine. Store parser in
+ # local variable to indicate success of parsing.
+
+ # If no parser was stored, fail.
+ if not self.parser: return []
+
+ rawlinks = self.parser.getlinks()
+ base = urlparse.urljoin(self.url, self.parser.getbase() or "")
+ infos = []
+ for rawlink in rawlinks:
+ t = urlparse.urlparse(rawlink)
+ # DON'T DISCARD THE FRAGMENT! Instead, include
+ # it in the tuples which are returned. See Checker.dopage().
+ fragment = t[-1]
+ t = t[:-1] + ('',)
+ rawlink = urlparse.urlunparse(t)
+ link = urlparse.urljoin(base, rawlink)
+ infos.append((link, rawlink, fragment))
+
+ return infos
+
+
+class MyStringIO(StringIO.StringIO):
+
+ def __init__(self, url, info):
+ self.__url = url
+ self.__info = info
+ StringIO.StringIO.__init__(self)
+
+ def info(self):
+ return self.__info
+
+ def geturl(self):
+ return self.__url
+
+
+class MyURLopener(urllib.FancyURLopener):
+
+ http_error_default = urllib.URLopener.http_error_default
+
+ def __init__(*args):
+ self = args[0]
+ apply(urllib.FancyURLopener.__init__, args)
+ self.addheaders = [
+ ('User-agent', 'Python-webchecker/%s' % __version__),
+ ]
+
+ def http_error_401(self, url, fp, errcode, errmsg, headers):
+ return None
+
+ def open_file(self, url):
+ path = urllib.url2pathname(urllib.unquote(url))
+ if os.path.isdir(path):
+ if path[-1] != os.sep:
+ url = url + '/'
+ indexpath = os.path.join(path, "index.html")
+ if os.path.exists(indexpath):
+ return self.open_file(url + "index.html")
+ try:
+ names = os.listdir(path)
+ except os.error, msg:
+ exc_type, exc_value, exc_tb = sys.exc_info()
+ raise IOError, msg, exc_tb
+ names.sort()
+ s = MyStringIO("file:"+url, {'content-type': 'text/html'})
+ s.write('<BASE HREF="file:%s">\n' %
+ urllib.quote(os.path.join(path, "")))
+ for name in names:
+ q = urllib.quote(name)
+ s.write('<A HREF="%s">%s</A>\n' % (q, q))
+ s.seek(0)
+ return s
+ return urllib.FancyURLopener.open_file(self, url)
+
+
+class MyHTMLParser(sgmllib.SGMLParser):
+
+ def __init__(self, url, verbose=VERBOSE, checker=None):
+ self.myverbose = verbose # now unused
+ self.checker = checker
+ self.base = None
+ self.links = {}
+ self.names = []
+ self.url = url
+ sgmllib.SGMLParser.__init__(self)
+
+ def check_name_id(self, attributes):
+ """ Check the name or id attributes on an element.
+ """
+ # We must rescue the NAME or id (name is deprecated in XHTML)
+ # attributes from the anchor, in order to
+ # cache the internal anchors which are made
+ # available in the page.
+ for name, value in attributes:
+ if name == "name" or name == "id":
+ if value in self.names:
+ self.checker.message("WARNING: duplicate ID name %s in %s",
+ value, self.url)
+ else: self.names.append(value)
+ break
+
+ def unknown_starttag(self, tag, attributes):
+ """ In XHTML, you can have id attributes on any element.
+ """
+ self.check_name_id(attributes)
+
+ def start_a(self, attributes):
+ self.link_attr(attributes, 'href')
+ self.check_name_id(attributes)
+
+ def end_a(self): pass
+
+ def do_area(self, attributes):
+ self.link_attr(attributes, 'href')
+ self.check_name_id(attributes)
+
+ def do_body(self, attributes):
+ self.link_attr(attributes, 'background', 'bgsound')
+ self.check_name_id(attributes)
+
+ def do_img(self, attributes):
+ self.link_attr(attributes, 'src', 'lowsrc')
+ self.check_name_id(attributes)
+
+ def do_frame(self, attributes):
+ self.link_attr(attributes, 'src', 'longdesc')
+ self.check_name_id(attributes)
+
+ def do_iframe(self, attributes):
+ self.link_attr(attributes, 'src', 'longdesc')
+ self.check_name_id(attributes)
+
+ def do_link(self, attributes):
+ for name, value in attributes:
+ if name == "rel":
+ parts = value.lower().split()
+ if ( parts == ["stylesheet"]
+ or parts == ["alternate", "stylesheet"]):
+ self.link_attr(attributes, "href")
+ break
+ self.check_name_id(attributes)
+
+ def do_object(self, attributes):
+ self.link_attr(attributes, 'data', 'usemap')
+ self.check_name_id(attributes)
+
+ def do_script(self, attributes):
+ self.link_attr(attributes, 'src')
+ self.check_name_id(attributes)
+
+ def do_table(self, attributes):
+ self.link_attr(attributes, 'background')
+ self.check_name_id(attributes)
+
+ def do_td(self, attributes):
+ self.link_attr(attributes, 'background')
+ self.check_name_id(attributes)
+
+ def do_th(self, attributes):
+ self.link_attr(attributes, 'background')
+ self.check_name_id(attributes)
+
+ def do_tr(self, attributes):
+ self.link_attr(attributes, 'background')
+ self.check_name_id(attributes)
+
+ def link_attr(self, attributes, *args):
+ for name, value in attributes:
+ if name in args:
+ if value: value = value.strip()
+ if value: self.links[value] = None
+
+ def do_base(self, attributes):
+ for name, value in attributes:
+ if name == 'href':
+ if value: value = value.strip()
+ if value:
+ if self.checker:
+ self.checker.note(1, " Base %s", value)
+ self.base = value
+ self.check_name_id(attributes)
+
+ def getlinks(self):
+ return self.links.keys()
+
+ def getbase(self):
+ return self.base
+
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/websucker.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/websucker.py
new file mode 100644
index 0000000000..9e4fd292c8
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/websucker.py
@@ -0,0 +1,123 @@
+#! /usr/bin/env python
+
+"""A variant on webchecker that creates a mirror copy of a remote site."""
+
+__version__ = "$Revision$"
+
+import os
+import sys
+import urllib
+import getopt
+
+import webchecker
+
+# Extract real version number if necessary
+if __version__[0] == '$':
+ _v = __version__.split()
+ if len(_v) == 3:
+ __version__ = _v[1]
+
+def main():
+ verbose = webchecker.VERBOSE
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "qv")
+ except getopt.error, msg:
+ print msg
+ print "usage:", sys.argv[0], "[-qv] ... [rooturl] ..."
+ return 2
+ for o, a in opts:
+ if o == "-q":
+ verbose = 0
+ if o == "-v":
+ verbose = verbose + 1
+ c = Sucker()
+ c.setflags(verbose=verbose)
+ c.urlopener.addheaders = [
+ ('User-agent', 'websucker/%s' % __version__),
+ ]
+ for arg in args:
+ print "Adding root", arg
+ c.addroot(arg)
+ print "Run..."
+ c.run()
+
+class Sucker(webchecker.Checker):
+
+ checkext = 0
+ nonames = 1
+
+ # SAM 11/13/99: in general, URLs are now URL pairs.
+ # Since we've suppressed name anchor checking,
+ # we can ignore the second dimension.
+
+ def readhtml(self, url_pair):
+ url = url_pair[0]
+ text = None
+ path = self.savefilename(url)
+ try:
+ f = open(path, "rb")
+ except IOError:
+ f = self.openpage(url_pair)
+ if f:
+ info = f.info()
+ nurl = f.geturl()
+ if nurl != url:
+ url = nurl
+ path = self.savefilename(url)
+ text = f.read()
+ f.close()
+ self.savefile(text, path)
+ if not self.checkforhtml(info, url):
+ text = None
+ else:
+ if self.checkforhtml({}, url):
+ text = f.read()
+ f.close()
+ return text, url
+
+ def savefile(self, text, path):
+ dir, base = os.path.split(path)
+ makedirs(dir)
+ try:
+ f = open(path, "wb")
+ f.write(text)
+ f.close()
+ self.message("saved %s", path)
+ except IOError, msg:
+ self.message("didn't save %s: %s", path, str(msg))
+
+ def savefilename(self, url):
+ type, rest = urllib.splittype(url)
+ host, path = urllib.splithost(rest)
+ path = path.lstrip("/")
+ user, host = urllib.splituser(host)
+ host, port = urllib.splitnport(host)
+ host = host.lower()
+ if not path or path[-1] == "/":
+ path = path + "index.html"
+ if os.sep != "/":
+ path = os.sep.join(path.split("/"))
+ path = os.path.join(host, path)
+ return path
+
+def makedirs(dir):
+ if not dir:
+ return
+ if os.path.exists(dir):
+ if not os.path.isdir(dir):
+ try:
+ os.rename(dir, dir + ".bak")
+ os.mkdir(dir)
+ os.rename(dir + ".bak", os.path.join(dir, "index.html"))
+ except os.error:
+ pass
+ return
+ head, tail = os.path.split(dir)
+ if not tail:
+ print "Huh? Don't know how to make dir", dir
+ return
+ makedirs(head)
+ os.mkdir(dir, 0777)
+
+if __name__ == '__main__':
+ sys.exit(main() or 0)
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wsgui.py b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wsgui.py
new file mode 100644
index 0000000000..09fac2f3d9
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/webchecker/wsgui.py
@@ -0,0 +1,240 @@
+#! /usr/bin/env python
+
+"""Tkinter-based GUI for websucker.
+
+Easy use: type or paste source URL and destination directory in
+their respective text boxes, click GO or hit return, and presto.
+"""
+
+from Tkinter import *
+import websucker
+import os
+import threading
+import Queue
+import time
+
+VERBOSE = 2
+
+
+try:
+ class Canceled(Exception):
+ "Exception used to cancel run()."
+except (NameError, TypeError):
+ Canceled = __name__ + ".Canceled"
+
+
+class SuckerThread(websucker.Sucker):
+
+ stopit = 0
+ savedir = None
+ rootdir = None
+
+ def __init__(self, msgq):
+ self.msgq = msgq
+ websucker.Sucker.__init__(self)
+ self.setflags(verbose=VERBOSE)
+ self.urlopener.addheaders = [
+ ('User-agent', 'websucker/%s' % websucker.__version__),
+ ]
+
+ def message(self, format, *args):
+ if args:
+ format = format%args
+ ##print format
+ self.msgq.put(format)
+
+ def run1(self, url):
+ try:
+ try:
+ self.reset()
+ self.addroot(url)
+ self.run()
+ except Canceled:
+ self.message("[canceled]")
+ else:
+ self.message("[done]")
+ finally:
+ self.msgq.put(None)
+
+ def savefile(self, text, path):
+ if self.stopit:
+ raise Canceled
+ websucker.Sucker.savefile(self, text, path)
+
+ def getpage(self, url):
+ if self.stopit:
+ raise Canceled
+ return websucker.Sucker.getpage(self, url)
+
+ def savefilename(self, url):
+ path = websucker.Sucker.savefilename(self, url)
+ if self.savedir:
+ n = len(self.rootdir)
+ if path[:n] == self.rootdir:
+ path = path[n:]
+ while path[:1] == os.sep:
+ path = path[1:]
+ path = os.path.join(self.savedir, path)
+ return path
+
+ def XXXaddrobot(self, *args):
+ pass
+
+ def XXXisallowed(self, *args):
+ return 1
+
+
+class App:
+
+ sucker = None
+ msgq = None
+
+ def __init__(self, top):
+ self.top = top
+ top.columnconfigure(99, weight=1)
+ self.url_label = Label(top, text="URL:")
+ self.url_label.grid(row=0, column=0, sticky='e')
+ self.url_entry = Entry(top, width=60, exportselection=0)
+ self.url_entry.grid(row=0, column=1, sticky='we',
+ columnspan=99)
+ self.url_entry.focus_set()
+ self.url_entry.bind("<Key-Return>", self.go)
+ self.dir_label = Label(top, text="Directory:")
+ self.dir_label.grid(row=1, column=0, sticky='e')
+ self.dir_entry = Entry(top)
+ self.dir_entry.grid(row=1, column=1, sticky='we',
+ columnspan=99)
+ self.go_button = Button(top, text="Go", command=self.go)
+ self.go_button.grid(row=2, column=1, sticky='w')
+ self.cancel_button = Button(top, text="Cancel",
+ command=self.cancel,
+ state=DISABLED)
+ self.cancel_button.grid(row=2, column=2, sticky='w')
+ self.auto_button = Button(top, text="Paste+Go",
+ command=self.auto)
+ self.auto_button.grid(row=2, column=3, sticky='w')
+ self.status_label = Label(top, text="[idle]")
+ self.status_label.grid(row=2, column=4, sticky='w')
+ self.top.update_idletasks()
+ self.top.grid_propagate(0)
+
+ def message(self, text, *args):
+ if args:
+ text = text % args
+ self.status_label.config(text=text)
+
+ def check_msgq(self):
+ while not self.msgq.empty():
+ msg = self.msgq.get()
+ if msg is None:
+ self.go_button.configure(state=NORMAL)
+ self.auto_button.configure(state=NORMAL)
+ self.cancel_button.configure(state=DISABLED)
+ if self.sucker:
+ self.sucker.stopit = 0
+ self.top.bell()
+ else:
+ self.message(msg)
+ self.top.after(100, self.check_msgq)
+
+ def go(self, event=None):
+ if not self.msgq:
+ self.msgq = Queue.Queue(0)
+ self.check_msgq()
+ if not self.sucker:
+ self.sucker = SuckerThread(self.msgq)
+ if self.sucker.stopit:
+ return
+ self.url_entry.selection_range(0, END)
+ url = self.url_entry.get()
+ url = url.strip()
+ if not url:
+ self.top.bell()
+ self.message("[Error: No URL entered]")
+ return
+ self.rooturl = url
+ dir = self.dir_entry.get().strip()
+ if not dir:
+ self.sucker.savedir = None
+ else:
+ self.sucker.savedir = dir
+ self.sucker.rootdir = os.path.dirname(
+ websucker.Sucker.savefilename(self.sucker, url))
+ self.go_button.configure(state=DISABLED)
+ self.auto_button.configure(state=DISABLED)
+ self.cancel_button.configure(state=NORMAL)
+ self.message( '[running...]')
+ self.sucker.stopit = 0
+ t = threading.Thread(target=self.sucker.run1, args=(url,))
+ t.start()
+
+ def cancel(self):
+ if self.sucker:
+ self.sucker.stopit = 1
+ self.message("[canceling...]")
+
+ def auto(self):
+ tries = ['PRIMARY', 'CLIPBOARD']
+ text = ""
+ for t in tries:
+ try:
+ text = self.top.selection_get(selection=t)
+ except TclError:
+ continue
+ text = text.strip()
+ if text:
+ break
+ if not text:
+ self.top.bell()
+ self.message("[Error: clipboard is empty]")
+ return
+ self.url_entry.delete(0, END)
+ self.url_entry.insert(0, text)
+ self.go()
+
+
+class AppArray:
+
+ def __init__(self, top=None):
+ if not top:
+ top = Tk()
+ top.title("websucker GUI")
+ top.iconname("wsgui")
+ top.wm_protocol('WM_DELETE_WINDOW', self.exit)
+ self.top = top
+ self.appframe = Frame(self.top)
+ self.appframe.pack(fill='both')
+ self.applist = []
+ self.exit_button = Button(top, text="Exit", command=self.exit)
+ self.exit_button.pack(side=RIGHT)
+ self.new_button = Button(top, text="New", command=self.addsucker)
+ self.new_button.pack(side=LEFT)
+ self.addsucker()
+ ##self.applist[0].url_entry.insert(END, "http://www.python.org/doc/essays/")
+
+ def addsucker(self):
+ self.top.geometry("")
+ frame = Frame(self.appframe, borderwidth=2, relief=GROOVE)
+ frame.pack(fill='x')
+ app = App(frame)
+ self.applist.append(app)
+
+ done = 0
+
+ def mainloop(self):
+ while not self.done:
+ time.sleep(0.1)
+ self.top.update()
+
+ def exit(self):
+ for app in self.applist:
+ app.cancel()
+ app.message("[exiting...]")
+ self.done = 1
+
+
+def main():
+ AppArray().mainloop()
+
+if __name__ == '__main__':
+ main()
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/world/README b/AppPkg/Applications/Python/Python-2.7.2/Tools/world/README
new file mode 100644
index 0000000000..3250a32c44
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/world/README
@@ -0,0 +1,85 @@
+world -- Print mappings between country names and DNS country codes.
+
+Contact: Barry Warsaw
+Email: bwarsaw@python.org
+
+This script will take a list of Internet addresses and print out where in the
+world those addresses originate from, based on the top-level domain country
+code found in the address. Addresses can be in any of the following forms:
+
+ xx -- just the country code or top-level domain identifier
+ host.domain.xx -- any Internet host or network name
+ somebody@where.xx -- an Internet email address
+
+If no match is found, the address is interpreted as a regular expression [*]
+and a reverse lookup is attempted. This script will search the country names
+and print a list of matching entries. You can force reverse mappings with the
+`-r' flag (see below).
+
+For example:
+
+ %% world tz us
+ tz originated from Tanzania, United Republic of
+ us originated from United States
+
+ %% world united
+ united matches 6 countries:
+ ae: United Arab Emirates
+ uk: United Kingdom (common practice)
+ um: United States Minor Outlying Islands
+ us: United States
+ tz: Tanzania, United Republic of
+ gb: United Kingdom
+
+
+ [*] Note that regular expressions must conform to Python 1.5's re.py module
+ syntax. The comparison is done with the search() method.
+
+Country codes are maintained by the RIPE Network Coordination Centre,
+in coordination with the ISO 3166 Maintenance Agency at DIN Berlin. The
+authoritative source of counry code mappings is:
+
+ <url:ftp://info.ripe.net/iso3166-countrycodes>
+
+The latest known change to this information was:
+
+ Thu Aug 7 17:59:51 MET DST 1997
+
+This script also knows about non-geographic top-level domains.
+
+Usage: world [-d] [-p file] [-o] [-h] addr [addr ...]
+
+ --dump
+ -d
+ Print mapping of all top-level domains.
+
+ --parse file
+ -p file
+ Parse an iso3166-countrycodes file extracting the two letter country
+ code followed by the country name. Note that the three letter country
+ codes and numbers, which are also provided in the standard format
+ file, are ignored.
+
+ --outputdict
+ -o
+ When used in conjunction with the `-p' option, output is in the form
+ of a Python dictionary, and country names are normalized
+ w.r.t. capitalization. This makes it appropriate for cutting and
+ pasting back into this file.
+
+ --reverse
+ -r
+ Force reverse lookup. In this mode the address can be any Python
+ regular expression; this is matched against all country names and a
+ list of matching mappings is printed. In normal mode (e.g. without
+ this flag), reverse lookup is performed on addresses if no matching
+ country code is found.
+
+ -h
+ --help
+ Print this message.
+
+
+Local Variables:
+indent-tabs-mode: nil
+End:
diff --git a/AppPkg/Applications/Python/Python-2.7.2/Tools/world/world b/AppPkg/Applications/Python/Python-2.7.2/Tools/world/world
new file mode 100644
index 0000000000..a60f71c7f5
--- /dev/null
+++ b/AppPkg/Applications/Python/Python-2.7.2/Tools/world/world
@@ -0,0 +1,551 @@
+#! /usr/bin/env python
+
+"""world -- Print mappings between country names and DNS country codes.
+
+Contact: Barry Warsaw
+Email: barry@python.org
+Version: %(__version__)s
+
+This script will take a list of Internet addresses and print out where in the
+world those addresses originate from, based on the top-level domain country
+code found in the address. Addresses can be in any of the following forms:
+
+ xx -- just the country code or top-level domain identifier
+ host.domain.xx -- any Internet host or network name
+ somebody@where.xx -- an Internet email address
+
+If no match is found, the address is interpreted as a regular expression and a
+reverse lookup is attempted. This script will search the country names and
+print a list of matching entries. You can force reverse mappings with the
+`-r' flag (see below).
+
+For example:
+
+ %% world tz us
+ tz originated from Tanzania, United Republic of
+ us originated from United States
+
+ %% world united
+ united matches 6 countries:
+ ae: United Arab Emirates
+ uk: United Kingdom (common practice)
+ um: United States Minor Outlying Islands
+ us: United States
+ tz: Tanzania, United Republic of
+ gb: United Kingdom
+
+Country codes are maintained by the RIPE Network Coordination Centre,
+in coordination with the ISO 3166 Maintenance Agency at DIN Berlin. The
+authoritative source of country code mappings is:
+
+ <url:ftp://ftp.ripe.net/iso3166-countrycodes.txt>
+
+The latest known change to this information was:
+
+ Friday, 5 April 2002, 12.00 CET 2002
+
+This script also knows about non-geographic top-level domains, and the
+additional ccTLDs reserved by IANA.
+
+Usage: %(PROGRAM)s [-d] [-p file] [-o] [-h] addr [addr ...]
+
+ --dump
+ -d
+ Print mapping of all top-level domains.
+
+ --parse file
+ -p file
+ Parse an iso3166-countrycodes file extracting the two letter country
+ code followed by the country name. Note that the three letter country
+ codes and numbers, which are also provided in the standard format
+ file, are ignored.
+
+ --outputdict
+ -o
+ When used in conjunction with the `-p' option, output is in the form
+ of a Python dictionary, and country names are normalized
+ w.r.t. capitalization. This makes it appropriate for cutting and
+ pasting back into this file. Output is always to standard out.
+
+ --reverse
+ -r
+ Force reverse lookup. In this mode the address can be any Python
+ regular expression; this is matched against all country names and a
+ list of matching mappings is printed. In normal mode (e.g. without
+ this flag), reverse lookup is performed on addresses if no matching
+ country code is found.
+
+ -h
+ --help
+ Print this message.
+"""
+__version__ = '$Revision$'
+
+
+import sys
+import getopt
+import re
+
+PROGRAM = sys.argv[0]
+
+
+
+def usage(code, msg=''):
+ print __doc__ % globals()
+ if msg:
+ print msg
+ sys.exit(code)
+
+
+
+def resolve(rawaddr):
+ parts = rawaddr.split('.')
+ if not len(parts):
+ # no top level domain found, bounce it to the next step
+ return rawaddr
+ addr = parts[-1]
+ if nameorgs.has_key(addr):
+ print rawaddr, 'is in the', nameorgs[addr], 'top level domain'
+ return None
+ elif countries.has_key(addr):
+ print rawaddr, 'originated from', countries[addr]
+ return None
+ else:
+ # Not resolved, bounce it to the next step
+ return rawaddr
+
+
+
+def reverse(regexp):
+ matches = []
+ cre = re.compile(regexp, re.IGNORECASE)
+ for code, country in all.items():
+ mo = cre.search(country)
+ if mo:
+ matches.append(code)
+ # print results
+ if not matches:
+ # not resolved, bounce it to the next step
+ return regexp
+ if len(matches) == 1:
+ code = matches[0]
+ print regexp, "matches code `%s', %s" % (code, all[code])
+ else:
+ print regexp, 'matches %d countries:' % len(matches)
+ for code in matches:
+ print " %s: %s" % (code, all[code])
+ return None
+
+
+
+def parse(file, normalize):
+ try:
+ fp = open(file)
+ except IOError, (err, msg):
+ print msg, ':', file
+
+ cre = re.compile('(.*?)[ \t]+([A-Z]{2})[ \t]+[A-Z]{3}[ \t]+[0-9]{3}')
+ scanning = 0
+
+ if normalize:
+ print 'countries = {'
+
+ while 1:
+ line = fp.readline()
+ if line == '':
+ break # EOF
+ if scanning:
+ mo = cre.match(line)
+ if not mo:
+ line = line.strip()
+ if not line:
+ continue
+ elif line[0] == '-':
+ break
+ else:
+ print 'Could not parse line:', line
+ continue
+ country, code = mo.group(1, 2)
+ if normalize:
+ words = country.split()
+ for i in range(len(words)):
+ w = words[i]
+ # XXX special cases
+ if w in ('AND', 'OF', 'OF)', 'name:', 'METROPOLITAN'):
+ words[i] = w.lower()
+ elif w == 'THE' and i <> 1:
+ words[i] = w.lower()
+ elif len(w) > 3 and w[1] == "'":
+ words[i] = w[0:3].upper() + w[3:].lower()
+ elif w in ('(U.S.)', 'U.S.'):
+ pass
+ elif w[0] == '(' and w <> '(local':
+ words[i] = '(' + w[1:].capitalize()
+ elif w.find('-') <> -1:
+ words[i] = '-'.join(
+ [s.capitalize() for s in w.split('-')])
+ else:
+ words[i] = w.capitalize()
+ code = code.lower()
+ country = ' '.join(words)
+ print ' "%s": "%s",' % (code, country)
+ else:
+ print code, country
+
+ elif line[0] == '-':
+ scanning = 1
+
+ if normalize:
+ print ' }'
+
+
+def main():
+ help = 0
+ status = 0
+ dump = 0
+ parsefile = None
+ normalize = 0
+ forcerev = 0
+
+ try:
+ opts, args = getopt.getopt(
+ sys.argv[1:],
+ 'p:rohd',
+ ['parse=', 'reverse', 'outputdict', 'help', 'dump'])
+ except getopt.error, msg:
+ usage(1, msg)
+
+ for opt, arg in opts:
+ if opt in ('-h', '--help'):
+ help = 1
+ elif opt in ('-d', '--dump'):
+ dump = 1
+ elif opt in ('-p', '--parse'):
+ parsefile = arg
+ elif opt in ('-o', '--outputdict'):
+ normalize = 1
+ elif opt in ('-r', '--reverse'):
+ forcerev = 1
+
+ if help:
+ usage(status)
+
+ if dump:
+ print 'Non-geographic domains:'
+ codes = nameorgs.keys()
+ codes.sort()
+ for code in codes:
+ print ' %4s:' % code, nameorgs[code]
+
+ print '\nCountry coded domains:'
+ codes = countries.keys()
+ codes.sort()
+ for code in codes:
+ print ' %2s:' % code, countries[code]
+ elif parsefile:
+ parse(parsefile, normalize)
+ else:
+ if not forcerev:
+ args = filter(None, map(resolve, args))
+ args = filter(None, map(reverse, args))
+ for arg in args:
+ print 'Where in the world is %s?' % arg
+
+
+
+# The mappings
+nameorgs = {
+ # New top level domains as described by ICANN
+ # http://www.icann.org/tlds/
+ "aero": "air-transport industry",
+ "arpa": "Arpanet",
+ "biz": "business",
+ "com": "commercial",
+ "coop": "cooperatives",
+ "edu": "educational",
+ "gov": "government",
+ "info": "unrestricted `info'",
+ "int": "international",
+ "mil": "military",
+ "museum": "museums",
+ "name": "`name' (for registration by individuals)",
+ "net": "networking",
+ "org": "non-commercial",
+ "pro": "professionals",
+ # These additional ccTLDs are included here even though they are not part
+ # of ISO 3166. IANA has 5 reserved ccTLDs as described here:
+ #
+ # http://www.iso.org/iso/en/prods-services/iso3166ma/04background-on-iso-3166/iso3166-1-and-ccTLDs.html
+ #
+ # but I can't find an official list anywhere.
+ #
+ # Note that `uk' is the common practice country code for the United
+ # Kingdom. AFAICT, the official `gb' code is routinely ignored!
+ #
+ # <D.M.Pick@qmw.ac.uk> tells me that `uk' was long in use before ISO3166
+ # was adopted for top-level DNS zone names (although in the reverse order
+ # like uk.ac.qmw) and was carried forward (with the reversal) to avoid a
+ # large-scale renaming process as the UK switched from their old `Coloured
+ # Book' protocols over X.25 to Internet protocols over IP.
+ #
+ # See <url:ftp://ftp.ripe.net/ripe/docs/ripe-159.txt>
+ #
+ # Also, `su', while obsolete is still in limited use.
+ "ac": "Ascension Island",
+ "gg": "Guernsey",
+ "im": "Isle of Man",
+ "je": "Jersey",
+ "uk": "United Kingdom (common practice)",
+ "su": "Soviet Union (still in limited use)",
+ }
+
+
+
+countries = {
+ "af": "Afghanistan",
+ "al": "Albania",
+ "dz": "Algeria",
+ "as": "American Samoa",
+ "ad": "Andorra",
+ "ao": "Angola",
+ "ai": "Anguilla",
+ "aq": "Antarctica",
+ "ag": "Antigua and Barbuda",
+ "ar": "Argentina",
+ "am": "Armenia",
+ "aw": "Aruba",
+ "au": "Australia",
+ "at": "Austria",
+ "az": "Azerbaijan",
+ "bs": "Bahamas",
+ "bh": "Bahrain",
+ "bd": "Bangladesh",
+ "bb": "Barbados",
+ "by": "Belarus",
+ "be": "Belgium",
+ "bz": "Belize",
+ "bj": "Benin",
+ "bm": "Bermuda",
+ "bt": "Bhutan",
+ "bo": "Bolivia",
+ "ba": "Bosnia and Herzegowina",
+ "bw": "Botswana",
+ "bv": "Bouvet Island",
+ "br": "Brazil",
+ "io": "British Indian Ocean Territory",
+ "bn": "Brunei Darussalam",
+ "bg": "Bulgaria",
+ "bf": "Burkina Faso",
+ "bi": "Burundi",
+ "kh": "Cambodia",
+ "cm": "Cameroon",
+ "ca": "Canada",
+ "cv": "Cape Verde",
+ "ky": "Cayman Islands",
+ "cf": "Central African Republic",
+ "td": "Chad",
+ "cl": "Chile",
+ "cn": "China",
+ "cx": "Christmas Island",
+ "cc": "Cocos (Keeling) Islands",
+ "co": "Colombia",
+ "km": "Comoros",
+ "cg": "Congo",
+ "cd": "Congo, The Democratic Republic of the",
+ "ck": "Cook Islands",
+ "cr": "Costa Rica",
+ "ci": "Cote D'Ivoire",
+ "hr": "Croatia",
+ "cu": "Cuba",
+ "cy": "Cyprus",
+ "cz": "Czech Republic",
+ "dk": "Denmark",
+ "dj": "Djibouti",
+ "dm": "Dominica",
+ "do": "Dominican Republic",
+ "tp": "East Timor",
+ "ec": "Ecuador",
+ "eg": "Egypt",
+ "sv": "El Salvador",
+ "gq": "Equatorial Guinea",
+ "er": "Eritrea",
+ "ee": "Estonia",
+ "et": "Ethiopia",
+ "fk": "Falkland Islands (Malvinas)",
+ "fo": "Faroe Islands",
+ "fj": "Fiji",
+ "fi": "Finland",
+ "fr": "France",
+ "gf": "French Guiana",
+ "pf": "French Polynesia",
+ "tf": "French Southern Territories",
+ "ga": "Gabon",
+ "gm": "Gambia",
+ "ge": "Georgia",
+ "de": "Germany",
+ "gh": "Ghana",
+ "gi": "Gibraltar",
+ "gr": "Greece",
+ "gl": "Greenland",
+ "gd": "Grenada",
+ "gp": "Guadeloupe",
+ "gu": "Guam",
+ "gt": "Guatemala",
+ "gn": "Guinea",
+ "gw": "Guinea-Bissau",
+ "gy": "Guyana",
+ "ht": "Haiti",
+ "hm": "Heard Island and Mcdonald Islands",
+ "va": "Holy See (Vatican City State)",
+ "hn": "Honduras",
+ "hk": "Hong Kong",
+ "hu": "Hungary",
+ "is": "Iceland",
+ "in": "India",
+ "id": "Indonesia",
+ "ir": "Iran, Islamic Republic of",
+ "iq": "Iraq",
+ "ie": "Ireland",
+ "il": "Israel",
+ "it": "Italy",
+ "jm": "Jamaica",
+ "jp": "Japan",
+ "jo": "Jordan",
+ "kz": "Kazakstan",
+ "ke": "Kenya",
+ "ki": "Kiribati",
+ "kp": "Korea, Democratic People's Republic of",
+ "kr": "Korea, Republic of",
+ "kw": "Kuwait",
+ "kg": "Kyrgyzstan",
+ "la": "Lao People's Democratic Republic",
+ "lv": "Latvia",
+ "lb": "Lebanon",
+ "ls": "Lesotho",
+ "lr": "Liberia",
+ "ly": "Libyan Arab Jamahiriya",
+ "li": "Liechtenstein",
+ "lt": "Lithuania",
+ "lu": "Luxembourg",
+ "mo": "Macau",
+ "mk": "Macedonia, The Former Yugoslav Republic of",
+ "mg": "Madagascar",
+ "mw": "Malawi",
+ "my": "Malaysia",
+ "mv": "Maldives",
+ "ml": "Mali",
+ "mt": "Malta",
+ "mh": "Marshall Islands",
+ "mq": "Martinique",
+ "mr": "Mauritania",
+ "mu": "Mauritius",
+ "yt": "Mayotte",
+ "mx": "Mexico",
+ "fm": "Micronesia, Federated States of",
+ "md": "Moldova, Republic of",
+ "mc": "Monaco",
+ "mn": "Mongolia",
+ "ms": "Montserrat",
+ "ma": "Morocco",
+ "mz": "Mozambique",
+ "mm": "Myanmar",
+ "na": "Namibia",
+ "nr": "Nauru",
+ "np": "Nepal",
+ "nl": "Netherlands",
+ "an": "Netherlands Antilles",
+ "nc": "New Caledonia",
+ "nz": "New Zealand",
+ "ni": "Nicaragua",
+ "ne": "Niger",
+ "ng": "Nigeria",
+ "nu": "Niue",
+ "nf": "Norfolk Island",
+ "mp": "Northern Mariana Islands",
+ "no": "Norway",
+ "om": "Oman",
+ "pk": "Pakistan",
+ "pw": "Palau",
+ "ps": "Palestinian Territory, Occupied",
+ "pa": "Panama",
+ "pg": "Papua New Guinea",
+ "py": "Paraguay",
+ "pe": "Peru",
+ "ph": "Philippines",
+ "pn": "Pitcairn",
+ "pl": "Poland",
+ "pt": "Portugal",
+ "pr": "Puerto Rico",
+ "qa": "Qatar",
+ "re": "Reunion",
+ "ro": "Romania",
+ "ru": "Russian Federation",
+ "rw": "Rwanda",
+ "sh": "Saint Helena",
+ "kn": "Saint Kitts and Nevis",
+ "lc": "Saint Lucia",
+ "pm": "Saint Pierre and Miquelon",
+ "vc": "Saint Vincent and the Grenadines",
+ "ws": "Samoa",
+ "sm": "San Marino",
+ "st": "Sao Tome and Principe",
+ "sa": "Saudi Arabia",
+ "sn": "Senegal",
+ "sc": "Seychelles",
+ "sl": "Sierra Leone",
+ "sg": "Singapore",
+ "sk": "Slovakia",
+ "si": "Slovenia",
+ "sb": "Solomon Islands",
+ "so": "Somalia",
+ "za": "South Africa",
+ "gs": "South Georgia and the South Sandwich Islands",
+ "es": "Spain",
+ "lk": "Sri Lanka",
+ "sd": "Sudan",
+ "sr": "Suriname",
+ "sj": "Svalbard and Jan Mayen",
+ "sz": "Swaziland",
+ "se": "Sweden",
+ "ch": "Switzerland",
+ "sy": "Syrian Arab Republic",
+ "tw": "Taiwan, Province of China",
+ "tj": "Tajikistan",
+ "tz": "Tanzania, United Republic of",
+ "th": "Thailand",
+ "tg": "Togo",
+ "tk": "Tokelau",
+ "to": "Tonga",
+ "tt": "Trinidad and Tobago",
+ "tn": "Tunisia",
+ "tr": "Turkey",
+ "tm": "Turkmenistan",
+ "tc": "Turks and Caicos Islands",
+ "tv": "Tuvalu",
+ "ug": "Uganda",
+ "ua": "Ukraine",
+ "ae": "United Arab Emirates",
+ "gb": "United Kingdom",
+ "us": "United States",
+ "um": "United States Minor Outlying Islands",
+ "uy": "Uruguay",
+ "uz": "Uzbekistan",
+ "vu": "Vanuatu",
+ "ve": "Venezuela",
+ "vn": "Viet Nam",
+ "vg": "Virgin Islands, British",
+ "vi": "Virgin Islands, U.S.",
+ "wf": "Wallis and Futuna",
+ "eh": "Western Sahara",
+ "ye": "Yemen",
+ "yu": "Yugoslavia",
+ "zm": "Zambia",
+ "zw": "Zimbabwe",
+ }
+
+all = nameorgs.copy()
+all.update(countries)
+
+
+if __name__ == '__main__':
+ main()