Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Removed irrelevant parts of CPython; added *.pyc to gitignore.

  • Loading branch information...
commit 17fa443b36790e14f5692a01a9ae7f901ed54a40 1 parent ef1575c
Max Shawabkeh max99x authored
Showing with 2 additions and 32,547 deletions.
  1. +2 −0  .gitignore
  2. +0 −61 cpython/Demo/README
  3. +0 −11 cpython/Demo/cgi/README
  4. +0 −8 cpython/Demo/cgi/cgi0.sh
  5. +0 −14 cpython/Demo/cgi/cgi1.py
  6. +0 −22 cpython/Demo/cgi/cgi2.py
  7. +0 −10 cpython/Demo/cgi/cgi3.py
  8. +0 −123 cpython/Demo/cgi/wiki.py
  9. +0 −320 cpython/Demo/classes/Complex.py
  10. +0 −227 cpython/Demo/classes/Dates.py
  11. +0 −66 cpython/Demo/classes/Dbm.py
  12. +0 −12 cpython/Demo/classes/README
  13. +0 −93 cpython/Demo/classes/Range.py
  14. +0 −95 cpython/Demo/classes/Rev.py
  15. +0 −68 cpython/Demo/classes/Vec.py
  16. +0 −333 cpython/Demo/classes/bitvec.py
  17. +0 −60 cpython/Demo/comparisons/README
  18. +0 −4 cpython/Demo/comparisons/patterns
  19. +0 −47 cpython/Demo/comparisons/regextest.py
  20. +0 −45 cpython/Demo/comparisons/sortingtest.py
  21. +0 −74 cpython/Demo/comparisons/systemtest.py
  22. +0 −25 cpython/Demo/curses/README
  23. +0 −216 cpython/Demo/curses/life.py
  24. +0 −273 cpython/Demo/curses/ncurses.py
  25. +0 −94 cpython/Demo/curses/rain.py
  26. +0 −58 cpython/Demo/curses/repeat.py
  27. +0 −147 cpython/Demo/curses/tclock.py
  28. +0 −906 cpython/Demo/curses/xmas.py
  29. +0 −57 cpython/Demo/embed/Makefile
  30. +0 −19 cpython/Demo/embed/README
  31. +0 −74 cpython/Demo/embed/demo.c
  32. +0 −17 cpython/Demo/embed/importexc.c
  33. +0 −33 cpython/Demo/embed/loop.c
  34. +0 −10 cpython/Demo/md5test/README
  35. +0 −1  cpython/Demo/md5test/foo
  36. +0 −123 cpython/Demo/md5test/md5driver.py
  37. +0 −113 cpython/Demo/metaclasses/Eiffel.py
  38. +0 −169 cpython/Demo/metaclasses/Enum.py
  39. +0 −118 cpython/Demo/metaclasses/Meta.py
  40. +0 −45 cpython/Demo/metaclasses/Simple.py
  41. +0 −256 cpython/Demo/metaclasses/Synch.py
  42. +0 −144 cpython/Demo/metaclasses/Trace.py
  43. +0 −605 cpython/Demo/metaclasses/index.html
  44. +0 −256 cpython/Demo/metaclasses/meta-vladimir.txt
  45. +0 −141 cpython/Demo/newmetaclasses/Eiffel.py
  46. +0 −177 cpython/Demo/newmetaclasses/Enum.py
  47. +0 −6 cpython/Demo/parser/FILES
  48. +0 −32 cpython/Demo/parser/README
  49. +0 −2  cpython/Demo/parser/docstring.py
  50. +0 −190 cpython/Demo/parser/example.py
  51. +0 −1  cpython/Demo/parser/simple.py
  52. +0 −27 cpython/Demo/parser/source.py
  53. +0 −48 cpython/Demo/parser/test_parser.py
  54. +0 −213 cpython/Demo/parser/test_unparse.py
  55. +0 −606 cpython/Demo/parser/unparse.py
  56. +0 −301 cpython/Demo/pdist/FSProxy.py
  57. +0 −198 cpython/Demo/pdist/RCSProxy.py
  58. +0 −121 cpython/Demo/pdist/README
  59. +0 −157 cpython/Demo/pdist/client.py
  60. +0 −144 cpython/Demo/pdist/cmdfw.py
  61. +0 −208 cpython/Demo/pdist/cmptree.py
  62. +0 −364 cpython/Demo/pdist/cvslib.py
  63. +0 −280 cpython/Demo/pdist/cvslock.py
  64. +0 −19 cpython/Demo/pdist/mac.py
  65. +0 −109 cpython/Demo/pdist/makechangelog.py
  66. +0 −33 cpython/Demo/pdist/rcsbump
  67. +0 −71 cpython/Demo/pdist/rcsclient.py
  68. +0 −334 cpython/Demo/pdist/rcslib.py
  69. +0 −8 cpython/Demo/pdist/rcvs
  70. +0 −477 cpython/Demo/pdist/rcvs.py
  71. +0 −8 cpython/Demo/pdist/rrcs
  72. +0 −160 cpython/Demo/pdist/rrcs.py
  73. +0 −33 cpython/Demo/pdist/security.py
  74. +0 −145 cpython/Demo/pdist/server.py
  75. +0 −24 cpython/Demo/pdist/sumtree.py
  76. +0 −57 cpython/Demo/pysvr/Makefile
  77. +0 −9 cpython/Demo/pysvr/README
  78. +0 −370 cpython/Demo/pysvr/pysvr.c
  79. +0 −124 cpython/Demo/pysvr/pysvr.py
  80. +0 −10 cpython/Demo/rpc/MANIFEST
  81. +0 −31 cpython/Demo/rpc/README
  82. +0 −22 cpython/Demo/rpc/T.py
  83. +0 −202 cpython/Demo/rpc/mountclient.py
  84. +0 −201 cpython/Demo/rpc/nfsclient.py
  85. +0 −98 cpython/Demo/rpc/rnusersclient.py
  86. +0 −893 cpython/Demo/rpc/rpc.py
  87. +0 −24 cpython/Demo/rpc/test
  88. +0 −200 cpython/Demo/rpc/xdr.py
  89. +0 −22 cpython/Demo/scripts/README
  90. +0 −20 cpython/Demo/scripts/beer.py
  91. +0 −198 cpython/Demo/scripts/eqfix.py
  92. +0 −49 cpython/Demo/scripts/fact.py
  93. +0 −40 cpython/Demo/scripts/find-uname.py
  94. +0 −35 cpython/Demo/scripts/from.py
  95. +0 −102 cpython/Demo/scripts/lpwatch.py
  96. +0 −21 cpython/Demo/scripts/makedir.py
  97. +0 −121 cpython/Demo/scripts/markov.py
  98. +0 −124 cpython/Demo/scripts/mboxconvert.py
  99. +0 −138 cpython/Demo/scripts/morse.py
  100. +0 −59 cpython/Demo/scripts/newslist.doc
  101. +0 −362 cpython/Demo/scripts/newslist.py
  102. +0 −33 cpython/Demo/scripts/pi.py
  103. +0 −129 cpython/Demo/scripts/pp.py
  104. +0 −30 cpython/Demo/scripts/primes.py
  105. +0 −85 cpython/Demo/scripts/queens.py
  106. +0 −42 cpython/Demo/scripts/script.py
  107. +0 −104 cpython/Demo/scripts/unbirthday.py
  108. +0 −92 cpython/Demo/scripts/update.py
  109. +0 −14 cpython/Demo/sockets/README
  110. +0 −15 cpython/Demo/sockets/broadcast.py
  111. +0 −31 cpython/Demo/sockets/echosvr.py
  112. +0 −58 cpython/Demo/sockets/finger.py
  113. +0 −146 cpython/Demo/sockets/ftp.py
  114. +0 −347 cpython/Demo/sockets/gopher.py
  115. +0 −80 cpython/Demo/sockets/mcast.py
  116. +0 −14 cpython/Demo/sockets/radio.py
  117. +0 −35 cpython/Demo/sockets/rpython.py
  118. +0 −52 cpython/Demo/sockets/rpythond.py
  119. +0 −109 cpython/Demo/sockets/telnet.py
  120. +0 −93 cpython/Demo/sockets/throughput.py
  121. +0 −63 cpython/Demo/sockets/udpecho.py
  122. +0 −14 cpython/Demo/sockets/unicast.py
  123. +0 −12 cpython/Demo/sockets/unixclient.py
  124. +0 −24 cpython/Demo/sockets/unixserver.py
  125. +0 −159 cpython/Demo/threads/Coroutine.py
  126. +0 −92 cpython/Demo/threads/Generator.py
  127. +0 −11 cpython/Demo/threads/README
  128. +0 −64 cpython/Demo/threads/fcmp.py
  129. +0 −155 cpython/Demo/threads/find.py
  130. +0 −105 cpython/Demo/threads/squasher.py
  131. +0 −603 cpython/Demo/threads/sync.py
  132. +0 −114 cpython/Demo/threads/telnet.py
  133. +0 −89 cpython/Demo/tix/INSTALL.txt
  134. +0 −19 cpython/Demo/tix/README.txt
  135. +0 −50 cpython/Demo/tix/bitmaps/about.xpm
  136. +0 −6 cpython/Demo/tix/bitmaps/bold.xbm
  137. +0 −6 cpython/Demo/tix/bitmaps/capital.xbm
  138. +0 −6 cpython/Demo/tix/bitmaps/centerj.xbm
  139. +0 −14 cpython/Demo/tix/bitmaps/combobox.xbm
  140. +0 −49 cpython/Demo/tix/bitmaps/combobox.xpm
  141. +0 −47 cpython/Demo/tix/bitmaps/combobox.xpm.1
  142. +0 −14 cpython/Demo/tix/bitmaps/drivea.xbm
  143. +0 −43 cpython/Demo/tix/bitmaps/drivea.xpm
  144. +0 −48 cpython/Demo/tix/bitmaps/exit.xpm
  145. +0 −14 cpython/Demo/tix/bitmaps/filebox.xbm
  146. +0 −49 cpython/Demo/tix/bitmaps/filebox.xpm
  147. +0 −6 cpython/Demo/tix/bitmaps/italic.xbm
  148. +0 −6 cpython/Demo/tix/bitmaps/justify.xbm
  149. +0 −6 cpython/Demo/tix/bitmaps/leftj.xbm
  150. +0 −14 cpython/Demo/tix/bitmaps/netw.xbm
  151. +0 −45 cpython/Demo/tix/bitmaps/netw.xpm
  152. +0 −48 cpython/Demo/tix/bitmaps/optmenu.xpm
  153. +0 −6 cpython/Demo/tix/bitmaps/rightj.xbm
  154. +0 −52 cpython/Demo/tix/bitmaps/select.xpm
  155. BIN  cpython/Demo/tix/bitmaps/tix.gif
  156. +0 −6 cpython/Demo/tix/bitmaps/underline.xbm
  157. +0 −28 cpython/Demo/tix/grid.py
  158. +0 −68 cpython/Demo/tix/samples/Balloon.py
  159. +0 −44 cpython/Demo/tix/samples/BtnBox.py
  160. +0 −196 cpython/Demo/tix/samples/CmpImg.py
  161. +0 −102 cpython/Demo/tix/samples/ComboBox.py
  162. +0 −122 cpython/Demo/tix/samples/Control.py
  163. +0 −131 cpython/Demo/tix/samples/DirList.py
  164. +0 −117 cpython/Demo/tix/samples/DirTree.py
  165. +0 −119 cpython/Demo/tix/samples/NoteBook.py
  166. +0 −68 cpython/Demo/tix/samples/OptMenu.py
  167. +0 −98 cpython/Demo/tix/samples/PanedWin.py
  168. +0 −57 cpython/Demo/tix/samples/PopMenu.py
  169. +0 −131 cpython/Demo/tix/samples/SHList1.py
  170. +0 −168 cpython/Demo/tix/samples/SHList2.py
  171. +0 −80 cpython/Demo/tix/samples/Tree.py
  172. +0 −1,003 cpython/Demo/tix/tixwidgets.py
  173. +0 −11 cpython/Demo/tkinter/README
  174. +0 −452 cpython/Demo/tkinter/guido/AttrDialog.py
  175. +0 −220 cpython/Demo/tkinter/guido/ManPage.py
  176. +0 −143 cpython/Demo/tkinter/guido/MimeViewer.py
  177. +0 −147 cpython/Demo/tkinter/guido/ShellWindow.py
  178. +0 −50 cpython/Demo/tkinter/guido/brownian.py
  179. +0 −55 cpython/Demo/tkinter/guido/brownian2.py
  180. +0 −244 cpython/Demo/tkinter/guido/canvasevents.py
  181. +0 −109 cpython/Demo/tkinter/guido/dialog.py
  182. +0 −91 cpython/Demo/tkinter/guido/electrons.py
  183. +0 −154 cpython/Demo/tkinter/guido/hanoi.py
  184. +0 −17 cpython/Demo/tkinter/guido/hello.py
  185. +0 −23 cpython/Demo/tkinter/guido/imagedraw.py
  186. +0 −12 cpython/Demo/tkinter/guido/imageview.py
  187. +0 −98 cpython/Demo/tkinter/guido/kill.py
  188. +0 −37 cpython/Demo/tkinter/guido/listtree.py
  189. +0 −285 cpython/Demo/tkinter/guido/mbox.py
  190. +0 −47 cpython/Demo/tkinter/guido/newmenubardemo.py
  191. +0 −27 cpython/Demo/tkinter/guido/optionmenu.py
  192. +0 −60 cpython/Demo/tkinter/guido/paint.py
  193. +0 −159 cpython/Demo/tkinter/guido/rmt.py
  194. +0 −637 cpython/Demo/tkinter/guido/solitaire.py
  195. +0 −634 cpython/Demo/tkinter/guido/sortvisu.py
  196. +0 −845 cpython/Demo/tkinter/guido/ss1.py
  197. +0 −128 cpython/Demo/tkinter/guido/svkill.py
  198. +0 −55 cpython/Demo/tkinter/guido/switch.py
  199. +0 −267 cpython/Demo/tkinter/guido/tkman.py
  200. +0 −27 cpython/Demo/tkinter/guido/wish.py
  201. +0 −27 cpython/Demo/tkinter/matt/00-HELLO-WORLD.py
  202. +0 −30 cpython/Demo/tkinter/matt/README
  203. +0 −35 cpython/Demo/tkinter/matt/animation-simple.py
  204. +0 −44 cpython/Demo/tkinter/matt/animation-w-velocity-ctrl.py
  205. +0 −44 cpython/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
  206. +0 −28 cpython/Demo/tkinter/matt/canvas-demo-simple.py
  207. +0 −61 cpython/Demo/tkinter/matt/canvas-gridding.py
  208. +0 −62 cpython/Demo/tkinter/matt/canvas-moving-or-creating.py
  209. +0 −55 cpython/Demo/tkinter/matt/canvas-moving-w-mouse.py
  210. +0 −78 cpython/Demo/tkinter/matt/canvas-mult-item-sel.py
  211. +0 −49 cpython/Demo/tkinter/matt/canvas-reading-tag-info.py
  212. +0 −36 cpython/Demo/tkinter/matt/canvas-w-widget-draw-el.py
  213. +0 −60 cpython/Demo/tkinter/matt/canvas-with-scrollbars.py
  214. +0 −64 cpython/Demo/tkinter/matt/dialog-box.py
  215. +0 −24 cpython/Demo/tkinter/matt/entry-simple.py
  216. +0 −46 cpython/Demo/tkinter/matt/entry-with-shared-variable.py
  217. +0 −42 cpython/Demo/tkinter/matt/killing-window-w-wm.py
  218. +0 −244 cpython/Demo/tkinter/matt/menu-all-types-of-entries.py
  219. +0 −112 cpython/Demo/tkinter/matt/menu-simple.py
  220. +0 −28 cpython/Demo/tkinter/matt/not-what-you-might-think-1.py
  221. +0 −30 cpython/Demo/tkinter/matt/not-what-you-might-think-2.py
  222. +0 −41 cpython/Demo/tkinter/matt/packer-and-placer-together.py
  223. +0 −32 cpython/Demo/tkinter/matt/packer-simple.py
  224. +0 −39 cpython/Demo/tkinter/matt/placer-simple.py
  225. +0 −54 cpython/Demo/tkinter/matt/pong-demo-1.py
  226. +0 −61 cpython/Demo/tkinter/matt/printing-coords-of-items.py
  227. +0 −62 cpython/Demo/tkinter/matt/radiobutton-simple.py
  228. +0 −58 cpython/Demo/tkinter/matt/rubber-band-box-demo-1.py
  229. +0 −51 cpython/Demo/tkinter/matt/rubber-line-demo-1.py
  230. +0 −36 cpython/Demo/tkinter/matt/slider-demo-1.py
  231. +0 −28 cpython/Demo/tkinter/matt/subclass-existing-widgets.py
  232. +0 −110 cpython/Demo/tkinter/matt/two-radio-groups.py
  233. +0 −35 cpython/Demo/tkinter/matt/window-creation-more.py
  234. +0 −31 cpython/Demo/tkinter/matt/window-creation-simple.py
  235. +0 −45 cpython/Demo/tkinter/matt/window-creation-w-location.py
  236. +0 −46 cpython/Demo/tkinter/ttk/combo_themes.py
  237. +0 −93 cpython/Demo/tkinter/ttk/dirbrowser.py
  238. BIN  cpython/Demo/tkinter/ttk/img/close.gif
  239. BIN  cpython/Demo/tkinter/ttk/img/close_active.gif
  240. BIN  cpython/Demo/tkinter/ttk/img/close_pressed.gif
  241. +0 −37 cpython/Demo/tkinter/ttk/listbox_scrollcmd.py
  242. +0 −78 cpython/Demo/tkinter/ttk/mac_searchentry.py
  243. +0 −78 cpython/Demo/tkinter/ttk/notebook_closebtn.py
  244. +0 −269 cpython/Demo/tkinter/ttk/plastik_theme.py
  245. +0 −111 cpython/Demo/tkinter/ttk/roundframe.py
  246. +0 −61 cpython/Demo/tkinter/ttk/theme_selector.py
  247. +0 −107 cpython/Demo/tkinter/ttk/treeview_multicolumn.py
  248. +0 −231 cpython/Demo/tkinter/ttk/ttkcalendar.py
  249. +0 −83 cpython/Demo/tkinter/ttk/widget_state.py
  250. +0 −77 cpython/Demo/turtle/about_turtle.txt
  251. +0 −14 cpython/Demo/turtle/about_turtledemo.txt
  252. +0 −75 cpython/Demo/turtle/demohelp.txt
  253. +0 −58 cpython/Demo/turtle/tdemo_I_dontlike_tiltdemo.py
  254. +0 −162 cpython/Demo/turtle/tdemo_bytedesign.py
  255. +0 −59 cpython/Demo/turtle/tdemo_chaos.py
  256. +0 −132 cpython/Demo/turtle/tdemo_clock.py
  257. +0 −58 cpython/Demo/turtle/tdemo_colormixer.py
  258. +0 −137 cpython/Demo/turtle/tdemo_fractalcurves.py
  259. +0 −119 cpython/Demo/turtle/tdemo_lindenmayer_indian.py
  260. +0 −76 cpython/Demo/turtle/tdemo_minimal_hanoi.py
  261. +0 −227 cpython/Demo/turtle/tdemo_nim.py
  262. +0 −50 cpython/Demo/turtle/tdemo_paint.py
  263. +0 −65 cpython/Demo/turtle/tdemo_peace.py
  264. +0 −181 cpython/Demo/turtle/tdemo_penrose.py
  265. +0 −113 cpython/Demo/turtle/tdemo_planet_and_moon.py
  266. +0 −63 cpython/Demo/turtle/tdemo_tree.py
  267. +0 −65 cpython/Demo/turtle/tdemo_wikipedia.py
  268. +0 −49 cpython/Demo/turtle/tdemo_yinyang.py
  269. +0 −10 cpython/Demo/turtle/turtle.cfg
  270. +0 −280 cpython/Demo/turtle/turtleDemo.py
  271. +0 −49 cpython/Demo/turtle/turtledemo_two_canvases.py
  272. +0 −42 cpython/Demo/xml/elem_count.py
  273. +0 −46 cpython/Demo/xml/roundtrip.py
  274. +0 −97 cpython/Demo/xml/rss2html.py
  275. +0 −133 cpython/Demo/zlib/minigzip.py
  276. +0 −48 cpython/Demo/zlib/zlibdemo.py
  277. +0 −223 cpython/Doc/ACKS.txt
  278. +0 −180 cpython/Doc/Makefile
  279. +0 −144 cpython/Doc/README.txt
  280. +0 −36 cpython/Doc/about.rst
  281. +0 −73 cpython/Doc/bugs.rst
  282. +0 −26 cpython/Doc/c-api/abstract.rst
  283. +0 −122 cpython/Doc/c-api/allocation.rst
  284. +0 −559 cpython/Doc/c-api/arg.rst
  285. +0 −54 cpython/Doc/c-api/bool.rst
  286. +0 −450 cpython/Doc/c-api/buffer.rst
  287. +0 −87 cpython/Doc/c-api/bytearray.rst
  288. +0 −150 cpython/Doc/c-api/capsule.rst
  289. +0 −62 cpython/Doc/c-api/cell.rst
  290. +0 −65 cpython/Doc/c-api/class.rst
Sorry, we could not display the entire diff because too many files (1,311) changed.
2  .gitignore
View
@@ -0,0 +1,2 @@
+*.pyc
+
61 cpython/Demo/README
View
@@ -1,61 +0,0 @@
-This directory contains various demonstrations of what you can do with
-Python. They were all written by me except where explicitly stated
-otherwise -- in general, demos contributed by others ends up in the
-../Contrib directory, unless I think they're of utmost general
-importance (like Matt Conway's Tk demos).
-
-A fair number of utilities that are useful when while developing
-Python code can be found in the ../Tools directory -- some of these
-can also be considered good examples of how to write Python code.
-
-Finally, in order to save disk space and net bandwidth, not all
-subdirectories listed here are distributed. They are listed just
-in case I change my mind about them.
-
-
-cgi CGI examples (see also ../Tools/faqwiz/.)
-
-classes Some examples of how to use classes.
-
-comparisons A set of responses to a really old language-comparison
- challenge.
-
-curses A set of curses demos.
-
-embed An example of embedding Python in another application
- (see also pysvr).
-
-imputil Demonstration subclasses of imputil.Importer.
-
-md5test Test program for the optional md5 module.
-
-metaclasses The code from the 1.5 metaclasses paper on the web.
-
-parser Example using the parser module.
-
-pdist Old, unfinished code messing with CVS, RCS and remote
- files.
-
-pysvr An example of embedding Python in a threaded
- application.
-
-rpc A set of classes for building clients and servers for
- Sun RPC.
-
-scripts Some useful Python scripts that I put in my bin
- directory. No optional built-in modules needed.
-
-sockets Examples for the new built-in module 'socket'.
-
-threads Demos that use the 'thread' module. (Currently these
- only run on SGIs, but this may change in the future.)
-
-tix Demos using the Tix widget set addition to Tkinter.
-
-tkinter Demos using the Tk interface (including Matt Conway's
- excellent set of demos).
-
-xml Some XML demos.
-
-zlib Some demos for the zlib module (see also the standard
- library module gzip.py).
11 cpython/Demo/cgi/README
View
@@ -1,11 +0,0 @@
-CGI Examples
-------------
-
-Here are some example CGI programs. For a larger example, see
-../../Tools/faqwiz/.
-
-cgi0.sh -- A shell script to test your server is configured for CGI
-cgi1.py -- A Python script to test your server is configured for CGI
-cgi2.py -- A Python script showing how to parse a form
-cgi3.py -- A Python script for driving an arbitrary CGI application
-wiki.py -- Sample CGI application: a minimal Wiki implementation
8 cpython/Demo/cgi/cgi0.sh
View
@@ -1,8 +0,0 @@
-#! /bin/sh
-
-# If you can't get this to work, your web server isn't set up right
-
-echo Content-type: text/plain
-echo
-echo Hello world
-echo This is cgi0.sh
14 cpython/Demo/cgi/cgi1.py
View
@@ -1,14 +0,0 @@
-#!/usr/bin/env python
-
-"""CGI test 1 - check server setup."""
-
-# Until you get this to work, your web server isn't set up right or
-# your Python isn't set up right.
-
-# If cgi0.sh works but cgi1.py doesn't, check the #! line and the file
-# permissions. The docs for the cgi.py module have debugging tips.
-
-print "Content-type: text/html"
-print
-print "<h1>Hello world</h1>"
-print "<p>This is cgi1.py"
22 cpython/Demo/cgi/cgi2.py
View
@@ -1,22 +0,0 @@
-#!/usr/bin/env python
-
-"""CGI test 2 - basic use of cgi module."""
-
-import cgitb; cgitb.enable()
-
-import cgi
-
-def main():
- form = cgi.FieldStorage()
- print "Content-type: text/html"
- print
- if not form:
- print "<h1>No Form Keys</h1>"
- else:
- print "<h1>Form Keys</h1>"
- for key in form.keys():
- value = form[key].value
- print "<p>", cgi.escape(key), ":", cgi.escape(value)
-
-if __name__ == "__main__":
- main()
10 cpython/Demo/cgi/cgi3.py
View
@@ -1,10 +0,0 @@
-#!/usr/bin/env python
-
-"""CGI test 3 (persistent data)."""
-
-import cgitb; cgitb.enable()
-
-from wiki import main
-
-if __name__ == "__main__":
- main()
123 cpython/Demo/cgi/wiki.py
View
@@ -1,123 +0,0 @@
-"""Wiki main program. Imported and run by cgi3.py."""
-
-import os, re, cgi, sys, tempfile
-escape = cgi.escape
-
-def main():
- form = cgi.FieldStorage()
- print "Content-type: text/html"
- print
- cmd = form.getvalue("cmd", "view")
- page = form.getvalue("page", "FrontPage")
- wiki = WikiPage(page)
- method = getattr(wiki, 'cmd_' + cmd, None) or wiki.cmd_view
- method(form)
-
-class WikiPage:
-
- homedir = tempfile.gettempdir()
- scripturl = os.path.basename(sys.argv[0])
-
- def __init__(self, name):
- if not self.iswikiword(name):
- raise ValueError, "page name is not a wiki word"
- self.name = name
- self.load()
-
- def cmd_view(self, form):
- print "<h1>", escape(self.splitwikiword(self.name)), "</h1>"
- print "<p>"
- for line in self.data.splitlines():
- line = line.rstrip()
- if not line:
- print "<p>"
- else:
- print self.formatline(line)
- print "<hr>"
- print "<p>", self.mklink("edit", self.name, "Edit this page") + ";"
- print self.mklink("view", "FrontPage", "go to front page") + "."
-
- def formatline(self, line):
- words = []
- for word in re.split('(\W+)', line):
- if self.iswikiword(word):
- if os.path.isfile(self.mkfile(word)):
- word = self.mklink("view", word, word)
- else:
- word = self.mklink("new", word, word + "*")
- else:
- word = escape(word)
- words.append(word)
- return "".join(words)
-
- def cmd_edit(self, form, label="Change"):
- print "<h1>", label, self.name, "</h1>"
- print '<form method="POST" action="%s">' % self.scripturl
- s = '<textarea cols="70" rows="20" name="text">%s</textarea>'
- print s % self.data
- print '<input type="hidden" name="cmd" value="create">'
- print '<input type="hidden" name="page" value="%s">' % self.name
- print '<br>'
- print '<input type="submit" value="%s Page">' % label
- print "</form>"
-
- def cmd_create(self, form):
- self.data = form.getvalue("text", "").strip()
- error = self.store()
- if error:
- print "<h1>I'm sorry. That didn't work</h1>"
- print "<p>An error occurred while attempting to write the file:"
- print "<p>", escape(error)
- else:
- # Use a redirect directive, to avoid "reload page" problems
- print "<head>"
- s = '<meta http-equiv="refresh" content="1; URL=%s">'
- print s % (self.scripturl + "?cmd=view&page=" + self.name)
- print "<head>"
- print "<h1>OK</h1>"
- print "<p>If nothing happens, please click here:",
- print self.mklink("view", self.name, self.name)
-
- def cmd_new(self, form):
- self.cmd_edit(form, label="Create")
-
- def iswikiword(self, word):
- return re.match("[A-Z][a-z]+([A-Z][a-z]*)+", word)
-
- def splitwikiword(self, word):
- chars = []
- for c in word:
- if chars and c.isupper():
- chars.append(' ')
- chars.append(c)
- return "".join(chars)
-
- def mkfile(self, name=None):
- if name is None:
- name = self.name
- return os.path.join(self.homedir, name + ".txt")
-
- def mklink(self, cmd, page, text):
- link = self.scripturl + "?cmd=" + cmd + "&page=" + page
- return '<a href="%s">%s</a>' % (link, text)
-
- def load(self):
- try:
- f = open(self.mkfile())
- data = f.read().strip()
- f.close()
- except IOError:
- data = ""
- self.data = data
-
- def store(self):
- data = self.data
- try:
- f = open(self.mkfile(), "w")
- f.write(data)
- if data and not data.endswith('\n'):
- f.write('\n')
- f.close()
- return ""
- except IOError, err:
- return "IOError: %s" % str(err)
320 cpython/Demo/classes/Complex.py
View
@@ -1,320 +0,0 @@
-# Complex numbers
-# ---------------
-
-# [Now that Python has a complex data type built-in, this is not very
-# useful, but it's still a nice example class]
-
-# This module represents complex numbers as instances of the class Complex.
-# A Complex instance z has two data attribues, z.re (the real part) and z.im
-# (the imaginary part). In fact, z.re and z.im can have any value -- all
-# arithmetic operators work regardless of the type of z.re and z.im (as long
-# as they support numerical operations).
-#
-# The following functions exist (Complex is actually a class):
-# Complex([re [,im]) -> creates a complex number from a real and an imaginary part
-# IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes)
-# ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true
-# if z is a tuple(re, im) it will also be converted
-# PolarToComplex([r [,phi [,fullcircle]]]) ->
-# the complex number z for which r == z.radius() and phi == z.angle(fullcircle)
-# (r and phi default to 0)
-# exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z).
-#
-# Complex numbers have the following methods:
-# z.abs() -> absolute value of z
-# z.radius() == z.abs()
-# z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units
-# z.phi([fullcircle]) == z.angle(fullcircle)
-#
-# These standard functions and unary operators accept complex arguments:
-# abs(z)
-# -z
-# +z
-# not z
-# repr(z) == `z`
-# str(z)
-# hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero
-# the result equals hash(z.re)
-# Note that hex(z) and oct(z) are not defined.
-#
-# These conversions accept complex arguments only if their imaginary part is zero:
-# int(z)
-# long(z)
-# float(z)
-#
-# The following operators accept two complex numbers, or one complex number
-# and one real number (int, long or float):
-# z1 + z2
-# z1 - z2
-# z1 * z2
-# z1 / z2
-# pow(z1, z2)
-# cmp(z1, z2)
-# Note that z1 % z2 and divmod(z1, z2) are not defined,
-# nor are shift and mask operations.
-#
-# The standard module math does not support complex numbers.
-# The cmath modules should be used instead.
-#
-# Idea:
-# add a class Polar(r, phi) and mixed-mode arithmetic which
-# chooses the most appropriate type for the result:
-# Complex for +,-,cmp
-# Polar for *,/,pow
-
-import math
-import sys
-
-twopi = math.pi*2.0
-halfpi = math.pi/2.0
-
-def IsComplex(obj):
- return hasattr(obj, 're') and hasattr(obj, 'im')
-
-def ToComplex(obj):
- if IsComplex(obj):
- return obj
- elif isinstance(obj, tuple):
- return Complex(*obj)
- else:
- return Complex(obj)
-
-def PolarToComplex(r = 0, phi = 0, fullcircle = twopi):
- phi = phi * (twopi / fullcircle)
- return Complex(math.cos(phi)*r, math.sin(phi)*r)
-
-def Re(obj):
- if IsComplex(obj):
- return obj.re
- return obj
-
-def Im(obj):
- if IsComplex(obj):
- return obj.im
- return 0
-
-class Complex:
-
- def __init__(self, re=0, im=0):
- _re = 0
- _im = 0
- if IsComplex(re):
- _re = re.re
- _im = re.im
- else:
- _re = re
- if IsComplex(im):
- _re = _re - im.im
- _im = _im + im.re
- else:
- _im = _im + im
- # this class is immutable, so setting self.re directly is
- # not possible.
- self.__dict__['re'] = _re
- self.__dict__['im'] = _im
-
- def __setattr__(self, name, value):
- raise TypeError, 'Complex numbers are immutable'
-
- def __hash__(self):
- if not self.im:
- return hash(self.re)
- return hash((self.re, self.im))
-
- def __repr__(self):
- if not self.im:
- return 'Complex(%r)' % (self.re,)
- else:
- return 'Complex(%r, %r)' % (self.re, self.im)
-
- def __str__(self):
- if not self.im:
- return repr(self.re)
- else:
- return 'Complex(%r, %r)' % (self.re, self.im)
-
- def __neg__(self):
- return Complex(-self.re, -self.im)
-
- def __pos__(self):
- return self
-
- def __abs__(self):
- return math.hypot(self.re, self.im)
-
- def __int__(self):
- if self.im:
- raise ValueError, "can't convert Complex with nonzero im to int"
- return int(self.re)
-
- def __long__(self):
- if self.im:
- raise ValueError, "can't convert Complex with nonzero im to long"
- return long(self.re)
-
- def __float__(self):
- if self.im:
- raise ValueError, "can't convert Complex with nonzero im to float"
- return float(self.re)
-
- def __cmp__(self, other):
- other = ToComplex(other)
- return cmp((self.re, self.im), (other.re, other.im))
-
- def __rcmp__(self, other):
- other = ToComplex(other)
- return cmp(other, self)
-
- def __nonzero__(self):
- return not (self.re == self.im == 0)
-
- abs = radius = __abs__
-
- def angle(self, fullcircle = twopi):
- return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi)
-
- phi = angle
-
- def __add__(self, other):
- other = ToComplex(other)
- return Complex(self.re + other.re, self.im + other.im)
-
- __radd__ = __add__
-
- def __sub__(self, other):
- other = ToComplex(other)
- return Complex(self.re - other.re, self.im - other.im)
-
- def __rsub__(self, other):
- other = ToComplex(other)
- return other - self
-
- def __mul__(self, other):
- other = ToComplex(other)
- return Complex(self.re*other.re - self.im*other.im,
- self.re*other.im + self.im*other.re)
-
- __rmul__ = __mul__
-
- def __div__(self, other):
- other = ToComplex(other)
- d = float(other.re*other.re + other.im*other.im)
- if not d: raise ZeroDivisionError, 'Complex division'
- return Complex((self.re*other.re + self.im*other.im) / d,
- (self.im*other.re - self.re*other.im) / d)
-
- def __rdiv__(self, other):
- other = ToComplex(other)
- return other / self
-
- def __pow__(self, n, z=None):
- if z is not None:
- raise TypeError, 'Complex does not support ternary pow()'
- if IsComplex(n):
- if n.im:
- if self.im: raise TypeError, 'Complex to the Complex power'
- else: return exp(math.log(self.re)*n)
- n = n.re
- r = pow(self.abs(), n)
- phi = n*self.angle()
- return Complex(math.cos(phi)*r, math.sin(phi)*r)
-
- def __rpow__(self, base):
- base = ToComplex(base)
- return pow(base, self)
-
-def exp(z):
- r = math.exp(z.re)
- return Complex(math.cos(z.im)*r,math.sin(z.im)*r)
-
-
-def checkop(expr, a, b, value, fuzz = 1e-6):
- print ' ', a, 'and', b,
- try:
- result = eval(expr)
- except:
- result = sys.exc_type
- print '->', result
- if isinstance(result, str) or isinstance(value, str):
- ok = (result == value)
- else:
- ok = abs(result - value) <= fuzz
- if not ok:
- print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
-
-def test():
- print 'test constructors'
- constructor_test = (
- # "expect" is an array [re,im] "got" the Complex.
- ( (0,0), Complex() ),
- ( (0,0), Complex() ),
- ( (1,0), Complex(1) ),
- ( (0,1), Complex(0,1) ),
- ( (1,2), Complex(Complex(1,2)) ),
- ( (1,3), Complex(Complex(1,2),1) ),
- ( (0,0), Complex(0,Complex(0,0)) ),
- ( (3,4), Complex(3,Complex(4)) ),
- ( (-1,3), Complex(1,Complex(3,2)) ),
- ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) )
- cnt = [0,0]
- for t in constructor_test:
- cnt[0] += 1
- if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)):
- print " expected", t[0], "got", t[1]
- cnt[1] += 1
- print " ", cnt[1], "of", cnt[0], "tests failed"
- # test operators
- testsuite = {
- 'a+b': [
- (1, 10, 11),
- (1, Complex(0,10), Complex(1,10)),
- (Complex(0,10), 1, Complex(1,10)),
- (Complex(0,10), Complex(1), Complex(1,10)),
- (Complex(1), Complex(0,10), Complex(1,10)),
- ],
- 'a-b': [
- (1, 10, -9),
- (1, Complex(0,10), Complex(1,-10)),
- (Complex(0,10), 1, Complex(-1,10)),
- (Complex(0,10), Complex(1), Complex(-1,10)),
- (Complex(1), Complex(0,10), Complex(1,-10)),
- ],
- 'a*b': [
- (1, 10, 10),
- (1, Complex(0,10), Complex(0, 10)),
- (Complex(0,10), 1, Complex(0,10)),
- (Complex(0,10), Complex(1), Complex(0,10)),
- (Complex(1), Complex(0,10), Complex(0,10)),
- ],
- 'a/b': [
- (1., 10, 0.1),
- (1, Complex(0,10), Complex(0, -0.1)),
- (Complex(0, 10), 1, Complex(0, 10)),
- (Complex(0, 10), Complex(1), Complex(0, 10)),
- (Complex(1), Complex(0,10), Complex(0, -0.1)),
- ],
- 'pow(a,b)': [
- (1, 10, 1),
- (1, Complex(0,10), 1),
- (Complex(0,10), 1, Complex(0,10)),
- (Complex(0,10), Complex(1), Complex(0,10)),
- (Complex(1), Complex(0,10), 1),
- (2, Complex(4,0), 16),
- ],
- 'cmp(a,b)': [
- (1, 10, -1),
- (1, Complex(0,10), 1),
- (Complex(0,10), 1, -1),
- (Complex(0,10), Complex(1), -1),
- (Complex(1), Complex(0,10), 1),
- ],
- }
- for expr in sorted(testsuite):
- print expr + ':'
- t = (expr,)
- for item in testsuite[expr]:
- checkop(*(t+item))
-
-
-if __name__ == '__main__':
- test()
227 cpython/Demo/classes/Dates.py
View
@@ -1,227 +0,0 @@
-# Class Date supplies date objects that support date arithmetic.
-#
-# Date(month,day,year) returns a Date object. An instance prints as,
-# e.g., 'Mon 16 Aug 1993'.
-#
-# Addition, subtraction, comparison operators, min, max, and sorting
-# all work as expected for date objects: int+date or date+int returns
-# the date `int' days from `date'; date+date raises an exception;
-# date-int returns the date `int' days before `date'; date2-date1 returns
-# an integer, the number of days from date1 to date2; int-date raises an
-# exception; date1 < date2 is true iff date1 occurs before date2 (&
-# similarly for other comparisons); min(date1,date2) is the earlier of
-# the two dates and max(date1,date2) the later; and date objects can be
-# used as dictionary keys.
-#
-# Date objects support one visible method, date.weekday(). This returns
-# the day of the week the date falls on, as a string.
-#
-# Date objects also have 4 read-only data attributes:
-# .month in 1..12
-# .day in 1..31
-# .year int or long int
-# .ord the ordinal of the date relative to an arbitrary staring point
-#
-# The Dates module also supplies function today(), which returns the
-# current date as a date object.
-#
-# Those entranced by calendar trivia will be disappointed, as no attempt
-# has been made to accommodate the Julian (etc) system. On the other
-# hand, at least this package knows that 2000 is a leap year but 2100
-# isn't, and works fine for years with a hundred decimal digits <wink>.
-
-# Tim Peters tim@ksr.com
-# not speaking for Kendall Square Research Corp
-
-# Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary)
-# by Guido van Rossum
-
-# Note that as of Python 2.3, a datetime module is included in the stardard
-# library.
-
-# vi:set tabsize=8:
-
-_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
- 'June', 'July', 'August', 'September', 'October',
- 'November', 'December' ]
-
-_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday',
- 'Tuesday', 'Wednesday', 'Thursday' ]
-
-_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
-
-_DAYS_BEFORE_MONTH = []
-dbm = 0
-for dim in _DAYS_IN_MONTH:
- _DAYS_BEFORE_MONTH.append(dbm)
- dbm = dbm + dim
-del dbm, dim
-
-_INT_TYPES = type(1), type(1L)
-
-def _is_leap(year): # 1 if leap year, else 0
- if year % 4 != 0: return 0
- if year % 400 == 0: return 1
- return year % 100 != 0
-
-def _days_in_year(year): # number of days in year
- return 365 + _is_leap(year)
-
-def _days_before_year(year): # number of days before year
- return year*365L + (year+3)//4 - (year+99)//100 + (year+399)//400
-
-def _days_in_month(month, year): # number of days in month of year
- if month == 2 and _is_leap(year): return 29
- return _DAYS_IN_MONTH[month-1]
-
-def _days_before_month(month, year): # number of days in year before month
- return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year))
-
-def _date2num(date): # compute ordinal of date.month,day,year
- return _days_before_year(date.year) + \
- _days_before_month(date.month, date.year) + \
- date.day
-
-_DI400Y = _days_before_year(400) # number of days in 400 years
-
-def _num2date(n): # return date with ordinal n
- if type(n) not in _INT_TYPES:
- raise TypeError, 'argument must be integer: %r' % type(n)
-
- ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj
- del ans.ord, ans.month, ans.day, ans.year # un-initialize it
- ans.ord = n
-
- n400 = (n-1)//_DI400Y # # of 400-year blocks preceding
- year, n = 400 * n400, n - _DI400Y * n400
- more = n // 365
- dby = _days_before_year(more)
- if dby >= n:
- more = more - 1
- dby = dby - _days_in_year(more)
- year, n = year + more, int(n - dby)
-
- try: year = int(year) # chop to int, if it fits
- except (ValueError, OverflowError): pass
-
- month = min(n//29 + 1, 12)
- dbm = _days_before_month(month, year)
- if dbm >= n:
- month = month - 1
- dbm = dbm - _days_in_month(month, year)
-
- ans.month, ans.day, ans.year = month, n-dbm, year
- return ans
-
-def _num2day(n): # return weekday name of day with ordinal n
- return _DAY_NAMES[ int(n % 7) ]
-
-
-class Date:
- def __init__(self, month, day, year):
- if not 1 <= month <= 12:
- raise ValueError, 'month must be in 1..12: %r' % (month,)
- dim = _days_in_month(month, year)
- if not 1 <= day <= dim:
- raise ValueError, 'day must be in 1..%r: %r' % (dim, day)
- self.month, self.day, self.year = month, day, year
- self.ord = _date2num(self)
-
- # don't allow setting existing attributes
- def __setattr__(self, name, value):
- if self.__dict__.has_key(name):
- raise AttributeError, 'read-only attribute ' + name
- self.__dict__[name] = value
-
- def __cmp__(self, other):
- return cmp(self.ord, other.ord)
-
- # define a hash function so dates can be used as dictionary keys
- def __hash__(self):
- return hash(self.ord)
-
- # print as, e.g., Mon 16 Aug 1993
- def __repr__(self):
- return '%.3s %2d %.3s %r' % (
- self.weekday(),
- self.day,
- _MONTH_NAMES[self.month-1],
- self.year)
-
- # Python 1.1 coerces neither int+date nor date+int
- def __add__(self, n):
- if type(n) not in _INT_TYPES:
- raise TypeError, 'can\'t add %r to date' % type(n)
- return _num2date(self.ord + n)
- __radd__ = __add__ # handle int+date
-
- # Python 1.1 coerces neither date-int nor date-date
- def __sub__(self, other):
- if type(other) in _INT_TYPES: # date-int
- return _num2date(self.ord - other)
- else:
- return self.ord - other.ord # date-date
-
- # complain about int-date
- def __rsub__(self, other):
- raise TypeError, 'Can\'t subtract date from integer'
-
- def weekday(self):
- return _num2day(self.ord)
-
-def today():
- import time
- local = time.localtime(time.time())
- return Date(local[1], local[2], local[0])
-
-class DateTestError(Exception):
- pass
-
-def test(firstyear, lastyear):
- a = Date(9,30,1913)
- b = Date(9,30,1914)
- if repr(a) != 'Tue 30 Sep 1913':
- raise DateTestError, '__repr__ failure'
- if (not a < b) or a == b or a > b or b != b:
- raise DateTestError, '__cmp__ failure'
- if a+365 != b or 365+a != b:
- raise DateTestError, '__add__ failure'
- if b-a != 365 or b-365 != a:
- raise DateTestError, '__sub__ failure'
- try:
- x = 1 - a
- raise DateTestError, 'int-date should have failed'
- except TypeError:
- pass
- try:
- x = a + b
- raise DateTestError, 'date+date should have failed'
- except TypeError:
- pass
- if a.weekday() != 'Tuesday':
- raise DateTestError, 'weekday() failure'
- if max(a,b) is not b or min(a,b) is not a:
- raise DateTestError, 'min/max failure'
- d = {a-1:b, b:a+1}
- if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
- raise DateTestError, 'dictionary failure'
-
- # verify date<->number conversions for first and last days for
- # all years in firstyear .. lastyear
-
- lord = _days_before_year(firstyear)
- y = firstyear
- while y <= lastyear:
- ford = lord + 1
- lord = ford + _days_in_year(y) - 1
- fd, ld = Date(1,1,y), Date(12,31,y)
- if (fd.ord,ld.ord) != (ford,lord):
- raise DateTestError, ('date->num failed', y)
- fd, ld = _num2date(ford), _num2date(lord)
- if (1,1,y,12,31,y) != \
- (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
- raise DateTestError, ('num->date failed', y)
- y = y + 1
-
-if __name__ == '__main__':
- test(1850, 2150)
66 cpython/Demo/classes/Dbm.py
View
@@ -1,66 +0,0 @@
-# A wrapper around the (optional) built-in class dbm, supporting keys
-# and values of almost any type instead of just string.
-# (Actually, this works only for keys and values that can be read back
-# correctly after being converted to a string.)
-
-
-class Dbm:
-
- def __init__(self, filename, mode, perm):
- import dbm
- self.db = dbm.open(filename, mode, perm)
-
- def __repr__(self):
- s = ''
- for key in self.keys():
- t = repr(key) + ': ' + repr(self[key])
- if s: t = ', ' + t
- s = s + t
- return '{' + s + '}'
-
- def __len__(self):
- return len(self.db)
-
- def __getitem__(self, key):
- return eval(self.db[repr(key)])
-
- def __setitem__(self, key, value):
- self.db[repr(key)] = repr(value)
-
- def __delitem__(self, key):
- del self.db[repr(key)]
-
- def keys(self):
- res = []
- for key in self.db.keys():
- res.append(eval(key))
- return res
-
- def has_key(self, key):
- return self.db.has_key(repr(key))
-
-
-def test():
- d = Dbm('@dbm', 'rw', 0600)
- print d
- while 1:
- try:
- key = input('key: ')
- if d.has_key(key):
- value = d[key]
- print 'currently:', value
- value = input('value: ')
- if value is None:
- del d[key]
- else:
- d[key] = value
- except KeyboardInterrupt:
- print ''
- print d
- except EOFError:
- print '[eof]'
- break
- print d
-
-
-test()
12 cpython/Demo/classes/README
View
@@ -1,12 +0,0 @@
-Examples of classes that implement special operators (see reference manual):
-
-Complex.py Complex numbers
-Dates.py Date manipulation package by Tim Peters
-Dbm.py Wrapper around built-in dbm, supporting arbitrary values
-Range.py Example of a generator: re-implement built-in range()
-Rev.py Yield the reverse of a sequence
-Vec.py A simple vector class
-bitvec.py A bit-vector class by Jan-Hein B\"uhrman
-
-(For straightforward examples of basic class features, such as use of
-methods and inheritance, see the library code.)
93 cpython/Demo/classes/Range.py
View
@@ -1,93 +0,0 @@
-"""Example of a generator: re-implement the built-in range function
-without actually constructing the list of values.
-
-OldStyleRange is coded in the way required to work in a 'for' loop before
-iterators were introduced into the language; using __getitem__ and __len__ .
-
-"""
-def handleargs(arglist):
- """Take list of arguments and extract/create proper start, stop, and step
- values and return in a tuple"""
- try:
- if len(arglist) == 1:
- return 0, int(arglist[0]), 1
- elif len(arglist) == 2:
- return int(arglist[0]), int(arglist[1]), 1
- elif len(arglist) == 3:
- if arglist[2] == 0:
- raise ValueError("step argument must not be zero")
- return tuple(int(x) for x in arglist)
- else:
- raise TypeError("range() accepts 1-3 arguments, given", len(arglist))
- except TypeError:
- raise TypeError("range() arguments must be numbers or strings "
- "representing numbers")
-
-def genrange(*a):
- """Function to implement 'range' as a generator"""
- start, stop, step = handleargs(a)
- value = start
- while value < stop:
- yield value
- value += step
-
-class oldrange:
- """Class implementing a range object.
- To the user the instances feel like immutable sequences
- (and you can't concatenate or slice them)
-
- Done using the old way (pre-iterators; __len__ and __getitem__) to have an
- object be used by a 'for' loop.
-
- """
-
- def __init__(self, *a):
- """ Initialize start, stop, and step values along with calculating the
- nubmer of values (what __len__ will return) in the range"""
- self.start, self.stop, self.step = handleargs(a)
- self.len = max(0, (self.stop - self.start) // self.step)
-
- def __repr__(self):
- """implement repr(x) which is also used by print"""
- return 'range(%r, %r, %r)' % (self.start, self.stop, self.step)
-
- def __len__(self):
- """implement len(x)"""
- return self.len
-
- def __getitem__(self, i):
- """implement x[i]"""
- if 0 <= i <= self.len:
- return self.start + self.step * i
- else:
- raise IndexError, 'range[i] index out of range'
-
-
-def test():
- import time, __builtin__
- #Just a quick sanity check
- correct_result = __builtin__.range(5, 100, 3)
- oldrange_result = list(oldrange(5, 100, 3))
- genrange_result = list(genrange(5, 100, 3))
- if genrange_result != correct_result or oldrange_result != correct_result:
- raise Exception("error in implementation:\ncorrect = %s"
- "\nold-style = %s\ngenerator = %s" %
- (correct_result, oldrange_result, genrange_result))
- print "Timings for range(1000):"
- t1 = time.time()
- for i in oldrange(1000):
- pass
- t2 = time.time()
- for i in genrange(1000):
- pass
- t3 = time.time()
- for i in __builtin__.range(1000):
- pass
- t4 = time.time()
- print t2-t1, 'sec (old-style class)'
- print t3-t2, 'sec (generator)'
- print t4-t3, 'sec (built-in)'
-
-
-if __name__ == '__main__':
- test()
95 cpython/Demo/classes/Rev.py
View
@@ -1,95 +0,0 @@
-'''
-A class which presents the reverse of a sequence without duplicating it.
-From: "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu>
-
-It works on mutable or inmutable sequences.
-
->>> chars = list(Rev('Hello World!'))
->>> print ''.join(chars)
-!dlroW olleH
-
-The .forw is so you can use anonymous sequences in __init__, and still
-keep a reference the forward sequence. )
-If you give it a non-anonymous mutable sequence, the reverse sequence
-will track the updated values. ( but not reassignment! - another
-good reason to use anonymous values in creating the sequence to avoid
-confusion. Maybe it should be change to copy input sequence to break
-the connection completely ? )
-
->>> nnn = range(3)
->>> rnn = Rev(nnn)
->>> for n in rnn: print n
-...
-2
-1
-0
->>> for n in range(4, 6): nnn.append(n) # update nnn
-...
->>> for n in rnn: print n # prints reversed updated values
-...
-5
-4
-2
-1
-0
->>> nnn = nnn[1:-1]
->>> nnn
-[1, 2, 4]
->>> for n in rnn: print n # prints reversed values of old nnn
-...
-5
-4
-2
-1
-0
-
-#
->>> WH = Rev('Hello World!')
->>> print WH.forw, WH.back
-Hello World! !dlroW olleH
->>> nnn = Rev(range(1, 10))
->>> print nnn.forw
-[1, 2, 3, 4, 5, 6, 7, 8, 9]
->>> print nnn.back
-[9, 8, 7, 6, 5, 4, 3, 2, 1]
-
->>> rrr = Rev(nnn)
->>> rrr
-<1, 2, 3, 4, 5, 6, 7, 8, 9>
-
-'''
-
-class Rev:
- def __init__(self, seq):
- self.forw = seq
- self.back = self
-
- def __len__(self):
- return len(self.forw)
-
- def __getitem__(self, j):
- return self.forw[-(j + 1)]
-
- def __repr__(self):
- seq = self.forw
- if isinstance(seq, list):
- wrap = '[]'
- sep = ', '
- elif isinstance(seq, tuple):
- wrap = '()'
- sep = ', '
- elif isinstance(seq, str):
- wrap = ''
- sep = ''
- else:
- wrap = '<>'
- sep = ', '
- outstrs = [str(item) for item in self.back]
- return wrap[:1] + sep.join(outstrs) + wrap[-1:]
-
-def _test():
- import doctest, Rev
- return doctest.testmod(Rev)
-
-if __name__ == "__main__":
- _test()
68 cpython/Demo/classes/Vec.py
View
@@ -1,68 +0,0 @@
-class Vec:
- """ A simple vector class
-
- Instances of the Vec class can be constructed from numbers
-
- >>> a = Vec(1, 2, 3)
- >>> b = Vec(3, 2, 1)
-
- added
- >>> a + b
- Vec(4, 4, 4)
-
- subtracted
- >>> a - b
- Vec(-2, 0, 2)
-
- and multiplied by a scalar on the left
- >>> 3.0 * a
- Vec(3.0, 6.0, 9.0)
-
- or on the right
- >>> a * 3.0
- Vec(3.0, 6.0, 9.0)
- """
- def __init__(self, *v):
- self.v = list(v)
-
- @classmethod
- def fromlist(cls, v):
- if not isinstance(v, list):
- raise TypeError
- inst = cls()
- inst.v = v
- return inst
-
- def __repr__(self):
- args = ', '.join(repr(x) for x in self.v)
- return 'Vec({0})'.format(args)
-
- def __len__(self):
- return len(self.v)
-
- def __getitem__(self, i):
- return self.v[i]
-
- def __add__(self, other):
- # Element-wise addition
- v = [x + y for x, y in zip(self.v, other.v)]
- return Vec.fromlist(v)
-
- def __sub__(self, other):
- # Element-wise subtraction
- v = [x - y for x, y in zip(self.v, other.v)]
- return Vec.fromlist(v)
-
- def __mul__(self, scalar):
- # Multiply by scalar
- v = [x * scalar for x in self.v]
- return Vec.fromlist(v)
-
- __rmul__ = __mul__
-
-
-def test():
- import doctest
- doctest.testmod()
-
-test()
333 cpython/Demo/classes/bitvec.py
View
@@ -1,333 +0,0 @@
-#
-# this is a rather strict implementation of a bit vector class
-# it is accessed the same way as an array of python-ints, except
-# the value must be 0 or 1
-#
-
-import sys; rprt = sys.stderr.write #for debugging
-
-class error(Exception):
- pass
-
-
-def _check_value(value):
- if type(value) != type(0) or not 0 <= value < 2:
- raise error, 'bitvec() items must have int value 0 or 1'
-
-
-import math
-
-def _compute_len(param):
- mant, l = math.frexp(float(param))
- bitmask = 1L << l
- if bitmask <= param:
- raise RuntimeError('(param, l) = %r' % ((param, l),))
- while l:
- bitmask = bitmask >> 1
- if param & bitmask:
- break
- l = l - 1
- return l
-
-
-def _check_key(len, key):
- if type(key) != type(0):
- raise TypeError, 'sequence subscript not int'
- if key < 0:
- key = key + len
- if not 0 <= key < len:
- raise IndexError, 'list index out of range'
- return key
-
-def _check_slice(len, i, j):
- #the type is ok, Python already checked that
- i, j = max(i, 0), min(len, j)
- if i > j:
- i = j
- return i, j
-
-
-class BitVec:
-
- def __init__(self, *params):
- self._data = 0L
- self._len = 0
- if not len(params):
- pass
- elif len(params) == 1:
- param, = params
- if type(param) == type([]):
- value = 0L
- bit_mask = 1L
- for item in param:
- # strict check
- #_check_value(item)
- if item:
- value = value | bit_mask
- bit_mask = bit_mask << 1
- self._data = value
- self._len = len(param)
- elif type(param) == type(0L):
- if param < 0:
- raise error, 'bitvec() can\'t handle negative longs'
- self._data = param
- self._len = _compute_len(param)
- else:
- raise error, 'bitvec() requires array or long parameter'
- elif len(params) == 2:
- param, length = params
- if type(param) == type(0L):
- if param < 0:
- raise error, \
- 'can\'t handle negative longs'
- self._data = param
- if type(length) != type(0):
- raise error, 'bitvec()\'s 2nd parameter must be int'
- computed_length = _compute_len(param)
- if computed_length > length:
- print 'warning: bitvec() value is longer than the length indicates, truncating value'
- self._data = self._data & \
- ((1L << length) - 1)
- self._len = length
- else:
- raise error, 'bitvec() requires array or long parameter'
- else:
- raise error, 'bitvec() requires 0 -- 2 parameter(s)'
-
-
- def append(self, item):
- #_check_value(item)
- #self[self._len:self._len] = [item]
- self[self._len:self._len] = \
- BitVec(long(not not item), 1)
-
-
- def count(self, value):
- #_check_value(value)
- if value:
- data = self._data
- else:
- data = (~self)._data
- count = 0
- while data:
- data, count = data >> 1, count + (data & 1 != 0)
- return count
-
-
- def index(self, value):
- #_check_value(value):
- if value:
- data = self._data
- else:
- data = (~self)._data
- index = 0
- if not data:
- raise ValueError, 'list.index(x): x not in list'
- while not (data & 1):
- data, index = data >> 1, index + 1
- return index
-
-
- def insert(self, index, item):
- #_check_value(item)
- #self[index:index] = [item]
- self[index:index] = BitVec(long(not not item), 1)
-
-
- def remove(self, value):
- del self[self.index(value)]
-
-
- def reverse(self):
- #ouch, this one is expensive!
- #for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i]
- data, result = self._data, 0L
- for i in range(self._len):
- if not data:
- result = result << (self._len - i)
- break
- result, data = (result << 1) | (data & 1), data >> 1
- self._data = result
-
-
- def sort(self):
- c = self.count(1)
- self._data = ((1L << c) - 1) << (self._len - c)
-
-
- def copy(self):
- return BitVec(self._data, self._len)
-
-
- def seq(self):
- result = []
- for i in self:
- result.append(i)
- return result
-
-
- def __repr__(self):
- ##rprt('<bitvec class instance object>.' + '__repr__()\n')
- return 'bitvec(%r, %r)' % (self._data, self._len)
-
- def __cmp__(self, other, *rest):
- #rprt('%r.__cmp__%r\n' % (self, (other,) + rest))
- if type(other) != type(self):
- other = apply(bitvec, (other, ) + rest)
- #expensive solution... recursive binary, with slicing
- length = self._len
- if length == 0 or other._len == 0:
- return cmp(length, other._len)
- if length != other._len:
- min_length = min(length, other._len)
- return cmp(self[:min_length], other[:min_length]) or \
- cmp(self[min_length:], other[min_length:])
- #the lengths are the same now...
- if self._data == other._data:
- return 0
- if length == 1:
- return cmp(self[0], other[0])
- else:
- length = length >> 1
- return cmp(self[:length], other[:length]) or \
- cmp(self[length:], other[length:])
-
-
- def __len__(self):
- #rprt('%r.__len__()\n' % (self,))
- return self._len
-
- def __getitem__(self, key):
- #rprt('%r.__getitem__(%r)\n' % (self, key))
- key = _check_key(self._len, key)
- return self._data & (1L << key) != 0
-
- def __setitem__(self, key, value):
- #rprt('%r.__setitem__(%r, %r)\n' % (self, key, value))
- key = _check_key(self._len, key)
- #_check_value(value)
- if value:
- self._data = self._data | (1L << key)
- else:
- self._data = self._data & ~(1L << key)
-
- def __delitem__(self, key):
- #rprt('%r.__delitem__(%r)\n' % (self, key))
- key = _check_key(self._len, key)
- #el cheapo solution...
- self._data = self[:key]._data | self[key+1:]._data >> key
- self._len = self._len - 1
-
- def __getslice__(self, i, j):
- #rprt('%r.__getslice__(%r, %r)\n' % (self, i, j))
- i, j = _check_slice(self._len, i, j)
- if i >= j:
- return BitVec(0L, 0)
- if i:
- ndata = self._data >> i
- else:
- ndata = self._data
- nlength = j - i
- if j != self._len:
- #we'll have to invent faster variants here
- #e.g. mod_2exp
- ndata = ndata & ((1L << nlength) - 1)
- return BitVec(ndata, nlength)
-
- def __setslice__(self, i, j, sequence, *rest):
- #rprt('%s.__setslice__%r\n' % (self, (i, j, sequence) + rest))
- i, j = _check_slice(self._len, i, j)
- if type(sequence) != type(self):
- sequence = apply(bitvec, (sequence, ) + rest)
- #sequence is now of our own type
- ls_part = self[:i]
- ms_part = self[j:]
- self._data = ls_part._data | \
- ((sequence._data | \
- (ms_part._data << sequence._len)) << ls_part._len)
- self._len = self._len - j + i + sequence._len
-
- def __delslice__(self, i, j):
- #rprt('%r.__delslice__(%r, %r)\n' % (self, i, j))
- i, j = _check_slice(self._len, i, j)
- if i == 0 and j == self._len:
- self._data, self._len = 0L, 0
- elif i < j:
- self._data = self[:i]._data | (self[j:]._data >> i)
- self._len = self._len - j + i
-
- def __add__(self, other):
- #rprt('%r.__add__(%r)\n' % (self, other))
- retval = self.copy()
- retval[self._len:self._len] = other
- return retval
-
- def __mul__(self, multiplier):
- #rprt('%r.__mul__(%r)\n' % (self, multiplier))
- if type(multiplier) != type(0):
- raise TypeError, 'sequence subscript not int'
- if multiplier <= 0:
- return BitVec(0L, 0)
- elif multiplier == 1:
- return self.copy()
- #handle special cases all 0 or all 1...
- if self._data == 0L:
- return BitVec(0L, self._len * multiplier)
- elif (~self)._data == 0L:
- return ~BitVec(0L, self._len * multiplier)
- #otherwise el cheapo again...
- retval = BitVec(0L, 0)
- while multiplier:
- retval, multiplier = retval + self, multiplier - 1
- return retval
-
- def __and__(self, otherseq, *rest):
- #rprt('%r.__and__%r\n' % (self, (otherseq,) + rest))
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- #sequence is now of our own type
- return BitVec(self._data & otherseq._data, \
- min(self._len, otherseq._len))
-
-
- def __xor__(self, otherseq, *rest):
- #rprt('%r.__xor__%r\n' % (self, (otherseq,) + rest))
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- #sequence is now of our own type
- return BitVec(self._data ^ otherseq._data, \
- max(self._len, otherseq._len))
-
-
- def __or__(self, otherseq, *rest):
- #rprt('%r.__or__%r\n' % (self, (otherseq,) + rest))
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- #sequence is now of our own type
- return BitVec(self._data | otherseq._data, \
- max(self._len, otherseq._len))
-
-
- def __invert__(self):
- #rprt('%r.__invert__()\n' % (self,))
- return BitVec(~self._data & ((1L << self._len) - 1), \
- self._len)
-
- def __coerce__(self, otherseq, *rest):
- #needed for *some* of the arithmetic operations
- #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest))
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- return self, otherseq
-
- def __int__(self):
- return int(self._data)
-
- def __long__(self):
- return long(self._data)
-
- def __float__(self):
- return float(self._data)
-
-
-bitvec = BitVec
60 cpython/Demo/comparisons/README
View
@@ -1,60 +0,0 @@
-Subject: Re: What language would you use?
-From: Tom Christiansen <tchrist@mox.perl.com>
-Date: 6 Nov 1994 15:14:51 GMT
-Newsgroups: comp.lang.python,comp.lang.tcl,comp.lang.scheme,comp.lang.misc,comp.lang.perl
-Message-Id: <39irtb$3t4@csnews.cs.Colorado.EDU>
-References: <39b7ha$j9v@zeno.nscf.org> <39hhjp$lgn@csnews.cs.Colorado.EDU> <39hvsu$dus@mathserv.mps.ohio-state.edu>
-
-[...]
-If you're really into benchmarks, I'd love it if someone were to code up
-the following problems in tcl, python, and scheme (and whatever else you'd
-like). Separate versions (one optimized for speed, one for beauty :-) are
-ok. Post your code so we can time it on our own systems.
-
-0) Factorial Test (numerics and function calls)
-
- (we did this already)
-
-1) Regular Expressions Test
-
- Read a file of (extended per egrep) regular expressions (one per line),
- and apply those to all files whose names are listed on the command line.
- Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns
- against a five /etc/termcap files. Tests using more elaborate patters
- would also be interesting. Your code should not break if given hundreds
- of regular expressions or binary files to scan.
-
-2) Sorting Test
-
- Sort an input file that consists of lines like this
-
- var1=23 other=14 ditto=23 fred=2
-
- such that each output line is sorted WRT to the number. Order
- of output lines does not change. Resolve collisions using the
- variable name. e.g.
-
- fred=2 other=14 ditto=23 var1=23
-
- Lines may be up to several kilobytes in length and contain
- zillions of variables.
-
-3) System Test
-
- Given a list of directories, report any bogus symbolic links contained
- anywhere in those subtrees. A bogus symbolic link is one that cannot
- be resolved because it points to a nonexistent or otherwise
- unresolvable file. Do *not* use an external find executable.
- Directories may be very very deep. Print a warning immediately if the
- system you're running on doesn't support symbolic links.
-
-
-I'll post perl solutions if people post the others.
-
-
---tom
---
-Tom Christiansen Perl Consultant, Gamer, Hiker tchrist@mox.perl.com
-
- "But Billy! A *small* allowance prepares you for a lifetime of small
- salaries and for your Social Security payments." --Family Circus
4 cpython/Demo/comparisons/patterns
View
@@ -1,4 +0,0 @@
-^def
-^class
-^import
-^from
47 cpython/Demo/comparisons/regextest.py
View
@@ -1,47 +0,0 @@
-#! /usr/bin/env python
-
-# 1) Regular Expressions Test
-#
-# Read a file of (extended per egrep) regular expressions (one per line),
-# and apply those to all files whose names are listed on the command line.
-# Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns
-# against a five /etc/termcap files. Tests using more elaborate patters
-# would also be interesting. Your code should not break if given hundreds
-# of regular expressions or binary files to scan.
-
-# This implementation:
-# - combines all patterns into a single one using ( ... | ... | ... )
-# - reads patterns from stdin, scans files given as command line arguments
-# - produces output in the format <file>:<lineno>:<line>
-# - is only about 2.5 times as slow as egrep (though I couldn't run
-# Tom's test -- this system, a vanilla SGI, only has /etc/terminfo)
-
-import string
-import sys
-import re
-
-def main():
- pats = map(chomp, sys.stdin.readlines())
- bigpat = '(' + '|'.join(pats) + ')'
- prog = re.compile(bigpat)
-
- for file in sys.argv[1:]:
- try:
- fp = open(file, 'r')
- except IOError, msg:
- print "%s: %s" % (file, msg)
- continue
- lineno = 0
- while 1:
- line = fp.readline()
- if not line:
- break
- lineno = lineno + 1
- if prog.search(line):
- print "%s:%s:%s" % (file, lineno, line),
-
-def chomp(s):
- return s.rstrip('\n')
-
-if __name__ == '__main__':
- main()
45 cpython/Demo/comparisons/sortingtest.py
View
@@ -1,45 +0,0 @@
-#! /usr/bin/env python
-
-# 2) Sorting Test
-#
-# Sort an input file that consists of lines like this
-#
-# var1=23 other=14 ditto=23 fred=2
-#
-# such that each output line is sorted WRT to the number. Order
-# of output lines does not change. Resolve collisions using the
-# variable name. e.g.
-#
-# fred=2 other=14 ditto=23 var1=23
-#
-# Lines may be up to several kilobytes in length and contain
-# zillions of variables.
-
-# This implementation:
-# - Reads stdin, writes stdout
-# - Uses any amount of whitespace to separate fields
-# - Allows signed numbers
-# - Treats illegally formatted fields as field=0
-# - Outputs the sorted fields with exactly one space between them
-# - Handles blank input lines correctly
-
-import re
-import sys
-
-def main():
- prog = re.compile('^(.*)=([-+]?[0-9]+)')
- def makekey(item, prog=prog):
- match = prog.match(item)
- if match:
- var, num = match.groups()
- return int(num), var
- else:
- # Bad input -- pretend it's a var with value 0
- return 0, item
- for line in sys.stdin:
- items = sorted(makekey(item) for item in line.split())
- for num, var in items:
- print "%s=%s" % (var, num),
- print
-
-main()
74 cpython/Demo/comparisons/systemtest.py
View
@@ -1,74 +0,0 @@
-#! /usr/bin/env python
-
-# 3) System Test
-#
-# Given a list of directories, report any bogus symbolic links contained
-# anywhere in those subtrees. A bogus symbolic link is one that cannot
-# be resolved because it points to a nonexistent or otherwise
-# unresolvable file. Do *not* use an external find executable.
-# Directories may be very very deep. Print a warning immediately if the
-# system you're running on doesn't support symbolic links.
-
-# This implementation:
-# - takes one optional argument, using the current directory as default
-# - uses chdir to increase performance
-# - sorts the names per directory
-# - prints output lines of the form "path1 -> path2" as it goes
-# - prints error messages about directories it can't list or chdir into
-
-import os
-import sys
-from stat import *
-
-def main():
- try:
- # Note: can't test for presence of lstat -- it's always there
- dummy = os.readlink
- except AttributeError:
- print "This system doesn't have symbolic links"
- sys.exit(0)
- if sys.argv[1:]:
- prefix = sys.argv[1]
- else:
- prefix = ''
- if prefix:
- os.chdir(prefix)
- if prefix[-1:] != '/': prefix = prefix + '/'
- reportboguslinks(prefix)
- else:
- reportboguslinks('')
-
-def reportboguslinks(prefix):
- try:
- names = os.listdir('.')
- except os.error, msg:
- print "%s%s: can't list: %s" % (prefix, '.', msg)
- return
- names.sort()
- for name in names:
- if name == os.curdir or name == os.pardir:
- continue
- try:
- mode = os.lstat(name)[ST_MODE]
- except os.error:
- print "%s%s: can't stat: %s" % (prefix, name, msg)
- continue
- if S_ISLNK(mode):
- try:
- os.stat(name)
- except os.error:
- print "%s%s -> %s" % \
- (prefix, name, os.readlink(name))
- elif S_ISDIR(mode):
- try:
- os.chdir(name)
- except os.error, msg:
- print "%s%s: can't chdir: %s" % \
- (prefix, name, msg)
- continue
- try:
- reportboguslinks(prefix + name + '/')
- finally:
- os.chdir('..')
-
-main()
25 cpython/Demo/curses/README
View
@@ -1,25 +0,0 @@
-This is a collection of demos and tests for the curses module.
-
-ncurses demos
-=============
-
-These demos are converted from the C versions in the ncurses
-distribution, and were contributed by Thomas Gellekum <tg@FreeBSD.org>
-I didn't strive for a `pythonic' style, but bluntly copied the
-originals. I won't attempt to `beautify' the program anytime soon, but
-I wouldn't mind someone else making an effort in that direction, of
-course.
-
-ncurses.py -- currently only a panels demo
-rain.py -- raindrops keep falling on my desktop
-tclock.py -- ASCII clock, by Howard Jones
-xmas.py -- I'm dreaming of an ASCII christmas
-
-Please submit bugfixes and new contributions to the Python bug tracker.
-
-
-Other demos
-===========
-
-life.py -- Simple game of Life
-repeat.py -- Repeatedly execute a shell command (like watch(1))
216 cpython/Demo/curses/life.py
View
@@ -1,216 +0,0 @@
-#!/usr/bin/env python
-# life.py -- A curses-based version of Conway's Game of Life.
-# Contributed by AMK
-#
-# An empty board will be displayed, and the following commands are available:
-# E : Erase the board
-# R : Fill the board randomly
-# S : Step for a single generation
-# C : Update continuously until a key is struck
-# Q : Quit
-# Cursor keys : Move the cursor around the board
-# Space or Enter : Toggle the contents of the cursor's position
-#
-# TODO :
-# Support the mouse
-# Use colour if available
-# Make board updates faster
-#
-
-import random, string, traceback
-import curses
-
-class LifeBoard:
- """Encapsulates a Life board
-
- Attributes:
- X,Y : horizontal and vertical size of the board
- state : dictionary mapping (x,y) to 0 or 1
-
- Methods:
- display(update_board) -- If update_board is true, compute the
- next generation. Then display the state
- of the board and refresh the screen.
- erase() -- clear the entire board
- makeRandom() -- fill the board randomly
- set(y,x) -- set the given cell to Live; doesn't refresh the screen
- toggle(y,x) -- change the given cell from live to dead, or vice
- versa, and refresh the screen display
-
- """
- def __init__(self, scr, char=ord('*')):
- """Create a new LifeBoard instance.
-
- scr -- curses screen object to use for display
- char -- character used to render live cells (default: '*')
- """
- self.state = {}
- self.scr = scr
- Y, X = self.scr.getmaxyx()
- self.X, self.Y = X-2, Y-2-1
- self.char = char
- self.scr.clear()
-
- # Draw a border around the board
- border_line = '+'+(self.X*'-')+'+'
- self.scr.addstr(0, 0, border_line)
- self.scr.addstr(self.Y+1,0, border_line)
- for y in range(0, self.Y):
- self.scr.addstr(1+y, 0, '|')
- self.scr.addstr(1+y, self.X+1, '|')
- self.scr.refresh()
-
- def set(self, y, x):
- """Set a cell to the live state"""
- if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError, "Coordinates out of range %i,%i"% (y,x)
- self.state[x,y] = 1
-
- def toggle(self, y, x):
- """Toggle a cell's state between live and dead"""
- if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError, "Coordinates out of range %i,%i"% (y,x)
- if self.state.has_key( (x,y) ):
- del self.state[x,y]
- self.scr.addch(y+1, x+1, ' ')
- else:
- self.state[x,y] = 1
- self.scr.addch(y+1, x+1, self.char)
- self.scr.refresh()
-
- def erase(self):
- """Clear the entire board and update the board display"""
- self.state = {}
- self.display(update_board=False)
-
- def display(self, update_board=True):
- """Display the whole board, optionally computing one generation"""
- M,N = self.X, self.Y
- if not update_board:
- for i in range(0, M):
- for j in range(0, N):
- if self.state.has_key( (i,j) ):
- self.scr.addch(j+1, i+1, self.char)
- else:
- self.scr.addch(j+1, i+1, ' ')
- self.scr.refresh()
- return
-
- d = {}
- self.boring = 1
- for i in range(0, M):
- L = range( max(0, i-1), min(M, i+2) )
- for j in range(0, N):
- s = 0
- live = self.state.has_key( (i,j) )
- for k in range( max(0, j-1), min(N, j+2) ):
- for l in L:
- if self.state.has_key( (l,k) ):
- s += 1
- s -= live
- if s == 3:
- # Birth
- d[i,j] = 1
- self.scr.addch(j+1, i+1, self.char)
- if not live: self.boring = 0
- elif s == 2 and live: d[i,j] = 1 # Survival
- elif live:
- # Death
- self.scr.addch(j+1, i+1, ' ')
- self.boring = 0
- self.state = d
- self.scr.refresh()
-
- def makeRandom(self):
- "Fill the board with a random pattern"
- self.state = {}
- for i in range(0, self.X):
- for j in range(0, self.Y):
- if random.random() > 0.5:
- self.set(j,i)
-
-
-def erase_menu(stdscr, menu_y):
- "Clear the space where the menu resides"
- stdscr.move(menu_y, 0)
- stdscr.clrtoeol()
- stdscr.move(menu_y+1, 0)
- stdscr.clrtoeol()
-
-def display_menu(stdscr, menu_y):
- "Display the menu of possible keystroke commands"
- erase_menu(stdscr, menu_y)
- stdscr.addstr(menu_y, 4,
- 'Use the cursor keys to move, and space or Enter to toggle a cell.')
- stdscr.addstr(menu_y+1, 4,
- 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
-
-def keyloop(stdscr):
- # Clear the screen and display the menu of keys
- stdscr.clear()
- stdscr_y, stdscr_x = stdscr.getmaxyx()
- menu_y = (stdscr_y-3)-1
- display_menu(stdscr, menu_y)
-
- # Allocate a subwindow for the Life board and create the board object
- subwin = stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0)
- board = LifeBoard(subwin, char=ord('*'))
- board.display(update_board=False)
-
- # xpos, ypos are the cursor's position
- xpos, ypos = board.X//2, board.Y//2
-
- # Main loop:
- while (1):
- stdscr.move(1+ypos, 1+xpos) # Move the cursor
- c = stdscr.getch() # Get a keystroke
- if 0<c<256:
- c = chr(c)
- if c in ' \n':
- board.toggle(ypos, xpos)
- elif c in 'Cc':
- erase_menu(stdscr, menu_y)
- stdscr.addstr(menu_y, 6, ' Hit any key to stop continuously '
- 'updating the screen.')
- stdscr.refresh()
- # Activate nodelay mode; getch() will return -1
- # if no keystroke is available, instead of waiting.
- stdscr.nodelay(1)
- while (1):
- c = stdscr.getch()
- if c != -1:
- break
- stdscr.addstr(0,0, '/')
- stdscr.refresh()
- board.display()
- stdscr.addstr(0,0, '+')
- stdscr.refresh()
-
- stdscr.nodelay(0) # Disable nodelay mode
- display_menu(stdscr, menu_y)
-
- elif c in 'Ee&